@tnunamak/dalan 0.6.1 → 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 (48) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +25 -64
  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 +99 -145
  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 +20 -15
  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 +38 -2
  35. package/src/service-auto-update.mjs +68 -0
  36. package/src/service-launchd.mjs +166 -0
  37. package/src/service-update-gate.mjs +20 -0
  38. package/src/service-update-lock.mjs +22 -0
  39. package/src/service-update-runtime.mjs +290 -0
  40. package/src/service-update.mjs +399 -0
  41. package/src/service.mjs +241 -58
  42. package/src/setup.mjs +55 -44
  43. package/src/try-exposure.mjs +7 -657
  44. package/src/try-hosted.mjs +71 -101
  45. package/src/try-selfcheck.mjs +15 -8
  46. package/src/try.mjs +9 -13
  47. package/scripts/lib/expose-tailscale.mjs +0 -408
  48. package/src/try-hosted-clients.mjs +0 -46
@@ -15,10 +15,59 @@ import { fileURLToPath } from 'node:url';
15
15
  import { parseArgs } from './live-trial/common.mjs';
16
16
  import { loadKeys } from '../src/as-files.mjs';
17
17
  import { writeWorkerInstructions } from '../src/worker-instructions.mjs';
18
- // Tailscale Funnel exposure (--expose tailscale). All of it lives in lib/expose-tailscale.mjs.
19
- import * as expose from './lib/expose-tailscale.mjs';
18
+ import https from 'node:https';
19
+ import { Resolver } from 'node:dns/promises';
20
+ import { buildQuery, ensureDurableRoute, gozarHomeFor, resolveGozar, describeCandidate, describeDisclosure } from '../src/gozar-routes.mjs';
21
+
22
+ // ---- checking the public address ---------------------------------------------------------------------------------------------------
23
+ // Public DNS through three resolvers in parallel (one can keep a negative-cached NXDOMAIN for a new name for >10 min).
24
+ const PUBLIC_DNS_SERVERS = ['1.1.1.1', '8.8.8.8', '9.9.9.9'];
25
+ const DNS_WAIT_MS = 600_000, DNS_PROGRESS_MS = 30_000, HTTPS_WAIT_MS = 120_000;
26
+ function makePublicResolver(resolvers = PUBLIC_DNS_SERVERS.map(server => { const resolver = new Resolver({ timeout: 3000, tries: 1 }); resolver.setServers([server]); return { server, resolver }; })) {
27
+ return name => new Promise(resolve => {
28
+ let pending = resolvers.length;
29
+ const settle = () => { if (--pending === 0) resolve(null); };
30
+ for (const { server, resolver } of resolvers) resolver.resolve4(name).then(addresses => (addresses[0] ? resolve({ address: addresses[0], server }) : settle()), settle);
31
+ });
32
+ }
33
+ // GET /admin pinned to the address DNS returned. The bridge answers 404 on its unauthenticated path.
34
+ function fetchPinned(url, address, { timeoutMs = 15_000 } = {}) {
35
+ const u = new URL(url);
36
+ return new Promise((resolve, reject) => {
37
+ const req = https.request({ hostname: u.hostname, port: u.port || 443, path: '/admin', method: 'GET', timeout: timeoutMs,
38
+ lookup: (_host, options, cb) => (options?.all ? cb(null, [{ address, family: 4 }]) : cb(null, address, 4)) }, res => { res.resume(); resolve(res.statusCode); });
39
+ req.on('timeout', () => req.destroy(new Error('timeout')));
40
+ req.on('error', reject);
41
+ req.end();
42
+ });
43
+ }
44
+ export async function verifyPublic({ url, dnsName, resolve4, request = fetchPinned, sleep = ms => new Promise(r => setTimeout(r, ms)), now = Date.now, timeoutMs = DNS_WAIT_MS, intervalMs = 5_000, progressMs = DNS_PROGRESS_MS, log = console.log }) {
45
+ const secs = ms => Math.round(ms / 1000);
46
+ const start = now(), end = start + timeoutMs;
47
+ let nextProgress = progressMs, found = null;
48
+ while (!found) {
49
+ found = await resolve4(dnsName);
50
+ if (found) break;
51
+ const elapsed = now() - start;
52
+ if (elapsed >= nextProgress && elapsed < timeoutMs) { log(`waiting for public DNS of ${dnsName} … ${secs(elapsed)} s / ${secs(timeoutMs)} s`); nextProgress += progressMs; }
53
+ if (now() >= end) break;
54
+ await sleep(intervalMs);
55
+ }
56
+ if (!found) { log(`FAIL public DNS: no A record for ${dnsName} from 1.1.1.1, 8.8.8.8 or 9.9.9.9 after ${secs(timeoutMs)} s. Next: run \`dig @8.8.8.8 ${dnsName} A\` (also try @1.1.1.1 and @9.9.9.9), check the route's state with Gozar, then retry.`); return false; }
57
+ log(`PASS public DNS: ${dnsName} -> ${found.address} (via ${found.server})`);
58
+ const httpsEnd = now() + HTTPS_WAIT_MS;
59
+ let nextHttpsProgress = now() + progressMs, last;
60
+ for (;;) {
61
+ try { const code = await request(url, found.address); if (code === 404) break; last = `GET /admin returned ${code}, expected 404 from the bridge`; } catch (e) { last = e.message; }
62
+ if (now() >= httpsEnd) { log(`FAIL public HTTPS: ${last} (still failing after ${secs(HTTPS_WAIT_MS)} s). Likely cause: the route is not active yet, or a different service answers on this address. Next: check the route's state with Gozar and the local port, then retry.`); return false; }
63
+ if (now() >= nextHttpsProgress) { log(`waiting for public HTTPS of ${dnsName} … last result: ${last}`); nextHttpsProgress += progressMs; }
64
+ await sleep(intervalMs);
65
+ }
66
+ log('PASS public HTTPS: GET /admin returned 404 from the bridge');
67
+ return true;
68
+ }
20
69
 
21
- const REPO = fileURLToPath(new URL('..', import.meta.url));
70
+ const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
22
71
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/; // no space, quote, %, $ or newline: the value goes into a unit or plist as is
23
72
  const PROXYD = ['/usr/lib/systemd/systemd-socket-proxyd', '/lib/systemd/systemd-socket-proxyd'];
24
73
  const MARKER = 'Generated by scripts/worker-bridge-setup.mjs'; // --remove only deletes files that carry this text
@@ -46,7 +95,7 @@ function stableNode(execPath) {
46
95
 
47
96
  function parseOptions(argv, platform) {
48
97
  const args = parseArgs(argv, {
49
- values: ['--worker', '--public-url', '--port', '--home', '--lan-forward', '--expose', '--funnel-port', '--ngrok-domain'],
98
+ values: ['--worker', '--public-url', '--port', '--home', '--lan-forward', '--route'],
50
99
  flags: ['--persistent', '--write-units-only', '--no-repo-tools', '--start', '--help', '--remove', '--purge-home', '--retry-public-check', '--repoint'],
51
100
  });
52
101
  if (args._.length) fail(`unexpected argument ${args._[0]}`);
@@ -56,7 +105,7 @@ function parseOptions(argv, platform) {
56
105
  const home = path.resolve(args['--home'] ?? path.join(os.homedir(), '.local/share/dbm'));
57
106
  if (args['--retry-public-check'] && args['--remove']) fail('--retry-public-check cannot be combined with --remove');
58
107
  if (args['--repoint']) {
59
- const others = ['--remove', '--retry-public-check', '--start', '--write-units-only', '--public-url', '--port', '--home', '--lan-forward', '--expose', '--funnel-port', '--ngrok-domain', '--purge-home', '--no-repo-tools', '--persistent'].filter(flag => args[flag] !== undefined && args[flag] !== false);
108
+ const others = ['--remove', '--retry-public-check', '--start', '--write-units-only', '--public-url', '--port', '--home', '--lan-forward', '--route', '--purge-home', '--no-repo-tools', '--persistent'].filter(flag => args[flag] !== undefined && args[flag] !== false);
60
109
  if (others.length) fail(`--repoint takes only --worker; remove ${others.join(' ')}`);
61
110
  const repo = REPO.replace(/\/$/, '');
62
111
  if (!SAFE_PATH.test(repo)) fail(`repo path contains a character that is not safe in a unit file: ${JSON.stringify(repo)}`);
@@ -64,23 +113,16 @@ function parseOptions(argv, platform) {
64
113
  }
65
114
  if (args['--remove']) {
66
115
  // Users rerun their install command with --remove appended, so install-only flags are ignored, not refused.
67
- const ignored = ['--public-url', '--port', '--lan-forward', '--write-units-only', '--start', '--no-repo-tools', '--expose', '--funnel-port', '--ngrok-domain'].filter(flag => args[flag] !== undefined && args[flag] !== false);
116
+ const ignored = ['--public-url', '--port', '--lan-forward', '--write-units-only', '--start', '--no-repo-tools', '--route'].filter(flag => args[flag] !== undefined && args[flag] !== false);
68
117
  if (ignored.length) console.error(`worker-bridge-setup: ignoring install-only flags with --remove: ${ignored.join(' ')}`);
69
118
  return { remove: true, worker, home, purge: !!args['--purge-home'] };
70
119
  }
71
120
  if (args['--purge-home']) fail('--purge-home is only valid with --remove');
72
- const mode = args['--expose'];
73
- if (args['--retry-public-check'] && (mode || args['--start'] || args['--write-units-only'] || args['--remove'])) fail('--retry-public-check takes --public-url and checks an existing service; omit --expose, --start, --write-units-only and --remove');
74
- if (mode !== undefined && mode !== 'tailscale' && mode !== 'ngrok') fail('--expose only supports "tailscale" (default on Linux and macOS) or "ngrok" (fallback)');
75
- if (args['--funnel-port'] !== undefined && mode !== 'tailscale') fail('--funnel-port needs --expose tailscale');
76
- if (args['--ngrok-domain'] !== undefined && mode !== 'ngrok') fail('--ngrok-domain needs --expose ngrok');
77
- if (mode === 'ngrok' && args['--ngrok-domain'] === undefined) fail('--expose ngrok needs --ngrok-domain <assigned-domain> (the static domain from your ngrok dashboard)');
78
- const ngrokDomain = args['--ngrok-domain'];
79
- if (ngrokDomain !== undefined && !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/.test(ngrokDomain)) fail('--ngrok-domain must be a bare host name such as your-name.ngrok-free.app (no https:// and no path)');
80
- if (mode && args['--public-url'] !== undefined) fail(`--public-url is derived with --expose ${mode}; do not pass both`);
81
- const funnelPort = args['--funnel-port'] === undefined ? undefined : Number(args['--funnel-port']);
82
- if (funnelPort !== undefined && (!Number.isInteger(funnelPort) || funnelPort < 1 || funnelPort > 65535)) fail('--funnel-port must be a port number');
83
- const publicUrl = mode ? null : parsePublicUrl(args['--public-url']);
121
+ const route = args['--route'];
122
+ if (route !== undefined && (!route || route.startsWith('-'))) fail('--route needs the name of a Gozar route');
123
+ if (args['--retry-public-check'] && (route || args['--start'] || args['--write-units-only'] || args['--remove'])) fail('--retry-public-check takes --public-url and checks an existing service; omit --route, --start, --write-units-only and --remove');
124
+ if (route !== undefined && args['--public-url'] !== undefined) fail('--public-url comes from the Gozar route with --route; do not pass both');
125
+ const publicUrl = route !== undefined ? null : parsePublicUrl(args['--public-url']);
84
126
  const port = Number(args['--port']);
85
127
  if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port N is required (1024-65535)');
86
128
  const node = stableNode(process.execPath);
@@ -104,7 +146,7 @@ function parseOptions(argv, platform) {
104
146
  return {
105
147
  worker, publicUrl, port, home, socketPath, node, repo, lan, writeUnitsOnly: !!args['--write-units-only'], start: !!args['--start'],
106
148
  repoTools: !args['--no-repo-tools'], retryPublicCheck: !!args['--retry-public-check'],
107
- expose: mode === 'tailscale' ? { mode, funnelPort } : mode === 'ngrok' ? { mode, domain: ngrokDomain } : null,
149
+ route,
108
150
  };
109
151
  }
110
152
 
@@ -712,17 +754,6 @@ function verifyRetryTarget(o, { platform, env }) {
712
754
  if(saved.origin!==o.publicUrl||saved.pathname!==`/${saved.pathname.split('/')[1]}/mcp`||!/^\/[a-f0-9]{64}\/mcp$/.test(saved.pathname)) fail('--retry-public-check refused: --public-url does not match this home resource URL');
713
755
  if(saved.pathname!==`/${secretMatch[1]}/mcp`) fail('--retry-public-check refused: the saved resource URL does not match this home path secret');
714
756
  if(as.public_url!==o.publicUrl) fail('--retry-public-check refused: --public-url does not match this home issuer');
715
- const exposureFile=expose.recordPath(o.home,o.worker);
716
- const exposure=JSON.parse(readOwnedFile(o.home,exposureFile,'exposure record'));
717
- const publicPort=Number(new URL(o.publicUrl).port||443);
718
- if(exposure.worker!==o.worker||exposure.public_url!==o.publicUrl||exposure.local_port!==o.port) fail('--retry-public-check refused: --public-url or --port does not match this worker exposure record');
719
- if (exposure.mode === 'tailscale') {
720
- if(exposure.dns_name!==saved.hostname||exposure.public_port!==publicPort) fail('--retry-public-check refused: --public-url or --port does not match this worker exposure record');
721
- } else if (exposure.mode === 'ngrok') {
722
- const configFile=expose.ngrokConfigPath(o.home,o.worker);
723
- const config=readOwnedFile(o.home,configFile,'ngrok config');
724
- if(exposure.domain!==saved.hostname||exposure.ngrok_config!==configFile||config!==expose.ngrokConfigText({worker:o.worker,domain:exposure.domain,localPort:o.port})) fail('--retry-public-check refused: ngrok domain or config does not match this worker exposure record');
725
- } else fail('--retry-public-check refused: exposure record has an unsupported mode');
726
757
  const dir=unitDirFor(platform,env), unit=platform==='darwin'?path.join(dir,`${launchLabel(o.worker)}.plist`):path.join(dir,`dot-bridge-${o.worker}.service`);
727
758
  const configRoot=platform==='darwin'?(env.HOME||os.homedir()):(env.XDG_CONFIG_HOME&&path.isAbsolute(env.XDG_CONFIG_HOME)?env.XDG_CONFIG_HOME:path.join(os.homedir(),'.config'));
728
759
  assertOwnedPath(configRoot,dir,'directory','service unit directory');
@@ -760,22 +791,19 @@ function waitForStartedBridge(o, env, platform, waitForSocket) {
760
791
  fail(`the service was started but the bridge did not answer on its admin socket ${o.socketPath} within ${Math.round(budget / 1000)} s. Read the service log with ${where}. Generated state is left in place; remove this install with: ${recoveryCommand(o)}`);
761
792
  }
762
793
 
763
- function runUnlocked(argv, { platform = process.platform, env = process.env, log = console.log, verifyPublic = expose.verifyPublic, resolve4 = expose.makePublicResolver(), preflight = expose.preflight, applyFunnel = expose.applyFunnel, initHome, spawn = spawnSync, tailscale, waitForSocket = waitForAdminSocket, holderProbe } = {}, parsed = null) {
794
+ function runUnlocked(argv, { platform = process.platform, env = process.env, log = console.log, verifyPublic: verify = verifyPublic, resolve4 = makePublicResolver(), initHome, spawn = spawnSync, waitForSocket = waitForAdminSocket, holderProbe } = {}, parsed = null) {
764
795
  const o = parsed ?? parseOptions(argv, platform);
765
796
  if (o.help) {
766
797
  log('usage: node scripts/worker-bridge-setup.mjs --worker NAME --public-url https://HOST --port N [--home DIR] [--lan-forward ADDR:PORT] [--write-units-only] [--start] [--no-repo-tools]');
767
- log(' or: node scripts/worker-bridge-setup.mjs --worker NAME --port N --expose tailscale [--funnel-port 443|8443|10000] [--start]');
768
- log(' or: node scripts/worker-bridge-setup.mjs --worker NAME --port N --expose ngrok --ngrok-domain ASSIGNED-DOMAIN [--start]');
798
+ log(' or: node scripts/worker-bridge-setup.mjs --worker NAME --port N --route GOZAR-ROUTE-NAME [--start]');
769
799
  log(' node scripts/worker-bridge-setup.mjs --retry-public-check --worker NAME --public-url https://HOST --port N [--home DIR]');
770
800
  log(' node scripts/worker-bridge-setup.mjs --repoint --worker NAME (point an existing service at this copy of the code)');
771
- log(' node scripts/worker-bridge-setup.mjs --remove --worker NAME [--home DIR] [--purge-home] (also turns off a recorded Funnel rule)');
801
+ log(' node scripts/worker-bridge-setup.mjs --remove --worker NAME [--home DIR] [--purge-home]');
772
802
  return;
773
803
  }
774
804
  if (o.repoint) return repointUnit(o, { platform, env, log });
775
805
  if (o.remove) {
776
- // The exposure record lives in the bridge home; turn our Funnel rule off before the unit and (optionally) the home go.
777
- const record = expose.recordPath(o.home, o.worker);
778
- if (fs.existsSync(record)) expose.removeExposure({ file: record, log, ...(tailscale ? { tailscale } : {}) });
806
+ // A durable Gozar route is the owner's; removing a worker never closes it.
779
807
  return removeUnit(o, { platform, env, log, spawn, ...(holderProbe ? { holderProbe } : {}) });
780
808
  }
781
809
  const linux = platform === 'linux', darwin = platform === 'darwin';
@@ -786,13 +814,8 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
786
814
  if(o.retryPublicCheck) {
787
815
  const {url,dnsName}=verifyRetryTarget(o,{platform,env});
788
816
  if(readEnv('DALAN_EXPOSE_SKIP_PUBLIC_CHECK',env)==='1') { log('SKIPPED public check (DALAN_EXPOSE_SKIP_PUBLIC_CHECK=1; tests only)'); return; }
789
- const exposureFile=expose.recordPath(o.home,o.worker);
790
- const retryRecord=JSON.parse(readOwnedFile(o.home,exposureFile,'exposure record'));
791
- if(retryRecord.mode==='ngrok') expose.updateExposureState(exposureFile,'unverified');
792
- return verifyPublic({url,dnsName,resolve4,log}).then(ok=>{
817
+ return verify({url,dnsName,resolve4,log}).then(ok=>{
793
818
  if(!ok) fail(`public verification failed; the service, home and keys were left in place. Retry after the public route is ready with: ${publicRetryCommand(o,url)}. To remove this install: ${recoveryCommand(o)}`);
794
- const record=JSON.parse(readOwnedFile(o.home,exposureFile,'exposure record'));
795
- if(record.mode==='ngrok') expose.updateExposureState(exposureFile,'verified');
796
819
  });
797
820
  }
798
821
 
@@ -805,19 +828,8 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
805
828
  }
806
829
  if (unitDir) for (const f of Object.keys(files)) if (fs.existsSync(path.join(unitDir, f))) fail(`${path.join(unitDir, f)} already exists; refusing to overwrite it`);
807
830
  if (darwin && !lintPlist(files[`${launchLabel(o.worker)}.plist`], env)) log('plutil not found: skipped the plist lint');
808
- // --expose tailscale: read-only preflight and port choice. Nothing above or below writes until this passes.
809
- let exposure = null;
810
- if (o.expose?.mode === 'tailscale') {
811
- const pf = preflight({ platform });
812
- for (const w of pf.warnings) log(`WARN ${w}`);
813
- const port = expose.choosePort({ requested: o.expose.funnelPort, allowed: pf.allowed, occupied: pf.occupied });
814
- o.publicUrl = expose.publicUrl(pf.dnsName, port);
815
- exposure = { mode: 'tailscale', dnsName: pf.dnsName, port, url: o.publicUrl, file: expose.recordPath(o.home, o.worker) };
816
- } else if (o.expose?.mode === 'ngrok') {
817
- // Nothing is run here. The URL is derived from the assigned domain; the config and commands come after the units.
818
- o.publicUrl = `https://${o.expose.domain}`;
819
- exposure = { mode: 'ngrok', domain: o.expose.domain, url: o.publicUrl, file: expose.recordPath(o.home, o.worker) };
820
- }
831
+ // --route: Gozar allocated or adopted the route before this point (see run()); only the public address is used here.
832
+ const exposure = o.route !== undefined ? { route: o.route, url: o.publicUrl, dnsName: new URL(o.publicUrl).hostname } : null;
821
833
 
822
834
  if (o.start) checkStartReadiness(platform, env);
823
835
  if (o.start) warnIfLingeringDisabled(platform, env, log, spawn);
@@ -853,26 +865,7 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
853
865
  log(`To stop: ${stop}`);
854
866
  } else log(`Not started. To start:\n launchctl bootstrap ${domain} ${plist}\nTo stop:\n ${stop}`);
855
867
  }
856
- // Tailscale Funnel: our own rule on our own port, then proof that it maps exactly that port to the bridge.
857
- if (exposure?.mode === 'tailscale') {
858
- try { expose.writeExposureRecord({ file: exposure.file, worker: o.worker, dnsName: exposure.dnsName, port: exposure.port, localPort: o.port, url: exposure.url }); }
859
- catch (error) { throw new Error(`${error.message}. Generated state is left in place; remove this install with: ${recoveryCommand(o)}`); }
860
- try {
861
- applyFunnel({ dnsName: exposure.dnsName, port: exposure.port, localPort: o.port });
862
- expose.updateExposureState(exposure.file, 'active');
863
- } catch (error) {
864
- throw new Error(`${error.message}. Funnel intent is recorded; remove this exact owned rule and install with: ${recoveryCommand(o)}`);
865
- }
866
- log(`Funnel: ${exposure.url} -> http://127.0.0.1:${o.port} (tailscale funnel --https=${exposure.port}); record ${exposure.file}`);
867
- } else if (exposure?.mode === 'ngrok') {
868
- let configFile;
869
- try { configFile = expose.writeNgrokExposure({ home: o.home, worker: o.worker, domain: exposure.domain, localPort: o.port, file: exposure.file }); }
870
- catch (error) { throw new Error(`${error.message}. Generated state is left in place; remove this install with: ${recoveryCommand(o)}`); }
871
- log(`ngrok config: ${configFile} (mode 0600, no authtoken in it); record ${exposure.file}`);
872
- log(`Public URL: ${exposure.url} -> http://127.0.0.1:${o.port}. ngrok was NOT run. Run these yourself:`);
873
- for (const c of expose.ngrokCommands(configFile)) log(` ${c}`);
874
- log(`QUOTA WARNING: ${expose.NGROK_QUOTA_WARNING}`);
875
- }
868
+ if (exposure) log(`Route: ${exposure.url} -> http://127.0.0.1:${o.port} (Gozar route ${exposure.route})`);
876
869
  if (o.lan) log(`LAN forwarder: ${o.lan.address}:${o.lan.port} -> 127.0.0.1:${o.port}. Point the reverse proxy there; anything on that network can reach it.`);
877
870
  log(`Resource URL file (private, mode 0600): ${urlFile}`);
878
871
  const dw = `dalan() { HOME=${shellQuote(o.home)} ${shellQuote(o.node)} ${shellQuote(path.join(o.repo, 'bin/dalan.mjs'))} "$@"; }`;
@@ -883,10 +876,6 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
883
876
  log(` dalan connect approve CODE --worker ${o.worker}`);
884
877
  log(' dalan connect signal-token # save wake URL privately for hook-driven workers; print path; --rotate replaces it');
885
878
  if (!exposure) return undefined;
886
- if (exposure.mode === 'ngrok') {
887
- log(`Public status: unverified until the ngrok service is started and --retry-public-check succeeds. ngrok was not started. After starting it, verify with: ${publicRetryCommand(o, exposure.url)}`);
888
- return undefined;
889
- }
890
879
  // Public check only after the bridge starts. Returns a promise; the entry point awaits it and exits 1 on failure.
891
880
  const { dnsName, url } = exposure;
892
881
  if (!o.start) {
@@ -894,15 +883,36 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
894
883
  return undefined;
895
884
  }
896
885
  if (readEnv('DALAN_EXPOSE_SKIP_PUBLIC_CHECK',env) === '1') { log('SKIPPED public check (DALAN_EXPOSE_SKIP_PUBLIC_CHECK=1; tests only)'); return undefined; }
897
- return verifyPublic({ url, dnsName, resolve4, log }).then(ok => {
886
+ return verify({ url, dnsName, resolve4, log }).then(ok => {
898
887
  if (!ok) fail(`public verification failed; the service, home and keys were left in place. Retry the check with: ${publicRetryCommand(o,url)}. To remove this install: ${recoveryCommand(o)}`);
899
888
  });
900
889
  }
901
890
 
891
+ // With --route, Gozar allocates (or finds) the durable route first; its origin is the bridge's public address. Nothing is written
892
+ // before Gozar answers, and an owner who declines leaves nothing behind.
893
+ async function allocateRoute(parsed, seams) {
894
+ const env = seams.env ?? process.env;
895
+ const gozar = seams.gozar ?? await resolveGozar();
896
+ const query = buildQuery({ home: gozarHomeFor(env), target: `127.0.0.1:${parsed.port}`, route: parsed.route, address: 'stable', usage: { kind: 'durable', routeId: `dalan-${parsed.worker}` } });
897
+ const consent = seams.consent ?? (async candidate => {
898
+ if (!process.stdin.isTTY) fail('this route needs your approval; run this in a terminal, or run `dalan setup --route NAME` first');
899
+ for (const line of [...describeCandidate(candidate), ...describeDisclosure(candidate)]) console.log(line);
900
+ const rl = (await import('node:readline')).createInterface({ input: process.stdin, output: process.stdout });
901
+ const answer = await new Promise(resolve => rl.question('Use this route? [y/N] ', resolve)); rl.close();
902
+ return ['y', 'yes'].includes(answer.trim().toLowerCase());
903
+ });
904
+ parsed.publicUrl = (await ensureDurableRoute({ gozar, query, consent })).origin;
905
+ }
906
+
902
907
  export function run(argv, seams = {}) {
903
908
  if (argv.includes('--help')) return runUnlocked(argv, seams);
904
909
  // Reject malformed arguments before creating the per-home lock directory.
905
910
  const parsed = parseOptions(argv, seams.platform ?? process.platform);
911
+ if (parsed.route !== undefined) return allocateRoute(parsed, seams).then(() => runLocked(argv, seams, parsed));
912
+ return runLocked(argv, seams, parsed);
913
+ }
914
+
915
+ function runLocked(argv, seams, parsed) {
906
916
  // The lock is per user and host-wide by default, so installers with different HOME values still serialize on one unit directory.
907
917
  // DALAN_SETUP_LOCK_DIR (an absolute path) moves it, for example so concurrent test runs do not collide.
908
918
  const envRoot = (seams.env ?? process.env).DALAN_SETUP_LOCK_DIR;
package/src/as-store.mjs CHANGED
@@ -390,8 +390,8 @@ export class AsStore {
390
390
  return this.db.prepare("SELECT * FROM pairings WHERE state='pending' AND expires_at>? ORDER BY created_at").all(now).map(row => this.#resource(row));
391
391
  }
392
392
  // Atomic reservation: exactly one approval wins a pending code, and it reserves only that code.
393
- // A web pairing (https redirect to a fixed vendor) is refused while a newer web pairing is pending for the same worker:
394
- // an app that registered again abandons its older attempts, and a re-registration reaches the same vendor.
393
+ // A web pairing (https redirect) is refused while a newer web pairing at the same redirect origin is pending for the same worker:
394
+ // an app that registered again abandons its older attempts, and a re-registration reaches the same origin. Other origins never displace it.
395
395
  // A native pairing (loopback redirect) is never refused for a newer attempt and never displaces another one: its
396
396
  // redirect names no party, so a newer registrant must not take the owner's approval from an older teammate.
397
397
  reserve(code) {
@@ -400,9 +400,11 @@ export class AsStore {
400
400
  const row = this.db.prepare("SELECT rowid AS rid, * FROM pairings WHERE code=? AND state='pending' AND expires_at>?").get(code, now);
401
401
  if (!row) return false;
402
402
  if (!isLoopbackCallback(new URL(row.redirect_uri))) {
403
+ // Only a newer web pairing at the SAME redirect origin displaces this one. A client at another origin cannot starve it.
404
+ const origin = new URL(row.redirect_uri).origin;
403
405
  const newer = this.db.prepare("SELECT redirect_uri FROM pairings WHERE state='pending' AND expires_at>? AND worker=? AND rowid<>? AND (created_at>? OR (created_at=? AND rowid>?))")
404
406
  .all(now, row.worker, row.rid, row.created_at, row.created_at, row.rid);
405
- if (newer.some(p => !isLoopbackCallback(new URL(p.redirect_uri)))) return false;
407
+ if (newer.some(p => !isLoopbackCallback(new URL(p.redirect_uri)) && new URL(p.redirect_uri).origin === origin)) return false;
406
408
  }
407
409
  return this.db.prepare("UPDATE pairings SET state='approving' WHERE code=? AND state='pending'").run(code).changes === 1;
408
410
  });
package/src/as.mjs CHANGED
@@ -7,6 +7,8 @@ import { randomUUID } from 'node:crypto';
7
7
  import { performance } from 'node:perf_hooks';
8
8
  import { acquireAsOwner, asFiles, LIFETIMES, PAIRING_MINUTES, loadAsConfig, loadKeys, isLoopbackCallback, matchesCallback, parseAsConfig, parseCallbackPattern, parseNativeLoopback, saveAsCallbacks, untrusted } from './as-files.mjs';
9
9
  import { AsStore, LIMITS, normalizeCode, showCode } from './as-store.mjs';
10
+ import { matchRegisteredRedirect, validateRedirectUri } from './redirect-policy.mjs';
11
+ import { approvalFacts, approvalRecord, describeClient } from './client-approval.mjs';
10
12
 
11
13
  // The built-in authorization server. The protocol (registration, PKCE, codes, tokens, rotation, revocation) is the maintained
12
14
  // oidc-provider library. This file holds only configuration, the owner-approval policy around it, and the lookup that turns a
@@ -53,17 +55,11 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
53
55
  if (!secure && !allowHttp && !loopback) throw new Error('as: an http public_url needs the explicit test flag');
54
56
  let patterns = config.patterns;
55
57
  if (new URL(resource).origin !== publicUrl.origin) throw new Error('as: resource must live on the public URL');
56
- const callbackAllowed = uri => matchesCallback(patterns, uri);
58
+ // Who may register is decided by the redirect URI's own properties (src/redirect-policy.mjs), never by a list of vendors or a client name.
59
+ // Owner-added patterns from older versions stay valid, so an existing registration keeps working; they only add, never restrict.
60
+ const callbackAllowed = uri => validateRedirectUri(uri).ok || matchesCallback(patterns, uri);
57
61
  // Native registrations ignore only the port; the approved request still binds the full redirect URI.
58
- const registeredRedirectAllowed = (client, redirect) => client?.redirectUris?.some(uri => {
59
- if(uri===redirect)return true;
60
- try {
61
- const requested = parseNativeLoopback(redirect);
62
- const registered = parseNativeLoopback(uri);
63
- return requested.loopback && registered.loopback
64
- && requested.hostname === registered.hostname && requested.pathname === registered.pathname;
65
- } catch { return false; }
66
- });
62
+ const registeredRedirectAllowed = (client, redirect) => matchRegisteredRedirect(client?.redirectUris, redirect);
67
63
 
68
64
  const policy = (ctx, metadata) => {
69
65
  if (Buffer.byteLength(JSON.stringify(metadata)) > 4096 || (metadata.client_name?.length ?? 0) > 128 || (metadata.redirect_uris?.length ?? 0) > 8 || metadata.redirect_uris?.some(uri => uri.length > 512)) throw new errors.InvalidClientMetadata('client metadata exceeds the size limit');
@@ -71,7 +67,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
71
67
  for (const uri of metadata.redirect_uris) {
72
68
  if (!callbackAllowed(uri)) {
73
69
  log({ kind: 'as_registration_refused' });
74
- throw new errors.InvalidClientMetadata('redirect_uris must each match an allowed vendor callback (dalan connect allow-callback)');
70
+ throw new errors.InvalidClientMetadata('redirect_uris must each be a plain https URL or a native loopback URL (http://127.0.0.1, http://[::1] or http://localhost)');
75
71
  }
76
72
  }
77
73
  const nativeRedirects = metadata.redirect_uris.map(uri => isLoopbackCallback(new URL(uri)));
@@ -349,7 +345,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
349
345
  const scopes = requestedScopes(details.params.scope);
350
346
  const redirect = details.params.redirect_uri;
351
347
  if (!scopes.some(s => ACCEPTED_SCOPES.includes(s))) return page(res, 400, 'No usable scope', '<p>The app asked for no scope that this bridge offers.</p>');
352
- if (!client || !registeredRedirectAllowed(client, redirect) || !callbackAllowed(redirect)) return page(res, 400, 'Callback not allowed', '<p>The app\'s callback address is not on this bridge\'s allowed list.</p>');
348
+ if (!client || !registeredRedirectAllowed(client, redirect) || !callbackAllowed(redirect)) return page(res, 400, 'Callback not allowed', '<p>The app\'s callback address is not an address this bridge accepts (a plain https URL, or a native loopback URL registered by the app).</p>');
353
349
  if (details.params.resource !== resource) return page(res, 400, 'Wrong resource', '<p>The app did not ask for this bridge\'s resource.</p>');
354
350
  try {
355
351
  pairing = store.pairingFor(uid, { client_id: client.clientId, client_name: untrusted(client.clientName), redirect_uri: redirect, resource, scopes: scopes.join(' '), interaction_expires_at: details.exp * 1000 }, window);
@@ -361,7 +357,9 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
361
357
  if (!window || window.worker !== pairing.worker) return page(res, 403, 'Not accepting connections', '<p>This bridge is not accepting new connections right now.</p>');
362
358
  const code = showCode(pairing.code);
363
359
  const native = isLoopbackCallback(new URL(pairing.redirect_uri));
364
- page(res, 200, 'Connect to Dalan', `<p>Pairing code</p><p class="code">${html(code)}</p><p>Run approval on the bridge computer:</p><pre>dalan connect approve ${html(code)} --worker ${html(pairing.worker)}</pre>${native ? '<p>Native client, identity not verified: host and name prove nothing. The owner must compare this code with the teammate\'s browser page over a trusted channel. The redirect confirmation is only a typo check, not proof of identity.</p>' : ''}<p>This page waits. It checks again every few seconds.</p>`, { refresh: 3 });
360
+ const facts = approvalFacts(describeClient({ name: pairing.client_name, clientId: pairing.client_id, redirectUri: pairing.redirect_uri, worker: pairing.worker, issuer: shownIssuer, resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), code }));
361
+ const factList = `<dl>${facts.map(([label, value]) => `<dt>${html(label)}</dt><dd>${html(value)}</dd>`).join('')}</dl>`;
362
+ page(res, 200, 'Connect to Dalan', `<p>Pairing code</p><p class="code">${html(code)}</p>${factList}<p>Run approval on the bridge computer:</p><pre>dalan connect approve ${html(code)} --worker ${html(pairing.worker)}</pre>${native ? '<p>Native client, identity not verified: host and name prove nothing. The owner must compare this code with the teammate\'s browser page over a trusted channel. The redirect confirmation is only a typo check, not proof of identity.</p>' : '<p>The client name and redirect above are set by the app and are not verified. The owner approves only the code that matches this page.</p>'}<p>This page waits. It checks again every few seconds.</p>`, { refresh: 3 });
365
363
  }
366
364
  async function complete(req, res, details, pairing, client) {
367
365
  const connection = store.connectionByGrant(pairing.grant_id);
@@ -379,24 +377,34 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
379
377
 
380
378
  // ---- owner operations (called from the owner Unix socket only) -------------------------------------------------
381
379
  // Some web apps register multiple clients during one connection flow, so an older pending web code for the same worker
382
- // may no longer finish its token exchange. Those older codes stay visible, marked superseded by the newest web one.
380
+ // may no longer finish its token exchange. Those older codes stay visible, marked superseded by the newest web one at the same redirect origin.
383
381
  // Native (loopback) pairings are never superseded: each is approved by its own code only.
384
382
  const supersede = views => {
385
- const newest = views.filter(view => !view.native).at(-1);
386
- return views.map(view => view.native || view === newest ? view : { ...view, superseded: true, superseded_by: newest.code });
383
+ const newestByOrigin = new Map();
384
+ for (const view of views) if (!view.native) newestByOrigin.set(new URL(view.redirect_uri).origin, view);
385
+ return views.map(view => {
386
+ const newest = view.native ? null : newestByOrigin.get(new URL(view.redirect_uri).origin);
387
+ return !newest || view === newest ? view : { ...view, superseded: true, superseded_by: newest.code };
388
+ });
387
389
  };
390
+
388
391
  // The owner CLI never prints the bridge path secret (approve output checks this), so show the resource's origin and shape only.
389
392
  const shownResource = resource => `${new URL(resource).origin}/<secret>/mcp`;
390
- const pendingView = pairing => ({
391
- code: showCode(pairing.code), worker: pairing.worker, client_id: pairing.client_id, client_name: untrusted(pairing.client_name), client_name_untrusted: true,
392
- native: isLoopbackCallback(new URL(pairing.redirect_uri)),
393
- redirect_uri: pairing.redirect_uri, resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), age_seconds: Math.max(0, Math.round((now() - pairing.created_at) / 1000)),
394
- expires_in_seconds: Math.max(0, Math.round((pairing.expires_at - now()) / 1000)),
395
- });
393
+ const shownIssuer = `${publicUrl.origin}/<secret>/oauth`; // the issuer carries the secret path prefix too
394
+ const pendingView = pairing => {
395
+ const shown = describeClient({ name: pairing.client_name, clientId: pairing.client_id, redirectUri: pairing.redirect_uri, worker: pairing.worker, issuer: shownIssuer, resource: '', scopes: [] });
396
+ return {
397
+ code: showCode(pairing.code), worker: pairing.worker, client_id: pairing.client_id, client_name: untrusted(pairing.client_name), client_name_untrusted: true,
398
+ native: isLoopbackCallback(new URL(pairing.redirect_uri)),
399
+ redirect_uri: pairing.redirect_uri, redirect_host: shown.redirect_host, redirect_origin: shown.redirect_origin, redirect_punycode: shown.redirect_punycode, known_client: shown.known_client,
400
+ resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), age_seconds: Math.max(0, Math.round((now() - pairing.created_at) / 1000)),
401
+ expires_in_seconds: Math.max(0, Math.round((pairing.expires_at - now()) / 1000)),
402
+ };
403
+ };
396
404
  const known = worker => typeof worker === 'string' && workerNames().includes(worker);
397
405
  const ops = {
398
406
  addClient({ redirectUri, name } = {}) {
399
- if (!callbackAllowed(redirectUri)) throw new Error('redirect_uri must match an allowed vendor callback');
407
+ if (!callbackAllowed(redirectUri)) throw new Error('redirect_uri must be a plain https URL or a native loopback URL');
400
408
  if (name !== undefined && (typeof name !== 'string' || name.length > 100 || !untrusted(name, 80))) throw new Error('name must be a non-empty string of at most 100 characters');
401
409
  const metadata = {
402
410
  client_id: randomUUID(), redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'],
@@ -409,7 +417,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
409
417
  delete persisted.client_secret_expires_at;
410
418
  const createdAt = store.addStaticClient(client.clientId, persisted);
411
419
  log({ kind: 'static_client_added', client_id: client.clientId });
412
- return { client_id: client.clientId, created_at: new Date(createdAt).toISOString() };
420
+ return { client_id: client.clientId, token_endpoint_auth_method: 'none', redirect_uris: [redirectUri], created_at: new Date(createdAt).toISOString() };
413
421
  },
414
422
  clients() {
415
423
  return { clients: store.clientRows().map(({ client_id, metadata, created_at, is_static }) => ({
@@ -472,7 +480,8 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
472
480
  const { connection_id, replaced } = store.commitApproval({ code: pairing.code, worker, grantId, snapshot: pairing, replace });
473
481
  if (replaced) store.revokeGrant(replaced.grant_id, 'replaced');
474
482
  log({ kind: 'connection_approved', connection_id, worker, client_id: pairing.client_id, replaced: !!replaced });
475
- return { approved: true, connection_id, worker, grant_id: grantId, client_id: pairing.client_id, redirect_uri: pairing.redirect_uri, scopes: pairing.scopes.split(' '), replaced: replaced?.connection_id ?? null };
483
+ const approval = approvalRecord({ worker, issuer: shownIssuer, resource: shownResource(pairing.resource), clientId: pairing.client_id, redirectUri: pairing.redirect_uri, scopes: pairing.scopes.split(' '), approvedAt: now(), connectionId: connection_id });
484
+ return { approved: true, connection_id, worker, grant_id: grantId, client_id: pairing.client_id, redirect_uri: pairing.redirect_uri, redirect_origin: approval.redirectOrigin, approval, scopes: pairing.scopes.split(' '), replaced: replaced?.connection_id ?? null };
476
485
  } catch (error) {
477
486
  store.failPairing(pairing.code);
478
487
  if (grantId) { try { store.revokeGrant(grantId, 'approval_failed'); } catch { /* the grant has no connection row; deleting its rows is enough */ } }
@@ -482,7 +491,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
482
491
  list() {
483
492
  const window = store.window();
484
493
  return { window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, callbacks: patterns.map(p => p.pattern),
485
- connections: store.connections().map(c => ({ connection_id: c.connection_id, worker: c.worker, client_id: c.client_id, redirect_uri: c.redirect_uri, scopes: c.scopes.split(' '), created_at: new Date(c.created_at).toISOString(), revoked_at: c.revoked_at === null ? null : new Date(c.revoked_at).toISOString(), revoked_reason: c.revoked_reason })) };
494
+ connections: store.connections().map(c => ({ connection_id: c.connection_id, worker: c.worker, client_id: c.client_id, redirect_uri: c.redirect_uri, redirect_origin: validateRedirectUri(c.redirect_uri).origin ?? null, scopes: c.scopes.split(' '), created_at: new Date(c.created_at).toISOString(), revoked_at: c.revoked_at === null ? null : new Date(c.revoked_at).toISOString(), revoked_reason: c.revoked_reason })) };
486
495
  },
487
496
  revoke({ worker }) {
488
497
  if (!known(worker)) throw new Error('unknown worker');
@@ -0,0 +1,53 @@
1
+ // `dalan doctor --auth`: a real OAuth client walk against the PUBLIC MCP URL of this home's bridge. The walk itself is
2
+ // runSelfCheck; here the owner's approval is done through the owner admin socket, and the one connection it creates is
3
+ // revoked when the walk ends. A worker that already has a connection is never touched: approving would replace it.
4
+ // No token, pairing code, secret path or full URL is written to any output.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { runSelfCheck } from './try-selfcheck.mjs';
8
+
9
+ const fail = (name, detail) => ({ ok: false, results: [{ name, status: 'FAIL', detail }] });
10
+
11
+ export async function runAuthCheck({ home, workers, worker, request, operator, fetchImpl = fetch, say = () => {}, approveWaitMs = 30_000 }) {
12
+ let url;
13
+ try { url = fs.readFileSync(path.join(home, 'resource-url'), 'utf8').trim(); } catch { url = ''; }
14
+ if (!url) {
15
+ const detail = `no resource-url file in ${home}: this home has no public MCP URL to check (run dalan setup or dalan try first)`;
16
+ say(`FAIL input: ${detail}`); say('RESULT FAIL');
17
+ return fail('input', detail);
18
+ }
19
+ const names = [...workers];
20
+ if (worker && !names.includes(worker)) { const detail = `unknown worker; configured workers: ${names.join(', ') || 'none'}`; say(`FAIL input: ${detail}`); say('RESULT FAIL'); return fail('input', detail); }
21
+ if (!worker) {
22
+ if (names.length !== 1) { const detail = names.length ? `${names.length} workers are configured (${names.join(', ')}); choose one with --worker NAME` : 'no worker is configured'; say(`FAIL input: ${detail}`); say('RESULT FAIL'); return fail('input', detail); }
23
+ worker = names[0];
24
+ }
25
+ const headers = () => ({ 'x-operator-key': operator() });
26
+ let listing;
27
+ try { listing = await request('/connect/list', 'GET', null, headers()); }
28
+ catch (error) { const detail = `cannot ask the bridge about connections: ${String(error?.message ?? error).split('\n')[0].slice(0, 160)}`; say(`FAIL bridge: ${detail}`); say('RESULT FAIL'); return fail('bridge', detail); }
29
+ const existing = (listing.connections ?? []).some(c => c.worker === worker && c.revoked_at === null);
30
+ if (existing) {
31
+ const partial = await runSelfCheck({ url, fetchImpl, say, discoveryOnly: true });
32
+ const detail = `worker ${worker} already has a connection (it would be replaced)`;
33
+ say(`SKIP full walk: ${detail}`);
34
+ return { ok: false, partial: true, results: [...partial.results, { name: 'full walk', status: 'SKIP', detail }] };
35
+ }
36
+ // Registration needs an open pairing window, so the window opens first. One that is already open belongs to someone else.
37
+ if (listing.window) { const detail = `a pairing window is already open (worker ${listing.window.worker}); finish it or run dalan connect stop, then retry`; say(`FAIL input: ${detail}`); say('RESULT FAIL'); return fail('input', detail); }
38
+ let approved = false;
39
+ const approve = async ({ code }) => {
40
+ try { await request('/connect/approve', 'POST', { code, worker, replace: false }, headers()); approved = true; }
41
+ catch (error) { throw new Error(`the owner approval was refused: ${String(error?.message ?? error).split('\n')[0].replaceAll(code, '[code]').slice(0, 120)}`); }
42
+ };
43
+ let outcome, cleanupFailed = false;
44
+ try { await request('/connect/start', 'POST', { worker }, headers()); }
45
+ catch (error) { const detail = `cannot open the pairing window: ${String(error?.message ?? error).split('\n')[0].slice(0, 120)}`; say(`FAIL bridge: ${detail}`); say('RESULT FAIL'); return fail('bridge', detail); }
46
+ try { outcome = await runSelfCheck({ url, fetchImpl, say, approve, approveWaitMs }); }
47
+ finally {
48
+ // Leave the worker as it was: this walk's one connection goes, and a window it opened closes.
49
+ if (approved) { try { await request('/connect/revoke', 'POST', { worker }, headers()); say(`cleanup: the self-check connection for worker ${worker} was revoked`); } catch { cleanupFailed = true; say('FAIL cleanup: the self-check connection could not be revoked; run: dalan connect revoke ' + worker); } }
50
+ try { await request('/connect/stop', 'POST', {}, headers()); } catch { /* the window expires by itself */ }
51
+ }
52
+ return cleanupFailed ? { ok: false, results: [...outcome.results, { name: 'cleanup', status: 'FAIL', detail: `the self-check connection for worker ${worker} was not revoked` }] } : outcome;
53
+ }
package/src/cli-help.mjs CHANGED
@@ -6,21 +6,26 @@ import { docsUrl } from './docs-url.mjs';
6
6
  // commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
7
7
  // `dalan help --internal`. Every command runs and has its own help either way.
8
8
  export const COMMANDS = [
9
- { name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--client chatgpt|claude] [--route auto|gozar|localhost.run|tailscale]] [--home DIR] [--port N] [--callback PATTERN]...',
10
- detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client such as ChatGPT or claude.ai (the default). `auto` honors a saved temporary-relay choice; otherwise it uses a usable Tailscale route and selects Gozar if no Tailscale route is usable. When it selects Gozar, Dalan names tunnl.gg, links its terms and privacy notice, and asks for consent before exposure. After consent, bundled Gozar creates an installation-owned key and opens the temporary demo link through tunnl.gg. Dalan never uses your SSH keys. The relay ends TLS and can see the connector URL and traffic; the link can stop or change without warning, including within minutes.',
11
- 'Dalan checks the original public address and ends the trial when it detects a change or route loss. The trial itself ends after 3 hours at most. Ctrl-C stops the run; Dalan closes its forwarding gate and attempts to remove its route. If cleanup cannot be confirmed, it reports this and prints a recovery command. Keep private work out of the demo. A Tailscale route is separate from the temporary relay. Choose this computer only, or pass --local, for a',
12
- 'self-check with a built-in demo worker; then connect a local client. With no terminal (dalan try < /dev/null) it runs the local self-check and never opens a route.', '',
13
- 'Options:', ' --local this computer only', ' --public public trial with the chatgpt or claude sign-in profile (other clients: see Connect any MCP worker in the README)', ' --client NAME chatgpt (default) or claude; implies --public',
14
- '', 'When `auto` selects Gozar because a temporary-relay choice was saved or Tailscale is unavailable, Gozar supplies the tunnl.gg key-bound relay; Dalan keeps OAuth sign-in and identity checks. After consent, Gozar creates a private key for this installation. Dalan does not use your SSH keys. Gozar is bundled; no separate install is needed.',
15
- ' --route NAME auto (saved temporary-relay choice, otherwise usable Tailscale, then bundled Gozar with relay consent), gozar, localhost.run or tailscale; implies --public', ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
9
+ { name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--route NAME]] [--home DIR] [--port N] [--callback PATTERN]...',
10
+ detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client (the default) or this computer only. For a hosted client, Dalan asks Gozar for a public HTTPS route, shows what Gozar says about it (who can read the traffic, whether the address is stable, what it costs), and asks for consent before anything is exposed.',
11
+ 'Dalan checks the original public address and ends the trial when it detects a change or route loss. A temporary route lasts for the trial, 3 hours at most; Ctrl-C stops the run and Dalan asks Gozar to remove the route. If cleanup cannot be confirmed, it reports this. A route you saved with `dalan setup` is durable: ending the run never removes it. Keep private work out of a temporary demo.',
12
+ 'Choose this computer only, or pass --local, for a self-check with a built-in demo worker; then connect a local client. With no terminal (dalan try < /dev/null) it runs the local self-check and never opens a route.', '',
13
+ 'Options:', ' --local this computer only', ' --public public trial through a Gozar route', ' --route NAME use the Gozar route with this name (Gozar decides what the name means); implies --public',
14
+ ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
16
15
  ' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN local mode only: allow one more OAuth callback pattern; repeatable', '',
17
- 'Example: dalan try', 'Use the Home this run prints for follow-up commands. With no --home or DALAN_HOME, local mode uses ~/.local/share/dalan-trial, a public trial creates a new home, and a usable Tailscale route on this computer uses ~/.local/share/dalan-hosted-<client>. A home is reused only at the same public address. --port is the local bridge port, never the public port.', `In local mode, connect your own worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
18
- { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup',
19
- detail: ['Saves a route choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in. If Tailscale is installed and ready for Funnel, it asks whether to save Tailscale; choosing no saves Gozar for temporary links.', 'If not, it lists the choices (install Tailscale, or save Gozar for temporary links) and saves nothing until you choose.',
20
- 'Afterwards `dalan try --public --route tailscale` selects Tailscale explicitly without a route question (Tailscale login, client sign-in and approval can still be asked). Auto honors a saved temporary-relay choice; otherwise it uses Tailscale when usable and bundled Gozar with consent when not. Explicit `--route tailscale` never falls back to a trial link.', '', 'Example: dalan setup'] },
21
- { name: 'service', group: 'operator', summary: 'Install or migrate a long-running bridge service', usage: 'dalan service install|migrate-workers [options]',
16
+ 'Example: dalan try', 'Use the Home this run prints for follow-up commands. With no --home or DALAN_HOME, local mode uses ~/.local/share/dalan-trial, a temporary public trial creates a new home, and a saved stable route uses ~/.local/share/dalan-hosted. A home is reused only at the same public address. --port is the local bridge port, never the public port.', `In local mode, connect your own worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
17
+ { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup [--route NAME]',
18
+ detail: ['Asks Gozar which routes can serve Dalan, shows what it returned, and saves your choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in.',
19
+ 'With --route NAME, asks Gozar for the route with that name. Afterwards `dalan try --public` uses the saved route.', '', 'Example: dalan setup'] },
20
+ { name: 'service', group: 'operator', summary: 'Install, update or inspect a long-running bridge service', usage: 'dalan service install|migrate-workers|update|auto-update|status [options]',
22
21
  detail: ['Install a bridge as a systemd user service and register its existing HTTPS origin with Gozar.', '',
23
- 'Install: 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] [--write-units-only]',
22
+ 'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--route NAME] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]',
23
+ 'New installs enable a daily update timer with up to one hour of jitter. Existing preferences are preserved.',
24
+ 'Update: dalan service update [--check|--yes] [--retry] [--home DIR] [--json]. --check only reports availability. --retry tries a release again after a rollback.',
25
+ 'Updates install side by side, check every worker catalog, then restart and health-check the bridge. Failures attempt to restore the previous install and saved state; a failed rollback is reported.',
26
+ 'Changed tool descriptors stage without switching. Refresh the hosted connectors when you explicitly switch with --yes. The timer never supplies --yes.',
27
+ 'Automatic updates: dalan service auto-update on|off [--home DIR]. Status: dalan service status [--home DIR] [--json] shows the last result.',
28
+ 'Service installation and update timers require Linux systemd; launchd is not supported by this command.',
24
29
  'Use --worker once per worker for an empty home. To preserve existing repository allowlists, run `dalan service migrate-workers` first and omit --worker.',
25
30
  'The bridge listens on 127.0.0.1. For a Gozar target on another address, systemd forwards that target to the fixed loopback port.',
26
31
  'Migrate: dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]',
@@ -73,8 +78,8 @@ export const COMMANDS = [
73
78
  detail: ['Subcommands:', ' allow NAME OWNER/REPO let a worker use a repository', ' deny NAME OWNER/REPO stop a worker using it', ' list [NAME] show each worker\'s repository access', ' migrate-repos convert an old repository policy; stop the service first'] },
74
79
  { name: 'tool', group: 'operator', summary: 'Register tools and choose which workers may call them', usage: 'dalan tool add --file PATH | remove NAME | list | grant NAME WORKER | revoke NAME WORKER [--json]',
75
80
  detail: ['Manages the owner-side tool registry. A worker sees and calls only the tools granted to it. Changing the registry never changes the advertised MCP tool list.', '', 'Subcommands:', ' add --file PATH register a tool from a JSON file: name, description, class (read|write), inputSchema, handler', ' remove NAME remove a tool and its grants', ' list show tools, classes, schema hashes and granted workers', ' grant NAME WORKER let a worker call a tool', ' revoke NAME WORKER stop a worker calling a tool'] },
76
- { name: 'doctor', group: 'operator', summary: 'Check the host setup', usage: 'dalan doctor [--checks] [--json]',
77
- detail: ['Reports whether this host can run jobs.', '', 'Options:', ' --checks lint the owner\'s checks.json instead (local only)', ' --json print JSON'] },
81
+ { name: 'doctor', group: 'operator', summary: 'Check the host setup', usage: 'dalan doctor [--checks | --auth [--worker NAME]] [--json]',
82
+ detail: ['Reports whether this host can run jobs.', '', 'Options:', ' --checks lint the owner\'s checks.json instead (local only)', ' --auth walk the public MCP URL as an OAuth client: challenge, discovery, sign-in, token, tools. Needs a running bridge and a resource-url file in this home.', ' It approves one pairing for the worker through the owner socket and revokes it after. A worker that already has a connection is not touched: only the steps that need no approval run (exit 2).', ' --worker the worker to walk with --auth (required when several are configured)', ' --json print JSON'] },
78
83
  { name: 'paths', group: 'operator', summary: 'Print where Dalan keeps its files', usage: 'dalan paths [--json | --workspace-root | --config-root | --data-root | --state-root]' },
79
84
  { name: 'pause', group: 'operator', summary: 'Stop handing out new jobs', usage: 'dalan pause --reason TEXT' },
80
85
  { name: 'resume', group: 'operator', summary: 'Resume handing out jobs', usage: 'dalan resume' },