@threenative/runtime-native 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,748 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const CONTAINER_MANIFEST = 'threenative-container.json';
7
+ // The scaffold copies this PNG to a starter's `public/icon.png` as the engine's own art. A
8
+ // distributed game whose embedded icon is still these bytes never replaced it.
9
+ const ENGINE_DEFAULT_ICON = new URL(
10
+ '../../create-threenative/template-assets/icon.png',
11
+ import.meta.url,
12
+ );
13
+
14
+ function sha256File(path) {
15
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
16
+ }
17
+
18
+ function isRecord(value) {
19
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
20
+ }
21
+
22
+ function assertBrandConfig(config, options) {
23
+ if (!isRecord(config) || !isRecord(options)) {
24
+ throw new Error('TN_NATIVE_STARTER_BRAND_CONFIG_INVALID: config and options must be objects.');
25
+ }
26
+ for (const field of ['app', 'ui', 'bootSplash']) {
27
+ if (config[field] !== undefined && !isRecord(config[field])) {
28
+ throw new Error(`TN_NATIVE_STARTER_BRAND_CONFIG_INVALID: ${field} must be an object.`);
29
+ }
30
+ }
31
+ const strings = {
32
+ 'app.name': config.app?.name,
33
+ 'app.icon': config.app?.icon,
34
+ 'bootSplash.image': config.bootSplash?.image,
35
+ 'bootSplash.backgroundColor': config.bootSplash?.backgroundColor,
36
+ 'options.project': options.project,
37
+ 'options.engineIcon': options.engineIcon,
38
+ };
39
+ for (const [field, value] of Object.entries(strings)) {
40
+ if (value !== undefined && (typeof value !== 'string' || value.trim().length === 0)) {
41
+ throw new Error(`TN_NATIVE_STARTER_BRAND_CONFIG_INVALID: ${field} must be a nonempty string.`);
42
+ }
43
+ }
44
+ if (config.ui?.renderer !== undefined && !['web', 'native'].includes(config.ui.renderer)) {
45
+ throw new Error('TN_NATIVE_STARTER_BRAND_CONFIG_INVALID: ui.renderer must be web or native.');
46
+ }
47
+ }
48
+
49
+ // Every inspected byte must belong to the extracted container, including through symlinks.
50
+ // Check Windows paths on all hosts: these fixtures also inspect foreign-platform containers.
51
+ function containerFile(root, path, missingCode) {
52
+ if (
53
+ typeof path !== 'string' ||
54
+ path.length === 0 ||
55
+ path.includes('\\') ||
56
+ path.includes('\0') ||
57
+ isAbsolute(path) ||
58
+ win32.isAbsolute(path) ||
59
+ path.split('/').includes('..')
60
+ ) {
61
+ throw new Error(`TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: unsafe resource path '${path}'.`);
62
+ }
63
+ const absolute = resolve(root, path);
64
+ if (!existsSync(absolute) || !statSync(absolute).isFile()) {
65
+ throw new Error(`${missingCode}: ${path} is not a file in the container.`);
66
+ }
67
+ const physical = relative(realpathSync(root), realpathSync(absolute));
68
+ if (physical === '..' || physical.startsWith(`..${sep}`) || isAbsolute(physical)) {
69
+ throw new Error(
70
+ `TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: ${path} resolves outside the container.`,
71
+ );
72
+ }
73
+ return absolute;
74
+ }
75
+
76
+ function containerResource(root, manifest, path, missingCode) {
77
+ const absolute = containerFile(root, path, missingCode);
78
+ const record = Object.hasOwn(manifest.resources, path) ? manifest.resources[path] : undefined;
79
+ if (
80
+ !isRecord(record) ||
81
+ typeof record.sha256 !== 'string' ||
82
+ !/^[a-f0-9]{64}$/u.test(record.sha256)
83
+ ) {
84
+ throw new Error(
85
+ `TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: ${path} has no valid payload hash.`,
86
+ );
87
+ }
88
+ if (sha256File(absolute) !== record.sha256) {
89
+ throw new Error(`TN_NATIVE_STARTER_CONTAINER_TAMPERED: ${path} differs from its payload hash.`);
90
+ }
91
+ return absolute;
92
+ }
93
+
94
+ function containerManifestPath(root) {
95
+ for (const path of ['Contents/Resources/threenative-container.json', CONTAINER_MANIFEST]) {
96
+ if (existsSync(join(root, path))) {
97
+ return containerFile(root, path, 'TN_NATIVE_STARTER_CONTAINER_MISSING');
98
+ }
99
+ }
100
+ return undefined;
101
+ }
102
+
103
+ /** Inspect the authored application's launcher, never a different inventory entry. */
104
+ function desktopEntryPath(manifest) {
105
+ const expected = `share/applications/${manifest.app.id}.desktop`;
106
+ return Object.hasOwn(manifest.resources, expected) ? expected : undefined;
107
+ }
108
+
109
+ function desktopEntryValues(text) {
110
+ const values = Object.create(null);
111
+ let inDesktopEntry = false;
112
+ for (const line of text.split('\n')) {
113
+ const trimmed = line.trim();
114
+ if (trimmed.startsWith('[')) {
115
+ inDesktopEntry = trimmed === '[Desktop Entry]';
116
+ continue;
117
+ }
118
+ if (!inDesktopEntry) continue;
119
+ const match = /^([A-Za-z][A-Za-z0-9-]*)=(.*)$/u.exec(line.trimStart().replace(/\r$/u, ''));
120
+ if (!match) continue;
121
+ if (Object.hasOwn(values, match[1])) {
122
+ throw new Error(
123
+ `TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: duplicate desktop key ${match[1]}.`,
124
+ );
125
+ }
126
+ values[match[1]] = match[2].replace(/\\([sntr\\])/gu, (_, escaped) =>
127
+ ({ s: ' ', n: '\n', t: '\t', r: '\r', '\\': '\\' })[escaped],
128
+ );
129
+ }
130
+ return values;
131
+ }
132
+
133
+ function plistString(plist, key) {
134
+ const matches = [
135
+ ...plist.matchAll(
136
+ new RegExp(`<key>${key}</key>\\s*<string>([\\s\\S]*?)</string>`, 'gu'),
137
+ ),
138
+ ];
139
+ if (matches.length > 1) {
140
+ throw new Error(`TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: duplicate plist key ${key}.`);
141
+ }
142
+ const match = matches[0];
143
+ return match?.[1]
144
+ .replaceAll('&lt;', '<')
145
+ .replaceAll('&gt;', '>')
146
+ .replaceAll('&quot;', '"')
147
+ .replaceAll('&apos;', "'")
148
+ .replaceAll('&amp;', '&');
149
+ }
150
+
151
+ // --- Windows PE resources -------------------------------------------------------------------
152
+ // A Windows game's launcher identity is the executable's own resource section, written by rcedit
153
+ // during packaging. The application manifest and the sidecar PNG beside it are inputs to that
154
+ // write, never evidence of it, so the bytes are read back out of the .exe here. Plain `fs` and
155
+ // `Buffer`: a resource directory is a fixed three-level tree and needs no dependency.
156
+ const RT_ICON = 3;
157
+ const RT_GROUP_ICON = 14;
158
+ const RT_VERSION = 16;
159
+ const VS_FIXEDFILEINFO_SIGNATURE = 0xfeef04bd;
160
+
161
+ function sha256Buffer(buffer) {
162
+ return createHash('sha256').update(buffer).digest('hex');
163
+ }
164
+
165
+ function parsePeImage(path) {
166
+ const buffer = readFileSync(path);
167
+ if (buffer.length < 0x40 || buffer.readUInt16LE(0) !== 0x5a4d) {
168
+ throw new Error(
169
+ `TN_NATIVE_STARTER_CONTAINER_BRAND_UNVERIFIED: ${path} is not a PE image, so its Windows brand cannot be read.`,
170
+ );
171
+ }
172
+ const peOffset = buffer.readUInt32LE(0x3c);
173
+ if (peOffset + 24 > buffer.length || buffer.readUInt32LE(peOffset) !== 0x00004550) {
174
+ throw new Error(
175
+ `TN_NATIVE_STARTER_CONTAINER_BRAND_UNVERIFIED: ${path} has no PE header, so its Windows brand cannot be read.`,
176
+ );
177
+ }
178
+ const optional = peOffset + 24;
179
+ const optionalSize = buffer.readUInt16LE(peOffset + 20);
180
+ const magic = optional + 2 <= buffer.length ? buffer.readUInt16LE(optional) : 0;
181
+ if (magic !== 0x10b && magic !== 0x20b) {
182
+ throw new Error(
183
+ `TN_NATIVE_STARTER_CONTAINER_BRAND_UNVERIFIED: ${path} declares optional-header magic 0x${magic.toString(16)}, which is neither PE32 nor PE32+.`,
184
+ );
185
+ }
186
+ const directoriesOffset = optional + (magic === 0x20b ? 112 : 96);
187
+ const countOffset = optional + (magic === 0x20b ? 108 : 92);
188
+ // Bound the read before taking it: a truncated .exe must name its cause, not raise a bare
189
+ // RangeError from deep inside the parser.
190
+ if (countOffset + 4 > buffer.length || directoriesOffset + 24 > buffer.length) {
191
+ throw new Error(
192
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: ${path} is truncated before its resource data directory.`,
193
+ );
194
+ }
195
+ if (buffer.readUInt32LE(countOffset) < 3) {
196
+ throw new Error(
197
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_MISSING: the packaged .exe has no resource data directory.',
198
+ );
199
+ }
200
+ const resourceRva = buffer.readUInt32LE(directoriesOffset + 16);
201
+ const resourceSize = buffer.readUInt32LE(directoriesOffset + 20);
202
+ if (resourceRva === 0 || resourceSize === 0) {
203
+ throw new Error(
204
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_MISSING: the packaged .exe carries an empty resource directory.',
205
+ );
206
+ }
207
+ const sections = [];
208
+ for (let index = 0; index < buffer.readUInt16LE(peOffset + 6); index += 1) {
209
+ const offset = optional + optionalSize + index * 40;
210
+ if (offset + 40 > buffer.length) {
211
+ throw new Error(
212
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: a section header runs past the end of the .exe.',
213
+ );
214
+ }
215
+ sections.push({
216
+ rawOffset: buffer.readUInt32LE(offset + 20),
217
+ rawSize: buffer.readUInt32LE(offset + 16),
218
+ virtualAddress: buffer.readUInt32LE(offset + 12),
219
+ virtualSize: buffer.readUInt32LE(offset + 8),
220
+ });
221
+ }
222
+ return { buffer, resourceRva, sections };
223
+ }
224
+
225
+ function rvaToOffset(image, rva) {
226
+ for (const section of image.sections) {
227
+ const span = Math.max(section.virtualSize, section.rawSize);
228
+ if (rva >= section.virtualAddress && rva < section.virtualAddress + span) {
229
+ const offset = section.rawOffset + (rva - section.virtualAddress);
230
+ if (offset < image.buffer.length) return offset;
231
+ }
232
+ }
233
+ throw new Error(
234
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: resource RVA 0x${rva.toString(16)} lies in no section of the .exe.`,
235
+ );
236
+ }
237
+
238
+ /** One IMAGE_RESOURCE_DIRECTORY: 16 bytes of header, then named entries and id entries. */
239
+ function resourceDirectoryEntries(image, base, offset) {
240
+ const { buffer } = image;
241
+ if (offset + 16 > buffer.length) {
242
+ throw new Error(
243
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: a resource directory runs past the end of the .exe.',
244
+ );
245
+ }
246
+ const count = buffer.readUInt16LE(offset + 12) + buffer.readUInt16LE(offset + 14);
247
+ const entries = [];
248
+ for (let index = 0; index < count; index += 1) {
249
+ const entry = offset + 16 + index * 8;
250
+ if (entry + 8 > buffer.length) {
251
+ throw new Error(
252
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: a resource entry runs past the end of the .exe.',
253
+ );
254
+ }
255
+ const name = buffer.readUInt32LE(entry);
256
+ const target = buffer.readUInt32LE(entry + 4);
257
+ entries.push({
258
+ directory: (target & 0x80000000) !== 0,
259
+ id: (name & 0x80000000) === 0 ? name : undefined,
260
+ offset: base + (target & 0x7fffffff),
261
+ });
262
+ }
263
+ return entries;
264
+ }
265
+
266
+ /** Every leaf of one resource type, addressed type -> name -> language, with its payload bytes. */
267
+ function resourceLeaves(image, type) {
268
+ const base = rvaToOffset(image, image.resourceRva);
269
+ const leaves = [];
270
+ for (const typeEntry of resourceDirectoryEntries(image, base, base)) {
271
+ if (typeEntry.id !== type || !typeEntry.directory) continue;
272
+ for (const nameEntry of resourceDirectoryEntries(image, base, typeEntry.offset)) {
273
+ if (!nameEntry.directory) continue;
274
+ for (const language of resourceDirectoryEntries(image, base, nameEntry.offset)) {
275
+ if (language.directory || language.offset + 16 > image.buffer.length) {
276
+ throw new Error(
277
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: a resource language entry is not a data entry.',
278
+ );
279
+ }
280
+ const start = rvaToOffset(image, image.buffer.readUInt32LE(language.offset));
281
+ const size = image.buffer.readUInt32LE(language.offset + 4);
282
+ if (size === 0 || start + size > image.buffer.length) {
283
+ throw new Error(
284
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: a resource payload is empty or runs past the end of the .exe.',
285
+ );
286
+ }
287
+ leaves.push({ data: image.buffer.subarray(start, start + size), id: nameEntry.id });
288
+ }
289
+ }
290
+ }
291
+ return leaves;
292
+ }
293
+
294
+ const align4 = (value) => (value + 3) & ~3;
295
+
296
+ /** VS_VERSIONINFO nodes: wLength, wValueLength, wType, a UTF-16 key, a padded value, children. */
297
+ function versionNodes(data, start, end) {
298
+ const nodes = [];
299
+ let cursor = start;
300
+ while (cursor + 6 <= end) {
301
+ const length = data.readUInt16LE(cursor);
302
+ if (length < 6) break;
303
+ const limit = Math.min(cursor + length, end);
304
+ const type = data.readUInt16LE(cursor + 4);
305
+ let keyEnd = cursor + 6;
306
+ while (keyEnd + 1 < limit && data.readUInt16LE(keyEnd) !== 0) keyEnd += 2;
307
+ const valueStart = align4(keyEnd + 2);
308
+ const valueLength = data.readUInt16LE(cursor + 2);
309
+ const valueEnd = Math.min(valueStart + (type === 1 ? valueLength * 2 : valueLength), limit);
310
+ nodes.push({
311
+ binary: type === 0 && valueEnd > valueStart ? data.subarray(valueStart, valueEnd) : undefined,
312
+ childrenEnd: limit,
313
+ childrenStart: align4(valueEnd),
314
+ key: data.toString('utf16le', cursor + 6, keyEnd),
315
+ value:
316
+ type === 1 && valueEnd > valueStart
317
+ ? data.toString('utf16le', valueStart, valueEnd).replace(/\0+$/u, '')
318
+ : undefined,
319
+ });
320
+ cursor = align4(limit);
321
+ }
322
+ return nodes;
323
+ }
324
+
325
+ function parseVersionResource(data) {
326
+ const [root] = versionNodes(data, 0, data.length);
327
+ if (
328
+ root?.key !== 'VS_VERSION_INFO' ||
329
+ root.binary === undefined ||
330
+ root.binary.length < 52 ||
331
+ root.binary.readUInt32LE(0) !== VS_FIXEDFILEINFO_SIGNATURE
332
+ ) {
333
+ throw new Error(
334
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: RT_VERSION carries no VS_FIXEDFILEINFO block.',
335
+ );
336
+ }
337
+ const fixed = root.binary;
338
+ const strings = Object.create(null);
339
+ for (const child of versionNodes(data, root.childrenStart, root.childrenEnd)) {
340
+ if (child.key !== 'StringFileInfo') continue;
341
+ for (const table of versionNodes(data, child.childrenStart, child.childrenEnd)) {
342
+ for (const entry of versionNodes(data, table.childrenStart, table.childrenEnd)) {
343
+ if (entry.value !== undefined) strings[entry.key] = entry.value;
344
+ }
345
+ }
346
+ }
347
+ return {
348
+ fileVersion: [
349
+ fixed.readUInt16LE(10),
350
+ fixed.readUInt16LE(8),
351
+ fixed.readUInt16LE(14),
352
+ fixed.readUInt16LE(12),
353
+ ].join('.'),
354
+ strings,
355
+ };
356
+ }
357
+
358
+ /** The icon ids one RT_GROUP_ICON directory points at, in GRPICONDIRENTRY order. */
359
+ function groupIconIds(data) {
360
+ if (data.length < 6 || data.readUInt16LE(2) !== 1) {
361
+ throw new Error(
362
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: RT_GROUP_ICON is not an icon directory.',
363
+ );
364
+ }
365
+ const count = data.readUInt16LE(4);
366
+ if (count === 0 || 6 + count * 14 > data.length) {
367
+ throw new Error(
368
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: RT_GROUP_ICON declares no usable image entries.',
369
+ );
370
+ }
371
+ return Array.from({ length: count }, (_, index) => data.readUInt16LE(6 + index * 14 + 12));
372
+ }
373
+
374
+ function inspectWindowsResources(containerRoot, manifest) {
375
+ const executable = containerResource(
376
+ containerRoot,
377
+ manifest,
378
+ manifest.executable,
379
+ 'TN_NATIVE_STARTER_CONTAINER_EXECUTABLE_MISSING',
380
+ );
381
+ const image = parsePeImage(executable);
382
+ const version = resourceLeaves(image, RT_VERSION);
383
+ if (version.length !== 1) {
384
+ throw new Error(
385
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_MISSING: the packaged .exe carries ${version.length} RT_VERSION resources, not one.`,
386
+ );
387
+ }
388
+ const groups = resourceLeaves(image, RT_GROUP_ICON);
389
+ if (groups.length === 0) {
390
+ throw new Error(
391
+ 'TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_MISSING: the packaged .exe carries no RT_GROUP_ICON, so no launcher icon is embedded.',
392
+ );
393
+ }
394
+ // Inspecting the first of several groups leaves the rest unexamined, and which one Explorer
395
+ // draws is the lowest id, not the tree order this walk returns. rcedit writes exactly one.
396
+ if (groups.length > 1) {
397
+ throw new Error(
398
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: the packaged .exe carries ${groups.length} RT_GROUP_ICON resources, so which icon it shows is ambiguous.`,
399
+ );
400
+ }
401
+ const icons = new Map(resourceLeaves(image, RT_ICON).map((leaf) => [leaf.id, leaf.data]));
402
+ const images = groupIconIds(groups[0].data).map((id) => {
403
+ const data = icons.get(id);
404
+ if (data === undefined) {
405
+ throw new Error(
406
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_INVALID: RT_GROUP_ICON names icon ${id}, which the .exe does not carry.`,
407
+ );
408
+ }
409
+ return { id, sha256: sha256Buffer(data) };
410
+ });
411
+ const { fileVersion, strings } = parseVersionResource(version[0].data);
412
+ return { fileVersion, images, source: manifest.executable, strings };
413
+ }
414
+
415
+ /**
416
+ * The version Explorer reports, against the version the author configured.
417
+ *
418
+ * Anchoring this on the container's own `app.version` alone let a manifest retire the assertion
419
+ * against itself by omitting the field, which is the shape every sibling check here refuses.
420
+ */
421
+ function assertWindowsVersion(windows, manifest, config) {
422
+ const declared = manifest.app.version;
423
+ if (typeof declared !== 'string' || declared.length === 0) {
424
+ throw new Error(
425
+ 'TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: a Windows container declares no application version to check its PE resources against.',
426
+ );
427
+ }
428
+ const authored = config.app?.version;
429
+ if (typeof authored === 'string' && authored !== declared) {
430
+ throw new Error(
431
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_VERSION_MISMATCH: the container says version ${declared}, config says ${authored}.`,
432
+ );
433
+ }
434
+ const expected = `${declared}.0.0.0`.split('.').slice(0, 4).join('.');
435
+ if (windows.fileVersion !== expected) {
436
+ throw new Error(
437
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_VERSION_MISMATCH: the .exe reports file version ${windows.fileVersion}, the container says ${declared}.`,
438
+ );
439
+ }
440
+ }
441
+
442
+ function windowsLauncherName(windows) {
443
+ // Both names are required, not just the one that happens to be present: the packager writes
444
+ // ProductName and FileDescription together, so an absent FileDescription is a name that was
445
+ // never embedded — and treating it as "nothing to compare" is the same self-retiring shape the
446
+ // review found in the version check, letting a stale second name ride along unexamined.
447
+ for (const key of ['ProductName', 'FileDescription']) {
448
+ if (typeof windows.strings[key] !== 'string' || windows.strings[key].length === 0) {
449
+ throw new Error(
450
+ `TN_NATIVE_STARTER_CONTAINER_WINDOWS_RESOURCES_MISSING: the packaged .exe declares no ${key} for Explorer to show.`,
451
+ );
452
+ }
453
+ }
454
+ return { displayName: windows.strings.FileDescription, name: windows.strings.ProductName, source: windows.source };
455
+ }
456
+
457
+ function inspectContainerIcon(containerRoot, manifest, config, options, windows) {
458
+ const configured = config.app?.icon;
459
+ if (configured === undefined) return undefined;
460
+ const configuredPath = resolve(options.project ?? process.cwd(), configured);
461
+ if (!existsSync(configuredPath) || !statSync(configuredPath).isFile()) {
462
+ throw new Error(
463
+ `TN_NATIVE_STARTER_BRAND_CONFIG_ICON_MISSING: app.icon is not a file: ${configuredPath}`,
464
+ );
465
+ }
466
+ const declared = manifest.app.icon;
467
+ if (typeof declared !== 'string' || declared.length === 0) {
468
+ throw new Error(
469
+ 'TN_NATIVE_STARTER_CONTAINER_ICON_MISSING: the container names no application icon.',
470
+ );
471
+ }
472
+ const iconPath = containerResource(
473
+ containerRoot,
474
+ manifest,
475
+ declared,
476
+ 'TN_NATIVE_STARTER_CONTAINER_ICON_MISSING',
477
+ );
478
+ const embedded = sha256File(iconPath);
479
+ const source = sha256File(configuredPath);
480
+ const engineIcon =
481
+ options.engineIcon ??
482
+ (existsSync(ENGINE_DEFAULT_ICON) ? fileURLToPath(ENGINE_DEFAULT_ICON) : undefined);
483
+ if (engineIcon === undefined || !existsSync(engineIcon) || !statSync(engineIcon).isFile()) {
484
+ throw new Error(
485
+ 'TN_NATIVE_STARTER_CONTAINER_BRAND_UNVERIFIED: engine-default icon comparison is unavailable.',
486
+ );
487
+ }
488
+ const engine = sha256File(engineIcon);
489
+ if (embedded === engine || source === engine || manifest.app.iconSha256 === engine) {
490
+ throw new Error(
491
+ 'TN_NATIVE_STARTER_CONTAINER_ICON_ENGINE_DEFAULT: the application icon is the engine default.',
492
+ );
493
+ }
494
+ if (
495
+ typeof manifest.app.iconSha256 !== 'string' ||
496
+ !/^[a-f0-9]{64}$/u.test(manifest.app.iconSha256)
497
+ ) {
498
+ throw new Error(
499
+ 'TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: the icon has no valid source hash.',
500
+ );
501
+ }
502
+ // PRD-365 records the input hash in app.iconSha256 and the final (possibly converted) bytes
503
+ // in resources[path].sha256. A PNG and its generated ICNS must not be compared byte-for-byte.
504
+ if (
505
+ manifest.app.iconSha256 !== source ||
506
+ (!manifest.platform.startsWith('darwin-') && embedded !== source)
507
+ ) {
508
+ throw new Error(
509
+ 'TN_NATIVE_STARTER_CONTAINER_ICON_MISMATCH: the container icon differs from app.icon.',
510
+ );
511
+ }
512
+ // The sidecar PNG proves provenance of the input; only the .exe's own RT_ICON proves what
513
+ // Explorer will draw, so a Windows container is judged on the bytes rcedit actually embedded.
514
+ if (windows !== undefined) {
515
+ const embeddedIcons = windows.images.map((image) => image.sha256);
516
+ if (embeddedIcons.includes(engine)) {
517
+ throw new Error(
518
+ 'TN_NATIVE_STARTER_CONTAINER_ICON_ENGINE_DEFAULT: the .exe embeds the engine-default icon.',
519
+ );
520
+ }
521
+ if (!embeddedIcons.includes(source)) {
522
+ throw new Error(
523
+ `TN_NATIVE_STARTER_CONTAINER_ICON_MISMATCH: the .exe embeds ${embeddedIcons.join(', ')}, none of which is app.icon (${source}).`,
524
+ );
525
+ }
526
+ }
527
+ return { path: declared, sha256: embedded, sourceSha256: source };
528
+ }
529
+
530
+ function linuxLauncherName(containerRoot, manifest) {
531
+ const relativePath = desktopEntryPath(manifest);
532
+ if (relativePath === undefined) {
533
+ throw new Error(
534
+ 'TN_NATIVE_STARTER_CONTAINER_DESKTOP_ENTRY_MISSING: the Linux container declares no .desktop application metadata.',
535
+ );
536
+ }
537
+ const path = containerResource(
538
+ containerRoot,
539
+ manifest,
540
+ relativePath,
541
+ 'TN_NATIVE_STARTER_CONTAINER_DESKTOP_ENTRY_MISSING',
542
+ );
543
+ const entry = desktopEntryValues(readFileSync(path, 'utf8'));
544
+ if (entry.Name === undefined || entry.Type !== 'Application') {
545
+ throw new Error(
546
+ `TN_NATIVE_STARTER_CONTAINER_DESKTOP_ENTRY_MISSING: ${relativePath} has no Name= entry for the file manager.`,
547
+ );
548
+ }
549
+ if (
550
+ manifest.app.icon !== undefined &&
551
+ (entry.Icon !== manifest.app.id ||
552
+ manifest.app.icon !== `share/icons/hicolor/256x256/apps/${manifest.app.id}.png`)
553
+ ) {
554
+ throw new Error(
555
+ 'TN_NATIVE_STARTER_CONTAINER_ICON_MISMATCH: the Linux launcher does not reference the inspected icon.',
556
+ );
557
+ }
558
+ return { name: entry.Name, source: relativePath };
559
+ }
560
+
561
+ function darwinLauncherName(containerRoot, manifest) {
562
+ const relativePath = 'Contents/Info.plist';
563
+ const path = containerResource(
564
+ containerRoot,
565
+ manifest,
566
+ relativePath,
567
+ 'TN_NATIVE_STARTER_CONTAINER_PLIST_ENTRY_MISSING',
568
+ );
569
+ const plist = readFileSync(path, 'utf8');
570
+ const bundleName = plistString(plist, 'CFBundleName');
571
+ const displayName = plistString(plist, 'CFBundleDisplayName');
572
+ const name = bundleName ?? displayName;
573
+ if (name === undefined) {
574
+ throw new Error(
575
+ 'TN_NATIVE_STARTER_CONTAINER_PLIST_ENTRY_MISSING: Info.plist has no application name.',
576
+ );
577
+ }
578
+ const icon = plistString(plist, 'CFBundleIconFile');
579
+ if (
580
+ manifest.app.icon !== undefined &&
581
+ (icon === undefined ||
582
+ `Contents/Resources/${icon.replace(/\.icns$/u, '')}.icns` !== manifest.app.icon)
583
+ ) {
584
+ throw new Error(
585
+ 'TN_NATIVE_STARTER_CONTAINER_ICON_MISMATCH: Info.plist does not reference the inspected icon.',
586
+ );
587
+ }
588
+ return { name, displayName, source: relativePath };
589
+ }
590
+
591
+ function inspectContainerName(containerRoot, manifest, config, platform, windows) {
592
+ const expected = config.app?.name;
593
+ if (expected === undefined) return undefined;
594
+ const found =
595
+ windows === undefined
596
+ ? platform === 'linux'
597
+ ? linuxLauncherName(containerRoot, manifest)
598
+ : darwinLauncherName(containerRoot, manifest)
599
+ : windowsLauncherName(windows);
600
+ if (
601
+ found.name !== expected ||
602
+ (found.displayName !== undefined && found.displayName !== expected) ||
603
+ manifest.app.name !== expected
604
+ ) {
605
+ throw new Error(
606
+ `TN_NATIVE_STARTER_CONTAINER_NAME_MISMATCH: the ${platform} launcher names '${found.name}', config says '${expected}'.`,
607
+ );
608
+ }
609
+ return found;
610
+ }
611
+
612
+ function assertDeclaredLoading(declared, config, options) {
613
+ const expected = config.bootSplash ?? null;
614
+ const actual = declared.bootSplash ?? null;
615
+ if (expected === null || actual === null) {
616
+ if (expected !== actual) {
617
+ throw new Error(
618
+ 'TN_NATIVE_STARTER_CONTAINER_LOADING_MISSING: the container does not declare the boot/loading sequence the config requires.',
619
+ );
620
+ }
621
+ return { bootSplash: actual, source: CONTAINER_MANIFEST };
622
+ }
623
+ let expectedImage = null;
624
+ if (expected.image !== undefined) {
625
+ const image = resolve(options.project ?? process.cwd(), expected.image);
626
+ if (!existsSync(image) || !statSync(image).isFile()) {
627
+ throw new Error(
628
+ `TN_NATIVE_STARTER_BRAND_CONFIG_IMAGE_MISSING: bootSplash.image is not a file: ${image}`,
629
+ );
630
+ }
631
+ expectedImage = sha256File(image);
632
+ }
633
+ if (
634
+ actual.backgroundColor !== expected.backgroundColor ||
635
+ (actual.imageSha256 ?? null) !== expectedImage
636
+ ) {
637
+ throw new Error(
638
+ 'TN_NATIVE_STARTER_CONTAINER_LOADING_MISMATCH: the container boot/loading sequence differs from the consumer config.',
639
+ );
640
+ }
641
+ return { bootSplash: actual, source: CONTAINER_MANIFEST };
642
+ }
643
+
644
+ function inspectContainerLoading(containerRoot, manifest, config, options) {
645
+ const renderer = config.ui?.renderer ?? 'native';
646
+ let uiEntry = null;
647
+ if (renderer === 'web') {
648
+ const entry = manifest.ui?.entry;
649
+ if (typeof entry !== 'string') {
650
+ throw new Error('TN_NATIVE_STARTER_CONTAINER_LOADING_MISSING: no web UI launch entry.');
651
+ }
652
+ containerResource(
653
+ containerRoot,
654
+ manifest,
655
+ entry,
656
+ 'TN_NATIVE_STARTER_CONTAINER_LOADING_MISSING',
657
+ );
658
+ uiEntry = entry;
659
+ } else if (manifest.ui !== null && manifest.ui !== undefined) {
660
+ throw new Error(
661
+ 'TN_NATIVE_STARTER_CONTAINER_LOADING_MISMATCH: a native UI config ships a web launch surface.',
662
+ );
663
+ }
664
+ // A UI entry proves only a launch surface. It cannot stand in for a configured splash, and
665
+ // a splash declaration must never bypass checking that the UI entry exists and is a file.
666
+ if (config.bootSplash !== undefined && manifest.loading === undefined) {
667
+ throw new Error(
668
+ 'TN_NATIVE_STARTER_CONTAINER_LOADING_MISSING: the configured splash has no container declaration.',
669
+ );
670
+ }
671
+ if (manifest.loading !== undefined) {
672
+ return { ...assertDeclaredLoading(manifest.loading, config, options), uiEntry };
673
+ }
674
+ if (config.ui === undefined) return undefined;
675
+ return { uiEntry, source: CONTAINER_MANIFEST };
676
+ }
677
+
678
+ function readContainerManifest(containerRoot) {
679
+ const manifestPath = containerManifestPath(containerRoot);
680
+ if (manifestPath === undefined) {
681
+ throw new Error(
682
+ `TN_NATIVE_STARTER_CONTAINER_MISSING: no ${CONTAINER_MANIFEST} under ${containerRoot}.`,
683
+ );
684
+ }
685
+ let manifest;
686
+ try {
687
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
688
+ } catch (error) {
689
+ throw new Error(
690
+ `TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: ${error instanceof Error ? error.message : String(error)}`,
691
+ );
692
+ }
693
+ if (
694
+ !isRecord(manifest) ||
695
+ !isRecord(manifest.app) ||
696
+ !isRecord(manifest.resources) ||
697
+ manifest.schemaVersion !== 1 ||
698
+ !['linux-x64', 'linux-arm64', 'darwin-x64', 'darwin-arm64', 'win32-x64'].includes(
699
+ manifest.platform,
700
+ ) ||
701
+ (manifest.ui !== undefined && manifest.ui !== null && !isRecord(manifest.ui)) ||
702
+ (manifest.loading !== undefined &&
703
+ (!isRecord(manifest.loading) ||
704
+ (manifest.loading.bootSplash !== undefined &&
705
+ manifest.loading.bootSplash !== null &&
706
+ !isRecord(manifest.loading.bootSplash))))
707
+ ) {
708
+ throw new Error(
709
+ 'TN_NATIVE_STARTER_CONTAINER_MANIFEST_INVALID: unsupported schema, platform or brand metadata.',
710
+ );
711
+ }
712
+ return manifest;
713
+ }
714
+
715
+ /**
716
+ * Inspect a distributed desktop container's brand against the consumer config that declared it.
717
+ *
718
+ * `root` is the directory PRD-365 packages (the single top-level folder an archive extracts to).
719
+ * Three independent surfaces are compared and each failure names the actual cause: the embedded
720
+ * application icon, the launcher/file-manager application name, and the declared loading/launch
721
+ * sequence. It never launches the app and never inspects the runtime SDL window, so it makes no
722
+ * claim about pixels a player sees.
723
+ */
724
+ export function inspectContainerBrand(root, config, options = {}) {
725
+ assertBrandConfig(config, options);
726
+ const containerRoot = resolve(root);
727
+ if (!existsSync(containerRoot) || !statSync(containerRoot).isDirectory()) {
728
+ throw new Error(`TN_NATIVE_STARTER_CONTAINER_MISSING: ${containerRoot} is not a directory.`);
729
+ }
730
+ const manifest = readContainerManifest(containerRoot);
731
+ const platform = manifest.platform.split('-')[0];
732
+ const windows = platform === 'win32' ? inspectWindowsResources(containerRoot, manifest) : undefined;
733
+ if (windows !== undefined) assertWindowsVersion(windows, manifest, config);
734
+ const evidence = {
735
+ icon: inspectContainerIcon(containerRoot, manifest, config, options, windows),
736
+ name: inspectContainerName(containerRoot, manifest, config, platform, windows),
737
+ loading: inspectContainerLoading(containerRoot, manifest, config, options),
738
+ windows,
739
+ };
740
+ const hasSplashAssertion =
741
+ config.bootSplash?.backgroundColor !== undefined || config.bootSplash?.image !== undefined;
742
+ if (evidence.icon === undefined && evidence.name === undefined && !hasSplashAssertion) {
743
+ throw new Error(
744
+ 'TN_NATIVE_STARTER_CONTAINER_BRAND_UNVERIFIED: the container and config declare no brand to inspect.',
745
+ );
746
+ }
747
+ return evidence;
748
+ }