@tnunamak/dalan 0.6.2 → 0.7.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +25 -68
  3. package/bin/dalan.mjs +9 -0
  4. package/bin/dot-worker.mjs +16 -2
  5. package/docs/chatgpt-worker-onboarding.md +10 -14
  6. package/docs/claude-worker-onboarding.md +9 -8
  7. package/docs/codex-to-muse.md +21 -35
  8. package/docs/connect-chatgpt.md +10 -16
  9. package/docs/dalan-upgrade.md +4 -2
  10. package/docs/local-agent-mcp.md +24 -4
  11. package/docs/manual-setup.md +2 -2
  12. package/docs/operations.md +10 -11
  13. package/docs/pull-workers.md +1 -2
  14. package/docs/service-setup.md +94 -170
  15. package/docs/setup-reference.md +5 -5
  16. package/docs/worker-clients.md +4 -4
  17. package/package.json +2 -3
  18. package/scripts/dalan-try-selfcheck.mjs +8 -7
  19. package/scripts/worker-bridge-setup.mjs +91 -81
  20. package/src/as-store.mjs +5 -3
  21. package/src/as.mjs +35 -26
  22. package/src/auth-check.mjs +53 -0
  23. package/src/cli-help.mjs +13 -14
  24. package/src/client-approval.mjs +57 -0
  25. package/src/client-convenience.mjs +166 -0
  26. package/src/client-conveniences.json +106 -0
  27. package/src/client-conveniences.schema.json +97 -0
  28. package/src/connect-cli.mjs +5 -5
  29. package/src/default-home.mjs +36 -0
  30. package/src/follow-current.mjs +25 -0
  31. package/src/gozar-routes.mjs +314 -0
  32. package/src/redirect-policy.mjs +61 -0
  33. package/src/route-setting.mjs +71 -12
  34. package/src/server.mjs +2 -0
  35. package/src/service-auto-update.mjs +8 -1
  36. package/src/service-launchd.mjs +166 -0
  37. package/src/service-update-runtime.mjs +40 -6
  38. package/src/service-update.mjs +20 -14
  39. package/src/service.mjs +175 -63
  40. package/src/setup.mjs +55 -44
  41. package/src/try-exposure.mjs +7 -657
  42. package/src/try-hosted.mjs +71 -101
  43. package/src/try-selfcheck.mjs +15 -8
  44. package/src/try.mjs +9 -13
  45. package/scripts/lib/expose-tailscale.mjs +0 -408
  46. package/src/try-hosted-clients.mjs +0 -46
package/src/service.mjs CHANGED
@@ -10,10 +10,12 @@ import { defaultPath } from './paths.mjs';
10
10
  import { initAsFiles, writeAtomic } from './as-files.mjs';
11
11
  import { parseWorkers } from './workers.mjs';
12
12
  import { parseArgs } from '../scripts/live-trial/common.mjs';
13
- import { resolveGozarCommand } from './try-exposure.mjs';
13
+ import { buildQuery, ensureDurableRoute, explainRouteError, describeCandidate, describeDisclosure, gozarHomeFor, registerExternalService, resolveGozar, resolveRouteWord } from './gozar-routes.mjs';
14
14
  import { autoUpdateUnits, setAutoUpdate } from './service-auto-update.mjs';
15
+ import { serviceHomeFor, readDefaultHome, recordDefaultHome, forgetDefaultHome, DEFAULT_SERVICE_HOME } from './default-home.mjs';
16
+ import { launchdLabels, launchAgentsDir, servicePlist, writeAgentFile, loadAgent, unloadAgent, removeAgents, lintPlist } from './service-launchd.mjs';
15
17
 
16
- const REPO = fileURLToPath(new URL('..', import.meta.url));
18
+ const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
17
19
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
18
20
  const fail = message => { throw new Error(message); };
19
21
 
@@ -49,20 +51,24 @@ function validateTopology({ port, target, lanPort = null, verifyCmd }) {
49
51
 
50
52
  function parseOptions(argv, env) {
51
53
  const parsed = parseArgs(argv, {
52
- values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--gozar-bin', '--lan-port'],
53
- flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--json', '--help'],
54
+ values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--route', '--lan-port'],
55
+ flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--yes', '--json', '--help'],
54
56
  });
55
57
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
56
58
  if (parsed['--help']) return { help: true };
57
59
  if (parsed['--auto-update'] && parsed['--no-auto-update']) fail('choose --auto-update or --no-auto-update');
58
- const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
59
- if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a systemd unit');
60
- const origin = parseOrigin(parsed['--public-url']);
61
- const port = Number(parsed['--port']);
62
- if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port must be a fixed port from 1024 through 65535');
63
- const target = parseTarget(parsed['--target']);
60
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(env));
61
+ if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a service definition');
62
+ // `--route NAME` alone is the one-command install: Gozar supplies the public address and Dalan picks a loopback port.
63
+ const auto = parsed['--public-url'] === undefined && parsed['--port'] === undefined && parsed['--target'] === undefined;
64
+ if (auto && parsed['--route'] === undefined) fail('pass --route NAME to publish through Gozar, or --public-url, --port and --target for a proxy you already run');
65
+ if (auto && (parsed['--lan-port'] !== undefined || parsed['--verify-cmd'] !== undefined)) fail('--lan-port and --verify-cmd belong with an explicit --public-url, --port and --target');
66
+ const origin = auto ? null : parseOrigin(parsed['--public-url']);
67
+ const port = auto ? null : Number(parsed['--port']);
68
+ if (!auto && (!Number.isInteger(port) || port < 1024 || port > 65535)) fail('--port must be a fixed port from 1024 through 65535');
69
+ const target = auto ? null : parseTarget(parsed['--target']);
64
70
  const lanPort = parsed['--lan-port'] === undefined ? null : Number(parsed['--lan-port']);
65
- validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
71
+ if (!auto) validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
66
72
  const workers = [];
67
73
  for (let i = 0; i < argv.length; i++) {
68
74
  if (argv[i] === '--worker') workers.push(argv[++i]);
@@ -73,10 +79,10 @@ function parseOptions(argv, env) {
73
79
  }
74
80
  if (new Set(workers).size !== workers.length) fail('--worker names must be unique');
75
81
  if (parsed['--verify-cmd']?.length > 4096) fail('--verify-cmd is too long');
76
- const gozarBin = parsed['--gozar-bin'];
77
- if (gozarBin !== undefined && (!gozarBin || gozarBin.startsWith('-'))) fail('--gozar-bin must name a command');
78
- return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
79
- gozarBin, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
82
+ const route = parsed['--route'];
83
+ if (route !== undefined && (!route || route.startsWith('-'))) fail('--route must name a Gozar route');
84
+ return { home, auto, homeExplicit: parsed['--home'] !== undefined, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
85
+ route, yes: parsed['--yes'] === true, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
80
86
  writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
81
87
  }
82
88
 
@@ -106,6 +112,23 @@ function nodePath(execPath) {
106
112
  return execPath;
107
113
  }
108
114
 
115
+ function readReceipt(home) {
116
+ const file = path.join(defaultPath(home, '.config/dot-bridge'), 'service-install.json');
117
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
118
+ }
119
+
120
+ function firstFreePort(start) {
121
+ return new Promise((resolve, reject) => {
122
+ const attempt = port => {
123
+ if (port > 65535) return reject(new Error('no free port from 8789 upward'));
124
+ const probe = net.createServer();
125
+ probe.once('error', () => attempt(port + 1));
126
+ probe.listen(port, '127.0.0.1', () => probe.close(() => resolve(port)));
127
+ };
128
+ attempt(start);
129
+ });
130
+ }
131
+
109
132
  function unitName(home) { return `dalan-${createHash('sha256').update(home).digest('hex').slice(0, 10)}`; }
110
133
 
111
134
  function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null, recover = true } = {}) {
@@ -208,7 +231,7 @@ function checkHomeScope(home, configDir, o, workers) {
208
231
  if (!fs.existsSync(home)) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
209
232
  const rootEntries = fs.readdirSync(home);
210
233
  if (!rootEntries.length) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
211
- const rootAllowed = ['.config', '.local', '.tmp', 'resource-url', 'current', 'versions', 'update-result.json', 'update-failed.json', 'update-transaction.json', 'update-backup', 'update-lock.sqlite', 'update-lock.sqlite-journal'];
234
+ const rootAllowed = ['.config', '.local', '.tmp', 'resource-url', 'logs', 'current', 'versions', 'update-result.json', 'update-failed.json', 'update-transaction.json', 'update-backup', 'update-lock.sqlite', 'update-lock.sqlite-journal'];
212
235
  if (rootEntries.some(name => !rootAllowed.includes(name))) fail(`${home} contains unrelated data; use a fresh home or one created by dalan service migrate-workers`);
213
236
  if (!rootEntries.includes('.config')) fail(`${home} has no Dalan config directory; refusing to adopt it`);
214
237
  const configRoot = path.join(home, '.config');
@@ -225,7 +248,7 @@ function checkHomeScope(home, configDir, o, workers) {
225
248
  const receiptFile = path.join(configDir, 'service-install.json');
226
249
  const entries = fs.readdirSync(configDir);
227
250
  const hasReceipt = entries.includes('service-install.json');
228
- if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url'].includes(name))) fail(`${home} contains update data without a service receipt`);
251
+ if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url', 'logs'].includes(name))) fail(`${home} contains update data without a service receipt`);
229
252
  if (hasReceipt) {
230
253
  const info = fs.lstatSync(receiptFile);
231
254
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
@@ -342,19 +365,36 @@ function assertGozarStatePath(env) {
342
365
 
343
366
  export async function installService(o, seams = {}) {
344
367
  const env = seams.env ?? process.env;
345
- if ((seams.platform ?? process.platform) !== 'linux') fail('dalan service install currently requires Linux with a systemd user manager');
346
- if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute systemd-safe path');
368
+ const platform = seams.platform ?? process.platform;
369
+ if (!['linux', 'darwin'].includes(platform)) fail('dalan service install needs Linux with a systemd user manager or macOS with launchd');
370
+ const mac = platform === 'darwin';
371
+ if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute service-safe path');
372
+ assertRealDirectoryPath(path.dirname(o.home), { owner: true });
373
+ assertRealDirectoryPath(o.home, { owner: true });
374
+ let gozar = null;
375
+ if (o.auto) {
376
+ // The one-command install: reuse the port and address a previous run recorded, or pick a free port and ask Gozar for the address.
377
+ const prior = readReceipt(o.home);
378
+ if (prior?.origin && prior.port) o = { ...o, origin: prior.origin, port: prior.port, target: parseTarget(prior.target) };
379
+ else {
380
+ const port = await (seams.freePort ?? firstFreePort)(8789);
381
+ gozar = seams.gozar ?? await resolveGozar();
382
+ const wanted = buildQuery({ home: gozarHomeFor(env), target: `127.0.0.1:${port}`, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, address: 'stable' });
383
+ const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
384
+ const view = await ensureDurableRoute({ gozar, query, pick, consent: seams.consent ?? (async () => fail('A durable route needs your approval; run `dalan setup --route NAME` first, then retry.')) });
385
+ o = { ...o, origin: parseOrigin(view.origin), port, target: parseTarget(`127.0.0.1:${port}`) };
386
+ }
387
+ }
347
388
  const target = parseTarget(typeof o.target === 'string' ? o.target : `${o.target?.host}:${o.target?.port}`);
348
389
  o = { ...o, target };
349
390
  validateTopology(o);
350
- assertRealDirectoryPath(path.dirname(o.home), { owner: true });
351
- assertRealDirectoryPath(o.home, { owner: true });
352
391
  const profile = profileFor(o.home, o.workers ?? []);
353
392
  assertRealDirectoryPath(path.dirname(profile.file));
354
- const unitDir = path.join(env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(os.homedir(), '.config'), 'systemd/user');
393
+ const unitDir = mac ? launchAgentsDir(env) : path.join(env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(os.homedir(), '.config'), 'systemd/user');
355
394
  assertRealDirectoryPath(unitDir, { owner: true });
356
395
  const configDir = path.dirname(profile.file);
357
396
  const homeScope = checkHomeScope(o.home, configDir, o, profile.workers);
397
+ if (mac && !(o.target.host === '127.0.0.1' && o.target.port === o.port)) fail('on macOS the target must be 127.0.0.1:<port> (the same as --port)');
358
398
  const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
359
399
  const repo = seams.repo ?? REPO, node = seams.node ?? nodePath(process.execPath);
360
400
  const receiptFile = homeScope.receiptFile;
@@ -363,12 +403,16 @@ export async function installService(o, seams = {}) {
363
403
  const current = path.join(o.home, 'current');
364
404
  const hasCurrent = fs.existsSync(current) || (() => { try { fs.lstatSync(current); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } })();
365
405
  if (hasCurrent && !fs.lstatSync(current).isSymbolicLink()) fail(`${current} must be the service package symlink`);
366
- const { files, enable, name } = unitFiles(o, { home: o.home, repo: current, node, proxy });
367
- const updateUnits = autoUpdateUnits({ home: o.home, unit: name, node });
368
- Object.assign(files, updateUnits.files);
406
+ const name = unitName(o.home), labels = launchdLabels(name);
407
+ let files, enable = [];
408
+ if (mac) files = { [`${labels.service}.plist`]: servicePlist({ unit: name, node, home: o.home, port: o.port, enableWorkspace: o.enableWorkspace, enableT3: o.enableT3 }) };
409
+ else {
410
+ ({ files, enable } = unitFiles(o, { home: o.home, repo: current, node, proxy }));
411
+ Object.assign(files, autoUpdateUnits({ home: o.home, unit: name, node }).files);
412
+ }
369
413
  let replaceLegacyUnit = false;
370
414
  // Check every collision before creating the bridge home or the first unit file.
371
- for (const [filename, text] of Object.entries(files)) {
415
+ for (const [filename, text] of mac ? [] : Object.entries(files)) {
372
416
  const file = path.join(unitDir, filename);
373
417
  if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) {
374
418
  const actual = fs.lstatSync(file).isFile() ? fs.readFileSync(file, 'utf8') : '';
@@ -383,19 +427,16 @@ export async function installService(o, seams = {}) {
383
427
  }
384
428
  if (o.writeUnitsOnly) {
385
429
  if (replaceLegacyUnit) fail('rerun without --write-units-only to enroll an existing service for updates');
386
- writeUnits(unitDir, files);
387
- return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
430
+ if (mac) for (const [filename, text] of Object.entries(files)) writeAgentFile(path.join(unitDir, filename), text); else writeUnits(unitDir, files);
431
+ return { schema_version: 1, home: o.home, unit: mac ? labels.service : `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
388
432
  }
389
- // An explicit --gozar-bin wins; otherwise the bundled Gozar, GOZAR_BIN, then PATH.
390
- const gozar = o.gozarBin !== undefined ? { binary: o.gozarBin, args: [] }
391
- : resolveGozarCommand({ env, resolveBundled: seams.resolveBundled, which: seams.which });
392
- if (!gozar.binary) fail('Gozar is unavailable; reinstall @tnunamak/dalan with its dependencies, or install gozar on PATH or set GOZAR_BIN to an executable path, then retry service install.');
433
+ gozar ??= seams.gozar ?? await resolveGozar();
393
434
  assertGozarStatePath(env);
394
435
  const needsEnrollmentRestart = replaceLegacyUnit || !!previous && (!previous.repo || previous.enrollment_pending === true);
395
436
  const spawn = seams.spawn ?? spawnSync;
396
- runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
437
+ if (!mac) runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
397
438
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
398
- if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate }, null, 2)}\n`);
439
+ if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate, platform, route: o.route ?? null }, null, 2)}\n`);
399
440
  if (!hasCurrent) fs.symlinkSync(repo, current);
400
441
  const homeFiles = prepareHome(o, profile);
401
442
  if (needsEnrollmentRestart) {
@@ -406,34 +447,81 @@ export async function installService(o, seams = {}) {
406
447
  writeAtomic(file, files[`${name}.service`]);
407
448
  fs.chmodSync(file, mode);
408
449
  }
409
- writeUnits(unitDir, files);
410
- runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
411
- runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
412
- if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
450
+ if (mac) {
451
+ fs.mkdirSync(path.join(o.home, 'logs'), { recursive: true, mode: 0o700 });
452
+ const plistFile = path.join(unitDir, `${labels.service}.plist`);
453
+ const changed = writeAgentFile(plistFile, files[`${labels.service}.plist`]);
454
+ if (lintPlist(plistFile, seams) === false) fail(`${plistFile} is not a valid property list`);
455
+ if (changed) unloadAgent({ label: labels.service }, seams.launchd);
456
+ loadAgent({ label: labels.service, plistFile }, seams.launchd);
457
+ } else {
458
+ writeUnits(unitDir, files);
459
+ runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
460
+ runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
461
+ if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
462
+ }
413
463
  const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
414
464
  const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
415
- if (!ready) fail(`Dalan did not start on its admin socket; the unit and home remain for inspection: systemctl --user status ${name}.service`);
416
- const gozarArgs = ['service', 'add', '--origin', o.origin, '--target', o.target.value];
417
- if (o.verifyCmd) gozarArgs.push('--verify-cmd', o.verifyCmd);
418
- gozarArgs.push('--json');
419
- const output = runCommand(gozar.binary, [...gozar.args, ...gozarArgs], { env, spawn, timeout: 120000 });
465
+ if (!ready) fail(`Dalan did not start on its admin socket; the service and home remain for inspection: ${mac ? `tail ${path.join(o.home, 'logs', 'bridge.err.log')}` : `systemctl --user status ${name}.service`}`);
466
+ const gozarHome = gozarHomeFor(env);
420
467
  let routeReply;
421
- try { routeReply = JSON.parse(output); } catch { fail('Gozar returned invalid JSON for service add; the bridge is running but its route is unverified'); }
422
- if (routeReply?.schemaVersion !== 1 || routeReply?.route?.origin !== o.origin || routeReply?.route?.target !== o.target.value) {
423
- fail('Gozar returned a service route that does not match the requested origin and target; the bridge is running but its route is unverified');
424
- }
425
- if (routeReply.route.verification?.status !== 'verified') {
426
- fail(`Gozar did not verify the service route; the bridge is running and the service route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
468
+ if (o.route !== undefined) {
469
+ // A named Gozar route: Gozar allocates or adopts it and pins the origin; nothing here interprets the name.
470
+ const wanted = buildQuery({ home: gozarHome, target: o.target.value, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, origin: o.origin, address: 'stable' });
471
+ const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
472
+ const view = await ensureDurableRoute({ gozar, query, pick, consent: seams.consent ?? (async () => fail('A durable route needs your approval; run `dalan setup --route NAME` first, then retry.')) });
473
+ if (view.origin !== o.origin) fail(`Gozar pinned ${view.origin}, not the requested ${o.origin}; the bridge is running but its route needs repair`);
474
+ routeReply = view;
475
+ } else {
476
+ routeReply = (await registerExternalService({ gozar, home: gozarHome, origin: o.origin, target: o.target.value, ...(o.verifyCmd ? { verifyCmd: o.verifyCmd } : {}) })).route;
427
477
  }
428
- await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn });
478
+ if (routeReply.verification?.status !== 'verified') fail(`Gozar did not verify the route; the bridge is running and the route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
479
+ { const done = JSON.parse(fs.readFileSync(receiptFile, 'utf8')); if (routeReply.handle && JSON.stringify(done.route_handle) !== JSON.stringify(routeReply.handle)) writeAtomic(receiptFile, `${JSON.stringify({ ...done, route_handle: routeReply.handle }, null, 2)}\n`); }
480
+ await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn, platform });
481
+ if (!env.DALAN_HOME) recordDefaultHome(o.home, env);
429
482
  if (needsEnrollmentRestart) {
430
483
  const enrolled = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
431
484
  delete enrolled.enrollment_pending;
432
485
  writeAtomic(receiptFile, `${JSON.stringify(enrolled, null, 2)}\n`);
433
486
  }
434
- return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), port: o.port,
487
+ return { schema_version: 1, origin: routeReply.published ?? o.origin, home: o.home, unit: mac ? labels.service : `${name}.service`, already_installed: homeScope.hasReceipt && !needsEnrollmentRestart, units: Object.keys(files), port: o.port,
435
488
  workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
436
- target: o.target.value, started: true, route: routeReply.route, auto_update: autoUpdate };
489
+ target: o.target.value, started: true, route: routeReply, auto_update: autoUpdate };
490
+ }
491
+
492
+ // Stop the service and its update job, delete the generated definitions and the public route, and forget the default home.
493
+ // The home itself (secrets, grants, data) stays; delete it by hand if you also want that gone.
494
+ export async function uninstallService({ home }, seams = {}) {
495
+ const env = seams.env ?? process.env, platform = seams.platform ?? process.platform, mac = platform === 'darwin';
496
+ home = path.resolve(home);
497
+ const receipt = readReceipt(home);
498
+ if (!receipt?.unit || receipt.home !== home) fail(`no Dalan service is installed for ${home}`);
499
+ const removed = [];
500
+ const unitDir = receipt.unit_dir;
501
+ if (!unitDir || !path.isAbsolute(unitDir)) fail('the service receipt names no unit directory');
502
+ if (receipt.auto_update) { try { await setAutoUpdate({ home, enabled: false }, { ...seams, env, platform }); removed.push('automatic updates off'); } catch (error) { removed.push(`update job not removed: ${error.message}`); } }
503
+ if (mac) removed.push(...removeAgents({ unit: receipt.unit, unit_dir: unitDir }, seams.launchd));
504
+ else {
505
+ const spawn = seams.spawn ?? spawnSync, name = receipt.unit;
506
+ const units = [`${name}.service`, `${name}-target.socket`, `${name}-target.service`, `${name}-update.service`, `${name}-update.timer`].filter(unit => fs.existsSync(path.join(unitDir, unit)));
507
+ if (units.length) { spawn('systemctl', ['--user', 'disable', '--now', ...units], { encoding: 'utf8', env }); }
508
+ for (const unit of units) { fs.rmSync(path.join(unitDir, unit)); removed.push(`removed ${path.join(unitDir, unit)}`); }
509
+ spawn('systemctl', ['--user', 'daemon-reload'], { encoding: 'utf8', env });
510
+ }
511
+ if (receipt.route_handle) {
512
+ try {
513
+ const gozar = seams.gozar ?? await resolveGozar();
514
+ const closed = await gozar.closeRoute({ home: gozarHomeFor(env), handle: receipt.route_handle, mode: 'remove' });
515
+ removed.push(`public route ${closed.state}`);
516
+ } catch (error) { removed.push(`public route not removed: ${explainRouteError(error).line}`); }
517
+ }
518
+ forgetDefaultHome(home, env);
519
+ // The home holds secrets, grants and data, so it is moved aside, never deleted. A new install then starts from a fresh home at the same path.
520
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);
521
+ let aside = `${home}.removed-${stamp}`;
522
+ for (let n = 2; fs.existsSync(aside); n++) aside = `${home}.removed-${stamp}-${n}`;
523
+ fs.renameSync(home, aside);
524
+ return { home, removed, kept: `${aside} (secrets and data, moved aside; delete it yourself to remove them)`, moved_to: aside };
437
525
  }
438
526
 
439
527
  export async function serviceMain(argv, seams = {}) {
@@ -446,7 +534,7 @@ export async function serviceMain(argv, seams = {}) {
446
534
  const parsed = parseArgs(args, { values: ['--home'], flags: ['--quiet', '--help'] });
447
535
  if (parsed['--help']) return serviceMain(['help'], seams);
448
536
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
449
- const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
537
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env));
450
538
  const { recoverService } = await import('./service-update.mjs');
451
539
  const result = recoverService({ home });
452
540
  if (!parsed['--quiet']) (seams.out ?? console.log)(JSON.stringify(result));
@@ -455,7 +543,7 @@ export async function serviceMain(argv, seams = {}) {
455
543
  if (['update', 'status', 'auto-update'].includes(action)) {
456
544
  const parsed = parseArgs(args, { values: ['--home'], flags: ['--check', '--yes', '--retry', '--json', '--help'] });
457
545
  if (parsed['--help']) return serviceMain(['help'], seams);
458
- const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
546
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env));
459
547
  let result;
460
548
  if (action === 'auto-update') {
461
549
  if (parsed._.length !== 1 || !['on', 'off'].includes(parsed._[0]) || parsed['--check'] || parsed['--yes'] || parsed['--retry']) fail('use dalan service auto-update on|off [--home DIR]');
@@ -472,21 +560,45 @@ export async function serviceMain(argv, seams = {}) {
472
560
  return result;
473
561
  }
474
562
  if (action === 'help' || action === '--help' || !action) {
475
- (seams.out ?? console.log)('Usage: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]\n dalan service update [--check|--yes] [--retry] [--home DIR] [--json]\n dalan service auto-update on|off [--home DIR]\n dalan service status [--home DIR] [--json]\n dalan service recover --home DIR [--quiet]\nNew installs check daily with jitter. Catalog changes stage until --yes authorizes a connector refresh. --check reports availability without installing. Linux systemd only.');
563
+ (seams.out ?? console.log)('Usage: dalan service install --worker NAME --route NAME [--yes] [--home DIR] [--enable-workspace] [--enable-t3] [--auto-update|--no-auto-update]\n dalan service install --public-url https://HOST --port N --target HOST:PORT [--home DIR] [--lan-port N] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only] (an address you already serve)\n dalan service uninstall [--home DIR]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]\n dalan service update [--check|--yes] [--retry] [--home DIR] [--json]\n dalan service auto-update on|off [--home DIR]\n dalan service status [--home DIR] [--json]\n dalan service recover --home DIR [--quiet]\nNew installs check daily with jitter. Catalog changes stage until --yes authorizes a connector refresh. --check reports availability without installing. Runs under systemd on Linux and launchd on macOS.');
476
564
  return null;
477
565
  }
478
- if (action !== 'install') fail('use dalan service install, update, auto-update, status, recover or migrate-workers');
566
+ if (action === 'uninstall') {
567
+ const parsed = parseArgs(args, { values: ['--home'], flags: ['--json', '--help'] });
568
+ if (parsed['--help']) return serviceMain(['help'], seams);
569
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
570
+ const result = await uninstallService({ home: parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env) }, seams);
571
+ const out = seams.out ?? console.log;
572
+ if (parsed['--json']) out(JSON.stringify(result)); else { for (const line of result.removed) out(line); out(`Kept: ${result.kept}`); }
573
+ return result;
574
+ }
575
+ if (action !== 'install') fail('use dalan service install, uninstall, update, auto-update, status, recover or migrate-workers');
479
576
  const o = parseOptions(args, seams.env ?? process.env);
480
577
  if (o.help) return serviceMain(['help'], seams);
481
- const result = await installService(o, seams);
578
+ const out0 = seams.out ?? console.log;
579
+ // Gozar describes the route it would open; the owner approves it once (the answer is kept with the route). `--yes` approves what was printed.
580
+ const consent = seams.consent ?? (async candidate => {
581
+ out0(describeCandidate(candidate).join('\n')); out0(describeDisclosure(candidate).join('\n'));
582
+ if (o.yes) return true;
583
+ if (!process.stdin.isTTY) { out0('Run this in a terminal to approve the route, or add --yes after reading the description above.'); return false; }
584
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
585
+ try { return /^y(es)?$/i.test((await rl.question('Use this route? [y/N] ')).trim()); } finally { rl.close(); }
586
+ });
587
+ const result = await installService(o, { ...seams, consent });
482
588
  if (o.json) (seams.out ?? console.log)(JSON.stringify(result));
483
589
  else {
484
- (seams.out ?? console.log)(`Service: ${result.unit} (${result.started ? 'active' : 'unit files written'})`);
485
- (seams.out ?? console.log)(`Home: ${result.home}`);
486
- (seams.out ?? console.log)(`Public MCP URL: ${result.public_url ?? `${o.origin}/<secret>/mcp`}`);
487
- (seams.out ?? console.log)(`Private URL file: ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
488
- (seams.out ?? console.log)(`Gozar target: ${result.target}`);
489
- if (result.route) (seams.out ?? console.log)(`Gozar route: ${result.route.verification.status}`);
590
+ const out = seams.out ?? console.log;
591
+ out(`Service: ${result.unit} (${result.started ? (result.already_installed ? 'already installed, running' : 'running') : 'files written'})`);
592
+ out(`Home: ${result.home}`);
593
+ out(`Public address: ${result.origin ?? o.origin ?? result.public_url}`);
594
+ out(`Connector URL (keep private): in ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
595
+ if (result.route) out(`Route: ${result.route.verification?.status ?? 'unknown'}`);
596
+ if (result.started) {
597
+ out(`Updates: ${result.auto_update ? 'automatic, once a day' : 'off; run dalan service update'}`);
598
+ const worker = result.workers?.[0] ?? 'WORKER';
599
+ out(`Next: dalan connect start --worker ${worker}`);
600
+ out('Check: dalan doctor --auth');
601
+ }
490
602
  }
491
603
  return result;
492
604
  }
package/src/setup.mjs CHANGED
@@ -1,63 +1,74 @@
1
- // `dalan setup`: choose the saved public route. It detects what Tailscale can do and asks as little as possible:
2
- // Tailscale ready for Funnel -> one yes/no question; not found -> one short choice. `dalan try --public` asks for relay consent
3
- // before it exposes the temporary demo link.
1
+ // `dalan setup`: choose the saved public route. Gozar owns every route; Dalan asks it what is possible, shows what it returned, asks once,
2
+ // and saves only the requirements, the opaque route name and the pinned origin (route-setting.mjs, version 2).
4
3
  import readline from 'node:readline';
5
- import { INSTALL_URL, defaultTailscale, preflight, whichOnPath } from '../scripts/lib/expose-tailscale.mjs';
6
- import { readRouteSetting, writeRouteSetting } from './route-setting.mjs';
4
+ import {
5
+ RouteError, buildQuery, dalanRequirements, describeCandidate, describeDisclosure, ensureDurableRoute, explainRouteError, gozarHomeFor, resolveGozar, targetFor,
6
+ } from './gozar-routes.mjs';
7
+ import { inspectRouteSetting, writeRouteSetting } from './route-setting.mjs';
7
8
 
8
- // What this computer's Tailscale can do now: { ok, node } or { ok: false, installed, reason }.
9
- // The address is the OAuth issuer, so a new address is a new sign-in identity: nothing from a trial carries over.
10
9
  export const SWITCH_NOTE = 'Next: run `dalan try --public`, then in your MCP client remove the trial connector and add the new URL it prints; a new address cannot reuse the trial sign-in.';
10
+ export const ROUTE_ID = 'dalan-main';
11
+ const DEFAULT_PORT = 8789;
11
12
 
12
- export function detectTailscale({ env = process.env, tailscale = defaultTailscale, which = name => whichOnPath(name, env), platform = process.platform, mac } = {}) {
13
- if (!which('tailscale')) return { ok: false, installed: false, reason: 'Tailscale is not installed.' };
14
- try {
15
- const found = preflight({ tailscale, platform, mac });
16
- return { ok: true, node: found.dnsName.split('.')[0], dnsName: found.dnsName };
17
- } catch (error) { return { ok: false, installed: true, reason: String(error.message).split('\n')[0] }; }
13
+ export function parseSetupArgs(argv) {
14
+ const out = { route: undefined };
15
+ for (let i = 0; i < argv.length; i++) {
16
+ const arg = argv[i];
17
+ if (arg === '--route') { out.route = argv[++i]; if (out.route === undefined) throw new Error('--route needs a name'); } else if (arg.startsWith('--route=')) out.route = arg.slice(8);
18
+ else throw new Error(`unknown option ${arg}; usage: dalan setup [--route NAME]`);
19
+ }
20
+ return out;
18
21
  }
19
22
 
20
- export async function runSetup({ env = process.env, out = process.stdout, input = process.stdin, interactive = Boolean(process.stdin.isTTY), detect = () => detectTailscale({ env }) } = {}) {
23
+ export async function runSetup({
24
+ argv = [], env = process.env, out = process.stdout, input = process.stdin, interactive = Boolean(process.stdin.isTTY), gozar, gozarHome, answers, port = DEFAULT_PORT,
25
+ } = {}) {
21
26
  const say = line => out.write(`${line}\n`);
22
- const found = detect();
23
- const saved = readRouteSetting(env);
24
- const lines = interactive ? readline.createInterface({ input }) : null;
27
+ const { route: routeName } = parseSetupArgs(argv);
28
+ const found = inspectRouteSetting(env);
29
+ if (found.state === 'legacy') {
30
+ say('A saved 0.6 route setting exists. It is left untouched. Moving it to Gozar is a separate, journaled step that keeps the same address; setup never rewrites it.');
31
+ return { route: null, changed: false, legacy: true };
32
+ }
33
+ if (found.state === 'unreadable') { say(`The saved route setting could not be read (${found.reason}). It was left untouched.`); return { route: null, changed: false }; }
34
+ const lines = !answers && interactive ? readline.createInterface({ input }) : null;
35
+ const queued = answers ? [...answers] : null;
25
36
  const ask = question => new Promise(resolve => {
37
+ if (queued) { out.write(question); return resolve(queued.shift() ?? null); }
38
+ if (!lines) return resolve(null);
26
39
  let done = false;
27
40
  const finish = answer => { if (!done) { done = true; lines.off('close', onClose); resolve(answer); } };
28
41
  const onClose = () => finish(null);
29
42
  out.write(question); lines.once('line', finish); lines.once('close', onClose);
30
43
  });
31
44
  try {
32
- if (found.ok) {
33
- if (!interactive) { say(`Tailscale is ready on this computer (${found.node}). Run \`dalan setup\` in a terminal to use it.`); return { route: saved, changed: false }; }
34
- const answer = ((await ask(`Use Tailscale (${found.node}) for a stable address? [Y/n] `)) ?? '').trim().toLowerCase();
35
- if (answer === '' || answer === 'y' || answer === 'yes') {
36
- writeRouteSetting('tailscale', env);
37
- say('Saved Tailscale for public runs. Reuse the same node and public address to keep the connector identity; changing that address requires a new sign-in.');
38
- say(SWITCH_NOTE);
39
- return { route: 'tailscale', changed: saved !== 'tailscale' };
40
- }
41
- writeRouteSetting('gozar', env);
42
- say('Saved. `dalan try --public` uses Gozar for a temporary demo link. It can change or stop without warning. Run `dalan setup` again to switch.');
43
- return { route: 'gozar', changed: saved !== 'gozar' };
44
- }
45
- say(found.reason);
46
- say('For daily use, pick one:');
47
- say(` 1. Tailscale (recommended): install it from ${INSTALL_URL}, run \`tailscale up\`, then run \`dalan setup\` again.`);
48
- say(' 2. Use Gozar for a temporary demo link: it can change or stop without warning.');
49
- if (!interactive) return { route: saved, changed: false };
50
- const answer = ((await ask('Choose [1]: ')) ?? '').trim();
51
- if (answer === '2') {
52
- writeRouteSetting('gozar', env);
53
- say('Saved. `dalan try --public` uses Gozar for a temporary demo link. It can change or stop without warning.');
54
- return { route: 'gozar', changed: saved !== 'gozar' };
45
+ const runtime = gozar ?? await resolveGozar();
46
+ const home = gozarHome ?? gozarHomeFor(env);
47
+ const query = buildQuery({ home, target: targetFor(port), usage: { kind: 'durable', routeId: ROUTE_ID }, address: 'stable', ...(routeName !== undefined ? { route: routeName } : {}) });
48
+ if (!interactive && !answers) { say('Run `dalan setup` in a terminal to choose a public route.'); return { route: found.setting ?? null, changed: false }; }
49
+ const consent = async candidate => {
50
+ for (const line of describeCandidate(candidate)) say(line);
51
+ for (const line of describeDisclosure(candidate)) say(line);
52
+ const answer = String((await ask('Use this route for public runs? [y/N] ')) ?? '').trim().toLowerCase();
53
+ return answer === 'y' || answer === 'yes';
54
+ };
55
+ let view;
56
+ try { view = await ensureDurableRoute({ gozar: runtime, query, consent }); } catch (error) {
57
+ if (error?.tryKind === 'consent') { say('Nothing saved.'); return { route: found.setting ?? null, changed: false }; }
58
+ if (error?.code === 'setup_required' || error?.nextAction) { const e = explainRouteError(error); say(e.line); if (e.fix) say(`Next: ${e.fix}`); return { route: found.setting ?? null, changed: false }; }
59
+ throw error;
55
60
  }
56
- say('Nothing saved. Install Tailscale, then run `dalan setup` again.');
57
- return { route: saved, changed: false };
61
+ const setting = { version: 2, requirements: dalanRequirements({ address: 'stable' }), gozarHome: home, routeName: routeName ?? null, routeId: ROUTE_ID, origin: view.origin, bridgeHome: null };
62
+ writeRouteSetting(setting, env);
63
+ say(`Saved. Public runs use ${view.origin}. A changed address needs a new sign-in.`);
64
+ say(SWITCH_NOTE);
65
+ return { route: setting, changed: found.state !== 'current' || found.setting.origin !== setting.origin || found.setting.routeName !== setting.routeName };
58
66
  } finally { lines?.close(); }
59
67
  }
60
68
 
61
- export async function main() {
62
- try { await runSetup(); } catch (error) { process.stderr.write(`dalan: ${error.message}\n`); process.exitCode = 1; }
69
+ export async function main(argv = process.argv.slice(2)) {
70
+ try { await runSetup({ argv }); } catch (error) {
71
+ const e = error instanceof RouteError || error?.code ? explainRouteError(error) : { line: error.message, fix: null };
72
+ process.stderr.write(`dalan: ${e.line}\n${e.fix ? `${e.fix}\n` : ''}`); process.exitCode = 1;
73
+ }
63
74
  }