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