@jmanuelcorral/bond-app 0.1.6 → 0.2.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.
package/src/cli.ts CHANGED
@@ -8,7 +8,6 @@
8
8
  * - --version, --help.
9
9
  */
10
10
  import fs from 'node:fs';
11
- import os from 'node:os';
12
11
  import path from 'node:path';
13
12
  import http from 'node:http';
14
13
  import { spawn, execFileSync } from 'node:child_process';
@@ -18,22 +17,54 @@ import { bootstrap } from './index.ts';
18
17
  import type { ServerHooks } from './server/app.ts';
19
18
  import { MIN_HC_VERSION, MIN_HERDR_APP_VERSION } from './runner/hc-client.ts';
20
19
  import { install, parseInstallArgs, removeLauncher } from '../scripts/app-install.ts';
20
+ import { runDoctor, type DoctorDeps, type DoctorReport } from './core/doctor.ts';
21
+ import {
22
+ maybeHandleFirstRun,
23
+ runSetup,
24
+ runUninstall,
25
+ runUpdate,
26
+ warnFirstRunIfNeeded,
27
+ type SetupDeps,
28
+ } from './core/setup-install.ts';
29
+ import {
30
+ getServiceStatus,
31
+ installService,
32
+ restartService,
33
+ startService,
34
+ stopService,
35
+ uninstallService,
36
+ type ServiceAction,
37
+ type ServiceDeps,
38
+ } from './core/service.ts';
39
+ import { defaultDataDir, defaultHerdrAppHome, defaultLauncherDataHome } from './core/paths.ts';
40
+ import { restrictPathSync } from './core/permissions.ts';
21
41
 
22
42
  const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
23
43
  const pkgJson = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8'));
24
44
  export const VERSION = pkgJson.version as string;
25
45
 
26
- export function findExecutable(name: string, customPath?: string): string | null {
46
+ export function findExecutable(
47
+ name: string,
48
+ customPath?: string,
49
+ platform: NodeJS.Platform = process.platform
50
+ ): string | null {
27
51
  const pathEnv = customPath ?? process.env.PATH ?? '';
52
+ const candidates =
53
+ platform === 'win32' && !/\.(exe|cmd|bat)$/i.test(name)
54
+ ? [`${name}.exe`, `${name}.cmd`, name]
55
+ : [name];
56
+ const mode = platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK;
28
57
  for (const dir of pathEnv.split(path.delimiter)) {
29
58
  if (!dir || !path.isAbsolute(dir)) continue;
30
- const full = path.join(dir, name);
31
- try {
32
- fs.accessSync(full, fs.constants.X_OK);
33
- const st = fs.statSync(full);
34
- if (st.isFile()) return full;
35
- } catch {
36
- // not executable or does not exist
59
+ for (const candidate of candidates) {
60
+ const full = path.join(dir, candidate);
61
+ try {
62
+ fs.accessSync(full, mode);
63
+ const st = fs.statSync(full);
64
+ if (st.isFile()) return full;
65
+ } catch {
66
+ // not executable or does not exist
67
+ }
37
68
  }
38
69
  }
39
70
  return null;
@@ -219,6 +250,11 @@ export function relaunchSelf(dataDir: string, spawnFn: typeof spawn = spawn): nu
219
250
  fs.mkdirSync(dataDir, { recursive: true });
220
251
  const logPath = path.join(dataDir, 'orchestrator.log');
221
252
  const fd = fs.openSync(logPath, 'a', 0o600);
253
+ try {
254
+ restrictPathSync(logPath, 0o600);
255
+ } catch {
256
+ // ignore permission errors
257
+ }
222
258
  try {
223
259
  const child = spawnFn(process.execPath, [...process.execArgv, ...process.argv.slice(1)], {
224
260
  detached: true,
@@ -237,7 +273,8 @@ export function relaunchSelf(dataDir: string, spawnFn: typeof spawn = spawn): nu
237
273
  export async function handleStart(
238
274
  args: string[],
239
275
  bootstrapFn: (overrides?: any, hooks?: ServerHooks) => Promise<{ server: any; orchestrator: any; port: number }> = bootstrap,
240
- relaunchFn: (dataDir: string) => unknown = relaunchSelf
276
+ relaunchFn: (dataDir: string) => unknown = relaunchSelf,
277
+ setupDeps?: SetupDeps
241
278
  ): Promise<number> {
242
279
  const overrides: Record<string, any> = {};
243
280
  for (let i = 0; i < args.length; i++) {
@@ -262,6 +299,50 @@ export async function handleStart(
262
299
  }
263
300
  }
264
301
 
302
+ const isTTY = setupDeps?.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
303
+ if (isTTY) {
304
+ const firstRun = await maybeHandleFirstRun({
305
+ fromStart: true,
306
+ dataDir: overrides.dataDir,
307
+ deps: setupDeps,
308
+ });
309
+ if (firstRun.ranSetup && !firstRun.setupOk) {
310
+ return 1;
311
+ }
312
+ } else {
313
+ warnFirstRunIfNeeded({ dataDir: overrides.dataDir, deps: setupDeps });
314
+ }
315
+
316
+ const startPort = overrides.port ?? parseInt(process.env.BOND_APP_PORT || '3000', 10);
317
+ const startHost = overrides.host ?? process.env.BOND_APP_HOST ?? '127.0.0.1';
318
+ const startDataDir =
319
+ overrides.dataDir ?? process.env.BOND_APP_DATA_DIR ?? defaultDataDir();
320
+
321
+ if (bootstrapFn === bootstrap || setupDeps?.serviceDeps || setupDeps?.checkHealth) {
322
+ const svcStatus = await getServiceStatus({
323
+ port: startPort,
324
+ host: startHost,
325
+ dataDir: startDataDir,
326
+ deps: setupDeps?.serviceDeps,
327
+ });
328
+ if (svcStatus.active) {
329
+ console.error(
330
+ `bond-app: port ${startPort} is already in use by the bond-app user service (${svcStatus.serviceName}).`
331
+ );
332
+ console.error('Stop it first with: bond-app service stop');
333
+ return 1;
334
+ }
335
+
336
+ const checkHealthFn = setupDeps?.checkHealth ?? checkHttpHealth;
337
+ const existingHealth = await checkHealthFn(startHost, startPort, 1000).catch(() => ({ ok: false }));
338
+ if (existingHealth.ok) {
339
+ console.error(
340
+ `bond-app: port ${startPort} is already in use by a running orchestrator at http://${startHost}:${startPort}.`
341
+ );
342
+ return 1;
343
+ }
344
+ }
345
+
265
346
  return new Promise<number>((resolve, reject) => {
266
347
  let shuttingDown = false;
267
348
  let restartRequested = false;
@@ -310,8 +391,7 @@ export async function handleStart(
310
391
  if (restartRequested) {
311
392
  const dataDir = orchestratorInstance?.config?.dataDir
312
393
  || overrides.dataDir
313
- || process.env.BOND_APP_DATA_DIR
314
- || path.join(os.homedir(), '.bond-app');
394
+ || defaultDataDir();
315
395
  try {
316
396
  relaunchFn(dataDir);
317
397
  } catch (err: any) {
@@ -357,10 +437,7 @@ export async function handleInstall(args: string[]): Promise<number> {
357
437
  }
358
438
 
359
439
  if (args.includes('--remove-launcher')) {
360
- const dataHome =
361
- process.env.XDG_DATA_HOME && path.isAbsolute(process.env.XDG_DATA_HOME)
362
- ? process.env.XDG_DATA_HOME
363
- : path.join(os.homedir(), '.local', 'share');
440
+ const dataHome = defaultLauncherDataHome();
364
441
  const { removed, kept } = removeLauncher(dataHome);
365
442
  console.log(
366
443
  removed.length
@@ -418,8 +495,8 @@ export async function handleOpen(args: string[]): Promise<number> {
418
495
  export async function handleStatus(args: string[]): Promise<number> {
419
496
  let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
420
497
  let host = process.env.BOND_APP_HOST || '127.0.0.1';
421
- let dataDir = process.env.BOND_APP_DATA_DIR || path.join(os.homedir(), '.bond-app');
422
- let home = process.env.HERDR_APP_HOME || path.join(os.homedir(), '.config', 'herdr-app');
498
+ let dataDir = defaultDataDir();
499
+ let home = defaultHerdrAppHome();
423
500
  let json = false;
424
501
 
425
502
  for (let i = 0; i < args.length; i++) {
@@ -472,14 +549,316 @@ export async function handleStatus(args: string[]): Promise<number> {
472
549
  return res.running ? 0 : 1;
473
550
  }
474
551
 
552
+ export async function handleDoctor(args: string[], deps?: DoctorDeps): Promise<number> {
553
+ let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
554
+ let host = process.env.BOND_APP_HOST || '127.0.0.1';
555
+ let dataDir = defaultDataDir();
556
+ let home = defaultHerdrAppHome();
557
+ let runnerImage: string | undefined = undefined;
558
+ let json = false;
559
+
560
+ for (let i = 0; i < args.length; i++) {
561
+ const arg = args[i];
562
+ if (arg === '--port') {
563
+ const v = args[++i];
564
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
565
+ port = parseInt(v, 10);
566
+ } else if (arg === '--host') {
567
+ const v = args[++i];
568
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
569
+ host = v;
570
+ } else if (arg === '--data-dir') {
571
+ const v = args[++i];
572
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
573
+ dataDir = path.resolve(v);
574
+ } else if (arg === '--home') {
575
+ const v = args[++i];
576
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
577
+ home = path.resolve(v);
578
+ } else if (arg === '--image') {
579
+ const v = args[++i];
580
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
581
+ runnerImage = v;
582
+ } else if (arg === '--json') {
583
+ json = true;
584
+ } else if (arg === '-h' || arg === '--help') {
585
+ printDoctorHelp();
586
+ return 0;
587
+ } else {
588
+ throw new Error(`unknown option '${arg}' for doctor`);
589
+ }
590
+ }
591
+
592
+ const report: DoctorReport = await runDoctor({ port, host, dataDir, home, runnerImage, deps });
593
+
594
+ if (json) {
595
+ console.log(JSON.stringify(report, null, 2));
596
+ return report.ok ? 0 : 1;
597
+ }
598
+
599
+ console.log(`bond-app doctor (${report.platform})`);
600
+ for (const c of report.checks) {
601
+ const icon = c.status === 'ok' ? '✓' : c.status === 'warn' ? '!' : '✗';
602
+ console.log(` ${icon} ${c.name}: ${c.detail}`);
603
+ if (c.fix) {
604
+ console.log(` fix: ${c.fix}`);
605
+ }
606
+ }
607
+ console.log(`Summary: ${report.summary.ok} ok, ${report.summary.warn} warn, ${report.summary.fail} fail`);
608
+
609
+ return report.ok ? 0 : 1;
610
+ }
611
+
612
+ export async function handleSetup(args: string[], deps?: SetupDeps): Promise<number> {
613
+ let yes = false;
614
+ let noLauncher = false;
615
+ let noService = false;
616
+ let dryRun = false;
617
+ let port: number | undefined = undefined;
618
+ let host: string | undefined = undefined;
619
+ let dataDir: string | undefined = undefined;
620
+ let home: string | undefined = undefined;
621
+ let runnerImage: string | undefined = undefined;
622
+
623
+ for (let i = 0; i < args.length; i++) {
624
+ const arg = args[i];
625
+ if (arg === '--yes' || arg === '-y') {
626
+ yes = true;
627
+ } else if (arg === '--no-launcher') {
628
+ noLauncher = true;
629
+ } else if (arg === '--no-service') {
630
+ noService = true;
631
+ } else if (arg === '--dry-run') {
632
+ dryRun = true;
633
+ } else if (arg === '--port') {
634
+ const v = args[++i];
635
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
636
+ port = parseInt(v, 10);
637
+ } else if (arg === '--host') {
638
+ const v = args[++i];
639
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
640
+ host = v;
641
+ } else if (arg === '--data-dir') {
642
+ const v = args[++i];
643
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
644
+ dataDir = path.resolve(v);
645
+ } else if (arg === '--home') {
646
+ const v = args[++i];
647
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
648
+ home = path.resolve(v);
649
+ } else if (arg === '--image') {
650
+ const v = args[++i];
651
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
652
+ runnerImage = v;
653
+ } else if (arg === '-h' || arg === '--help') {
654
+ printSetupHelp();
655
+ return 0;
656
+ } else {
657
+ throw new Error(`unknown option '${arg}' for setup`);
658
+ }
659
+ }
660
+
661
+ const res = await runSetup({
662
+ yes,
663
+ noLauncher,
664
+ noService,
665
+ dryRun,
666
+ port,
667
+ host,
668
+ dataDir,
669
+ home,
670
+ runnerImage,
671
+ deps,
672
+ });
673
+ return res.ok ? 0 : 1;
674
+ }
675
+
676
+ export async function handleUpdate(args: string[], deps?: SetupDeps): Promise<number> {
677
+ let dryRun = false;
678
+ let port: number | undefined = undefined;
679
+ let host: string | undefined = undefined;
680
+ let dataDir: string | undefined = undefined;
681
+ let home: string | undefined = undefined;
682
+ let runnerImage: string | undefined = undefined;
683
+
684
+ for (let i = 0; i < args.length; i++) {
685
+ const arg = args[i];
686
+ if (arg === '--dry-run') {
687
+ dryRun = true;
688
+ } else if (arg === '--port') {
689
+ const v = args[++i];
690
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
691
+ port = parseInt(v, 10);
692
+ } else if (arg === '--host') {
693
+ const v = args[++i];
694
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
695
+ host = v;
696
+ } else if (arg === '--data-dir') {
697
+ const v = args[++i];
698
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
699
+ dataDir = path.resolve(v);
700
+ } else if (arg === '--home') {
701
+ const v = args[++i];
702
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
703
+ home = path.resolve(v);
704
+ } else if (arg === '--image') {
705
+ const v = args[++i];
706
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
707
+ runnerImage = v;
708
+ } else if (arg === '-h' || arg === '--help') {
709
+ printUpdateHelp();
710
+ return 0;
711
+ } else {
712
+ throw new Error(`unknown option '${arg}' for update`);
713
+ }
714
+ }
715
+
716
+ const res = await runUpdate({ dryRun, port, host, dataDir, home, runnerImage, deps });
717
+ return res.ok ? 0 : 1;
718
+ }
719
+
720
+ export async function handleUninstall(args: string[], deps?: SetupDeps): Promise<number> {
721
+ let purge = false;
722
+ let yes = false;
723
+ let dryRun = false;
724
+ let port: number | undefined = undefined;
725
+ let host: string | undefined = undefined;
726
+ let dataDir: string | undefined = undefined;
727
+ let home: string | undefined = undefined;
728
+
729
+ for (let i = 0; i < args.length; i++) {
730
+ const arg = args[i];
731
+ if (arg === '--purge') {
732
+ purge = true;
733
+ } else if (arg === '--yes' || arg === '-y') {
734
+ yes = true;
735
+ } else if (arg === '--dry-run') {
736
+ dryRun = true;
737
+ } else if (arg === '--port') {
738
+ const v = args[++i];
739
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
740
+ port = parseInt(v, 10);
741
+ } else if (arg === '--host') {
742
+ const v = args[++i];
743
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
744
+ host = v;
745
+ } else if (arg === '--data-dir') {
746
+ const v = args[++i];
747
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
748
+ dataDir = path.resolve(v);
749
+ } else if (arg === '--home') {
750
+ const v = args[++i];
751
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
752
+ home = path.resolve(v);
753
+ } else if (arg === '-h' || arg === '--help') {
754
+ printUninstallHelp();
755
+ return 0;
756
+ } else {
757
+ throw new Error(`unknown option '${arg}' for uninstall`);
758
+ }
759
+ }
760
+
761
+ const res = await runUninstall({ purge, yes, dryRun, port, host, dataDir, home, deps });
762
+ return res.ok ? 0 : 1;
763
+ }
764
+
765
+ export async function handleService(args: string[], deps?: ServiceDeps): Promise<number> {
766
+ if (args.length === 0 || args[0] === '-h' || args[0] === '--help') {
767
+ printServiceHelp();
768
+ return 0;
769
+ }
770
+
771
+ const sub = args[0] as ServiceAction;
772
+ const validActions: ServiceAction[] = ['status', 'install', 'start', 'stop', 'restart', 'uninstall'];
773
+ if (!validActions.includes(sub)) {
774
+ throw new Error(`unknown service action '${args[0]}' (expected: ${validActions.join('|')})`);
775
+ }
776
+
777
+ let port: number | undefined = undefined;
778
+ let host: string | undefined = undefined;
779
+ let dataDir: string | undefined = undefined;
780
+ let runnerImage: string | undefined = undefined;
781
+ let serviceName: string | undefined = undefined;
782
+ let json = false;
783
+
784
+ for (let i = 1; i < args.length; i++) {
785
+ const arg = args[i];
786
+ if (arg === '--port') {
787
+ const v = args[++i];
788
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
789
+ port = parseInt(v, 10);
790
+ } else if (arg === '--host') {
791
+ const v = args[++i];
792
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
793
+ host = v;
794
+ } else if (arg === '--data-dir') {
795
+ const v = args[++i];
796
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
797
+ dataDir = path.resolve(v);
798
+ } else if (arg === '--image') {
799
+ const v = args[++i];
800
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
801
+ runnerImage = v;
802
+ } else if (arg === '--name') {
803
+ const v = args[++i];
804
+ if (!v || v.startsWith('--')) throw new Error('--name requires a value');
805
+ serviceName = v;
806
+ } else if (arg === '--json') {
807
+ json = true;
808
+ } else if (arg === '-h' || arg === '--help') {
809
+ printServiceHelp();
810
+ return 0;
811
+ } else {
812
+ throw new Error(`unknown option '${arg}' for service ${sub}`);
813
+ }
814
+ }
815
+
816
+ const opts = { port, host, dataDir, runnerImage, serviceName, deps };
817
+
818
+ if (sub === 'status') {
819
+ const st = await getServiceStatus(opts);
820
+ if (json) {
821
+ console.log(JSON.stringify(st, null, 2));
822
+ return st.supported && st.active ? 0 : 1;
823
+ }
824
+ console.log(`bond-app service (${st.manager}): ${st.detail}`);
825
+ if (st.unitPath) console.log(` unit: ${st.unitPath}`);
826
+ console.log(` installed: ${st.installed ? 'yes' : 'no'}, active: ${st.active ? 'yes' : 'no'}`);
827
+ return st.supported && st.active ? 0 : 1;
828
+ }
829
+
830
+ const actionMap = {
831
+ install: installService,
832
+ start: startService,
833
+ stop: stopService,
834
+ restart: restartService,
835
+ uninstall: uninstallService,
836
+ } as const;
837
+
838
+ const res = await actionMap[sub](opts);
839
+ if (json) {
840
+ console.log(JSON.stringify(res, null, 2));
841
+ } else if (res.ok) {
842
+ console.log(`bond-app service ${sub}: ${res.detail}`);
843
+ } else {
844
+ console.error(`bond-app service ${sub}: ${res.detail}`);
845
+ }
846
+ return res.ok ? 0 : 1;
847
+ }
848
+
475
849
  export function printHelp(): void {
476
850
  console.log(`Usage: bond-app <command> [options]
477
851
 
478
852
  Commands:
853
+ setup Check requirements, install binaries/mods, prepare ~/.bond-app and open herdr-app
854
+ update Update bond-app and bond via npm, reinstall mods, restart service and check image
855
+ uninstall Remove service, bond-app mods/layout/themes and launcher (data only with --purge)
856
+ service Manage the orchestrator user service (status|install|start|stop|restart|uninstall)
479
857
  start Run the orchestrator in the foreground (default data dir: ~/.bond-app)
480
858
  install Install bond layout, mods and themes into herdr-app
481
859
  open Open herdr-app and switch to the bond layout
482
860
  status Check the status of the orchestrator and herdr-app integration
861
+ doctor Diagnose requirements, binaries, mods, data dir, orchestrator and image
483
862
 
484
863
  Options:
485
864
  -v, --version Show version number
@@ -546,9 +925,111 @@ Options:
546
925
  `);
547
926
  }
548
927
 
549
- export async function runCli(argv: string[]): Promise<number> {
928
+ function printDoctorHelp(): void {
929
+ console.log(`Usage: bond-app doctor [options]
930
+
931
+ Diagnose environment requirements without modifying anything.
932
+ Exits 0 if no essential check fails, 1 otherwise.
933
+
934
+ Options:
935
+ --port <port> Orchestrator port to query (default: 3000 or $BOND_APP_PORT)
936
+ --host <host> Orchestrator host to query (default: 127.0.0.1 or $BOND_APP_HOST)
937
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
938
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
939
+ --image <name> Runner image name (default: bond-app-runner:p5 or $RUNNER_IMAGE)
940
+ --json Output report in JSON format
941
+ -h, --help Show this help
942
+ `);
943
+ }
944
+
945
+ function printSetupHelp(): void {
946
+ console.log(`Usage: bond-app setup [options]
947
+
948
+ Idempotent installer: checks Node and Docker, installs/updates herdr-app and hc
949
+ (with sha256 verification), installs bond CLI and bond-app, installs layout/mods/themes,
950
+ prepares ~/.bond-app and token, checks runner image, opens herdr-app and writes setup.json.
951
+
952
+ Options:
953
+ --yes, -y Accept defaults without interactive prompts (installs desktop launcher and user service)
954
+ --no-launcher Skip installing the desktop launcher
955
+ --no-service Skip installing the orchestrator user service (run manually with bond-app start)
956
+ --dry-run Show what would be done without modifying anything
957
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
958
+ --host <host> Orchestrator host (default: 127.0.0.1 or $BOND_APP_HOST)
959
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
960
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
961
+ --image <name> Runner image name (default: bond-app-runner:p5 or $RUNNER_IMAGE)
962
+ -h, --help Show this help
963
+ `);
964
+ }
965
+
966
+ function printUpdateHelp(): void {
967
+ console.log(`Usage: bond-app update [options]
968
+
969
+ Update bond-app and bond via npm (public registry), reinstall layout/mods/themes,
970
+ restart the user service if installed, and warn if the runner image recipe is outdated.
971
+
972
+ Options:
973
+ --dry-run Show what would be done without modifying anything
974
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
975
+ --host <host> Orchestrator host (default: 127.0.0.1 or $BOND_APP_HOST)
976
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
977
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
978
+ --image <name> Runner image name (default: bond-app-runner:p5 or $RUNNER_IMAGE)
979
+ -h, --help Show this help
980
+ `);
981
+ }
982
+
983
+ function printUninstallHelp(): void {
984
+ console.log(`Usage: bond-app uninstall [options]
985
+
986
+ Remove the orchestrator user service, bond-app's layout/mods/themes and desktop launcher.
987
+ Preserves ~/.bond-app unless --purge is given. Never uninstalls herdr-app, hc or bond.
988
+
989
+ Options:
990
+ --purge Also remove ~/.bond-app (database, token and credentials)
991
+ --yes, -y Confirm --purge without prompting
992
+ --dry-run Show what would be done without modifying anything
993
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
994
+ --host <host> Orchestrator host (default: 127.0.0.1 or $BOND_APP_HOST)
995
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
996
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
997
+ -h, --help Show this help
998
+ `);
999
+ }
1000
+
1001
+ function printServiceHelp(): void {
1002
+ console.log(`Usage: bond-app service <action> [options]
1003
+
1004
+ Manage the orchestrator user service (systemd --user on Linux, launchd on macOS).
1005
+
1006
+ Actions:
1007
+ status Show service installation and running state
1008
+ install Write unit/plist file, enable and start the service
1009
+ start Start the installed service
1010
+ stop Stop the running service
1011
+ restart Restart the service
1012
+ uninstall Stop, disable and remove the unit/plist file
1013
+
1014
+ Options:
1015
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
1016
+ --host <host> Loopback host to bind to (default: 127.0.0.1 or $BOND_APP_HOST)
1017
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
1018
+ --image <name> Runner image name to store in service environment ($RUNNER_IMAGE)
1019
+ --name <name> Custom unit/label name (default: bond-app / dev.bond-app.orchestrator)
1020
+ --json Output result in JSON format
1021
+ -h, --help Show this help
1022
+ `);
1023
+ }
1024
+
1025
+ export async function runCli(argv: string[], setupDeps?: SetupDeps): Promise<number> {
550
1026
  const [cmd, ...rest] = argv;
551
- if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') {
1027
+ if (!cmd) {
1028
+ printHelp();
1029
+ const firstRun = await maybeHandleFirstRun({ fromStart: false, deps: setupDeps });
1030
+ return firstRun.setupOk ? 0 : 1;
1031
+ }
1032
+ if (cmd === '-h' || cmd === '--help' || cmd === 'help') {
552
1033
  printHelp();
553
1034
  return 0;
554
1035
  }
@@ -558,14 +1039,24 @@ export async function runCli(argv: string[]): Promise<number> {
558
1039
  }
559
1040
 
560
1041
  switch (cmd) {
1042
+ case 'setup':
1043
+ return await handleSetup(rest, setupDeps);
1044
+ case 'update':
1045
+ return await handleUpdate(rest, setupDeps);
1046
+ case 'uninstall':
1047
+ return await handleUninstall(rest, setupDeps);
1048
+ case 'service':
1049
+ return await handleService(rest, setupDeps?.serviceDeps);
561
1050
  case 'start':
562
- return await handleStart(rest);
1051
+ return await handleStart(rest, bootstrap, relaunchSelf, setupDeps);
563
1052
  case 'install':
564
1053
  return await handleInstall(rest);
565
1054
  case 'open':
566
1055
  return await handleOpen(rest);
567
1056
  case 'status':
568
1057
  return await handleStatus(rest);
1058
+ case 'doctor':
1059
+ return await handleDoctor(rest);
569
1060
  default:
570
1061
  console.error(`bond-app: unknown command '${cmd}'\n`);
571
1062
  printHelp();
package/src/config.ts CHANGED
@@ -2,6 +2,8 @@ import path from 'node:path';
2
2
  import os from 'node:os';
3
3
  import fs from 'node:fs';
4
4
  import crypto from 'node:crypto';
5
+ import { defaultDataDir } from './core/paths.ts';
6
+ import { restrictPathSync } from './core/permissions.ts';
5
7
 
6
8
  export interface AppConfig {
7
9
  port: number;
@@ -77,15 +79,20 @@ export function getOrCreateAuthToken(dataDir: string): string {
77
79
  if (dataDir === ':memory:') {
78
80
  return 'test-token-in-memory-mode-1234567890';
79
81
  }
80
- // N8: Only apply mode 0700 if creating the directory; do not alter pre-existing dirs
82
+ // N8: Only apply mode 0700 / user ACL if creating the directory; do not alter pre-existing dirs
81
83
  if (!fs.existsSync(dataDir)) {
82
84
  fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
85
+ try {
86
+ restrictPathSync(dataDir, 0o700);
87
+ } catch {
88
+ // ignore
89
+ }
83
90
  }
84
91
 
85
92
  const tokenPath = path.join(dataDir, 'token');
86
93
  if (fs.existsSync(tokenPath)) {
87
94
  try {
88
- fs.chmodSync(tokenPath, 0o600);
95
+ restrictPathSync(tokenPath, 0o600);
89
96
  } catch {
90
97
  // ignore
91
98
  }
@@ -94,11 +101,16 @@ export function getOrCreateAuthToken(dataDir: string): string {
94
101
 
95
102
  const token = crypto.randomBytes(32).toString('hex');
96
103
  fs.writeFileSync(tokenPath, token, { encoding: 'utf8', mode: 0o600 });
104
+ try {
105
+ restrictPathSync(tokenPath, 0o600);
106
+ } catch {
107
+ // ignore
108
+ }
97
109
  return token;
98
110
  }
99
111
 
100
112
  export function loadConfig(overrides: Partial<AppConfig> = {}): AppConfig {
101
- const dataDir = overrides.dataDir || process.env.BOND_APP_DATA_DIR || path.join(os.homedir(), '.bond-app');
113
+ const dataDir = overrides.dataDir || defaultDataDir();
102
114
  const host = overrides.host || process.env.BOND_APP_HOST || '127.0.0.1';
103
115
 
104
116
  // D13: refuse to start on non-loopback interface
@@ -6,6 +6,7 @@ import crypto from 'node:crypto';
6
6
  import http from 'node:http';
7
7
  import type { AgyLoginSessionState, AgyLoginStatus } from '../types.ts';
8
8
  import { credentialAccount } from '../db/settings-repo.ts';
9
+ import { restrictPathSync } from './permissions.ts';
9
10
 
10
11
  const execFileAsync = promisify(execFile);
11
12
 
@@ -611,7 +612,7 @@ export class AgyLoginManager {
611
612
  if (this.dataDir !== ':memory:') {
612
613
  fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
613
614
  fs.writeFileSync(destPath, result.content, { mode: 0o600 });
614
- fs.chmodSync(destPath, 0o600);
615
+ restrictPathSync(destPath, 0o600);
615
616
  } else {
616
617
  this.inMemoryToken = result.content;
617
618
  }