@ziptie-soft/orca-local-decider 0.0.0 → 1.0.0

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,892 @@
1
+ /**
2
+ * Small, dependency-free gateway launcher shared by local-decider clients. It never reads
3
+ * process.env: callers pass the environment explicitly so tests and hosts control child envs.
4
+ */
5
+ import { execFile as nodeExecFile } from 'node:child_process';
6
+ import { randomBytes } from 'node:crypto';
7
+ import {
8
+ chmodSync,
9
+ closeSync,
10
+ constants,
11
+ fchmodSync,
12
+ fstatSync,
13
+ ftruncateSync,
14
+ mkdirSync,
15
+ openSync,
16
+ readFileSync,
17
+ realpathSync,
18
+ renameSync,
19
+ rmSync,
20
+ writeSync,
21
+ } from 'node:fs';
22
+ import { homedir, userInfo } from 'node:os';
23
+ import { delimiter, dirname, extname, isAbsolute, join } from 'node:path';
24
+
25
+ import { gatewaySocketPath } from './socket-path.ts';
26
+ import { socketFetch } from './transport.ts';
27
+
28
+ export interface EngineStatus {
29
+ readonly status: string;
30
+ readonly engineState: string | null;
31
+ readonly detail: string | null;
32
+ readonly version?: string;
33
+ readonly instance?: string;
34
+ }
35
+
36
+ export type LaunchStatus =
37
+ | 'disabled'
38
+ | 'remote'
39
+ | 'running'
40
+ | 'started'
41
+ | 'service-started'
42
+ | 'legacy'
43
+ | 'port-busy'
44
+ | 'mismatch'
45
+ | 'stopped'
46
+ | 'unsafe-path'
47
+ | 'failed'
48
+ | 'not-installed'
49
+ | 'too-new'
50
+ | 'not-published';
51
+
52
+ export interface LaunchResult {
53
+ readonly ok: boolean;
54
+ readonly status: LaunchStatus;
55
+ readonly message: string;
56
+ readonly engine?: EngineStatus | null;
57
+ readonly guideUrl?: string;
58
+ }
59
+
60
+ export interface LauncherFs {
61
+ mkdirSync(path: string, options: { recursive?: boolean; mode?: number }): unknown;
62
+ openSync(path: string, flags: number, mode?: number): number;
63
+ fstatSync(fd: number): {
64
+ readonly uid: number;
65
+ readonly mode: number;
66
+ readonly size: number;
67
+ isDirectory(): boolean;
68
+ isFile(): boolean;
69
+ };
70
+ ftruncateSync(fd: number, length: number): void;
71
+ closeSync(fd: number): void;
72
+ fchmodSync(fd: number, mode: number): void;
73
+ chmodSync(path: string, mode: number): void;
74
+ readFileSync(pathOrFd: string | number, encoding: BufferEncoding): string;
75
+ realpathSync(path: string): string;
76
+ renameSync(oldPath: string, newPath: string): void;
77
+ rmSync(path: string, options: { recursive?: boolean; force?: boolean }): void;
78
+ writeSync(fd: number, data: string): number;
79
+ }
80
+
81
+ export interface ExecOptions {
82
+ readonly cwd: string;
83
+ readonly env: NodeJS.ProcessEnv;
84
+ readonly timeout: number;
85
+ readonly windowsHide: true;
86
+ readonly maxBuffer: number;
87
+ }
88
+
89
+ export type ExecFile = (
90
+ file: string,
91
+ args: readonly string[],
92
+ options: ExecOptions,
93
+ ) => Promise<{
94
+ readonly stdout: string;
95
+ readonly stderr: string;
96
+ readonly error?: Error & { readonly killed?: boolean };
97
+ }>;
98
+
99
+ export interface LauncherDeps {
100
+ readonly fetch?: typeof fetch;
101
+ readonly execFile?: ExecFile;
102
+ readonly fs?: LauncherFs;
103
+ readonly now?: () => number;
104
+ readonly home?: string;
105
+ readonly uid?: number;
106
+ readonly execPath?: string;
107
+ readonly nodeReleaseName?: string;
108
+ readonly nodeVersion?: string;
109
+ readonly electronVersion?: string;
110
+ readonly random?: () => string;
111
+ }
112
+
113
+ export interface LaunchOptions {
114
+ readonly url: string;
115
+ /** True only when no user URL setting selected this built-in local endpoint. */
116
+ readonly defaultEndpoint?: boolean;
117
+ readonly clientId?: string;
118
+ readonly env: NodeJS.ProcessEnv;
119
+ readonly pinnedVersion: string;
120
+ readonly guideUrl: string;
121
+ readonly deps?: LauncherDeps;
122
+ }
123
+
124
+ interface DataPaths {
125
+ readonly data: string;
126
+ readonly run: string;
127
+ readonly logs: string;
128
+ readonly gateway: string;
129
+ }
130
+
131
+ const REGISTRY = 'https://registry.npmjs.org/@ziptie-soft/local-decider';
132
+ const REGISTRY_ROOT = 'https://registry.npmjs.org/';
133
+ const INSTALL_AGE_MS = 72 * 60 * 60 * 1000;
134
+ const HEALTH_TIMEOUT_MS = 1000;
135
+ const ENSURE_TIMEOUT_MS = 45_000;
136
+ const INSTALL_TIMEOUT_MS = 600_000;
137
+ const LOG_LIMIT = 256 * 1024;
138
+ const MANUAL_START = 'local-decider gateway start';
139
+
140
+ const defaultFs: LauncherFs = {
141
+ mkdirSync,
142
+ openSync,
143
+ fstatSync,
144
+ ftruncateSync,
145
+ closeSync,
146
+ fchmodSync,
147
+ chmodSync,
148
+ readFileSync,
149
+ realpathSync,
150
+ renameSync,
151
+ rmSync,
152
+ writeSync,
153
+ };
154
+
155
+ const execFile: ExecFile = (file, args, options) =>
156
+ new Promise((resolvePromise) => {
157
+ nodeExecFile(file, [...args], options, (error, stdout, stderr) => {
158
+ if (error !== null) {
159
+ resolvePromise({ stdout, stderr, error });
160
+ return;
161
+ }
162
+ resolvePromise({ stdout, stderr });
163
+ });
164
+ });
165
+
166
+ function result(
167
+ status: LaunchStatus,
168
+ message: string,
169
+ engine?: EngineStatus | null,
170
+ guideUrl?: string,
171
+ ): LaunchResult {
172
+ const listenerUp = status === 'running' || status === 'started' || status === 'service-started';
173
+ const ok = listenerUp && engine?.status !== 'down';
174
+ return {
175
+ ok,
176
+ status,
177
+ message,
178
+ ...(engine === undefined ? {} : { engine }),
179
+ ...(guideUrl === undefined ? {} : { guideUrl }),
180
+ };
181
+ }
182
+
183
+ function record(value: unknown): value is Record<string, unknown> {
184
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
185
+ }
186
+
187
+ function engineStatus(value: Record<string, unknown>): EngineStatus {
188
+ return {
189
+ status: value['status'] as string,
190
+ engineState: typeof value['engineState'] === 'string' ? value['engineState'] : null,
191
+ detail: typeof value['detail'] === 'string' ? value['detail'] : null,
192
+ ...(typeof value['version'] === 'string' ? { version: value['version'] } : {}),
193
+ ...(typeof value['instance'] === 'string' ? { instance: value['instance'] } : {}),
194
+ };
195
+ }
196
+
197
+ function loopback(host: string): boolean {
198
+ const normalized = host.toLowerCase().replace(/^\[(.*)\]$/, '$1');
199
+ if (normalized === 'localhost' || normalized === '::1') return true;
200
+ const octets = normalized.split('.').map(Number);
201
+ return (
202
+ octets.length === 4 &&
203
+ octets[0] === 127 &&
204
+ octets.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)
205
+ );
206
+ }
207
+
208
+ export function isLoopbackUrl(value: string): boolean {
209
+ try {
210
+ return loopback(new URL(value).hostname);
211
+ } catch {
212
+ return false;
213
+ }
214
+ }
215
+
216
+ function isDefaultEndpoint(options: LaunchOptions): boolean {
217
+ return (
218
+ options.defaultEndpoint ??
219
+ ((options.env['LOCAL_DECIDER_URL']?.trim() ?? '') === '' &&
220
+ options.url === 'http://127.0.0.1:8765')
221
+ );
222
+ }
223
+
224
+ function dataDirectory(options: LaunchOptions, deps: LauncherDeps): string {
225
+ const home = deps.home ?? homedir();
226
+ return (
227
+ options.env['LOCAL_DECIDER_HOME'] ??
228
+ join(options.env['XDG_DATA_HOME'] ?? join(home, '.local', 'share'), 'local-decider')
229
+ );
230
+ }
231
+
232
+ function ensurePrivateDir(path: string, fs: LauncherFs, uid: number): void {
233
+ let fd: number | undefined;
234
+ try {
235
+ fs.mkdirSync(path, { recursive: true, mode: 0o700 });
236
+ fd = fs.openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
237
+ const stat = fs.fstatSync(fd);
238
+ if (!stat.isDirectory() || stat.uid !== uid || (stat.mode & 0o022) !== 0) {
239
+ throw new UnsafePathError(path);
240
+ }
241
+ } catch (error) {
242
+ if (error instanceof UnsafePathError) throw error;
243
+ throw new UnsafePathError(path);
244
+ } finally {
245
+ if (fd !== undefined) fs.closeSync(fd);
246
+ }
247
+ }
248
+
249
+ class UnsafePathError extends Error {
250
+ constructor(path: string) {
251
+ super(`unsafe private directory: ${path}`);
252
+ }
253
+ }
254
+
255
+ function privateDirectories(data: string, fs: LauncherFs, uid: number): DataPaths {
256
+ const paths = {
257
+ data,
258
+ run: join(data, 'run'),
259
+ logs: join(data, 'logs'),
260
+ gateway: join(data, 'gateway'),
261
+ };
262
+ for (const path of Object.values(paths)) ensurePrivateDir(path, fs, uid);
263
+ return paths;
264
+ }
265
+
266
+ function absolutePath(value: string | undefined): value is string {
267
+ return value !== undefined && value !== '' && isAbsolute(value);
268
+ }
269
+
270
+ function pathEntries(env: NodeJS.ProcessEnv): string[] {
271
+ const fromPath = (env['PATH'] ?? '')
272
+ .split(delimiter)
273
+ .filter((entry) => entry !== '' && isAbsolute(entry));
274
+ return [...fromPath, '/opt/homebrew/bin', '/usr/local/bin'];
275
+ }
276
+
277
+ function readableFile(path: string, fs: LauncherFs): boolean {
278
+ let fd: number | undefined;
279
+ try {
280
+ fd = fs.openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
281
+ if (!fs.fstatSync(fd).isFile()) return false;
282
+ if (['.js', '.mjs', '.cjs'].includes(extname(path))) return true;
283
+ const firstLine = fs.readFileSync(fd, 'utf8').split(/\r?\n/, 1)[0] ?? '';
284
+ return /^#!.*\bnode(?:\s|$)/i.test(firstLine);
285
+ } catch {
286
+ return false;
287
+ } finally {
288
+ if (fd !== undefined) fs.closeSync(fd);
289
+ }
290
+ }
291
+
292
+ function findCli(options: LaunchOptions, data: string, fs: LauncherFs): string | null {
293
+ const managed = join(
294
+ data,
295
+ 'gateway',
296
+ options.pinnedVersion,
297
+ 'node_modules',
298
+ '@ziptie-soft',
299
+ 'local-decider',
300
+ 'dist',
301
+ 'cli.js',
302
+ );
303
+ const candidates = [
304
+ ...(absolutePath(options.env['LOCAL_DECIDER_BIN']) ? [options.env['LOCAL_DECIDER_BIN']] : []),
305
+ managed,
306
+ ...pathEntries(options.env).map((entry) => join(entry, 'local-decider')),
307
+ ];
308
+ for (const candidate of candidates) {
309
+ let resolved: string;
310
+ try {
311
+ resolved = fs.realpathSync(candidate);
312
+ } catch {
313
+ // Keep searching; a dangling or unreadable executable is not an installation.
314
+ continue;
315
+ }
316
+ if (readableFile(resolved, fs)) return resolved;
317
+ }
318
+ return null;
319
+ }
320
+
321
+ function parseVersion(value: string): [number, number, number] | null {
322
+ const found = /^v?(\d+)\.(\d+)\.(\d+)/.exec(value.trim());
323
+ if (found === null) return null;
324
+ return [Number(found[1]), Number(found[2]), Number(found[3])];
325
+ }
326
+
327
+ function supportedNode(version: string): boolean {
328
+ const found = parseVersion(version);
329
+ if (found === null) return false;
330
+ return (
331
+ found[0] > 24 || (found[0] === 24 && found[1] > 15) || (found[0] === 24 && found[1] === 15)
332
+ );
333
+ }
334
+
335
+ async function checkNode(
336
+ file: string,
337
+ cwd: string,
338
+ env: NodeJS.ProcessEnv,
339
+ run: ExecFile,
340
+ ): Promise<string | null> {
341
+ try {
342
+ const { stdout, error } = await run(file, ['--version'], {
343
+ cwd,
344
+ env,
345
+ timeout: 5000,
346
+ windowsHide: true,
347
+ maxBuffer: 4096,
348
+ });
349
+ return error === undefined && supportedNode(stdout) ? file : null;
350
+ } catch {
351
+ return null;
352
+ }
353
+ }
354
+
355
+ function cleanEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
356
+ const child = { ...env };
357
+ delete child['NODE_OPTIONS'];
358
+ delete child['NODE_PATH'];
359
+ return child;
360
+ }
361
+
362
+ async function findNode(
363
+ options: LaunchOptions,
364
+ cwd: string,
365
+ run: ExecFile,
366
+ deps: LauncherDeps,
367
+ ): Promise<string | null> {
368
+ const runtimeIsNode =
369
+ (deps.nodeReleaseName ?? process.release.name) === 'node' &&
370
+ (deps.electronVersion ?? process.versions['electron']) === undefined;
371
+ const execPath = deps.execPath ?? process.execPath;
372
+ if (runtimeIsNode && supportedNode(deps.nodeVersion ?? process.versions.node)) return execPath;
373
+ const env = cleanEnv(options.env);
374
+ for (const dir of pathEntries(options.env)) {
375
+ const candidate = join(dir, 'node');
376
+ if (!isAbsolute(candidate)) continue;
377
+ const found = await checkNode(candidate, cwd, env, run);
378
+ if (found !== null) return found;
379
+ }
380
+ return null;
381
+ }
382
+
383
+ function npmCli(node: string): string {
384
+ const prefix = dirname(dirname(node));
385
+ return join(prefix, 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js');
386
+ }
387
+
388
+ function readJsonFile(path: string, fs: LauncherFs): unknown {
389
+ let fd: number | undefined;
390
+ try {
391
+ fd = fs.openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
392
+ if (!fs.fstatSync(fd).isFile()) return null;
393
+ return JSON.parse(fs.readFileSync(fd, 'utf8')) as unknown;
394
+ } catch {
395
+ return null;
396
+ } finally {
397
+ if (fd !== undefined) fs.closeSync(fd);
398
+ }
399
+ }
400
+
401
+ function installVerified(root: string, version: string, fs: LauncherFs): boolean {
402
+ const packageDir = join(root, 'node_modules', '@ziptie-soft', 'local-decider');
403
+ const manifest = readJsonFile(join(packageDir, 'package.json'), fs);
404
+ return (
405
+ record(manifest) &&
406
+ manifest['version'] === version &&
407
+ readableFile(join(packageDir, 'dist', 'cli.js'), fs)
408
+ );
409
+ }
410
+
411
+ async function registryAge(
412
+ version: string,
413
+ now: number,
414
+ fetcher: typeof fetch,
415
+ ): Promise<'ok' | 'too-new' | 'not-published'> {
416
+ try {
417
+ const response = await fetcher(REGISTRY, {
418
+ method: 'GET',
419
+ redirect: 'error',
420
+ signal: AbortSignal.timeout(10_000),
421
+ });
422
+ if (!response.ok) return 'not-published';
423
+ const metadata: unknown = await response.json();
424
+ const time =
425
+ record(metadata) && record(metadata['time']) ? metadata['time'][version] : undefined;
426
+ if (typeof time !== 'string' || !Number.isFinite(Date.parse(time))) return 'not-published';
427
+ return now - Date.parse(time) >= INSTALL_AGE_MS ? 'ok' : 'too-new';
428
+ } catch {
429
+ return 'not-published';
430
+ }
431
+ }
432
+
433
+ function createStage(gatewayDir: string, fs: LauncherFs, random: () => string): string {
434
+ for (let attempt = 0; attempt < 5; attempt++) {
435
+ const stage = join(gatewayDir, `.tmp-${random()}`);
436
+ try {
437
+ fs.mkdirSync(stage, { mode: 0o700 });
438
+ return stage;
439
+ } catch (error) {
440
+ if (!record(error) || error['code'] !== 'EEXIST') throw error;
441
+ }
442
+ }
443
+ throw new Error('could not create a unique gateway install stage');
444
+ }
445
+
446
+ function stageDirs(stage: string, fs: LauncherFs, uid: number): void {
447
+ for (const path of ['home', 'tmp', 'cache']) ensurePrivateDir(join(stage, path), fs, uid);
448
+ }
449
+
450
+ function installAgeResult(
451
+ age: 'ok' | 'too-new' | 'not-published',
452
+ options: LaunchOptions,
453
+ ): LaunchResult | null {
454
+ if (age === 'ok') return null;
455
+ if (age === 'too-new') {
456
+ return result(
457
+ 'too-new',
458
+ 'the pinned gateway release is younger than 72 hours',
459
+ null,
460
+ options.guideUrl,
461
+ );
462
+ }
463
+ return result(
464
+ 'not-published',
465
+ 'the pinned gateway release could not be verified in npm registry metadata',
466
+ null,
467
+ options.guideUrl,
468
+ );
469
+ }
470
+
471
+ async function executeNpmInstall(
472
+ options: LaunchOptions,
473
+ stage: string,
474
+ node: string,
475
+ npm: string,
476
+ now: number,
477
+ run: ExecFile,
478
+ ): Promise<LaunchResult | null> {
479
+ const environment: NodeJS.ProcessEnv = {
480
+ HOME: join(stage, 'home'),
481
+ PATH: dirname(node),
482
+ TMPDIR: join(stage, 'tmp'),
483
+ LANG: 'C',
484
+ LC_ALL: 'C',
485
+ };
486
+ const cutoff = new Date(now - INSTALL_AGE_MS).toISOString();
487
+ const args = [
488
+ npm,
489
+ 'install',
490
+ '--prefix',
491
+ stage,
492
+ '--no-save',
493
+ '--ignore-scripts',
494
+ '--omit=dev',
495
+ '--omit=optional',
496
+ '--no-audit',
497
+ '--no-fund',
498
+ '--no-package-lock',
499
+ `--registry=${REGISTRY_ROOT}`,
500
+ `--userconfig=${join(stage, 'user.npmrc')}`,
501
+ `--globalconfig=${join(stage, 'global.npmrc')}`,
502
+ `--cache=${join(stage, 'cache')}`,
503
+ '--strict-ssl=true',
504
+ `--before=${cutoff}`,
505
+ `@ziptie-soft/local-decider@${options.pinnedVersion}`,
506
+ ];
507
+ const installed = await run(node, args, {
508
+ cwd: stage,
509
+ env: environment,
510
+ timeout: INSTALL_TIMEOUT_MS,
511
+ windowsHide: true,
512
+ maxBuffer: 1024 * 1024,
513
+ });
514
+ return installed.error === undefined
515
+ ? null
516
+ : result('failed', 'npm failed while installing the pinned gateway', null, options.guideUrl);
517
+ }
518
+
519
+ function discardInstallPrivateFiles(stage: string, fs: LauncherFs): void {
520
+ for (const path of ['home', 'tmp', 'cache', 'user.npmrc', 'global.npmrc']) {
521
+ fs.rmSync(join(stage, path), { recursive: true, force: true });
522
+ }
523
+ }
524
+
525
+ function promoteInstall(
526
+ stage: string,
527
+ destination: string,
528
+ version: string,
529
+ fs: LauncherFs,
530
+ guideUrl: string,
531
+ ): LaunchResult | null {
532
+ if (!installVerified(stage, version, fs)) {
533
+ return result(
534
+ 'failed',
535
+ 'npm completed but the installed gateway did not match the pinned version',
536
+ null,
537
+ guideUrl,
538
+ );
539
+ }
540
+ try {
541
+ fs.renameSync(stage, destination);
542
+ return null;
543
+ } catch {
544
+ return installVerified(destination, version, fs)
545
+ ? null
546
+ : result(
547
+ 'failed',
548
+ 'could not publish the verified staged gateway installation',
549
+ null,
550
+ guideUrl,
551
+ );
552
+ }
553
+ }
554
+
555
+ async function installGateway(
556
+ options: LaunchOptions,
557
+ dirs: DataPaths,
558
+ node: string,
559
+ fs: LauncherFs,
560
+ run: ExecFile,
561
+ deps: LauncherDeps,
562
+ ): Promise<LaunchResult | null> {
563
+ const now = (deps.now ?? Date.now)();
564
+ const age = await registryAge(options.pinnedVersion, now, deps.fetch ?? globalThis.fetch);
565
+ const ageResult = installAgeResult(age, options);
566
+ if (ageResult !== null) return ageResult;
567
+ const npm = npmCli(node);
568
+ if (!readableFile(npm, fs)) {
569
+ return result(
570
+ 'failed',
571
+ 'npm-cli.js was not found beside the selected Node installation',
572
+ null,
573
+ options.guideUrl,
574
+ );
575
+ }
576
+ const stage = createStage(
577
+ dirs.gateway,
578
+ fs,
579
+ deps.random ?? (() => randomBytes(16).toString('hex')),
580
+ );
581
+ try {
582
+ const uid =
583
+ deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : userInfo().uid);
584
+ ensurePrivateDir(stage, fs, uid);
585
+ stageDirs(stage, fs, uid);
586
+ const destination = join(dirs.gateway, options.pinnedVersion);
587
+ const installResult = await executeNpmInstall(options, stage, node, npm, now, run);
588
+ if (installResult !== null) return installResult;
589
+ discardInstallPrivateFiles(stage, fs);
590
+ return promoteInstall(stage, destination, options.pinnedVersion, fs, options.guideUrl);
591
+ } catch (error) {
592
+ return result(
593
+ 'failed',
594
+ error instanceof Error ? error.message : 'gateway installation failed',
595
+ null,
596
+ options.guideUrl,
597
+ );
598
+ } finally {
599
+ fs.rmSync(stage, { recursive: true, force: true });
600
+ }
601
+ }
602
+
603
+ async function probe(
604
+ url: string,
605
+ fetcher: typeof fetch,
606
+ clientId: string,
607
+ ): Promise<EngineStatus | null> {
608
+ try {
609
+ const response = await fetcher(new URL('/health', url), {
610
+ method: 'GET',
611
+ redirect: 'error',
612
+ headers: { 'x-local-decider-client': clientId },
613
+ signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
614
+ });
615
+ const value: unknown = await response.json();
616
+ return record(value) && typeof value['status'] === 'string' ? engineStatus(value) : null;
617
+ } catch {
618
+ return null;
619
+ }
620
+ }
621
+
622
+ function logAttempt(data: string, status: LaunchStatus, fs: LauncherFs, now: number): void {
623
+ let fd: number | undefined;
624
+ try {
625
+ fd = fs.openSync(
626
+ join(data, 'logs', 'launcher.log'),
627
+ constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW,
628
+ 0o600,
629
+ );
630
+ fs.fchmodSync(fd, 0o600);
631
+ if (fs.fstatSync(fd).size > LOG_LIMIT) {
632
+ fs.ftruncateSync(fd, 0);
633
+ }
634
+ fs.writeSync(fd, `${new Date(now).toISOString()} ${status}\n`);
635
+ } catch {
636
+ // Logging must never block a client launch.
637
+ } finally {
638
+ if (fd !== undefined) fs.closeSync(fd);
639
+ }
640
+ }
641
+
642
+ function fromEnsure(output: string, guideUrl: string): LaunchResult {
643
+ const lines = output.trim().split(/\r?\n/);
644
+ if (lines.length !== 1)
645
+ return result('failed', 'gateway ensure returned an invalid response', null, guideUrl);
646
+ try {
647
+ const value: unknown = JSON.parse(lines[0] ?? '');
648
+ if (
649
+ !record(value) ||
650
+ typeof value['listener'] !== 'string' ||
651
+ typeof value['message'] !== 'string'
652
+ ) {
653
+ return result('failed', 'gateway ensure returned an invalid response', null, guideUrl);
654
+ }
655
+ const status = value['listener'] as LaunchStatus;
656
+ const known: readonly string[] = [
657
+ 'running',
658
+ 'started',
659
+ 'service-started',
660
+ 'legacy',
661
+ 'remote',
662
+ 'port-busy',
663
+ 'mismatch',
664
+ 'stopped',
665
+ 'unsafe-path',
666
+ 'failed',
667
+ ];
668
+ if (!known.includes(status))
669
+ return result('failed', 'gateway ensure returned an unknown status', null, guideUrl);
670
+ const engine =
671
+ record(value['engine']) && typeof value['engine']['status'] === 'string'
672
+ ? engineStatus(value['engine'])
673
+ : null;
674
+ return result(status, value['message'], engine, guideUrl);
675
+ } catch {
676
+ return result('failed', 'gateway ensure returned an invalid response', null, guideUrl);
677
+ }
678
+ }
679
+
680
+ function manualInstall(options: LaunchOptions): LaunchResult {
681
+ return result(
682
+ 'not-installed',
683
+ `gateway is not installed; run: npm install -g @ziptie-soft/local-decider@${options.pinnedVersion}, then ${MANUAL_START}`,
684
+ null,
685
+ options.guideUrl,
686
+ );
687
+ }
688
+
689
+ interface LaunchAttempt {
690
+ readonly result: LaunchResult;
691
+ readonly data: string;
692
+ readonly logSafe: boolean;
693
+ }
694
+
695
+ function canLog(data: string, fs: LauncherFs, uid: number): boolean {
696
+ try {
697
+ privateDirectories(data, fs, uid);
698
+ return true;
699
+ } catch {
700
+ return false;
701
+ }
702
+ }
703
+
704
+ function failedLaunch(error: unknown, guideUrl: string): LaunchResult {
705
+ const message = error instanceof Error ? error.message : 'gateway launcher failed';
706
+ const status = message.includes('unsafe private directory') ? 'unsafe-path' : 'failed';
707
+ return result(status, message, null, guideUrl);
708
+ }
709
+
710
+ async function quickOutcome(
711
+ options: LaunchOptions,
712
+ deps: LauncherDeps,
713
+ ): Promise<LaunchResult | null> {
714
+ const autostart = options.env['LOCAL_DECIDER_AUTOSTART']?.toLowerCase();
715
+ if (autostart === '0' || autostart === 'off' || autostart === 'false') {
716
+ return result('disabled', 'gateway auto-start is disabled');
717
+ }
718
+ if (!isLoopbackUrl(options.url)) {
719
+ return result('remote', 'gateway URL is not loopback; remote gateways are never started');
720
+ }
721
+ const useSocket = isDefaultEndpoint(options);
722
+ const clientId = options.clientId ?? 'launcher/0.0.0';
723
+ const runDir = join(dataDirectory(options, deps), 'run');
724
+ const path = useSocket ? gatewaySocketPath(runDir) : null;
725
+ return probeExistingGateway(options, deps, path, clientId);
726
+ }
727
+
728
+ async function probeExistingGateway(
729
+ options: LaunchOptions,
730
+ deps: LauncherDeps,
731
+ path: string | null,
732
+ clientId: string,
733
+ ): Promise<LaunchResult | null> {
734
+ const fetcher = deps.fetch ?? (path === null ? globalThis.fetch : socketFetch(path));
735
+ const foundHealth = await probe(options.url, fetcher, clientId);
736
+ if (foundHealth !== null) return result('running', 'gateway is answering /health', foundHealth);
737
+ if (path === null || deps.fetch !== undefined) return null;
738
+ const tcpHealth = await probe(options.url, globalThis.fetch, clientId);
739
+ if (tcpHealth === null) return null;
740
+ if (tcpHealth.instance === undefined) {
741
+ return result(
742
+ 'legacy',
743
+ `an older gateway runs on :${new URL(options.url).port || '8765'} without a socket; run \`local-decider gateway restart\``,
744
+ );
745
+ }
746
+ return result('failed', 'gateway answers TCP but its default Unix socket is unavailable');
747
+ }
748
+
749
+ interface PreparedGateway {
750
+ readonly cli: string;
751
+ readonly node: string;
752
+ readonly runDir: string;
753
+ }
754
+
755
+ async function prepareGateway(
756
+ options: LaunchOptions,
757
+ paths: DataPaths,
758
+ fs: LauncherFs,
759
+ deps: LauncherDeps,
760
+ run: ExecFile,
761
+ ): Promise<PreparedGateway | LaunchResult> {
762
+ let cli = findCli(options, paths.data, fs);
763
+ let node: string | null = null;
764
+ if (cli === null && options.env['LOCAL_DECIDER_AUTOINSTALL'] === '1') {
765
+ node = await findNode(options, paths.run, run, deps);
766
+ if (node === null) {
767
+ return result(
768
+ 'failed',
769
+ 'Node.js 24.15 or newer is required to install the gateway',
770
+ null,
771
+ options.guideUrl,
772
+ );
773
+ }
774
+ const installed = await installGateway(options, paths, node, fs, run, deps);
775
+ if (installed !== null) return installed;
776
+ cli = findCli(options, paths.data, fs);
777
+ }
778
+ if (cli === null) return manualInstall(options);
779
+ node ??= await findNode(options, paths.run, run, deps);
780
+ if (node === null) {
781
+ return result(
782
+ 'failed',
783
+ 'Node.js 24.15 or newer is required to start the gateway',
784
+ null,
785
+ options.guideUrl,
786
+ );
787
+ }
788
+ return { cli, node, runDir: paths.run };
789
+ }
790
+
791
+ async function ensureGateway(
792
+ options: LaunchOptions,
793
+ prepared: PreparedGateway,
794
+ run: ExecFile,
795
+ ): Promise<LaunchResult> {
796
+ const defaultEndpoint = isDefaultEndpoint(options);
797
+ const url = defaultEndpoint ? null : ensureArgumentUrl(options.url);
798
+ if (!defaultEndpoint && url === null)
799
+ return result(
800
+ 'failed',
801
+ 'gateway URL cannot be passed safely to the gateway CLI',
802
+ null,
803
+ options.guideUrl,
804
+ );
805
+ const args = [prepared.cli, 'gateway', 'ensure'];
806
+ if (url !== null) args.push('--url', url);
807
+ args.push('--json');
808
+ const executed = await run(prepared.node, args, {
809
+ cwd: prepared.runDir,
810
+ env: cleanEnv(options.env),
811
+ timeout: ENSURE_TIMEOUT_MS,
812
+ windowsHide: true,
813
+ maxBuffer: 64 * 1024,
814
+ });
815
+ if (executed.error?.killed === true) {
816
+ return result(
817
+ 'failed',
818
+ 'gateway ensure exceeded its 45 second timeout',
819
+ null,
820
+ options.guideUrl,
821
+ );
822
+ }
823
+ return fromEnsure(executed.stdout, options.guideUrl);
824
+ }
825
+
826
+ function ensureArgumentUrl(value: string): string | null {
827
+ try {
828
+ const url = new URL(value);
829
+ if (
830
+ (url.protocol !== 'http:' && url.protocol !== 'https:') ||
831
+ url.username !== '' ||
832
+ url.password !== ''
833
+ ) {
834
+ return null;
835
+ }
836
+ return url.origin;
837
+ } catch {
838
+ return null;
839
+ }
840
+ }
841
+
842
+ async function performAttempt(
843
+ options: LaunchOptions,
844
+ deps: LauncherDeps,
845
+ fs: LauncherFs,
846
+ ): Promise<LaunchAttempt> {
847
+ const quick = await quickOutcome(options, deps);
848
+ const data = dataDirectory(options, deps);
849
+ const uid =
850
+ deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : userInfo().uid);
851
+ if (quick !== null) return { result: quick, data, logSafe: canLog(data, fs, uid) };
852
+ let logSafe = false;
853
+ try {
854
+ const dirs = privateDirectories(data, fs, uid);
855
+ logSafe = true;
856
+ const run = deps.execFile ?? execFile;
857
+ const prepared = await prepareGateway(options, dirs, fs, deps, run);
858
+ if ('status' in prepared) return { result: prepared, data, logSafe };
859
+ return { result: await ensureGateway(options, prepared, run), data, logSafe };
860
+ } catch (error) {
861
+ return { result: failedLaunch(error, options.guideUrl), data, logSafe };
862
+ }
863
+ }
864
+
865
+ /**
866
+ * Probe, locate (or opt-in install), and ask the gateway CLI to ensure its configured listener.
867
+ * All failures are returned as values so callers can preserve their normal fail-open behavior.
868
+ */
869
+ export async function launchGateway(options: LaunchOptions): Promise<LaunchResult> {
870
+ const deps = options.deps ?? {};
871
+ const fs = deps.fs ?? defaultFs;
872
+ const now = (deps.now ?? Date.now)();
873
+ let attempt: LaunchAttempt = {
874
+ result: result('failed', 'gateway launcher failed', null, options.guideUrl),
875
+ data: '',
876
+ logSafe: false,
877
+ };
878
+ try {
879
+ attempt = await performAttempt(options, deps, fs);
880
+ } catch (error) {
881
+ attempt = { result: failedLaunch(error, options.guideUrl), data: '', logSafe: false };
882
+ } finally {
883
+ if (attempt.logSafe) {
884
+ try {
885
+ logAttempt(attempt.data, attempt.result.status, fs, now);
886
+ } catch {
887
+ // A log failure must not escape the launch API.
888
+ }
889
+ }
890
+ }
891
+ return attempt.result;
892
+ }