@orkestrel/sea 0.0.1

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,2465 @@
1
+ import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
2
+ import { brotliCompressSync, constants } from "node:zlib";
3
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { execFileSync, spawn } from "node:child_process";
5
+ import { randomUUID } from "node:crypto";
6
+ import { Emitter } from "@orkestrel/emitter";
7
+ import { getAssetKeys, getRawAsset, isSea } from "node:sea";
8
+ import { isArrayBuffer } from "@orkestrel/contract";
9
+ //#region src/server/constants.ts
10
+ /** SEA sentinel fuse value embedded in the Node.js binary */
11
+ var SEA_SENTINEL_FUSE = "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2";
12
+ /** Resource name for the SEA blob in the executable */
13
+ var SEA_BLOB_RESOURCE = "NODE_SEA_BLOB";
14
+ /** Default Brotli compression quality level (maximum) */
15
+ var DEFAULT_SEA_COMPRESSION_QUALITY = 11;
16
+ /** Windows PE subsystem value: GUI application (no terminal window) */
17
+ var WINDOWS_SUBSYSTEM_GUI = 2;
18
+ /** Windows PE subsystem value: console application */
19
+ var WINDOWS_SUBSYSTEM_CONSOLE = 3;
20
+ /** File extension indicating Brotli compression */
21
+ var BROTLI_EXTENSION = ".br";
22
+ /** File extensions that should NOT be Brotli-compressed */
23
+ var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
24
+ ".br",
25
+ ".gz",
26
+ ".zst",
27
+ ".png",
28
+ ".jpg",
29
+ ".jpeg",
30
+ ".gif",
31
+ ".webp",
32
+ ".avif",
33
+ ".ico",
34
+ ".woff",
35
+ ".woff2",
36
+ ".ttf",
37
+ ".otf",
38
+ ".eot",
39
+ ".mp3",
40
+ ".mp4",
41
+ ".webm",
42
+ ".ogg",
43
+ ".zip",
44
+ ".tar"
45
+ ]);
46
+ /** Default SEA entry point module format when none is specified */
47
+ var DEFAULT_ENTRY_FORMAT = "cjs";
48
+ /** Asset key for the raw (uncompressed) client HTML entry */
49
+ var CLIENT_ASSET_KEY_RAW = "client.html";
50
+ /** Asset key for the Brotli-compressed client HTML entry */
51
+ var CLIENT_ASSET_KEY_BR = "client.html.br";
52
+ /** DOS MZ header magic (first 2 bytes of a PE file) */
53
+ var PE_MAGIC = 23117;
54
+ /** PE signature: "PE\0\0" as a 32-bit value */
55
+ var PE_SIGNATURE = 17744;
56
+ /** PE32 optional header magic */
57
+ var PE32_MAGIC = 267;
58
+ /** PE32+ (64-bit) optional header magic */
59
+ var PE32_PLUS_MAGIC = 523;
60
+ /** ELF magic: 0x7F 'E' 'L' 'F' as a 32-bit big-endian value */
61
+ var ELF_MAGIC = 2135247942;
62
+ /** ELF 64-bit class identifier */
63
+ var ELF_CLASS_64 = 2;
64
+ /** ELF little-endian data encoding */
65
+ var ELF_DATA_LSB = 1;
66
+ /** ELF program header type: note segment */
67
+ var ELF_PT_NOTE = 4;
68
+ /** Mach-O 64-bit magic (little-endian) */
69
+ var MACHO_MAGIC_64 = 4277009103;
70
+ /** Mach-O LC_SEGMENT_64 load command */
71
+ var MACHO_LC_SEGMENT_64 = 25;
72
+ /** PE resource type: RT_RCDATA (raw data) */
73
+ var PE_RT_RCDATA = 10;
74
+ /** Size of IMAGE_RESOURCE_DIRECTORY in bytes */
75
+ var PE_RESOURCE_DIR_SIZE = 16;
76
+ /** Size of IMAGE_RESOURCE_DIRECTORY_ENTRY in bytes */
77
+ var PE_RESOURCE_ENTRY_SIZE = 8;
78
+ /** Size of IMAGE_RESOURCE_DATA_ENTRY in bytes */
79
+ var PE_RESOURCE_DATA_ENTRY_SIZE = 16;
80
+ /** PE section header size in bytes */
81
+ var PE_SECTION_HEADER_SIZE = 40;
82
+ /** High bit mask for resource directory entry offset (indicates subdirectory) */
83
+ var PE_RESOURCE_SUBDIR_FLAG = 2147483648;
84
+ /** High bit mask for resource name entry (indicates named vs integer ID) */
85
+ var PE_RESOURCE_NAME_FLAG = 2147483648;
86
+ /** Section contains initialized data */
87
+ var PE_SCN_INITIALIZED_DATA = 64;
88
+ /** Section is readable */
89
+ var PE_SCN_MEM_READ = 1073741824;
90
+ /** Platform-specific SEA build configurations */
91
+ var SEA_PLATFORMS = Object.freeze({
92
+ win32: Object.freeze({
93
+ executable: "node.exe",
94
+ remove: void 0,
95
+ sign: void 0,
96
+ verify: Object.freeze([
97
+ "signtool",
98
+ "verify",
99
+ "/pa"
100
+ ])
101
+ }),
102
+ darwin: Object.freeze({
103
+ executable: "node",
104
+ remove: Object.freeze(["codesign", "--remove-signature"]),
105
+ sign: Object.freeze([
106
+ "codesign",
107
+ "--sign",
108
+ "-"
109
+ ]),
110
+ verify: Object.freeze([
111
+ "codesign",
112
+ "--verify",
113
+ "--strict"
114
+ ])
115
+ }),
116
+ linux: Object.freeze({
117
+ executable: "node",
118
+ remove: void 0,
119
+ sign: void 0,
120
+ verify: void 0
121
+ })
122
+ });
123
+ /** Maps a {@link SEACompressionMode} to its numeric Brotli mode value */
124
+ var SEA_COMPRESSION_MODE_VALUES = Object.freeze({
125
+ generic: 0,
126
+ text: 1,
127
+ font: 2
128
+ });
129
+ //#endregion
130
+ //#region src/server/errors.ts
131
+ /**
132
+ * The coded base error for every failure raised by the seal build.
133
+ *
134
+ * @remarks
135
+ * Carries a machine-readable {@link SEAErrorCode} and optional `context`
136
+ * for structured diagnostics. Narrow a caught value with {@link isSEAError}.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * try {
141
+ * seal.execute()
142
+ * } catch (error) {
143
+ * if (isSEAError(error)) {
144
+ * console.error(error.code, error.context)
145
+ * }
146
+ * }
147
+ * ```
148
+ */
149
+ var SEAError = class extends Error {
150
+ code;
151
+ context;
152
+ constructor(code, message, context) {
153
+ super(message);
154
+ this.name = "SEAError";
155
+ this.code = code;
156
+ this.context = context;
157
+ }
158
+ };
159
+ /**
160
+ * Whether a value is a {@link SEAError}.
161
+ *
162
+ * @param value - The value to test
163
+ * @returns `true` when `value` is a `SEAError`
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * if (isSEAError(caught)) {
168
+ * console.error(caught.code)
169
+ * }
170
+ * ```
171
+ */
172
+ function isSEAError(value) {
173
+ return value instanceof SEAError;
174
+ }
175
+ /**
176
+ * An error thrown when a shell command run via `runShell` exits non-zero.
177
+ *
178
+ * @remarks
179
+ * Carries the captured `stdout` and `stderr` buffers from the failed process.
180
+ * Always carries {@link SEAErrorCode} `'SHELL'`. Narrow a caught value with
181
+ * {@link isShellError}.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * try {
186
+ * runShell(['codesign', '--sign', '-', path])
187
+ * } catch (error) {
188
+ * if (isShellError(error)) {
189
+ * console.error(error.stderr.toString())
190
+ * }
191
+ * }
192
+ * ```
193
+ */
194
+ var ShellError = class extends SEAError {
195
+ stdout;
196
+ stderr;
197
+ constructor(message, stdout, stderr) {
198
+ super("SHELL", message);
199
+ this.name = "ShellError";
200
+ this.stdout = stdout;
201
+ this.stderr = stderr;
202
+ }
203
+ };
204
+ /**
205
+ * Whether a value is a {@link ShellError}.
206
+ *
207
+ * @param value - The value to test
208
+ * @returns `true` when `value` is a `ShellError`
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * if (isShellError(caught)) {
213
+ * console.error(caught.stdout.toString())
214
+ * }
215
+ * ```
216
+ */
217
+ function isShellError(value) {
218
+ return value instanceof ShellError;
219
+ }
220
+ //#endregion
221
+ //#region src/server/helpers.ts
222
+ /**
223
+ * Check if a value is a valid {@link ExecutableFormat}.
224
+ *
225
+ * @param value - Value to check
226
+ * @returns True when value is `'pe'`, `'elf'`, or `'macho'`
227
+ */
228
+ function isExecutableFormat(value) {
229
+ return value === "pe" || value === "elf" || value === "macho";
230
+ }
231
+ /**
232
+ * Get the platform configuration for the current OS.
233
+ *
234
+ * @param platform - Platform identifier. Default: `process.platform`.
235
+ * @returns Platform configuration, or undefined if unsupported
236
+ */
237
+ function platformConfig(platform) {
238
+ return SEA_PLATFORMS[platform ?? process.platform];
239
+ }
240
+ /**
241
+ * Check if the current or specified platform is supported for SEA builds.
242
+ *
243
+ * @param platform - Platform identifier to check
244
+ * @returns True when the platform has a known configuration
245
+ */
246
+ function isPlatformSupported(platform) {
247
+ return (platform ?? process.platform) in SEA_PLATFORMS;
248
+ }
249
+ /**
250
+ * Assert that a path exists, throwing a coded {@link SEAError} if not.
251
+ *
252
+ * @param path - Absolute or relative path to check
253
+ * @param message - Error message when path is missing
254
+ * @param code - Error code to throw with. Default: `'STATE'`.
255
+ */
256
+ function ensureExists(path, message, code) {
257
+ if (!existsSync(path)) throw new SEAError(code ?? "STATE", message, { path });
258
+ }
259
+ /**
260
+ * Check if a file should be Brotli-compressed based on its extension.
261
+ *
262
+ * @param path - Path to the file
263
+ * @returns True when the file type benefits from compression
264
+ */
265
+ function isCompressible(path) {
266
+ const ext = extname(path).toLowerCase();
267
+ return !SKIP_EXTENSIONS.has(ext);
268
+ }
269
+ /**
270
+ * Recursively walk a directory and return all file paths.
271
+ *
272
+ * @param directory - Directory to walk
273
+ * @param base - Base directory for relative path calculation
274
+ * @returns Array of relative file paths
275
+ */
276
+ function walkDirectory(directory, base) {
277
+ const root = base ?? directory;
278
+ const result = [];
279
+ const entries = readdirSync(directory, { withFileTypes: true });
280
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
281
+ for (const entry of entries) {
282
+ if (entry.isSymbolicLink()) continue;
283
+ const fullPath = join(directory, entry.name);
284
+ if (entry.isDirectory()) result.push(...walkDirectory(fullPath, root));
285
+ else if (entry.isFile()) result.push(relative(root, fullPath));
286
+ }
287
+ return result;
288
+ }
289
+ /**
290
+ * Run a command synchronously and return stdout.
291
+ *
292
+ * @param command - Command to execute (first element is the binary)
293
+ * @param options - Shell options (cwd, env, timeout, signal)
294
+ * @returns stdout as a Buffer
295
+ * @throws SEAError with code `'STATE'` when `command` is empty
296
+ * @throws SEAError with code `'ABORT'` when `options.signal` is already aborted
297
+ * @throws SEAError with code `'TIMEOUT'` when the command exceeds `options.timeout`
298
+ * @throws ShellError when the command exits with non-zero status
299
+ */
300
+ function runShell(command, options) {
301
+ function redactCommand(argv) {
302
+ const secretFlags = /* @__PURE__ */ new Set([
303
+ "/p",
304
+ "-p",
305
+ "--password"
306
+ ]);
307
+ return argv.map((token, index) => {
308
+ const previous = argv[index - 1];
309
+ if (previous !== void 0 && secretFlags.has(previous.toLowerCase())) return "***";
310
+ return token;
311
+ });
312
+ }
313
+ const [cmd, ...args] = command;
314
+ if (cmd === void 0) throw new SEAError("STATE", "Command array must not be empty");
315
+ if (options?.signal?.aborted === true) throw new SEAError("ABORT", "Shell command aborted", { command: redactCommand(command) });
316
+ const useShell = cmd.endsWith(".cmd") || cmd.endsWith(".bat");
317
+ try {
318
+ return execFileSync(cmd, args, {
319
+ cwd: options?.cwd,
320
+ env: options?.env !== void 0 ? {
321
+ ...process.env,
322
+ ...options.env
323
+ } : void 0,
324
+ stdio: [
325
+ "pipe",
326
+ "pipe",
327
+ "pipe"
328
+ ],
329
+ shell: useShell,
330
+ timeout: options?.timeout
331
+ });
332
+ } catch (thrown) {
333
+ if (!(thrown instanceof Error)) throw thrown;
334
+ const redacted = redactCommand(command);
335
+ if (("code" in thrown && typeof thrown.code === "string" ? thrown.code : void 0) === "ETIMEDOUT") throw new SEAError("TIMEOUT", "Shell command timed out", {
336
+ command: redacted,
337
+ timeout: options?.timeout
338
+ });
339
+ const stdout = "stdout" in thrown && Buffer.isBuffer(thrown.stdout) ? thrown.stdout : Buffer.alloc(0);
340
+ const stderr = "stderr" in thrown && Buffer.isBuffer(thrown.stderr) ? thrown.stderr : Buffer.alloc(0);
341
+ throw new ShellError("Command failed: " + redacted.join(" "), stdout, stderr);
342
+ }
343
+ }
344
+ /**
345
+ * Compute a size comparison between original and compressed byte counts.
346
+ *
347
+ * @param original - Original byte count
348
+ * @param compressed - Compressed byte count
349
+ * @returns SEACompressionSize with ratio
350
+ */
351
+ function computeSize(original, compressed) {
352
+ return {
353
+ original,
354
+ compressed,
355
+ ratio: original > 0 ? compressed / original : 0
356
+ };
357
+ }
358
+ /**
359
+ * Brotli-compress a single file, writing the output alongside it.
360
+ *
361
+ * @param input - Absolute path to the source file
362
+ * @param output - Absolute path for the compressed output
363
+ * @param options - Compression options (quality, mode)
364
+ * @returns Compression result with size comparison
365
+ */
366
+ function compressFile(input, output, options) {
367
+ const quality = options?.quality ?? 11;
368
+ const mode = SEA_COMPRESSION_MODE_VALUES[options?.mode ?? "generic"];
369
+ const raw = readFileSync(input);
370
+ const compressed = brotliCompressSync(raw, { params: {
371
+ [constants.BROTLI_PARAM_QUALITY]: quality,
372
+ [constants.BROTLI_PARAM_MODE]: mode
373
+ } });
374
+ let outputStat;
375
+ try {
376
+ outputStat = lstatSync(output);
377
+ } catch {
378
+ outputStat = void 0;
379
+ }
380
+ if (outputStat !== void 0 && outputStat.isSymbolicLink()) throw new SEAError("OUTPUT", "Refusing to write compressed output through a symlink", { output });
381
+ writeFileSync(output, compressed);
382
+ return {
383
+ input,
384
+ output,
385
+ size: computeSize(raw.length, compressed.length)
386
+ };
387
+ }
388
+ /**
389
+ * Compress all compressible files in a directory tree.
390
+ *
391
+ * @param directory - Absolute path to the directory
392
+ * @param options - Compression options
393
+ * @param progress - Optional callback invoked after each file is compressed
394
+ * @returns Compression manifest with all results
395
+ */
396
+ function compressDirectory(directory, options, progress) {
397
+ const files = walkDirectory(directory);
398
+ const results = [];
399
+ let totalOriginal = 0;
400
+ let totalCompressed = 0;
401
+ for (const relativePath of files) {
402
+ const fullPath = resolve(directory, relativePath);
403
+ if (!isCompressible(fullPath)) continue;
404
+ const result = compressFile(fullPath, fullPath + ".br", options);
405
+ results.push(result);
406
+ totalOriginal += result.size.original;
407
+ totalCompressed += result.size.compressed;
408
+ progress?.(result);
409
+ }
410
+ return {
411
+ assets: results,
412
+ total: computeSize(totalOriginal, totalCompressed)
413
+ };
414
+ }
415
+ /**
416
+ * Parse the PE header offset from a Windows executable.
417
+ *
418
+ * @param fd - Open file descriptor
419
+ * @returns The offset to the PE signature
420
+ */
421
+ function parsePEOffset(fd) {
422
+ const buf = Buffer.alloc(4);
423
+ readSync(fd, buf, 0, 4, 60);
424
+ return buf.readUInt32LE(0);
425
+ }
426
+ /**
427
+ * Read a 16-bit unsigned integer from a file descriptor.
428
+ *
429
+ * @param fd - Open file descriptor
430
+ * @param offset - Byte offset to read from
431
+ * @returns The 16-bit value
432
+ */
433
+ function readU16(fd, offset) {
434
+ const buf = Buffer.alloc(2);
435
+ readSync(fd, buf, 0, 2, offset);
436
+ return buf.readUInt16LE(0);
437
+ }
438
+ /**
439
+ * Write a 16-bit unsigned integer to a file descriptor.
440
+ *
441
+ * @param fd - Open file descriptor
442
+ * @param offset - Byte offset to write at
443
+ * @param value - The 16-bit value to write
444
+ */
445
+ function writeU16(fd, offset, value) {
446
+ const buf = Buffer.alloc(2);
447
+ buf.writeUInt16LE(value, 0);
448
+ writeSync(fd, buf, 0, 2, offset);
449
+ }
450
+ /**
451
+ * Check if a file is a Windows PE executable.
452
+ *
453
+ * @param path - Path to the file
454
+ * @returns True when the file has a valid PE signature
455
+ */
456
+ function isPEExecutable(path) {
457
+ let fd;
458
+ try {
459
+ fd = openSync(path, "r");
460
+ const peOffset = parsePEOffset(fd);
461
+ const sig = Buffer.alloc(4);
462
+ readSync(fd, sig, 0, 4, peOffset);
463
+ return sig.toString("ascii") === "PE\0\0";
464
+ } catch {
465
+ return false;
466
+ } finally {
467
+ if (fd !== void 0) closeSync(fd);
468
+ }
469
+ }
470
+ /**
471
+ * Patch the PE subsystem field in a Windows executable.
472
+ *
473
+ * @param path - Path to the executable
474
+ * @param subsystem - Numeric subsystem value (2 = GUI, 3 = Console)
475
+ */
476
+ function patchPESubsystem(path, subsystem) {
477
+ const fd = openSync(path, "r+");
478
+ try {
479
+ writeU16(fd, parsePEOffset(fd) + 92, subsystem);
480
+ } finally {
481
+ closeSync(fd);
482
+ }
483
+ }
484
+ /**
485
+ * Remove the Authenticode signature from a PE executable by zeroing
486
+ * the security directory entry in the optional header.
487
+ *
488
+ * @remarks
489
+ * If the certificate overlay described by the security directory sits at the
490
+ * very end of the file (the common case for `signtool`-signed binaries), the
491
+ * file is truncated to the certificate's start FIRST so the overlay bytes are
492
+ * discarded rather than left as dead weight for a downstream injector to
493
+ * bury mid-file. The directory read is bounds-checked so a malformed or
494
+ * truncated security directory cannot throw unexpectedly — it is simply
495
+ * skipped and only the directory entry is zeroed.
496
+ *
497
+ * @param path - Path to the executable
498
+ */
499
+ function stripPESignature(path) {
500
+ const fd = openSync(path, "r+");
501
+ try {
502
+ const peOffset = parsePEOffset(fd);
503
+ const securityDirOffset = readU16(fd, peOffset + 24) === 523 ? peOffset + 168 : peOffset + 152;
504
+ const dirBuf = Buffer.alloc(8);
505
+ if (readSync(fd, dirBuf, 0, 8, securityDirOffset) === 8) {
506
+ const certOffset = dirBuf.readUInt32LE(0);
507
+ const certSize = dirBuf.readUInt32LE(4);
508
+ if (certOffset > 0 && certSize > 0) {
509
+ const fileSize = fstatSync(fd).size;
510
+ if (certOffset <= fileSize && certOffset + certSize === fileSize) ftruncateSync(fd, certOffset);
511
+ }
512
+ }
513
+ writeSync(fd, Buffer.alloc(8), 0, 8, securityDirOffset);
514
+ } finally {
515
+ closeSync(fd);
516
+ }
517
+ }
518
+ /**
519
+ * Build the `signtool sign` argv for signing a Windows executable.
520
+ *
521
+ * @remarks
522
+ * Requires EXACTLY ONE certificate source — `sign.file` (a `.pfx`/`.p12`
523
+ * file, paired with `sign.password` when present) XOR `sign.thumbprint` (a
524
+ * certificate already installed in the Windows store). When `sign.timestamp`
525
+ * is set it is parsed with the `URL` constructor and must be an `http:` or
526
+ * `https:` URL. The returned argv is passed directly to `runShell` — never
527
+ * through a shell — so nothing in `sign` can be interpreted as a flag or
528
+ * injected into a command line. `sign.password` is NEVER included in a
529
+ * thrown error's message or `context`.
530
+ *
531
+ * @param sign - Windows signing options
532
+ * @param target - Absolute path to the executable to sign
533
+ * @returns The `signtool` argv, ready for `runShell`
534
+ * @throws SEAError with code `'SIGN'` when neither `file` nor `thumbprint` is set
535
+ * @throws SEAError with code `'SIGN'` when both `file` and `thumbprint` are set
536
+ * @throws SEAError with code `'SIGN'` when `timestamp` is not a parseable http(s) URL
537
+ * @throws SEAError with code `'SIGN'` when `digest` is not `'sha1'`, `'sha256'`, `'sha384'`, or `'sha512'`
538
+ *
539
+ * @example
540
+ * ```ts
541
+ * createSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')
542
+ * // ['signtool', 'sign', '/fd', 'sha256', '/sha1', 'AABBCCDDEEFF00112233445566778899AABBCCDD', 'dist/sea/app.exe']
543
+ * ```
544
+ */
545
+ function createSignCommand(sign, target) {
546
+ const hasFile = sign.file !== void 0;
547
+ const hasThumbprint = sign.thumbprint !== void 0;
548
+ if (!hasFile && !hasThumbprint) throw new SEAError("SIGN", "Windows signing requires exactly one of sign.file or sign.thumbprint");
549
+ if (hasFile && hasThumbprint) throw new SEAError("SIGN", "Windows signing accepts only one of sign.file or sign.thumbprint, not both");
550
+ if (sign.timestamp !== void 0) {
551
+ let parsed;
552
+ try {
553
+ parsed = new URL(sign.timestamp);
554
+ } catch {
555
+ throw new SEAError("SIGN", "Windows signing timestamp must be an http(s) URL", { timestamp: sign.timestamp });
556
+ }
557
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new SEAError("SIGN", "Windows signing timestamp must be an http(s) URL", { timestamp: sign.timestamp });
558
+ }
559
+ const digest = sign.digest ?? "sha256";
560
+ if (!(/* @__PURE__ */ new Set([
561
+ "sha1",
562
+ "sha256",
563
+ "sha384",
564
+ "sha512"
565
+ ])).has(digest)) throw new SEAError("SIGN", "Unsupported signing digest", { digest: sign.digest });
566
+ return [
567
+ "signtool",
568
+ "sign",
569
+ "/fd",
570
+ digest,
571
+ ...sign.file !== void 0 ? [
572
+ "/f",
573
+ sign.file,
574
+ ...sign.password !== void 0 ? ["/p", sign.password] : []
575
+ ] : [],
576
+ ...sign.thumbprint !== void 0 ? ["/sha1", sign.thumbprint] : [],
577
+ ...sign.timestamp !== void 0 ? [
578
+ "/tr",
579
+ sign.timestamp,
580
+ "/td",
581
+ digest
582
+ ] : [],
583
+ target
584
+ ];
585
+ }
586
+ /**
587
+ * Format a byte count as a human-readable string.
588
+ *
589
+ * @param bytes - Byte count
590
+ * @returns Formatted string (e.g. `"1.23 MB"`, `"456 KB"`)
591
+ */
592
+ function formatSize(bytes) {
593
+ if (bytes < 1024) return `${String(bytes)} B`;
594
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
595
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
596
+ }
597
+ /**
598
+ * Assert that an asset key is safe to use as a relative filesystem/archive key.
599
+ *
600
+ * @remarks
601
+ * Rejects an empty key, an absolute path, a key containing a backslash, a
602
+ * Windows drive-relative specifier (e.g. `'C:foo'`), or any `/`-separated
603
+ * segment equal to `'..'` — all of which could escape the intended asset root.
604
+ *
605
+ * @param key - Asset key to validate
606
+ * @throws SEAError with code `'ASSET'` when the key is unsafe
607
+ *
608
+ * @example
609
+ * ```ts
610
+ * ensureSafeKey('client.html.br') // ok
611
+ * ensureSafeKey('../secrets') // throws SEAError('ASSET', ...)
612
+ * ensureSafeKey('C:foo') // throws SEAError('ASSET', ...)
613
+ * ```
614
+ */
615
+ function ensureSafeKey(key) {
616
+ if (key.length === 0) throw new SEAError("ASSET", "Asset key must not be empty", { key });
617
+ if (isAbsolute(key)) throw new SEAError("ASSET", "Asset key must not be an absolute path", { key });
618
+ if (key.includes("\\")) throw new SEAError("ASSET", "Asset key must not contain a backslash", { key });
619
+ if (/^[A-Za-z]:/.test(key)) throw new SEAError("ASSET", "Asset key must not be a drive-relative specifier", { key });
620
+ if (key.split("/").includes("..")) throw new SEAError("ASSET", "Asset key must not contain a \"..\" segment", { key });
621
+ }
622
+ /**
623
+ * Assert that `path` (resolved against `base`) real-path-resolves to a
624
+ * location inside `base`, defeating a symlink escape.
625
+ *
626
+ * @remarks
627
+ * Resolves `path` against `base`, then dereferences both the resolved path
628
+ * and `base` with `realpathSync` and requires the real resolved path to
629
+ * equal the real base or begin with the real base plus a path separator.
630
+ * Dereferencing BOTH sides means a symlinked base itself (e.g. macOS `/tmp`
631
+ * -> `/private/tmp`) still matches, while a symlink inside the tree that
632
+ * points outside the real base is correctly rejected. A `realpathSync`
633
+ * failure (e.g. `ENOENT`) is wrapped as a coded `SEAError` rather than
634
+ * leaking the raw Node error.
635
+ *
636
+ * @param base - Absolute path to the containing root
637
+ * @param path - Path to validate, resolved against `base` if relative
638
+ * @returns The real (symlink-resolved) contained path
639
+ * @throws SEAError with code `'ASSET'` when the real path escapes `base`
640
+ * @throws SEAError with code `'ASSET'` when the path cannot be resolved
641
+ *
642
+ * @example
643
+ * ```ts
644
+ * ensureContained('/dist/app', 'browser') // '/dist/app/browser' (real path)
645
+ * ensureContained('/dist/app', '../../etc') // throws SEAError('ASSET', ...)
646
+ * ```
647
+ */
648
+ function ensureContained(base, path) {
649
+ const resolved = resolve(base, path);
650
+ let real;
651
+ let realBase;
652
+ try {
653
+ real = realpathSync(resolved);
654
+ realBase = realpathSync(base);
655
+ } catch (thrown) {
656
+ throw new SEAError("ASSET", "Path not found or unresolvable", {
657
+ path,
658
+ cause: thrown instanceof Error ? thrown.message : String(thrown)
659
+ });
660
+ }
661
+ if (real !== realBase && !real.startsWith(realBase + sep)) throw new SEAError("ASSET", "Path escapes the build root", {
662
+ base,
663
+ path
664
+ });
665
+ return real;
666
+ }
667
+ /**
668
+ * Assert that `name` is a single safe path segment suitable as an output
669
+ * executable base name.
670
+ *
671
+ * @remarks
672
+ * Rejects an empty name, `'.'`, `'..'`, a name containing a `/` or `\`
673
+ * separator, an absolute path, or a Windows drive-relative specifier (e.g.
674
+ * `'C:foo'`) — all of which could redirect the output executable outside
675
+ * the intended output directory.
676
+ *
677
+ * @param name - Output executable base name to validate
678
+ * @throws SEAError with code `'ASSET'` when the name is unsafe
679
+ *
680
+ * @example
681
+ * ```ts
682
+ * ensureSafeName('myapp') // ok
683
+ * ensureSafeName('../evil') // throws SEAError('ASSET', ...)
684
+ * ```
685
+ */
686
+ function ensureSafeName(name) {
687
+ if (name.length === 0 || name === "." || name === "..") throw new SEAError("ASSET", "Executable name must be a single path segment", { name });
688
+ if (name.includes("/") || name.includes("\\")) throw new SEAError("ASSET", "Executable name must not contain a path separator", { name });
689
+ if (isAbsolute(name)) throw new SEAError("ASSET", "Executable name must not be an absolute path", { name });
690
+ if (/^[A-Za-z]:/.test(name)) throw new SEAError("ASSET", "Executable name must not be a drive-relative specifier", { name });
691
+ }
692
+ /**
693
+ * Fsync a directory to durably persist a prior file rename/create within it.
694
+ *
695
+ * @remarks
696
+ * A `rename`/`create` is only durable once its CONTAINING directory entry is
697
+ * flushed — fsyncing the file itself is not enough. `path` is the directory
698
+ * to fsync (callers pass `dirname(target)`, not the file itself). On Windows
699
+ * there is no directory file handle to fsync, so this is a no-op there (the
700
+ * platform lacks the primitive, not a failure). Some filesystems/platforms
701
+ * return a benign errno for a directory fsync attempt (`EINVAL`, `ENOTSUP`,
702
+ * `EISDIR`, `EPERM`, `EACCES`) — those are treated as "fsync unsupported
703
+ * here" and swallowed; anything else (e.g. `ENOENT`, meaning the directory
704
+ * itself is missing) is a genuine failure and is thrown as a coded `SEAError`.
705
+ *
706
+ * @param path - Directory path to fsync
707
+ * @throws SEAError with code `'OUTPUT'` when the directory sync fails for an
708
+ * unrecognized reason
709
+ *
710
+ * @example
711
+ * ```ts
712
+ * syncDirectory('/dist/app/bin')
713
+ * ```
714
+ */
715
+ function syncDirectory(path) {
716
+ if (process.platform === "win32") return;
717
+ try {
718
+ const fd = openSync(path, "r");
719
+ try {
720
+ fsyncSync(fd);
721
+ } finally {
722
+ closeSync(fd);
723
+ }
724
+ } catch (thrown) {
725
+ const code = thrown instanceof Error && "code" in thrown && typeof thrown.code === "string" ? thrown.code : void 0;
726
+ if (code === "EINVAL" || code === "ENOTSUP" || code === "EISDIR" || code === "EPERM" || code === "EACCES") return;
727
+ throw new SEAError("OUTPUT", "Failed to sync output directory", {
728
+ path,
729
+ cause: thrown instanceof Error ? thrown.message : String(thrown)
730
+ });
731
+ }
732
+ }
733
+ /**
734
+ * Finalize a built executable by durably flushing it to disk and atomically
735
+ * moving it into place.
736
+ *
737
+ * @remarks
738
+ * Opens `source` for read/write, `fsync`s it to force the OS to flush buffered
739
+ * writes, closes it, then `rename`s it to `target`. Never deletes `target` on
740
+ * failure — the caller retains whatever was previously there. After the file
741
+ * is already in place, the containing directory is fsynced ({@link syncDirectory})
742
+ * as a further durability step so the rename itself survives a crash.
743
+ *
744
+ * @param source - Absolute path to the built (temporary) executable
745
+ * @param target - Absolute path to move the finalized executable to
746
+ * @throws SEAError with code `'OUTPUT'` when any step fails
747
+ *
748
+ * @example
749
+ * ```ts
750
+ * finalizeExecutable('/tmp/build/app.tmp', '/dist/app')
751
+ * ```
752
+ */
753
+ function finalizeExecutable(source, target) {
754
+ try {
755
+ const fd = openSync(source, "r+");
756
+ try {
757
+ fsyncSync(fd);
758
+ } finally {
759
+ closeSync(fd);
760
+ }
761
+ renameSync(source, target);
762
+ } catch (thrown) {
763
+ throw new SEAError("OUTPUT", "Failed to finalize executable", {
764
+ source,
765
+ target,
766
+ cause: thrown instanceof Error ? thrown.message : String(thrown)
767
+ });
768
+ }
769
+ syncDirectory(dirname(target));
770
+ }
771
+ /**
772
+ * Build the Node.js `--experimental-sea-config` JSON object for a SEA blob.
773
+ *
774
+ * @remarks
775
+ * A pure leaf extracted from the SEA build orchestrator. The `mainFormat`
776
+ * field (`'commonjs' | 'module'`) exists only in Node >= 25.7 — for a `'cjs'`
777
+ * entry (the default) `mainFormat` is OMITTED entirely so the config still
778
+ * builds on older Node hosts where `'commonjs'` is already the implicit
779
+ * default; for an `'esm'` entry `mainFormat: 'module'` is set explicitly
780
+ * (this requires a Node >= 25.7 build host). Node also documents that
781
+ * `useSnapshot` is incompatible with an ESM entry — combining the two throws.
782
+ *
783
+ * @param entry - SEA entry point options
784
+ * @param blob - Absolute output path for the generated blob
785
+ * @param assets - Optional key→path mapping for embedded assets
786
+ * @param options - Optional blob behavior overrides (cache, snapshot)
787
+ * @returns the SEA config object, ready to be written to disk as JSON
788
+ * @throws SEAError with code `'BLOB'` when `useSnapshot` is combined with an ESM entry
789
+ *
790
+ * @example
791
+ * ```ts
792
+ * const config = createBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)
793
+ * ```
794
+ */
795
+ function createBlobConfig(entry, blob, assets, options) {
796
+ const format = entry.format ?? "cjs";
797
+ const snapshot = options?.snapshot ?? false;
798
+ if (format === "esm" && snapshot) throw new SEAError("BLOB", "useSnapshot cannot be combined with an ESM entry (mainFormat module)");
799
+ return {
800
+ main: entry.path,
801
+ output: blob,
802
+ disableExperimentalSEAWarning: true,
803
+ useSnapshot: snapshot,
804
+ useCodeCache: options?.cache ?? true,
805
+ ...assets ? { assets } : {},
806
+ ...format === "esm" ? { mainFormat: "module" } : {}
807
+ };
808
+ }
809
+ /**
810
+ * Build an ELF `PT_NOTE` entry's header bytes (namesz/descsz/type + padded
811
+ * name) for the SEA blob note, without the blob body itself.
812
+ *
813
+ * @remarks
814
+ * A pure leaf extracted from the ELF injector: the blob body is streamed
815
+ * from disk separately (never buffered here) so this only produces the
816
+ * fixed-size note header and reports the total on-disk size the complete
817
+ * note entry (header + 4-byte-padded blob) will occupy, so the caller can
818
+ * size the covering `PT_LOAD`/`PT_NOTE` segments before writing anything.
819
+ * The Node.js SEA runtime matches a note by the first 8 bytes of its name
820
+ * (`strncmp(name, "NODE_SEA", 8)`), so `resource` is written in full but
821
+ * only needs to begin with those 8 bytes to be found at runtime.
822
+ *
823
+ * @param resource - Note name (SEA resource identifier, e.g. `NODE_SEA_BLOB`)
824
+ * @param blobSize - Size in bytes of the SEA blob that will follow the header
825
+ * @returns The note header bytes and the total on-disk size of header + blob
826
+ *
827
+ * @example
828
+ * ```ts
829
+ * const { header, entryTotal } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)
830
+ * ```
831
+ */
832
+ function buildELFNoteHeader(resource, blobSize) {
833
+ const alignTo4 = (value) => {
834
+ const remainder = value % 4;
835
+ return remainder === 0 ? value : value + (4 - remainder);
836
+ };
837
+ const nameBytes = Buffer.from(`${resource}\0`, "utf-8");
838
+ const alignedNameSize = alignTo4(nameBytes.length);
839
+ const header = Buffer.alloc(12 + alignedNameSize);
840
+ header.writeUInt32LE(nameBytes.length, 0);
841
+ header.writeUInt32LE(blobSize, 4);
842
+ header.writeUInt32LE(0, 8);
843
+ nameBytes.copy(header, 12);
844
+ const alignedDescSize = alignTo4(blobSize);
845
+ return {
846
+ header,
847
+ entryTotal: header.length + alignedDescSize
848
+ };
849
+ }
850
+ /**
851
+ * Copy a byte range from one open file descriptor to another, streaming in
852
+ * fixed-size chunks instead of buffering the whole range in memory.
853
+ *
854
+ * @remarks
855
+ * Reads `length` bytes from `source` starting at file offset `start`, in
856
+ * `chunk`-sized reads, and writes each chunk to `target` with a `null`
857
+ * write position so writes land sequentially at `target`'s current file
858
+ * position (rather than at `start`, which is meaningless for `target`). A
859
+ * short read from `source` (fewer bytes returned than requested, including
860
+ * `0` before `length` is exhausted) is treated as a genuine failure and
861
+ * throws rather than silently writing a truncated range.
862
+ *
863
+ * @param source - Open, readable file descriptor to copy from
864
+ * @param target - Open, writable file descriptor to copy to
865
+ * @param start - Byte offset in `source` to begin reading from
866
+ * @param length - Number of bytes to copy; `0` is a no-op
867
+ * @param chunk - Read/write chunk size in bytes, for tuning memory use and
868
+ * exercising the streaming loop in tests. Default: 4 MB.
869
+ * @throws SEAError with code `'OUTPUT'` when `source` is exhausted before
870
+ * `length` bytes have been copied
871
+ *
872
+ * @example
873
+ * ```ts
874
+ * const srcFd = openSync('big.bin', 'r')
875
+ * const dstFd = openSync('out.bin', 'w')
876
+ * copyRange(srcFd, dstFd, 1024, 4096)
877
+ * ```
878
+ */
879
+ function copyRange(source, target, start, length, chunk = 4 * 1024 * 1024) {
880
+ if (length <= 0) return;
881
+ const bufferSize = Math.min(chunk, length);
882
+ const buffer = Buffer.alloc(bufferSize);
883
+ let position = start;
884
+ let remaining = length;
885
+ while (remaining > 0) {
886
+ const bytesRead = readSync(source, buffer, 0, Math.min(chunk, remaining), position);
887
+ if (bytesRead === 0) throw new SEAError("OUTPUT", "Unexpected end of file while copying byte range", {
888
+ start,
889
+ length,
890
+ position,
891
+ remaining
892
+ });
893
+ writeSync(target, buffer, 0, bytesRead, null);
894
+ position += bytesRead;
895
+ remaining -= bytesRead;
896
+ }
897
+ }
898
+ /**
899
+ * Patch the sentinel fuse in a binary from `:0` to `:1`.
900
+ *
901
+ * Searches the file in 64 MB chunks with overlap to handle any file size.
902
+ * The fuse signals to the Node.js runtime that a SEA blob is present.
903
+ * This is normally handled by the Injector but is also available standalone
904
+ * when using native PE resource injection.
905
+ *
906
+ * @param executable - Absolute path to the executable
907
+ * @param fuse - Sentinel fuse string (without the `:0` suffix)
908
+ */
909
+ function patchSentinelFuse(executable, fuse) {
910
+ const fd = openSync(executable, "r+");
911
+ try {
912
+ const needle = Buffer.from(fuse, "utf-8");
913
+ const chunkSize = 64 * 1024 * 1024;
914
+ const readSize = chunkSize + needle.length;
915
+ const buffer = Buffer.alloc(readSize);
916
+ let offset = 0;
917
+ while (true) {
918
+ const bytesRead = readSync(fd, buffer, 0, readSize, offset);
919
+ if (bytesRead === 0) break;
920
+ const idx = buffer.subarray(0, bytesRead).indexOf(needle);
921
+ if (idx !== -1) {
922
+ const fuseEnd = offset + idx + needle.length;
923
+ const valueBuf = Buffer.alloc(2);
924
+ if (readSync(fd, valueBuf, 0, 2, fuseEnd) < 2) throw new SEAError("FUSE", "Could not read sentinel fuse value", {
925
+ executable,
926
+ fuse
927
+ });
928
+ const value = valueBuf.toString("utf-8");
929
+ if (value === ":0") {
930
+ writeSync(fd, Buffer.from("1", "utf-8"), 0, 1, fuseEnd + 1);
931
+ return;
932
+ }
933
+ if (value === ":1") return;
934
+ throw new SEAError("FUSE", `Unexpected sentinel fuse value: ${value}`, {
935
+ executable,
936
+ fuse
937
+ });
938
+ }
939
+ offset += chunkSize;
940
+ }
941
+ throw new SEAError("FUSE", `Sentinel fuse not found in executable: ${fuse}`, {
942
+ executable,
943
+ fuse
944
+ });
945
+ } finally {
946
+ closeSync(fd);
947
+ }
948
+ }
949
+ /**
950
+ * Launch the system default browser at an http(s) URL.
951
+ *
952
+ * @remarks
953
+ * A best-effort launch for bundled local-UI apps: dispatches by
954
+ * `process.platform` (`win32` -> `rundll32 url.dll,FileProtocolHandler`,
955
+ * `darwin` -> `open`, else -> `xdg-open`), each invoked with an argv array
956
+ * (never a shell) so the URL cannot be interpreted as a flag or injected
957
+ * into a command line. The child process is spawned `detached` with
958
+ * `stdio: 'ignore'` and immediately `unref()`d so it never keeps the host
959
+ * app alive. Only `http:` and `https:` URLs are accepted — any other
960
+ * scheme (including a string that merely looks like a CLI flag, e.g.
961
+ * `'-e ...'`) fails to parse as an http(s) URL and is rejected before
962
+ * anything is spawned.
963
+ *
964
+ * @param url - Absolute http or https URL to open
965
+ * @throws SEAError with code `'BROWSER'` when `url` is not a parseable absolute URL
966
+ * @throws SEAError with code `'BROWSER'` when `url` is not an `http:`/`https:` URL
967
+ *
968
+ * @example
969
+ * ```ts
970
+ * openBrowser('http://localhost:3000')
971
+ * ```
972
+ */
973
+ function openBrowser(url) {
974
+ let parsed;
975
+ try {
976
+ parsed = new URL(url);
977
+ } catch {
978
+ throw new SEAError("BROWSER", "openBrowser requires a valid absolute URL", { url });
979
+ }
980
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new SEAError("BROWSER", "openBrowser only supports http and https URLs", {
981
+ url,
982
+ protocol: parsed.protocol
983
+ });
984
+ const child = process.platform === "win32" ? spawn("rundll32", ["url.dll,FileProtocolHandler", parsed.href], {
985
+ detached: true,
986
+ stdio: "ignore"
987
+ }) : process.platform === "darwin" ? spawn("open", [parsed.href], {
988
+ detached: true,
989
+ stdio: "ignore"
990
+ }) : spawn("xdg-open", [parsed.href], {
991
+ detached: true,
992
+ stdio: "ignore"
993
+ });
994
+ child.on("error", () => {});
995
+ child.unref();
996
+ }
997
+ //#endregion
998
+ //#region src/server/injectors/Injector.ts
999
+ var Injector = class {
1000
+ #options;
1001
+ #format;
1002
+ constructor(options) {
1003
+ this.#options = options;
1004
+ this.#format = this.#detect();
1005
+ }
1006
+ get format() {
1007
+ return this.#format;
1008
+ }
1009
+ inject() {
1010
+ let peOptionalOffset;
1011
+ switch (this.#format) {
1012
+ case "pe":
1013
+ peOptionalOffset = this.#injectPe();
1014
+ break;
1015
+ case "elf":
1016
+ this.#injectElf();
1017
+ break;
1018
+ case "macho":
1019
+ this.#injectMacho();
1020
+ break;
1021
+ }
1022
+ if (this.#options.fuse !== void 0) patchSentinelFuse(this.#options.executable, this.#options.fuse);
1023
+ if (peOptionalOffset !== void 0) this.#patchChecksum(peOptionalOffset);
1024
+ }
1025
+ #detect() {
1026
+ const fd = openSync(this.#options.executable, "r");
1027
+ try {
1028
+ const header = Buffer.alloc(4);
1029
+ readSync(fd, header, 0, 4, 0);
1030
+ const magic16 = header.readUInt16LE(0);
1031
+ const magic32 = header.readUInt32BE(0);
1032
+ const magic32le = header.readUInt32LE(0);
1033
+ if (magic16 === 23117) return "pe";
1034
+ if (magic32 === 2135247942) return "elf";
1035
+ if (magic32le === 4277009103) return "macho";
1036
+ if (magic32 === 3405691582 || magic32 === 3199925962) throw new SEAError("FORMAT", "Mach-O universal/fat binaries are not supported; provide a thin arm64 or x86_64 binary", {
1037
+ executable: this.#options.executable,
1038
+ magic: magic32
1039
+ });
1040
+ if (magic32le === 4277009102 || magic32le === 3472551422 || magic32 === 4277009102 || magic32 === 3472551422) throw new SEAError("FORMAT", "Only 64-bit little-endian Mach-O is supported", {
1041
+ executable: this.#options.executable,
1042
+ magic: magic32
1043
+ });
1044
+ throw new SEAError("FORMAT", `Unknown executable format (magic: 0x${magic32.toString(16).padStart(8, "0")})`, {
1045
+ executable: this.#options.executable,
1046
+ magic: magic32
1047
+ });
1048
+ } finally {
1049
+ closeSync(fd);
1050
+ }
1051
+ }
1052
+ #injectPe() {
1053
+ const fd = openSync(this.#options.executable, "r+");
1054
+ try {
1055
+ const peOffset = this.#readU32(fd, 60);
1056
+ const sig = this.#readU32(fd, peOffset);
1057
+ if (sig !== 17744) throw new SEAError("FORMAT", "Invalid PE signature", {
1058
+ executable: this.#options.executable,
1059
+ signature: sig
1060
+ });
1061
+ const coffOffset = peOffset + 4;
1062
+ const numberOfSections = this.#readU16(fd, coffOffset + 2);
1063
+ const optionalHeaderSize = this.#readU16(fd, coffOffset + 16);
1064
+ const optionalOffset = coffOffset + 20;
1065
+ const optMagic = this.#readU16(fd, optionalOffset);
1066
+ const is64 = optMagic === 523;
1067
+ if (optMagic !== 267 && optMagic !== 523) throw new SEAError("FORMAT", `Unsupported PE optional header magic: 0x${optMagic.toString(16)}`, {
1068
+ executable: this.#options.executable,
1069
+ optionalHeaderMagic: optMagic
1070
+ });
1071
+ const sectionAlignment = this.#readU32(fd, optionalOffset + 32);
1072
+ const fileAlignment = this.#readU32(fd, optionalOffset + 36);
1073
+ this.#ensureValidPEAlignment(sectionAlignment, fileAlignment);
1074
+ const sizeOfImageOffset = optionalOffset + 56;
1075
+ const resourceDirRvaOffset = optionalOffset + (is64 ? 112 : 96) + 16;
1076
+ const resourceDirSizeOffset = resourceDirRvaOffset + 4;
1077
+ const existingResourceRva = this.#readU32(fd, resourceDirRvaOffset);
1078
+ const sectionTableOffset = optionalOffset + optionalHeaderSize;
1079
+ const sections = [];
1080
+ let rsrcSectionIndex = -1;
1081
+ for (let i = 0; i < numberOfSections; i++) {
1082
+ const off = sectionTableOffset + i * 40;
1083
+ const nameBuf = Buffer.alloc(8);
1084
+ readSync(fd, nameBuf, 0, 8, off);
1085
+ const name = this.#stripTrailingNulls(nameBuf.toString("ascii"));
1086
+ const virtualSize = this.#readU32(fd, off + 8);
1087
+ const virtualAddress = this.#readU32(fd, off + 12);
1088
+ const rawSize = this.#readU32(fd, off + 16);
1089
+ const rawOffset = this.#readU32(fd, off + 20);
1090
+ const characteristics = this.#readU32(fd, off + 36);
1091
+ sections.push({
1092
+ name,
1093
+ virtualSize,
1094
+ virtualAddress,
1095
+ rawSize,
1096
+ rawOffset,
1097
+ characteristics,
1098
+ headerOffset: off
1099
+ });
1100
+ if (existingResourceRva >= virtualAddress && existingResourceRva < virtualAddress + Math.max(virtualSize, rawSize)) rsrcSectionIndex = i;
1101
+ }
1102
+ const sectionTableEnd = sectionTableOffset + numberOfSections * 40;
1103
+ const availableHeaderSpace = sections.reduce((min, s) => s.rawOffset > 0 && s.rawOffset < min ? s.rawOffset : min, Infinity) - sectionTableEnd;
1104
+ if (availableHeaderSpace < 40) throw new SEAError("INJECT", `No room in PE header for a new section entry (${String(availableHeaderSpace)} bytes available, need ${String(40)})`, {
1105
+ executable: this.#options.executable,
1106
+ availableHeaderSpace,
1107
+ requiredHeaderSpace: 40
1108
+ });
1109
+ const existingLeaves = [];
1110
+ if (rsrcSectionIndex !== -1 && existingResourceRva !== 0) {
1111
+ const rsrc = sections[rsrcSectionIndex];
1112
+ if (rsrc !== void 0) this.#parseResourceDirectory(fd, rsrc.rawOffset, existingResourceRva, 0, existingLeaves, 0, 0, void 0, 0, void 0);
1113
+ }
1114
+ const overwrite = this.#options.overwrite !== false;
1115
+ const upperName = this.#options.resource.toUpperCase();
1116
+ const filteredLeaves = existingLeaves.filter((leaf) => {
1117
+ if (!overwrite) return true;
1118
+ if (leaf.typeId !== 10) return true;
1119
+ return leaf.nameName?.toUpperCase() !== upperName;
1120
+ });
1121
+ const leafDataMap = /* @__PURE__ */ new Map();
1122
+ for (let i = 0; i < filteredLeaves.length; i++) {
1123
+ const leaf = filteredLeaves[i];
1124
+ if (leaf === void 0) continue;
1125
+ const fileOffset = this.#rvaToFileOffset(leaf.dataRva, sections);
1126
+ if (fileOffset >= 0) {
1127
+ const buf = Buffer.alloc(leaf.dataSize);
1128
+ readSync(fd, buf, 0, leaf.dataSize, fileOffset);
1129
+ leafDataMap.set(i, buf);
1130
+ }
1131
+ }
1132
+ const blobSize = statSync(this.#options.blob).size;
1133
+ const tree = this.#buildResourceTree(filteredLeaves, upperName, blobSize);
1134
+ const { directoryBuffer, dataRegionSize } = this.#serializeResourceTree(tree, leafDataMap, blobSize);
1135
+ const totalRawSize = directoryBuffer.length + dataRegionSize;
1136
+ const alignedRawSize = this.#align(totalRawSize, fileAlignment);
1137
+ let highestVaEnd = 0;
1138
+ for (const s of sections) {
1139
+ const end = s.virtualAddress + Math.max(s.virtualSize, s.rawSize);
1140
+ if (end > highestVaEnd) highestVaEnd = end;
1141
+ }
1142
+ const newVa = this.#align(highestVaEnd, sectionAlignment);
1143
+ const newVirtualSize = totalRawSize;
1144
+ const fileSize = statSync(this.#options.executable).size;
1145
+ const newRawOffset = this.#align(fileSize, fileAlignment);
1146
+ const newHeaderOffset = sectionTableEnd;
1147
+ const headerBuf = Buffer.alloc(40);
1148
+ headerBuf.write(".rsrc2", 0, 6, "ascii");
1149
+ headerBuf.writeUInt32LE(newVirtualSize, 8);
1150
+ headerBuf.writeUInt32LE(newVa, 12);
1151
+ headerBuf.writeUInt32LE(alignedRawSize, 16);
1152
+ headerBuf.writeUInt32LE(newRawOffset, 20);
1153
+ headerBuf.writeUInt32LE(0, 24);
1154
+ headerBuf.writeUInt32LE(0, 28);
1155
+ headerBuf.writeUInt16LE(0, 32);
1156
+ headerBuf.writeUInt16LE(0, 34);
1157
+ headerBuf.writeUInt32LE(64 | PE_SCN_MEM_READ, 36);
1158
+ writeSync(fd, headerBuf, 0, 40, newHeaderOffset);
1159
+ this.#writeU16(fd, coffOffset + 2, numberOfSections + 1);
1160
+ this.#writeU32(fd, resourceDirRvaOffset, newVa);
1161
+ this.#writeU32(fd, resourceDirSizeOffset, directoryBuffer.length);
1162
+ const newSizeOfImage = this.#align(newVa + Math.max(newVirtualSize, alignedRawSize), sectionAlignment);
1163
+ this.#writeU32(fd, sizeOfImageOffset, newSizeOfImage);
1164
+ closeSync(fd);
1165
+ const currentFileSize = statSync(this.#options.executable).size;
1166
+ if (newRawOffset > currentFileSize) {
1167
+ const padding = Buffer.alloc(newRawOffset - currentFileSize);
1168
+ appendFileSync(this.#options.executable, padding);
1169
+ }
1170
+ this.#fixupDirectoryRvas(directoryBuffer, newVa);
1171
+ appendFileSync(this.#options.executable, directoryBuffer);
1172
+ for (let i = 0; i < filteredLeaves.length; i++) {
1173
+ const data = leafDataMap.get(i);
1174
+ if (data !== void 0) {
1175
+ appendFileSync(this.#options.executable, data);
1176
+ const padLen = this.#align(data.length, 4) - data.length;
1177
+ if (padLen > 0) appendFileSync(this.#options.executable, Buffer.alloc(padLen));
1178
+ }
1179
+ }
1180
+ this.#appendFile(this.#options.executable, this.#options.blob);
1181
+ const writtenSize = statSync(this.#options.executable).size - newRawOffset;
1182
+ if (writtenSize < alignedRawSize) appendFileSync(this.#options.executable, Buffer.alloc(alignedRawSize - writtenSize));
1183
+ return optionalOffset;
1184
+ } catch (error) {
1185
+ try {
1186
+ closeSync(fd);
1187
+ } catch {}
1188
+ throw error;
1189
+ }
1190
+ }
1191
+ #parseResourceDirectory(fd, sectionFileOffset, sectionRva, dirOffset, leaves, depth, currentTypeId, currentTypeName, currentNameId, currentNameName) {
1192
+ const absOffset = sectionFileOffset + dirOffset;
1193
+ const totalEntries = this.#readU16(fd, absOffset + 12) + this.#readU16(fd, absOffset + 14);
1194
+ for (let i = 0; i < totalEntries; i++) {
1195
+ const entryOffset = absOffset + 16 + i * 8;
1196
+ const nameOrId = this.#readU32(fd, entryOffset);
1197
+ const offsetOrData = this.#readU32(fd, entryOffset + 4);
1198
+ let entryId = 0;
1199
+ let entryName;
1200
+ if ((nameOrId & 2147483648) !== 0) {
1201
+ const stringOffset = nameOrId & ~PE_RESOURCE_NAME_FLAG;
1202
+ entryName = this.#readResourceString(fd, sectionFileOffset + stringOffset);
1203
+ } else entryId = nameOrId;
1204
+ let typeId = currentTypeId;
1205
+ let typeName = currentTypeName;
1206
+ let nameId = currentNameId;
1207
+ let nameName = currentNameName;
1208
+ if (depth === 0) {
1209
+ typeId = entryId;
1210
+ typeName = entryName;
1211
+ } else if (depth === 1) {
1212
+ nameId = entryId;
1213
+ nameName = entryName;
1214
+ }
1215
+ if ((offsetOrData & 2147483648) !== 0) {
1216
+ const subDirOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG;
1217
+ this.#parseResourceDirectory(fd, sectionFileOffset, sectionRva, subDirOffset, leaves, depth + 1, typeId, typeName, nameId, nameName);
1218
+ } else {
1219
+ const dataEntryFileOffset = sectionFileOffset + offsetOrData;
1220
+ const dataRva = this.#readU32(fd, dataEntryFileOffset);
1221
+ const dataSize = this.#readU32(fd, dataEntryFileOffset + 4);
1222
+ const codePage = this.#readU32(fd, dataEntryFileOffset + 8);
1223
+ const language = depth === 2 ? entryId : 0;
1224
+ leaves.push({
1225
+ typeId,
1226
+ typeName,
1227
+ nameId,
1228
+ nameName,
1229
+ language,
1230
+ codePage,
1231
+ dataRva,
1232
+ dataSize
1233
+ });
1234
+ }
1235
+ }
1236
+ }
1237
+ #readResourceString(fd, offset) {
1238
+ const lenBuf = Buffer.alloc(2);
1239
+ readSync(fd, lenBuf, 0, 2, offset);
1240
+ const charCount = lenBuf.readUInt16LE(0);
1241
+ if (charCount === 0) return "";
1242
+ const strBuf = Buffer.alloc(charCount * 2);
1243
+ readSync(fd, strBuf, 0, charCount * 2, offset + 2);
1244
+ return strBuf.toString("utf16le");
1245
+ }
1246
+ #rvaToFileOffset(rva, sections) {
1247
+ for (const s of sections) {
1248
+ const sectionEnd = s.virtualAddress + Math.max(s.virtualSize, s.rawSize);
1249
+ if (rva >= s.virtualAddress && rva < sectionEnd) return rva - s.virtualAddress + s.rawOffset;
1250
+ }
1251
+ return -1;
1252
+ }
1253
+ #buildResourceTree(existingLeaves, blobName, blobSize) {
1254
+ const tree = /* @__PURE__ */ new Map();
1255
+ for (let i = 0; i < existingLeaves.length; i++) {
1256
+ const leaf = existingLeaves[i];
1257
+ if (leaf === void 0) continue;
1258
+ const typeKey = leaf.typeName !== void 0 ? `n:${leaf.typeName}` : `i:${String(leaf.typeId)}`;
1259
+ const nameKey = leaf.nameName !== void 0 ? `n:${leaf.nameName}` : `i:${String(leaf.nameId)}`;
1260
+ let typeMap = tree.get(typeKey);
1261
+ if (typeMap === void 0) {
1262
+ typeMap = /* @__PURE__ */ new Map();
1263
+ tree.set(typeKey, typeMap);
1264
+ }
1265
+ let langArr = typeMap.get(nameKey);
1266
+ if (langArr === void 0) {
1267
+ langArr = [];
1268
+ typeMap.set(nameKey, langArr);
1269
+ }
1270
+ langArr.push({
1271
+ language: leaf.language,
1272
+ codePage: leaf.codePage,
1273
+ leafIndex: i,
1274
+ dataSize: leaf.dataSize
1275
+ });
1276
+ }
1277
+ const blobTypeKey = `i:${String(10)}`;
1278
+ const blobNameKey = `n:${blobName}`;
1279
+ let typeMap = tree.get(blobTypeKey);
1280
+ if (typeMap === void 0) {
1281
+ typeMap = /* @__PURE__ */ new Map();
1282
+ tree.set(blobTypeKey, typeMap);
1283
+ }
1284
+ typeMap.set(blobNameKey, [{
1285
+ language: 0,
1286
+ codePage: 0,
1287
+ leafIndex: -1,
1288
+ dataSize: blobSize
1289
+ }]);
1290
+ return tree;
1291
+ }
1292
+ #serializeResourceTree(tree, leafDataMap, blobSize) {
1293
+ let dirTableSize = 0;
1294
+ let stringPoolSize = 0;
1295
+ let dataEntryCount = 0;
1296
+ dirTableSize += 16 + tree.size * 8;
1297
+ const allStrings = [];
1298
+ const allLeafEntries = [];
1299
+ for (const [typeKey, nameMap] of tree) {
1300
+ dirTableSize += 16 + nameMap.size * 8;
1301
+ if (typeKey.startsWith("n:")) {
1302
+ const str = typeKey.slice(2);
1303
+ allStrings.push({
1304
+ key: typeKey,
1305
+ value: str
1306
+ });
1307
+ stringPoolSize += 2 + str.length * 2;
1308
+ stringPoolSize = this.#align(stringPoolSize, 2);
1309
+ }
1310
+ for (const [nameKey, langEntries] of nameMap) {
1311
+ dirTableSize += 16 + langEntries.length * 8;
1312
+ if (nameKey.startsWith("n:")) {
1313
+ const str = nameKey.slice(2);
1314
+ allStrings.push({
1315
+ key: nameKey,
1316
+ value: str
1317
+ });
1318
+ stringPoolSize += 2 + str.length * 2;
1319
+ stringPoolSize = this.#align(stringPoolSize, 2);
1320
+ }
1321
+ for (const entry of langEntries) {
1322
+ allLeafEntries.push({
1323
+ leafIndex: entry.leafIndex,
1324
+ dataSize: entry.dataSize,
1325
+ codePage: entry.codePage
1326
+ });
1327
+ dataEntryCount++;
1328
+ }
1329
+ }
1330
+ }
1331
+ const dataEntriesSize = dataEntryCount * 16;
1332
+ const headerSize = dirTableSize + stringPoolSize + dataEntriesSize;
1333
+ let dataRegionOffset = 0;
1334
+ const leafFileOffsets = /* @__PURE__ */ new Map();
1335
+ for (let i = 0; i < allLeafEntries.length; i++) {
1336
+ const entry = allLeafEntries[i];
1337
+ if (entry === void 0) continue;
1338
+ if (entry.leafIndex === -1) continue;
1339
+ const data = leafDataMap.get(entry.leafIndex);
1340
+ if (data !== void 0) {
1341
+ leafFileOffsets.set(entry.leafIndex, dataRegionOffset);
1342
+ dataRegionOffset += this.#align(data.length, 4);
1343
+ }
1344
+ }
1345
+ const blobDataOffset = dataRegionOffset;
1346
+ dataRegionOffset += blobSize;
1347
+ const dataRegionSize = dataRegionOffset;
1348
+ const buf = Buffer.alloc(headerSize);
1349
+ let dirPos = 0;
1350
+ let stringPos = dirTableSize;
1351
+ let dataEntryPos = dirTableSize + stringPoolSize;
1352
+ const stringOffsets = /* @__PURE__ */ new Map();
1353
+ for (const { key, value } of allStrings) {
1354
+ stringOffsets.set(key, stringPos);
1355
+ buf.writeUInt16LE(value.length, stringPos);
1356
+ buf.write(value, stringPos + 2, value.length * 2, "utf16le");
1357
+ stringPos += 2 + value.length * 2;
1358
+ stringPos = this.#align(stringPos, 2);
1359
+ }
1360
+ const sortedTypeKeys = this.#sortResourceKeys([...tree.keys()]);
1361
+ const nextDirOffset = 16 + tree.size * 8;
1362
+ const namedTypes = sortedTypeKeys.filter((k) => k.startsWith("n:"));
1363
+ const idTypes = sortedTypeKeys.filter((k) => k.startsWith("i:"));
1364
+ buf.writeUInt32LE(0, dirPos);
1365
+ buf.writeUInt32LE(0, dirPos + 4);
1366
+ buf.writeUInt16LE(0, dirPos + 8);
1367
+ buf.writeUInt16LE(0, dirPos + 10);
1368
+ buf.writeUInt16LE(namedTypes.length, dirPos + 12);
1369
+ buf.writeUInt16LE(idTypes.length, dirPos + 14);
1370
+ dirPos += 16;
1371
+ const typeDirOffsets = /* @__PURE__ */ new Map();
1372
+ let accDirOffset = nextDirOffset;
1373
+ for (const typeKey of sortedTypeKeys) {
1374
+ typeDirOffsets.set(typeKey, accDirOffset);
1375
+ const nameMap = tree.get(typeKey);
1376
+ if (nameMap === void 0) continue;
1377
+ const typeEntryCount = nameMap.size;
1378
+ accDirOffset += 16 + typeEntryCount * 8;
1379
+ for (const [, langEntries] of nameMap) accDirOffset += 16 + langEntries.length * 8;
1380
+ }
1381
+ for (const typeKey of sortedTypeKeys) {
1382
+ const nameOrId = typeKey.startsWith("n:") ? (stringOffsets.get(typeKey) ?? 0) | PE_RESOURCE_NAME_FLAG : parseInt(typeKey.slice(2), 10);
1383
+ const subdirOffset = (typeDirOffsets.get(typeKey) ?? 0) | PE_RESOURCE_SUBDIR_FLAG;
1384
+ buf.writeUInt32LE(nameOrId >>> 0, dirPos);
1385
+ buf.writeUInt32LE(subdirOffset >>> 0, dirPos + 4);
1386
+ dirPos += 8;
1387
+ }
1388
+ for (const typeKey of sortedTypeKeys) {
1389
+ const nameMap = tree.get(typeKey);
1390
+ if (nameMap === void 0) continue;
1391
+ const sortedNameKeys = this.#sortResourceKeys([...nameMap.keys()]);
1392
+ const namedNames = sortedNameKeys.filter((k) => k.startsWith("n:"));
1393
+ const idNames = sortedNameKeys.filter((k) => k.startsWith("i:"));
1394
+ buf.writeUInt32LE(0, dirPos);
1395
+ buf.writeUInt32LE(0, dirPos + 4);
1396
+ buf.writeUInt16LE(0, dirPos + 8);
1397
+ buf.writeUInt16LE(0, dirPos + 10);
1398
+ buf.writeUInt16LE(namedNames.length, dirPos + 12);
1399
+ buf.writeUInt16LE(idNames.length, dirPos + 14);
1400
+ dirPos += 16;
1401
+ let langSubdirCursor = dirPos + sortedNameKeys.length * 8;
1402
+ for (const nameKey of sortedNameKeys) {
1403
+ const nameOrId = nameKey.startsWith("n:") ? (stringOffsets.get(nameKey) ?? 0) | PE_RESOURCE_NAME_FLAG : parseInt(nameKey.slice(2), 10);
1404
+ const langSubDirRelOffset = langSubdirCursor | PE_RESOURCE_SUBDIR_FLAG;
1405
+ buf.writeUInt32LE(nameOrId >>> 0, dirPos);
1406
+ buf.writeUInt32LE(langSubDirRelOffset >>> 0, dirPos + 4);
1407
+ dirPos += 8;
1408
+ const langEntries = nameMap.get(nameKey);
1409
+ if (langEntries !== void 0) langSubdirCursor += 16 + langEntries.length * 8;
1410
+ }
1411
+ for (const nameKey of sortedNameKeys) {
1412
+ const langEntries = nameMap.get(nameKey);
1413
+ if (langEntries === void 0) continue;
1414
+ buf.writeUInt32LE(0, dirPos);
1415
+ buf.writeUInt32LE(0, dirPos + 4);
1416
+ buf.writeUInt16LE(0, dirPos + 8);
1417
+ buf.writeUInt16LE(0, dirPos + 10);
1418
+ buf.writeUInt16LE(0, dirPos + 12);
1419
+ buf.writeUInt16LE(langEntries.length, dirPos + 14);
1420
+ dirPos += 16;
1421
+ for (const entry of langEntries) {
1422
+ buf.writeUInt32LE(entry.language, dirPos);
1423
+ buf.writeUInt32LE(dataEntryPos, dirPos + 4);
1424
+ dirPos += 8;
1425
+ let dataOffset;
1426
+ if (entry.leafIndex === -1) dataOffset = headerSize + blobDataOffset;
1427
+ else {
1428
+ const resolvedOffset = leafFileOffsets.get(entry.leafIndex);
1429
+ if (resolvedOffset === void 0) throw new SEAError("INJECT", "unresolvable resource RVA", {
1430
+ executable: this.#options.executable,
1431
+ leafIndex: entry.leafIndex
1432
+ });
1433
+ dataOffset = headerSize + resolvedOffset;
1434
+ }
1435
+ buf.writeUInt32LE(dataOffset, dataEntryPos);
1436
+ buf.writeUInt32LE(entry.dataSize, dataEntryPos + 4);
1437
+ buf.writeUInt32LE(entry.codePage, dataEntryPos + 8);
1438
+ buf.writeUInt32LE(0, dataEntryPos + 12);
1439
+ dataEntryPos += 16;
1440
+ }
1441
+ }
1442
+ }
1443
+ return {
1444
+ directoryBuffer: buf,
1445
+ dataRegionSize,
1446
+ blobDataOffset
1447
+ };
1448
+ }
1449
+ #fixupDirectoryRvas(directoryBuffer, sectionVa) {
1450
+ this.#fixupDataEntries(directoryBuffer, 0, 0, sectionVa);
1451
+ }
1452
+ #fixupDataEntries(buf, dirOffset, depth, sectionVa) {
1453
+ if (dirOffset + 16 > buf.length) return;
1454
+ const totalEntries = buf.readUInt16LE(dirOffset + 12) + buf.readUInt16LE(dirOffset + 14);
1455
+ for (let i = 0; i < totalEntries; i++) {
1456
+ const entryOffset = dirOffset + 16 + i * 8;
1457
+ if (entryOffset + 8 > buf.length) return;
1458
+ const offsetOrData = buf.readUInt32LE(entryOffset + 4);
1459
+ if ((offsetOrData & 2147483648) !== 0) {
1460
+ const subOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG;
1461
+ this.#fixupDataEntries(buf, subOffset, depth + 1, sectionVa);
1462
+ } else if (offsetOrData + 4 <= buf.length) {
1463
+ const currentRva = buf.readUInt32LE(offsetOrData);
1464
+ buf.writeUInt32LE(currentRva + sectionVa >>> 0, offsetOrData);
1465
+ }
1466
+ }
1467
+ }
1468
+ #patchChecksum(optionalOffset) {
1469
+ const checksumOffset = optionalOffset + 64;
1470
+ const fd = openSync(this.#options.executable, "r+");
1471
+ try {
1472
+ const fileSize = statSync(this.#options.executable).size;
1473
+ const chunkSize = 4 * 1024 * 1024;
1474
+ const chunk = Buffer.alloc(Math.min(chunkSize, fileSize));
1475
+ let sum = 0;
1476
+ let offset = 0;
1477
+ while (offset < fileSize) {
1478
+ const bytesRead = readSync(fd, chunk, 0, Math.min(chunkSize, fileSize - offset), offset);
1479
+ if (bytesRead === 0) break;
1480
+ for (let i = 0; i < bytesRead; i += 2) {
1481
+ const absolute = offset + i;
1482
+ let word;
1483
+ if (absolute === checksumOffset || absolute === checksumOffset + 2) word = 0;
1484
+ else if (i + 1 < bytesRead) word = chunk.readUInt16LE(i);
1485
+ else word = chunk.readUInt8(i);
1486
+ sum += word;
1487
+ sum = (sum & 65535) + (sum >>> 16);
1488
+ }
1489
+ offset += bytesRead;
1490
+ }
1491
+ sum = (sum & 65535) + (sum >>> 16);
1492
+ const checksum = sum + fileSize >>> 0;
1493
+ this.#writeU32(fd, checksumOffset, checksum);
1494
+ } finally {
1495
+ closeSync(fd);
1496
+ }
1497
+ }
1498
+ #sortResourceKeys(keys) {
1499
+ const named = keys.filter((k) => k.startsWith("n:")).sort((a, b) => a.slice(2).localeCompare(b.slice(2), "en", { sensitivity: "base" }));
1500
+ const ids = keys.filter((k) => k.startsWith("i:")).sort((a, b) => {
1501
+ return parseInt(a.slice(2), 10) - parseInt(b.slice(2), 10);
1502
+ });
1503
+ return [...named, ...ids];
1504
+ }
1505
+ #injectElf() {
1506
+ const exePath = this.#options.executable;
1507
+ const resource = this.#options.resource;
1508
+ const overwrite = this.#options.overwrite !== false;
1509
+ const PT_LOAD = 1;
1510
+ const PT_PHDR = 6;
1511
+ const PF_R = 4;
1512
+ const PAGE = 4096;
1513
+ let phdrOffset;
1514
+ let phdrEntrySize;
1515
+ let phdrCount;
1516
+ let headers;
1517
+ const fd = openSync(exePath, "r");
1518
+ try {
1519
+ const identBuf = Buffer.alloc(16);
1520
+ readSync(fd, identBuf, 0, 16, 0);
1521
+ const elfClass = identBuf.readUInt8(4);
1522
+ const elfData = identBuf.readUInt8(5);
1523
+ if (elfClass !== 2) throw new SEAError("FORMAT", "Only 64-bit ELF executables are supported", {
1524
+ executable: exePath,
1525
+ elfClass
1526
+ });
1527
+ if (elfData !== 1) throw new SEAError("FORMAT", "Only little-endian ELF executables are supported", {
1528
+ executable: exePath,
1529
+ elfData
1530
+ });
1531
+ phdrOffset = Number(this.#readU64(fd, 32));
1532
+ phdrEntrySize = this.#readU16(fd, 54);
1533
+ phdrCount = this.#readU16(fd, 56);
1534
+ headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1535
+ for (const header of headers) {
1536
+ if (header.type !== 4) continue;
1537
+ const existingName = this.#readElfNoteName(fd, header.offset, header.filesz);
1538
+ if (existingName === void 0 || !existingName.startsWith("NODE_SEA")) continue;
1539
+ if (!overwrite) throw new SEAError("INJECT", `Note with name "${resource}" already exists`, {
1540
+ executable: exePath,
1541
+ resource
1542
+ });
1543
+ header.type = 0;
1544
+ }
1545
+ } finally {
1546
+ closeSync(fd);
1547
+ }
1548
+ let maxVaddrEnd = 0;
1549
+ for (const header of headers) {
1550
+ if (header.type !== PT_LOAD) continue;
1551
+ const end = header.vaddr + header.memsz;
1552
+ if (end > maxVaddrEnd) maxVaddrEnd = end;
1553
+ }
1554
+ const regionVaddr = this.#align(maxVaddrEnd, PAGE);
1555
+ const blobSize = statSync(this.#options.blob).size;
1556
+ const { header: noteHeader, entryTotal: noteEntryTotal } = buildELFNoteHeader(resource, blobSize);
1557
+ const noteAreaSize = this.#align(noteEntryTotal, 8);
1558
+ const newEntryCount = headers.length + 2;
1559
+ const phtSize = newEntryCount * phdrEntrySize;
1560
+ const regionSize = noteAreaSize + phtSize;
1561
+ const fileSize = statSync(exePath).size;
1562
+ const regionStart = this.#align(fileSize, PAGE);
1563
+ const phtOff = regionStart + noteAreaSize;
1564
+ const newLoad = {
1565
+ type: PT_LOAD,
1566
+ flags: PF_R,
1567
+ offset: regionStart,
1568
+ vaddr: regionVaddr,
1569
+ paddr: regionVaddr,
1570
+ filesz: regionSize,
1571
+ memsz: regionSize,
1572
+ align: PAGE
1573
+ };
1574
+ const newNote = {
1575
+ type: 4,
1576
+ flags: PF_R,
1577
+ offset: regionStart,
1578
+ vaddr: regionVaddr,
1579
+ paddr: regionVaddr,
1580
+ filesz: noteEntryTotal,
1581
+ memsz: noteEntryTotal,
1582
+ align: 4
1583
+ };
1584
+ const finalHeaders = headers.map((header) => {
1585
+ if (header.type !== PT_PHDR) return header;
1586
+ const relVaddr = regionVaddr + (phtOff - regionStart);
1587
+ return {
1588
+ ...header,
1589
+ offset: phtOff,
1590
+ vaddr: relVaddr,
1591
+ paddr: relVaddr,
1592
+ filesz: phtSize,
1593
+ memsz: phtSize
1594
+ };
1595
+ });
1596
+ finalHeaders.push(newLoad, newNote);
1597
+ const phtBuffer = Buffer.alloc(phtSize);
1598
+ for (let i = 0; i < finalHeaders.length; i++) {
1599
+ const entry = finalHeaders[i];
1600
+ if (entry === void 0) continue;
1601
+ this.#writeElfProgramHeaderEntry(phtBuffer, i * phdrEntrySize, entry);
1602
+ }
1603
+ if (regionStart > fileSize) appendFileSync(exePath, Buffer.alloc(regionStart - fileSize));
1604
+ appendFileSync(exePath, noteHeader);
1605
+ this.#appendFile(exePath, this.#options.blob);
1606
+ const descPadding = this.#align(blobSize, 4) - blobSize;
1607
+ if (descPadding > 0) appendFileSync(exePath, Buffer.alloc(descPadding));
1608
+ const trailingPad = noteAreaSize - noteEntryTotal;
1609
+ if (trailingPad > 0) appendFileSync(exePath, Buffer.alloc(trailingPad));
1610
+ appendFileSync(exePath, phtBuffer);
1611
+ const fd2 = openSync(exePath, "r+");
1612
+ try {
1613
+ this.#writeU64(fd2, 32, BigInt(phtOff));
1614
+ this.#writeU16(fd2, 56, newEntryCount);
1615
+ this.#verifyElfNoteMapping(fd2, phtOff, newEntryCount, phdrEntrySize);
1616
+ } finally {
1617
+ closeSync(fd2);
1618
+ }
1619
+ }
1620
+ #readElfProgramHeaders(fd, phdrOffset, entrySize, count) {
1621
+ const headers = [];
1622
+ for (let i = 0; i < count; i++) {
1623
+ const off = phdrOffset + i * entrySize;
1624
+ headers.push({
1625
+ type: this.#readU32(fd, off),
1626
+ flags: this.#readU32(fd, off + 4),
1627
+ offset: Number(this.#readU64(fd, off + 8)),
1628
+ vaddr: Number(this.#readU64(fd, off + 16)),
1629
+ paddr: Number(this.#readU64(fd, off + 24)),
1630
+ filesz: Number(this.#readU64(fd, off + 32)),
1631
+ memsz: Number(this.#readU64(fd, off + 40)),
1632
+ align: Number(this.#readU64(fd, off + 48))
1633
+ });
1634
+ }
1635
+ return headers;
1636
+ }
1637
+ #writeElfProgramHeaderEntry(buf, pos, entry) {
1638
+ buf.writeUInt32LE(entry.type >>> 0, pos);
1639
+ buf.writeUInt32LE(entry.flags >>> 0, pos + 4);
1640
+ buf.writeBigUInt64LE(BigInt(entry.offset), pos + 8);
1641
+ buf.writeBigUInt64LE(BigInt(entry.vaddr), pos + 16);
1642
+ buf.writeBigUInt64LE(BigInt(entry.paddr), pos + 24);
1643
+ buf.writeBigUInt64LE(BigInt(entry.filesz), pos + 32);
1644
+ buf.writeBigUInt64LE(BigInt(entry.memsz), pos + 40);
1645
+ buf.writeBigUInt64LE(BigInt(entry.align), pos + 48);
1646
+ }
1647
+ #readElfNoteName(fd, offset, size) {
1648
+ if (size < 12) return void 0;
1649
+ const namesz = this.#readU32(fd, offset);
1650
+ const descsz = this.#readU32(fd, offset + 4);
1651
+ if (namesz === 0 || namesz > 256) return void 0;
1652
+ if (12 + this.#align(namesz, 4) + this.#align(descsz, 4) > size) return void 0;
1653
+ const nameBuf = Buffer.alloc(namesz);
1654
+ readSync(fd, nameBuf, 0, namesz, offset + 12);
1655
+ return this.#stripTrailingNulls(nameBuf.toString("utf-8"));
1656
+ }
1657
+ #verifyElfNoteMapping(fd, phdrOffset, phdrCount, phdrEntrySize) {
1658
+ const headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1659
+ const loads = headers.filter((h) => h.type === 1);
1660
+ const notes = headers.filter((h) => h.type === 4);
1661
+ for (const note of notes) {
1662
+ const name = this.#readElfNoteName(fd, note.offset, note.filesz);
1663
+ if (name === void 0 || !name.startsWith("NODE_SEA")) continue;
1664
+ const covering = loads.find((load) => note.offset >= load.offset && note.offset < load.offset + load.filesz);
1665
+ if (covering === void 0) continue;
1666
+ if (covering.vaddr + (note.offset - covering.offset) === note.vaddr) return;
1667
+ }
1668
+ throw new SEAError("INJECT", "Injected ELF note is not reachable via a mapped PT_LOAD segment at runtime", {
1669
+ executable: this.#options.executable,
1670
+ resource: this.#options.resource
1671
+ });
1672
+ }
1673
+ #injectMacho() {
1674
+ const exePath = this.#options.executable;
1675
+ const fileSize = statSync(exePath).size;
1676
+ let srcFd = openSync(exePath, "r");
1677
+ let destFd;
1678
+ let blobFd;
1679
+ let injTemp;
1680
+ try {
1681
+ const headerSize = 32;
1682
+ const preHeader = Buffer.alloc(headerSize);
1683
+ readSync(srcFd, preHeader, 0, headerSize, 0);
1684
+ const preSizeofcmds = preHeader.readUInt32LE(20);
1685
+ if (headerSize + preSizeofcmds > fileSize) throw new SEAError("FORMAT", "Mach-O load command region exceeds file size", {
1686
+ executable: exePath,
1687
+ headerSize,
1688
+ sizeofcmds: preSizeofcmds,
1689
+ fileSize
1690
+ });
1691
+ const buf = Buffer.alloc(headerSize + preSizeofcmds);
1692
+ readSync(srcFd, buf, 0, headerSize + preSizeofcmds, 0);
1693
+ const magic = buf.readUInt32LE(0);
1694
+ if (magic !== 4277009103) throw new SEAError("FORMAT", `Unsupported Mach-O magic: 0x${magic.toString(16)}`, {
1695
+ executable: exePath,
1696
+ magic
1697
+ });
1698
+ const cputype = buf.readUInt32LE(4);
1699
+ const ncmds = buf.readUInt32LE(16);
1700
+ const sizeofcmds = buf.readUInt32LE(20);
1701
+ const segmentName = this.#options.macho?.segment ?? "NODE_SEA";
1702
+ let sectionName = this.#options.resource;
1703
+ if (!sectionName.startsWith("__")) sectionName = `__${sectionName}`;
1704
+ const commands = [];
1705
+ let cmdOffset = headerSize;
1706
+ for (let i = 0; i < ncmds; i++) {
1707
+ if (cmdOffset + 8 > buf.length) throw new SEAError("FORMAT", "Malformed Mach-O load command table", { executable: exePath });
1708
+ const cmdType = buf.readUInt32LE(cmdOffset);
1709
+ const cmdSize = buf.readUInt32LE(cmdOffset + 4);
1710
+ if (cmdSize < 8 || cmdOffset + cmdSize > buf.length) throw new SEAError("FORMAT", "Malformed Mach-O load command table", { executable: exePath });
1711
+ commands.push({
1712
+ type: cmdType,
1713
+ size: cmdSize,
1714
+ offset: cmdOffset
1715
+ });
1716
+ cmdOffset += cmdSize;
1717
+ }
1718
+ let linkeditIndex = -1;
1719
+ const existingSegmentIndices = [];
1720
+ for (let i = 0; i < commands.length; i++) {
1721
+ const cmd = commands[i];
1722
+ if (cmd === void 0 || cmd.type !== 25) continue;
1723
+ const segName = this.#stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii"));
1724
+ if (segName === "__LINKEDIT") linkeditIndex = i;
1725
+ if (segName === segmentName) existingSegmentIndices.push(i);
1726
+ }
1727
+ if (existingSegmentIndices.length > 0 && this.#options.overwrite === false) throw new SEAError("INJECT", `Segment "${segmentName}" already exists`, {
1728
+ executable: exePath,
1729
+ segmentName
1730
+ });
1731
+ const linkeditCmd = linkeditIndex === -1 ? void 0 : commands[linkeditIndex];
1732
+ if (linkeditCmd === void 0) throw new SEAError("INJECT", "Mach-O binary has no __LINKEDIT segment", { executable: exePath });
1733
+ const Loff = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40));
1734
+ const Lsize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48));
1735
+ const Lvm = buf.readBigUInt64LE(linkeditCmd.offset + 24);
1736
+ const blobSize = statSync(this.#options.blob).size;
1737
+ const pageSize = cputype === 16777228 ? 16384 : 4096;
1738
+ const shift = this.#align(blobSize, pageSize);
1739
+ let firstSectionOffset = fileSize;
1740
+ for (const cmd of commands) {
1741
+ if (cmd.type !== 25) continue;
1742
+ const nsects = buf.readUInt32LE(cmd.offset + 64);
1743
+ for (let s = 0; s < nsects; s++) {
1744
+ const sectOff = cmd.offset + 72 + s * 80;
1745
+ if (sectOff + 80 > buf.length) continue;
1746
+ const size = Number(buf.readBigUInt64LE(sectOff + 40));
1747
+ const offset = buf.readUInt32LE(sectOff + 48);
1748
+ if (size > 0 && offset > 0 && offset < firstSectionOffset) firstSectionOffset = offset;
1749
+ }
1750
+ }
1751
+ const newCmdSize = 152;
1752
+ const removedSize = commands.filter((_c, i) => existingSegmentIndices.includes(i)).reduce((sum, c) => sum + c.size, 0);
1753
+ const newNcmds = commands.length - existingSegmentIndices.length + 1;
1754
+ const newSizeofcmds = sizeofcmds - removedSize + newCmdSize;
1755
+ if (headerSize + newSizeofcmds + 16 > firstSectionOffset) throw new SEAError("INJECT", `Not enough header space for new Mach-O load command (need offset ${String(headerSize + newSizeofcmds + 16)}, first section at ${String(firstSectionOffset)})`, {
1756
+ executable: exePath,
1757
+ firstSectionOffset,
1758
+ requiredOffset: headerSize + newSizeofcmds + 16
1759
+ });
1760
+ for (let i = 0; i < commands.length; i++) {
1761
+ const cmd = commands[i];
1762
+ if (cmd === void 0 || existingSegmentIndices.includes(i)) continue;
1763
+ if (cmd.type === 25) {
1764
+ if (this.#stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii")) === "__LINKEDIT") {
1765
+ if (buf.readUInt32LE(cmd.offset + 64) > 0) throw new SEAError("INJECT", "__LINKEDIT segment with sections is not supported", { executable: exePath });
1766
+ buf.writeBigUInt64LE(Lvm + BigInt(shift), cmd.offset + 24);
1767
+ buf.writeBigUInt64LE(BigInt(Loff + shift), cmd.offset + 40);
1768
+ }
1769
+ continue;
1770
+ }
1771
+ this.#shiftMachoLinkeditOffsets(buf, cmd, Loff, shift);
1772
+ }
1773
+ buf.writeUInt32LE(newNcmds, 16);
1774
+ buf.writeUInt32LE(newSizeofcmds, 20);
1775
+ const cmd = Buffer.alloc(newCmdSize);
1776
+ cmd.writeUInt32LE(25, 0);
1777
+ cmd.writeUInt32LE(newCmdSize, 4);
1778
+ cmd.write(segmentName, 8, 16, "ascii");
1779
+ cmd.writeBigUInt64LE(Lvm, 24);
1780
+ cmd.writeBigUInt64LE(BigInt(shift), 32);
1781
+ cmd.writeBigUInt64LE(BigInt(Loff), 40);
1782
+ cmd.writeBigUInt64LE(BigInt(shift), 48);
1783
+ cmd.writeUInt32LE(1, 56);
1784
+ cmd.writeUInt32LE(1, 60);
1785
+ cmd.writeUInt32LE(1, 64);
1786
+ cmd.writeUInt32LE(0, 68);
1787
+ cmd.write(sectionName, 72, 16, "ascii");
1788
+ cmd.write(segmentName, 88, 16, "ascii");
1789
+ cmd.writeBigUInt64LE(Lvm, 104);
1790
+ cmd.writeBigUInt64LE(BigInt(blobSize), 112);
1791
+ cmd.writeUInt32LE(Loff, 120);
1792
+ cmd.writeUInt32LE(0, 124);
1793
+ cmd.writeUInt32LE(0, 128);
1794
+ cmd.writeUInt32LE(0, 132);
1795
+ cmd.writeUInt32LE(0, 136);
1796
+ cmd.writeUInt32LE(0, 140);
1797
+ cmd.writeUInt32LE(0, 144);
1798
+ cmd.writeUInt32LE(0, 148);
1799
+ const pieces = [];
1800
+ for (let i = 0; i < commands.length; i++) {
1801
+ if (existingSegmentIndices.includes(i)) continue;
1802
+ const c = commands[i];
1803
+ if (c === void 0) continue;
1804
+ if (i === linkeditIndex) pieces.push(cmd);
1805
+ pieces.push(Buffer.from(buf.subarray(c.offset, c.offset + c.size)));
1806
+ }
1807
+ const newLoadCmdsBuf = Buffer.concat(pieces);
1808
+ if (newLoadCmdsBuf.length !== newSizeofcmds) throw new SEAError("INJECT", "Internal Mach-O load command size mismatch", { executable: exePath });
1809
+ const mode = fstatSync(srcFd).mode;
1810
+ injTemp = join(dirname(exePath), `.inject-${randomUUID()}.tmp`);
1811
+ destFd = openSync(injTemp, "w", mode);
1812
+ writeSync(destFd, buf.subarray(0, headerSize));
1813
+ writeSync(destFd, newLoadCmdsBuf);
1814
+ copyRange(srcFd, destFd, headerSize + newSizeofcmds, Loff - (headerSize + newSizeofcmds));
1815
+ blobFd = openSync(this.#options.blob, "r");
1816
+ copyRange(blobFd, destFd, 0, blobSize);
1817
+ closeSync(blobFd);
1818
+ blobFd = void 0;
1819
+ const blobPadding = shift - blobSize;
1820
+ if (blobPadding > 0) writeSync(destFd, Buffer.alloc(blobPadding));
1821
+ copyRange(srcFd, destFd, Loff, Lsize);
1822
+ closeSync(destFd);
1823
+ destFd = void 0;
1824
+ closeSync(srcFd);
1825
+ srcFd = void 0;
1826
+ chmodSync(injTemp, mode & 4095);
1827
+ finalizeExecutable(injTemp, exePath);
1828
+ injTemp = void 0;
1829
+ this.#verifyMachoSection(exePath, segmentName, sectionName, Loff, blobSize);
1830
+ } finally {
1831
+ for (const fd of [
1832
+ blobFd,
1833
+ destFd,
1834
+ srcFd
1835
+ ]) if (fd !== void 0) try {
1836
+ closeSync(fd);
1837
+ } catch {}
1838
+ if (injTemp !== void 0) rmSync(injTemp, { force: true });
1839
+ }
1840
+ }
1841
+ #shiftMachoLinkeditOffsets(buf, cmd, threshold, shift) {
1842
+ const bump = (fieldOffset) => {
1843
+ if (fieldOffset + 4 > buf.length) return;
1844
+ const value = buf.readUInt32LE(fieldOffset);
1845
+ if (value >= threshold && value > 0) buf.writeUInt32LE(value + shift, fieldOffset);
1846
+ };
1847
+ const base = cmd.offset;
1848
+ switch (cmd.type) {
1849
+ case 2:
1850
+ bump(base + 8);
1851
+ bump(base + 16);
1852
+ break;
1853
+ case 11:
1854
+ bump(base + 32);
1855
+ bump(base + 40);
1856
+ bump(base + 48);
1857
+ bump(base + 56);
1858
+ bump(base + 64);
1859
+ bump(base + 72);
1860
+ break;
1861
+ case 34:
1862
+ case 2147483682:
1863
+ bump(base + 8);
1864
+ bump(base + 16);
1865
+ bump(base + 24);
1866
+ bump(base + 32);
1867
+ bump(base + 40);
1868
+ break;
1869
+ case 29:
1870
+ case 30:
1871
+ case 38:
1872
+ case 41:
1873
+ case 2147483699:
1874
+ case 2147483700:
1875
+ bump(base + 8);
1876
+ break;
1877
+ default: break;
1878
+ }
1879
+ }
1880
+ #verifyMachoSection(exePath, segmentName, sectionName, expectedOffset, expectedSize) {
1881
+ const fd = openSync(exePath, "r");
1882
+ try {
1883
+ const header = Buffer.alloc(32);
1884
+ readSync(fd, header, 0, 32, 0);
1885
+ const ncmds = header.readUInt32LE(16);
1886
+ let offset = 32;
1887
+ for (let i = 0; i < ncmds; i++) {
1888
+ const cmdHead = Buffer.alloc(8);
1889
+ readSync(fd, cmdHead, 0, 8, offset);
1890
+ const cmdType = cmdHead.readUInt32LE(0);
1891
+ const cmdSize = cmdHead.readUInt32LE(4);
1892
+ if (cmdType === 25 && cmdSize >= 72) {
1893
+ const segBuf = Buffer.alloc(cmdSize);
1894
+ readSync(fd, segBuf, 0, cmdSize, offset);
1895
+ if (this.#stripTrailingNulls(segBuf.subarray(8, 24).toString("ascii")) === segmentName) {
1896
+ const nsects = segBuf.readUInt32LE(64);
1897
+ for (let s = 0; s < nsects; s++) {
1898
+ const sectOff = 72 + s * 80;
1899
+ if (sectOff + 80 > segBuf.length) continue;
1900
+ if (this.#stripTrailingNulls(segBuf.subarray(sectOff, sectOff + 16).toString("ascii")) !== sectionName) continue;
1901
+ const secSize = Number(segBuf.readBigUInt64LE(sectOff + 40));
1902
+ if (segBuf.readUInt32LE(sectOff + 48) === expectedOffset && secSize === expectedSize) return;
1903
+ }
1904
+ }
1905
+ }
1906
+ offset += cmdSize;
1907
+ }
1908
+ } finally {
1909
+ closeSync(fd);
1910
+ }
1911
+ throw new SEAError("INJECT", "Injected Mach-O section not found after write", {
1912
+ executable: exePath,
1913
+ segmentName,
1914
+ sectionName
1915
+ });
1916
+ }
1917
+ #readU16(fd, offset) {
1918
+ const b = Buffer.alloc(2);
1919
+ readSync(fd, b, 0, 2, offset);
1920
+ return b.readUInt16LE(0);
1921
+ }
1922
+ #readU32(fd, offset) {
1923
+ const b = Buffer.alloc(4);
1924
+ readSync(fd, b, 0, 4, offset);
1925
+ return b.readUInt32LE(0);
1926
+ }
1927
+ #readU64(fd, offset) {
1928
+ const b = Buffer.alloc(8);
1929
+ readSync(fd, b, 0, 8, offset);
1930
+ return b.readBigUInt64LE(0);
1931
+ }
1932
+ #writeU16(fd, offset, value) {
1933
+ const b = Buffer.alloc(2);
1934
+ b.writeUInt16LE(value, 0);
1935
+ writeSync(fd, b, 0, 2, offset);
1936
+ }
1937
+ #writeU32(fd, offset, value) {
1938
+ const b = Buffer.alloc(4);
1939
+ b.writeUInt32LE(value >>> 0, 0);
1940
+ writeSync(fd, b, 0, 4, offset);
1941
+ }
1942
+ #writeU64(fd, offset, value) {
1943
+ const b = Buffer.alloc(8);
1944
+ b.writeBigUInt64LE(value, 0);
1945
+ writeSync(fd, b, 0, 8, offset);
1946
+ }
1947
+ #align(value, alignment) {
1948
+ const remainder = value % alignment;
1949
+ return remainder === 0 ? value : value + (alignment - remainder);
1950
+ }
1951
+ #ensureValidPEAlignment(sectionAlignment, fileAlignment) {
1952
+ const isPowerOfTwo = (n) => n > 0 && (n & n - 1) === 0;
1953
+ if (!isPowerOfTwo(sectionAlignment) || !isPowerOfTwo(fileAlignment)) throw new SEAError("FORMAT", "PE section/file alignment must be a nonzero power of two", {
1954
+ executable: this.#options.executable,
1955
+ sectionAlignment,
1956
+ fileAlignment
1957
+ });
1958
+ if (sectionAlignment < fileAlignment) throw new SEAError("FORMAT", "PE sectionAlignment must be >= fileAlignment", {
1959
+ executable: this.#options.executable,
1960
+ sectionAlignment,
1961
+ fileAlignment
1962
+ });
1963
+ }
1964
+ /** Append sourceFile to targetFile by streaming in 4 MB chunks */
1965
+ #appendFile(targetPath, sourcePath) {
1966
+ const chunkSize = 4 * 1024 * 1024;
1967
+ const srcFd = openSync(sourcePath, "r");
1968
+ try {
1969
+ const srcSize = statSync(sourcePath).size;
1970
+ const chunk = Buffer.alloc(Math.min(chunkSize, srcSize));
1971
+ let offset = 0;
1972
+ while (offset < srcSize) {
1973
+ const bytesRead = readSync(srcFd, chunk, 0, Math.min(chunkSize, srcSize - offset), offset);
1974
+ if (bytesRead === 0) break;
1975
+ appendFileSync(targetPath, chunk.subarray(0, bytesRead));
1976
+ offset += bytesRead;
1977
+ }
1978
+ } finally {
1979
+ closeSync(srcFd);
1980
+ }
1981
+ }
1982
+ #stripTrailingNulls(value) {
1983
+ const idx = value.indexOf(String.fromCharCode(0));
1984
+ return idx === -1 ? value : value.slice(0, idx);
1985
+ }
1986
+ };
1987
+ //#endregion
1988
+ //#region src/server/seals/SEA.ts
1989
+ var SEA = class {
1990
+ #status = "idle";
1991
+ #destroyed = false;
1992
+ #options;
1993
+ #emitter;
1994
+ constructor(options) {
1995
+ this.#options = options;
1996
+ this.#emitter = new Emitter({
1997
+ on: options.on,
1998
+ error: options.error
1999
+ });
2000
+ }
2001
+ get emitter() {
2002
+ return this.#emitter;
2003
+ }
2004
+ get status() {
2005
+ return this.#status;
2006
+ }
2007
+ async execute() {
2008
+ if (this.#destroyed) throw new SEAError("STATE", "SEA is destroyed");
2009
+ if (this.#status === "active") throw new SEAError("STATE", "SEA build already in progress");
2010
+ if (platformConfig() === void 0 || !isPlatformSupported()) {
2011
+ const error = new SEAError("PLATFORM", `Unsupported platform: ${process.platform}`, { platform: process.platform });
2012
+ this.#status = "error";
2013
+ this.#emitter.emit("error", error);
2014
+ throw error;
2015
+ }
2016
+ this.#status = "active";
2017
+ const start = Date.now();
2018
+ const root = this.#options.root ?? process.cwd();
2019
+ try {
2020
+ this.#check();
2021
+ this.#validate(root);
2022
+ this.#check();
2023
+ const compression = this.#compress(root);
2024
+ this.#check();
2025
+ const blob = this.#blob(root);
2026
+ this.#check();
2027
+ const assembled = this.#assemble(root, blob);
2028
+ const size = statSync(assembled.executable).size;
2029
+ const duration = Date.now() - start;
2030
+ const result = {
2031
+ executable: assembled.executable,
2032
+ platform: process.platform,
2033
+ size,
2034
+ duration,
2035
+ compression,
2036
+ signed: assembled.signed,
2037
+ stripped: assembled.stripped,
2038
+ terminal: assembled.terminal
2039
+ };
2040
+ this.#status = "done";
2041
+ this.#emitter.emit("complete", result);
2042
+ return result;
2043
+ } catch (thrown) {
2044
+ this.#status = "error";
2045
+ this.#emitter.emit("error", thrown);
2046
+ throw thrown;
2047
+ }
2048
+ }
2049
+ destroy() {
2050
+ if (this.#destroyed) return;
2051
+ this.#destroyed = true;
2052
+ this.#emitter.destroy();
2053
+ }
2054
+ #check() {
2055
+ if (this.#options.signal?.aborted === true) throw new SEAError("ABORT", "SEA build aborted");
2056
+ }
2057
+ #validate(root) {
2058
+ const base = resolve(root);
2059
+ ensureSafeName(this.#options.name);
2060
+ for (const [key, path] of Object.entries(this.#options.assets ?? {})) {
2061
+ ensureSafeKey(key);
2062
+ ensureSafeKey(path);
2063
+ ensureContained(base, path);
2064
+ }
2065
+ for (const path of this.#options.compression?.paths ?? []) {
2066
+ ensureSafeKey(path);
2067
+ if (existsSync(resolve(base, path))) ensureContained(base, path);
2068
+ }
2069
+ const sign = this.#options.windows?.sign;
2070
+ if (sign !== void 0) {
2071
+ createSignCommand(sign, "placeholder");
2072
+ if (sign.file !== void 0) ensureExists(resolve(base, sign.file), "Certificate file not found", "SIGN");
2073
+ }
2074
+ }
2075
+ #compress(root) {
2076
+ const compression = this.#options.compression;
2077
+ if (compression === void 0 || compression.paths.length === 0) {
2078
+ this.#emitter.emit("compress", void 0);
2079
+ return;
2080
+ }
2081
+ const directories = [];
2082
+ let total = 0;
2083
+ for (const path of compression.paths) {
2084
+ if (!existsSync(resolve(root, path))) continue;
2085
+ this.#check();
2086
+ const directory = ensureContained(root, path);
2087
+ directories.push(directory);
2088
+ total += walkDirectory(directory).filter(isCompressible).length;
2089
+ }
2090
+ const assets = [];
2091
+ let original = 0;
2092
+ let compressed = 0;
2093
+ let current = 0;
2094
+ for (const directory of directories) {
2095
+ this.#check();
2096
+ const manifest = compressDirectory(directory, compression, (result) => {
2097
+ current += 1;
2098
+ this.#emitter.emit("progress", {
2099
+ path: result.input,
2100
+ current,
2101
+ total
2102
+ });
2103
+ });
2104
+ assets.push(...manifest.assets);
2105
+ original += manifest.total.original;
2106
+ compressed += manifest.total.compressed;
2107
+ }
2108
+ const manifest = {
2109
+ assets,
2110
+ total: {
2111
+ original,
2112
+ compressed,
2113
+ ratio: original > 0 ? compressed / original : 0
2114
+ }
2115
+ };
2116
+ this.#emitter.emit("compress", manifest);
2117
+ return manifest;
2118
+ }
2119
+ #blob(root) {
2120
+ const entry = resolve(root, this.#options.entry.path);
2121
+ ensureExists(entry, `Entry not found: ${this.#options.entry.path}`, "ENTRY");
2122
+ const output = resolve(root, this.#options.output);
2123
+ mkdirSync(output, { recursive: true });
2124
+ const configPath = join(output, "sea-config.json");
2125
+ const blob = join(output, "sea-prep.blob");
2126
+ const config = createBlobConfig({
2127
+ path: entry,
2128
+ format: this.#options.entry.format
2129
+ }, blob, this.#assets(root), this.#options.blob);
2130
+ writeFileSync(configPath, JSON.stringify(config, null, 2));
2131
+ runShell([
2132
+ process.execPath,
2133
+ "--experimental-sea-config",
2134
+ configPath
2135
+ ], {
2136
+ cwd: output,
2137
+ signal: this.#options.signal
2138
+ });
2139
+ if (!existsSync(blob)) throw new SEAError("BLOB", "SEA blob generation failed — blob not found", { blob });
2140
+ this.#emitter.emit("blob", blob);
2141
+ return blob;
2142
+ }
2143
+ #assemble(root, blob) {
2144
+ const platform = platformConfig();
2145
+ if (platform === void 0) throw new SEAError("PLATFORM", `Unsupported platform: ${process.platform}`, { platform: process.platform });
2146
+ const output = resolve(root, this.#options.output);
2147
+ const ext = process.platform === "win32" ? ".exe" : "";
2148
+ const finalOutput = join(output, process.platform === "win32" ? `${this.#options.name}.exe` : this.#options.name);
2149
+ const temp = join(output, `.${this.#options.name}-${randomUUID()}.tmp${ext}`);
2150
+ let signed = false;
2151
+ let stripped = false;
2152
+ let terminal;
2153
+ try {
2154
+ if (process.platform === "darwin") {
2155
+ this.#check();
2156
+ copyFileSync(process.execPath, temp);
2157
+ chmodSync(temp, 493);
2158
+ if (platform.remove !== void 0) {
2159
+ this.#check();
2160
+ try {
2161
+ runShell([...platform.remove, temp], { signal: this.#options.signal });
2162
+ } catch (thrown) {
2163
+ throw new SEAError("SIGN", "Failed to strip existing signature", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2164
+ }
2165
+ stripped = true;
2166
+ }
2167
+ this.#check();
2168
+ new Injector({
2169
+ executable: temp,
2170
+ resource: SEA_BLOB_RESOURCE,
2171
+ blob,
2172
+ fuse: SEA_SENTINEL_FUSE,
2173
+ macho: { segment: "NODE_SEA" }
2174
+ }).inject();
2175
+ if (platform.sign !== void 0) {
2176
+ this.#check();
2177
+ try {
2178
+ runShell([...platform.sign, temp], { signal: this.#options.signal });
2179
+ } catch (thrown) {
2180
+ throw new SEAError("SIGN", "Failed to sign executable", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2181
+ }
2182
+ if (platform.verify !== void 0) {
2183
+ this.#check();
2184
+ try {
2185
+ runShell([...platform.verify, temp], { signal: this.#options.signal });
2186
+ } catch (thrown) {
2187
+ throw new SEAError("SIGN", "Signature verification failed", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2188
+ }
2189
+ }
2190
+ signed = true;
2191
+ }
2192
+ } else if (process.platform === "win32") {
2193
+ this.#check();
2194
+ copyFileSync(process.execPath, temp);
2195
+ stripPESignature(temp);
2196
+ stripped = true;
2197
+ if (isPEExecutable(temp)) {
2198
+ terminal = this.#options.windows?.terminal !== false;
2199
+ patchPESubsystem(temp, terminal ? 3 : 2);
2200
+ }
2201
+ this.#check();
2202
+ new Injector({
2203
+ executable: temp,
2204
+ resource: SEA_BLOB_RESOURCE,
2205
+ blob,
2206
+ fuse: SEA_SENTINEL_FUSE
2207
+ }).inject();
2208
+ const sign = this.#options.windows?.sign;
2209
+ if (sign !== void 0) {
2210
+ this.#check();
2211
+ const signArgs = createSignCommand(sign.file !== void 0 ? {
2212
+ ...sign,
2213
+ file: resolve(root, sign.file)
2214
+ } : sign, temp);
2215
+ try {
2216
+ runShell(signArgs, { signal: this.#options.signal });
2217
+ } catch {
2218
+ throw new SEAError("SIGN", "Windows signing failed", { executable: temp });
2219
+ }
2220
+ signed = true;
2221
+ if (platform.verify !== void 0) {
2222
+ this.#check();
2223
+ try {
2224
+ runShell([...platform.verify, temp], { signal: this.#options.signal });
2225
+ } catch {
2226
+ throw new SEAError("SIGN", "Signature verification failed", { executable: temp });
2227
+ }
2228
+ }
2229
+ }
2230
+ } else {
2231
+ this.#check();
2232
+ copyFileSync(process.execPath, temp);
2233
+ chmodSync(temp, 493);
2234
+ this.#check();
2235
+ new Injector({
2236
+ executable: temp,
2237
+ resource: SEA_BLOB_RESOURCE,
2238
+ blob,
2239
+ fuse: SEA_SENTINEL_FUSE
2240
+ }).inject();
2241
+ }
2242
+ finalizeExecutable(temp, finalOutput);
2243
+ } catch (thrown) {
2244
+ rmSync(temp, { force: true });
2245
+ throw thrown;
2246
+ }
2247
+ this.#emitter.emit("assemble", finalOutput);
2248
+ return {
2249
+ executable: finalOutput,
2250
+ signed,
2251
+ stripped,
2252
+ terminal
2253
+ };
2254
+ }
2255
+ #assets(root) {
2256
+ const assets = {};
2257
+ for (const [name, path] of Object.entries(this.#options.assets ?? {})) assets[name] = ensureContained(root, path);
2258
+ return assets;
2259
+ }
2260
+ };
2261
+ //#endregion
2262
+ //#region src/server/assets/Asset.ts
2263
+ var Asset = class {
2264
+ key;
2265
+ content;
2266
+ compressed;
2267
+ constructor(input) {
2268
+ this.key = input.key;
2269
+ this.content = input.content;
2270
+ this.compressed = input.compressed ?? input.key.endsWith(".br");
2271
+ }
2272
+ };
2273
+ //#endregion
2274
+ //#region src/server/assets/AssetManager.ts
2275
+ /**
2276
+ * AssetManager
2277
+ *
2278
+ * Named asset collection with SEA and disk loading.
2279
+ * In SEA mode, embedded assets are loaded automatically at construction.
2280
+ * In development, `load()` reads client assets from disk.
2281
+ */
2282
+ var AssetManager = class {
2283
+ #emitter;
2284
+ #assets = /* @__PURE__ */ new Map();
2285
+ #keys = [];
2286
+ #root;
2287
+ constructor(options) {
2288
+ this.#root = options?.root ?? process.cwd();
2289
+ this.#emitter = new Emitter({
2290
+ on: options?.on,
2291
+ error: options?.error
2292
+ });
2293
+ this.#loadSea();
2294
+ }
2295
+ get emitter() {
2296
+ return this.#emitter;
2297
+ }
2298
+ get count() {
2299
+ return this.#assets.size;
2300
+ }
2301
+ asset(key) {
2302
+ return this.#assets.get(key);
2303
+ }
2304
+ assets() {
2305
+ return [...this.#assets.values()];
2306
+ }
2307
+ keys() {
2308
+ return [...this.#keys];
2309
+ }
2310
+ register(input) {
2311
+ const items = Array.isArray(input) ? input : [input];
2312
+ for (const item of items) {
2313
+ const asset = new Asset(item);
2314
+ this.#add(asset);
2315
+ this.#emitter.emit("register", asset);
2316
+ }
2317
+ }
2318
+ load() {
2319
+ if (isSea()) return;
2320
+ const devPath = resolve(this.#root, "client", CLIENT_ASSET_KEY_RAW);
2321
+ const builtBrPath = resolve(this.#root, "dist", "client", CLIENT_ASSET_KEY_BR);
2322
+ if (existsSync(devPath)) {
2323
+ try {
2324
+ const raw = readFileSync(devPath, "utf-8");
2325
+ const content = new TextEncoder().encode(raw).buffer;
2326
+ if (!isArrayBuffer(content)) throw new Error("Failed to encode client asset");
2327
+ this.register({
2328
+ key: CLIENT_ASSET_KEY_RAW,
2329
+ content,
2330
+ compressed: false
2331
+ });
2332
+ this.#emitter.emit("load", [CLIENT_ASSET_KEY_RAW]);
2333
+ } catch (thrown) {
2334
+ this.#emitter.emit("error", thrown);
2335
+ }
2336
+ return;
2337
+ }
2338
+ if (existsSync(builtBrPath)) {
2339
+ try {
2340
+ const buffer = readFileSync(builtBrPath);
2341
+ const bufferData = buffer.buffer;
2342
+ if (!isArrayBuffer(bufferData)) throw new Error("Failed to read client asset");
2343
+ const content = bufferData.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
2344
+ this.register({
2345
+ key: CLIENT_ASSET_KEY_BR,
2346
+ content,
2347
+ compressed: true
2348
+ });
2349
+ this.#emitter.emit("load", [CLIENT_ASSET_KEY_BR]);
2350
+ } catch (thrown) {
2351
+ this.#emitter.emit("error", thrown);
2352
+ }
2353
+ return;
2354
+ }
2355
+ this.#emitter.emit("error", /* @__PURE__ */ new Error("Client assets not found"));
2356
+ }
2357
+ clear() {
2358
+ this.#assets.clear();
2359
+ this.#keys = [];
2360
+ this.#emitter.emit("clear");
2361
+ }
2362
+ destroy() {
2363
+ this.clear();
2364
+ this.#emitter.destroy();
2365
+ }
2366
+ #add(asset) {
2367
+ this.#assets.set(asset.key, asset);
2368
+ if (!this.#keys.includes(asset.key)) this.#keys.push(asset.key);
2369
+ }
2370
+ #loadSea() {
2371
+ if (isSea()) {
2372
+ const assetKeys = getAssetKeys();
2373
+ const registered = [];
2374
+ for (const key of assetKeys) {
2375
+ const content = getRawAsset(key);
2376
+ this.#add(new Asset({
2377
+ key,
2378
+ content
2379
+ }));
2380
+ registered.push(key);
2381
+ }
2382
+ if (registered.length > 0) this.#emitter.emit("load", registered);
2383
+ }
2384
+ }
2385
+ };
2386
+ //#endregion
2387
+ //#region src/server/factories.ts
2388
+ /**
2389
+ * Create a new SEA build orchestrator.
2390
+ *
2391
+ * @param options - SEA build options
2392
+ * @returns a new `SEAInterface`
2393
+ *
2394
+ * @example
2395
+ * ```ts
2396
+ * const seal = createSEA({
2397
+ * name: 'orkestrel',
2398
+ * entry: { path: 'dist/bin/serve.cjs' },
2399
+ * output: 'dist/sea',
2400
+ * assets: { 'index.html.br': 'dist/client/index.html.br' },
2401
+ * compression: { paths: ['dist/client'] },
2402
+ * })
2403
+ * const result = await seal.execute()
2404
+ * ```
2405
+ */
2406
+ function createSEA(options) {
2407
+ return new SEA(options);
2408
+ }
2409
+ /**
2410
+ * Create a cross-platform binary resource injector.
2411
+ *
2412
+ * Detects the executable format (PE, ELF, Mach-O) from the file header
2413
+ * and injects the blob using pure TypeScript file I/O — no WASM, no
2414
+ * external tools.
2415
+ *
2416
+ * @param options - Injector options
2417
+ * @returns a new `InjectorInterface`
2418
+ *
2419
+ * @example
2420
+ * ```ts
2421
+ * const injector = createInjector({
2422
+ * executable: 'dist/bin/myapp.exe',
2423
+ * resource: 'NODE_SEA_BLOB',
2424
+ * blob: 'dist/bin/sea-prep.blob',
2425
+ * fuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2',
2426
+ * })
2427
+ * injector.inject()
2428
+ * ```
2429
+ */
2430
+ function createInjector(options) {
2431
+ return new Injector(options);
2432
+ }
2433
+ /**
2434
+ * Create a single named asset.
2435
+ *
2436
+ * @param input - Asset key, content, and optional compression flag
2437
+ * @returns a new `AssetInterface`
2438
+ *
2439
+ * @example
2440
+ * ```ts
2441
+ * const asset = createAsset({ key: 'client.html.br', content: compressedBuffer })
2442
+ * ```
2443
+ */
2444
+ function createAsset(input) {
2445
+ return new Asset(input);
2446
+ }
2447
+ /**
2448
+ * Create an asset manager for SEA-embedded or disk-loaded assets.
2449
+ *
2450
+ * @param options - Asset manager options (root, event hooks)
2451
+ * @returns a new `AssetManagerInterface`
2452
+ *
2453
+ * @example
2454
+ * ```ts
2455
+ * const manager = createAssetManager({ root: process.cwd() })
2456
+ * manager.load()
2457
+ * ```
2458
+ */
2459
+ function createAssetManager(options) {
2460
+ return new AssetManager(options);
2461
+ }
2462
+ //#endregion
2463
+ export { Asset, AssetManager, BROTLI_EXTENSION, CLIENT_ASSET_KEY_BR, CLIENT_ASSET_KEY_RAW, DEFAULT_ENTRY_FORMAT, DEFAULT_SEA_COMPRESSION_QUALITY, ELF_CLASS_64, ELF_DATA_LSB, ELF_MAGIC, ELF_PT_NOTE, Injector, MACHO_LC_SEGMENT_64, MACHO_MAGIC_64, PE32_MAGIC, PE32_PLUS_MAGIC, PE_MAGIC, PE_RESOURCE_DATA_ENTRY_SIZE, PE_RESOURCE_DIR_SIZE, PE_RESOURCE_ENTRY_SIZE, PE_RESOURCE_NAME_FLAG, PE_RESOURCE_SUBDIR_FLAG, PE_RT_RCDATA, PE_SCN_INITIALIZED_DATA, PE_SCN_MEM_READ, PE_SECTION_HEADER_SIZE, PE_SIGNATURE, SEA, SEAError, SEA_BLOB_RESOURCE, SEA_COMPRESSION_MODE_VALUES, SEA_PLATFORMS, SEA_SENTINEL_FUSE, SKIP_EXTENSIONS, ShellError, WINDOWS_SUBSYSTEM_CONSOLE, WINDOWS_SUBSYSTEM_GUI, buildELFNoteHeader, compressDirectory, compressFile, computeSize, copyRange, createAsset, createAssetManager, createBlobConfig, createInjector, createSEA, createSignCommand, ensureContained, ensureExists, ensureSafeKey, ensureSafeName, finalizeExecutable, formatSize, isCompressible, isExecutableFormat, isPEExecutable, isPlatformSupported, isSEAError, isShellError, openBrowser, parsePEOffset, patchPESubsystem, patchSentinelFuse, platformConfig, readU16, runShell, stripPESignature, syncDirectory, walkDirectory, writeU16 };
2464
+
2465
+ //# sourceMappingURL=index.js.map