@tnunamak/dalan 0.0.0-stage → 0.6.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 (199) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +351 -0
  5. package/README.md +215 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +43 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +764 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/codex-to-muse.md +175 -0
  17. package/docs/connect-chatgpt.md +83 -0
  18. package/docs/connection-longevity.md +43 -0
  19. package/docs/dalan-upgrade.md +246 -0
  20. package/docs/deadman.md +61 -0
  21. package/docs/dot-pr-reviewer.config.example.json +9 -0
  22. package/docs/durability-audit.md +27 -0
  23. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  24. package/docs/keycloak-oauth-setup.md +30 -0
  25. package/docs/local-agent-mcp.md +41 -0
  26. package/docs/manual-setup.md +135 -0
  27. package/docs/mirror-fetch.md +97 -0
  28. package/docs/operations.md +799 -0
  29. package/docs/operator-duties.md +68 -0
  30. package/docs/owner-integrator.md +27 -0
  31. package/docs/portable-auth-profile.md +107 -0
  32. package/docs/pr-head-reviewer.md +70 -0
  33. package/docs/pr-preflight.md +28 -0
  34. package/docs/pull-queue.md +131 -0
  35. package/docs/pull-workers.md +94 -0
  36. package/docs/redaction.md +27 -0
  37. package/docs/service-setup.md +219 -0
  38. package/docs/setup-reference.md +80 -0
  39. package/docs/t3-connector-icon.png +0 -0
  40. package/docs/t3-integration.md +51 -0
  41. package/docs/t3-result-retry-delivery.md +41 -0
  42. package/docs/t3-reverse-control.md +107 -0
  43. package/docs/usage.md +443 -0
  44. package/docs/worker-clients.md +290 -0
  45. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  46. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  47. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  48. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  49. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  50. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  51. package/package.json +67 -4
  52. package/packages/job-core/README.md +18 -0
  53. package/packages/job-core/index.mjs +2 -0
  54. package/packages/job-core/package.json +8 -0
  55. package/packages/job-core/protocol/canonical.mjs +11 -0
  56. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  57. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  58. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  59. package/packages/job-core/transitions.mjs +25 -0
  60. package/scripts/daily-selfcheck.mjs +135 -0
  61. package/scripts/dalan-try-selfcheck.mjs +29 -0
  62. package/scripts/lib/expose-tailscale.mjs +408 -0
  63. package/scripts/live-trial/common.mjs +272 -0
  64. package/scripts/monitor-targets.mjs +44 -0
  65. package/scripts/upgrade-drain.mjs +39 -0
  66. package/scripts/worker-bridge-setup.mjs +925 -0
  67. package/src/ack-ledger.mjs +37 -0
  68. package/src/acp-bridge.mjs +418 -0
  69. package/src/acp-context.mjs +138 -0
  70. package/src/admin-socket.mjs +14 -0
  71. package/src/alerts.mjs +147 -0
  72. package/src/artifact-journal.mjs +75 -0
  73. package/src/as-files.mjs +347 -0
  74. package/src/as-store.mjs +456 -0
  75. package/src/as.mjs +538 -0
  76. package/src/auth.mjs +166 -0
  77. package/src/builtin-http.mjs +22 -0
  78. package/src/check-coverage.mjs +38 -0
  79. package/src/check-lint.mjs +88 -0
  80. package/src/check-readiness.mjs +112 -0
  81. package/src/check-response.mjs +19 -0
  82. package/src/child-exit.mjs +18 -0
  83. package/src/child-registry.mjs +94 -0
  84. package/src/claim-command-ledger.mjs +51 -0
  85. package/src/cli-help.mjs +186 -0
  86. package/src/cli-name.mjs +16 -0
  87. package/src/connect-cli.mjs +126 -0
  88. package/src/consumers.mjs +61 -0
  89. package/src/deadman.mjs +329 -0
  90. package/src/delivery.mjs +19 -0
  91. package/src/demo-worker.mjs +150 -0
  92. package/src/destinations/index.mjs +23 -0
  93. package/src/destinations/none.mjs +15 -0
  94. package/src/destinations/t3.mjs +109 -0
  95. package/src/diagnostic.mjs +78 -0
  96. package/src/docs-url.mjs +9 -0
  97. package/src/drain-runner.mjs +9 -0
  98. package/src/drained-owner.mjs +26 -0
  99. package/src/drained-slot.mjs +70 -0
  100. package/src/drained.mjs +40 -0
  101. package/src/durable-waiters.mjs +236 -0
  102. package/src/env.mjs +19 -0
  103. package/src/execution.mjs +112 -0
  104. package/src/failure-type.mjs +28 -0
  105. package/src/get-summary.mjs +32 -0
  106. package/src/git-env.mjs +15 -0
  107. package/src/host-budget-receipts.mjs +154 -0
  108. package/src/host-budget-seccomp.py +33 -0
  109. package/src/host-budget-service.mjs +54 -0
  110. package/src/host-budget-stop.mjs +26 -0
  111. package/src/host-budget-storage.py +259 -0
  112. package/src/host-budget.mjs +149 -0
  113. package/src/host-cgroup.mjs +23 -0
  114. package/src/host-check-allowlist.mjs +42 -0
  115. package/src/host-execution-policy.mjs +38 -0
  116. package/src/host-health.mjs +34 -0
  117. package/src/host-stop-reverify.mjs +44 -0
  118. package/src/inbox.mjs +55 -0
  119. package/src/integrator.mjs +322 -0
  120. package/src/job-retention.mjs +69 -0
  121. package/src/legacy-names.mjs +8 -0
  122. package/src/lifecycle.mjs +291 -0
  123. package/src/limits.mjs +31 -0
  124. package/src/loopback.mjs +9 -0
  125. package/src/mcp-outcome.mjs +79 -0
  126. package/src/mcp-sse.mjs +62 -0
  127. package/src/mcp-stdio.mjs +191 -0
  128. package/src/mirror-fetch-lock.py +164 -0
  129. package/src/mirror-fetch.mjs +174 -0
  130. package/src/notify-ledger.mjs +82 -0
  131. package/src/objectives.mjs +129 -0
  132. package/src/owner-report-artifact.mjs +66 -0
  133. package/src/patch-apply.mjs +84 -0
  134. package/src/path-syntax.mjs +16 -0
  135. package/src/paths.mjs +67 -0
  136. package/src/pr-head-reviewer.mjs +596 -0
  137. package/src/pr-preflight.mjs +51 -0
  138. package/src/prepared-node-modules.mjs +129 -0
  139. package/src/process-inspection.mjs +36 -0
  140. package/src/projects.mjs +480 -0
  141. package/src/protocol-artifact-commands.mjs +52 -0
  142. package/src/protocol-delivery-driver.mjs +167 -0
  143. package/src/protocol-finish.mjs +100 -0
  144. package/src/protocol-owner-command.mjs +35 -0
  145. package/src/protocol-owner-mutations.mjs +22 -0
  146. package/src/protocol-owner-waiters.mjs +67 -0
  147. package/src/protocol-retention.mjs +52 -0
  148. package/src/protocol-services.mjs +61 -0
  149. package/src/protocol-stop-observer.mjs +131 -0
  150. package/src/publish-plan.mjs +245 -0
  151. package/src/pull-queue.mjs +159 -0
  152. package/src/redaction.mjs +763 -0
  153. package/src/rejections.mjs +18 -0
  154. package/src/request-log.mjs +102 -0
  155. package/src/restore-check.mjs +90 -0
  156. package/src/result-binding.mjs +65 -0
  157. package/src/route-setting.mjs +24 -0
  158. package/src/runtime-check.mjs +13 -0
  159. package/src/sandbox-supervisor.mjs +105 -0
  160. package/src/schema-subset.mjs +186 -0
  161. package/src/scopes.mjs +15 -0
  162. package/src/server.mjs +1468 -0
  163. package/src/service-migrate-workers.mjs +113 -0
  164. package/src/service.mjs +388 -0
  165. package/src/setup.mjs +63 -0
  166. package/src/shutdown-signal.mjs +12 -0
  167. package/src/signal-sandbox-processes.py +56 -0
  168. package/src/signal.mjs +119 -0
  169. package/src/status-evidence.mjs +47 -0
  170. package/src/status-summary.mjs +54 -0
  171. package/src/store.mjs +3069 -0
  172. package/src/submission-policy.mjs +623 -0
  173. package/src/subscription-storage.mjs +64 -0
  174. package/src/t3-audit.mjs +120 -0
  175. package/src/t3-control.mjs +102 -0
  176. package/src/t3-transport.mjs +158 -0
  177. package/src/t3.mjs +209 -0
  178. package/src/terminal-safe.mjs +19 -0
  179. package/src/tool-registry.mjs +453 -0
  180. package/src/try-command.mjs +11 -0
  181. package/src/try-exposure.mjs +908 -0
  182. package/src/try-hosted-clients.mjs +46 -0
  183. package/src/try-hosted.mjs +444 -0
  184. package/src/try-selfcheck.mjs +168 -0
  185. package/src/try.mjs +635 -0
  186. package/src/webhooks.mjs +86 -0
  187. package/src/work-order.mjs +265 -0
  188. package/src/worker-instructions.mjs +26 -0
  189. package/src/worker-prompt.mjs +4 -0
  190. package/src/workers.mjs +632 -0
  191. package/src/workspace.mjs +1065 -0
  192. package/systemd/dot-bridge-heartbeat.service +18 -0
  193. package/systemd/dot-bridge-heartbeat.timer +10 -0
  194. package/systemd/dot-bridge-selfcheck.service +12 -0
  195. package/systemd/dot-bridge-selfcheck.timer +11 -0
  196. package/systemd/dot-bridge.service +17 -0
  197. package/systemd/dot-deadman.service +30 -0
  198. package/systemd/dot-pr-reviewer.service +11 -0
  199. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,113 @@
1
+ // Import policy into a NEW home. Source loaders are read-only: no jobs, connections or keys carry over.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { loadEffectiveOwnerWorkers, parseWorkers, updateWorkerRepoPolicy, workerRepoMigrationFile } from './workers.mjs';
6
+
7
+ function reenrollmentIntent(files, workers) {
8
+ const subscriptions = [], destinationApprovals = [];
9
+ for (const file of files) {
10
+ const db = new DatabaseSync(path.resolve(file), { readOnly: true });
11
+ try {
12
+ const hasTable = name => !!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(name);
13
+ if (hasTable('subscriptions')) {
14
+ // Never select encrypted connection/secret columns. Callback paths and queries can also contain credentials.
15
+ const hasExpiry = db.prepare("SELECT 1 FROM pragma_table_info('subscriptions') WHERE name='expires_at'").get();
16
+ const rows = hasExpiry
17
+ ? db.prepare("SELECT worker,url,count(*) count FROM subscriptions WHERE state='active' AND expires_at>? GROUP BY worker,url").all(new Date().toISOString())
18
+ : db.prepare("SELECT worker,url,count(*) count FROM subscriptions WHERE state='active' GROUP BY worker,url").all();
19
+ for (const row of rows) {
20
+ if (!Object.hasOwn(workers, row.worker)) throw new Error(`subscription refers to unknown worker ${row.worker}`);
21
+ let callbackOrigin = null;
22
+ try { const url = new URL(row.url); if (['https:', 'http:'].includes(url.protocol)) callbackOrigin = url.origin; } catch { /* manual re-enrolment required */ }
23
+ const old = subscriptions.find(item => item.worker === row.worker && item.callback_origin === callbackOrigin);
24
+ if (old) old.count += Number(row.count);
25
+ else subscriptions.push({ worker: row.worker, callback_origin: callbackOrigin, count: Number(row.count), action: 'reconnect_then_events_subscribe' });
26
+ }
27
+ }
28
+ if (hasTable('destination_approvals')) {
29
+ for (const row of db.prepare("SELECT json_extract(snapshot,'$.worker') worker,count(*) count FROM destination_approvals GROUP BY json_extract(snapshot,'$.worker')").all()) {
30
+ if (!Object.hasOwn(workers, row.worker)) throw new Error(`destination approval refers to unknown worker ${row.worker}`);
31
+ const old = destinationApprovals.find(item => item.worker === row.worker);
32
+ if (old) old.count += Number(row.count);
33
+ else destinationApprovals.push({ worker: row.worker, count: Number(row.count), action: 'review_new_destination_revision_on_each_new_job' });
34
+ }
35
+ }
36
+ } finally { db.close(); }
37
+ }
38
+ return { subscriptions, destination_approvals: destinationApprovals };
39
+ }
40
+
41
+ export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers = [] }) {
42
+ if (!home || !Array.isArray(sources) || !sources.length) throw new Error('--home and at least one --source workers.json are required');
43
+ if (!Array.isArray(sourceDbs) || !Array.isArray(workspaceWorkers)) throw new Error('sourceDbs and workspaceWorkers must be arrays');
44
+ home = path.resolve(home);
45
+ const workers = {};
46
+ const grants = new Map();
47
+ const deniedRepositories = [];
48
+ for (const source of sources) {
49
+ const file = path.resolve(source);
50
+ if (!fs.existsSync(file) && !fs.existsSync(workerRepoMigrationFile(file))) throw new Error(`no worker policy at ${file}`);
51
+ const profile = loadEffectiveOwnerWorkers(file);
52
+ deniedRepositories.push(...profile.deniedRepoGrants.map(item => ({ source: file, ...item })));
53
+ for (const [name, worker] of profile.workers) {
54
+ if (Object.hasOwn(workers, name)) throw new Error(`duplicate worker ${name} in sources`);
55
+ workers[name] = {
56
+ repos: [],
57
+ workspaceAllowed: worker.workspaceAllowed === true || workspaceWorkers.includes(name),
58
+ ...(worker.capabilities.size ? { capabilities: [...worker.capabilities] } : {}),
59
+ ...(worker.guidance ? { guidance: worker.guidance } : {}),
60
+ ...(worker.destination ? { destination: worker.destination } : {}),
61
+ };
62
+ grants.set(name, profile.repoPolicy(name).repos);
63
+ }
64
+ }
65
+ for (const name of workspaceWorkers) if (!Object.hasOwn(workers, name)) throw new Error(`unknown workspace worker ${name}`);
66
+ const value = { workers, default_execution: 'none' };
67
+ parseWorkers(value, { builtin: true });
68
+ const intent = reenrollmentIntent(sourceDbs, workers);
69
+ const manifest = {
70
+ schema_version: 1, authoritative: false, ...intent,
71
+ required_actions: [
72
+ 'Pair and approve every connector in the new home; old connections and tokens are not valid here.',
73
+ 'Each connector must call events/subscribe again with its callback and a fresh signing key; callback paths and credentials were omitted.',
74
+ 'Review the new destination disclosure and approve its current destination_revision when submitting each new job; old approvals bind old jobs and connections.',
75
+ ],
76
+ };
77
+ // mkdir without recursive fails for any existing destination, including symlinks and empty homes.
78
+ fs.mkdirSync(path.dirname(home), { recursive: true, mode: 0o700 });
79
+ fs.mkdirSync(home, { mode: 0o700 });
80
+ const config = path.join(home, '.config/dalan');
81
+ const workersFile = path.join(config, 'workers.json');
82
+ const manifestFile = path.join(config, 'service-migration.json');
83
+ try {
84
+ fs.mkdirSync(config, { recursive: true, mode: 0o700 });
85
+ fs.writeFileSync(workersFile, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
86
+ for (const [name, repos] of grants) for (const repo of repos) updateWorkerRepoPolicy(workersFile, name, 'allow', repo);
87
+ fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
88
+ } catch (error) {
89
+ fs.rmSync(home, { recursive: true, force: true });
90
+ throw error;
91
+ }
92
+ return { home, workers_file: workersFile, migration_manifest: manifestFile,
93
+ workers: [...grants].map(([worker, repos]) => ({ worker, repos, workspaceAllowed: workers[worker].workspaceAllowed })),
94
+ default_execution: 'none', reenrollment_required: true, denied_repositories: deniedRepositories };
95
+ }
96
+
97
+ export function migrationMain(args = process.argv.slice(4)) {
98
+ let home;
99
+ let json = false;
100
+ const sources = [], sourceDbs = [], workspaceWorkers = [];
101
+ for (let i = 0; i < args.length; i++) {
102
+ if (args[i] === '--json') { json = true; continue; }
103
+ if (!['--home', '--source', '--source-db', '--workspace-worker'].includes(args[i]) || !args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`invalid migration option ${args[i]}`);
104
+ const option = args[i++];
105
+ if (option === '--home') { if (home) throw new Error('duplicate --home'); home = args[i]; }
106
+ else if (option === '--source') sources.push(args[i]);
107
+ else if (option === '--source-db') sourceDbs.push(args[i]);
108
+ else workspaceWorkers.push(args[i]);
109
+ }
110
+ const result = migrateWorkers({ home, sources, sourceDbs, workspaceWorkers });
111
+ process.stdout.write(json ? JSON.stringify(result) + '\n' : `Created ${result.workers.length} workers in ${result.home}; execution defaults to none. Re-enrol connectors, subscriptions and destination approvals using ${result.migration_manifest}. No sign-ins or jobs were copied.${result.denied_repositories.length ? ` Denied unaudited additions: ${result.denied_repositories.map(item => `${item.worker}: ${item.repos.join(', ')}`).join('; ')}.` : ''}\n`);
112
+ return result;
113
+ }
@@ -0,0 +1,388 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import net from 'node:net';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { createHash, randomBytes } from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { isIP } from 'node:net';
9
+ import { defaultPath } from './paths.mjs';
10
+ import { initAsFiles } from './as-files.mjs';
11
+ import { parseWorkers } from './workers.mjs';
12
+ import { parseArgs } from '../scripts/live-trial/common.mjs';
13
+
14
+ const REPO = fileURLToPath(new URL('..', import.meta.url));
15
+ const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
16
+ const fail = message => { throw new Error(message); };
17
+
18
+ function parseOrigin(value) {
19
+ let url;
20
+ try { url = new URL(value); } catch { fail('--public-url must be an HTTPS origin'); }
21
+ if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash || value !== url.origin) {
22
+ fail('--public-url must contain only https://, a host and an optional port');
23
+ }
24
+ return url.origin;
25
+ }
26
+
27
+ function parseTarget(value) {
28
+ const match = /^((?:\d{1,3}\.){3}\d{1,3}):(\d{1,5})$/.exec(value ?? '');
29
+ if (!match || isIP(match[1]) !== 4 || match[1].split('.').some(part => Number(part) > 255)) {
30
+ fail('--target must be an IPv4 address and port, such as 127.0.0.1:8789');
31
+ }
32
+ const port = Number(match[2]);
33
+ if (port < 1 || port > 65535) fail('--target port must be 1 through 65535');
34
+ return { host: match[1], port, value: `${match[1]}:${port}` };
35
+ }
36
+
37
+ function validateTopology({ port, target, lanPort = null, verifyCmd }) {
38
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port must be a fixed port from 1024 through 65535');
39
+ if (lanPort !== null && (!Number.isInteger(lanPort) || lanPort < 1024 || lanPort > 65535)) fail('--lan-port must be a port from 1024 through 65535');
40
+ const direct = target.host === '127.0.0.1' && target.port === port;
41
+ if (!direct && lanPort !== target.port) fail('a forwarded --target requires --lan-port matching its port');
42
+ if (direct && lanPort !== null) fail('--lan-port needs a separate --target address and port');
43
+ if (!direct && target.port === port && target.host === '0.0.0.0') fail('same-port --target must not use wildcard 0.0.0.0; it collides with the loopback listener');
44
+ if (verifyCmd != null && (typeof verifyCmd !== 'string' || !verifyCmd.trim() || verifyCmd.length > 4096)) fail('--verify-cmd must be a nonempty command of at most 4096 characters');
45
+ if (target.port !== port && !(typeof verifyCmd === 'string' && verifyCmd.trim())) fail('translated target ports require an explicit nonempty --verify-cmd; challenge verification binds the receiving port');
46
+ }
47
+
48
+ function parseOptions(argv, env) {
49
+ const parsed = parseArgs(argv, {
50
+ values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--gozar-bin', '--lan-port'],
51
+ flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--json', '--help'],
52
+ });
53
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
54
+ if (parsed['--help']) return { help: true };
55
+ const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
56
+ if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a systemd unit');
57
+ const origin = parseOrigin(parsed['--public-url']);
58
+ const port = Number(parsed['--port']);
59
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port must be a fixed port from 1024 through 65535');
60
+ const target = parseTarget(parsed['--target']);
61
+ const lanPort = parsed['--lan-port'] === undefined ? null : Number(parsed['--lan-port']);
62
+ validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
63
+ const workers = [];
64
+ for (let i = 0; i < argv.length; i++) {
65
+ if (argv[i] === '--worker') workers.push(argv[++i]);
66
+ else if (argv[i].startsWith('--worker=')) workers.push(argv[i].slice('--worker='.length));
67
+ }
68
+ if (workers.some(name => typeof name !== 'string' || !/^[a-z][a-z0-9_-]{0,31}$/.test(name) || ['pool', 'unknown'].includes(name))) {
69
+ fail('--worker must be a lowercase name of up to 32 letters, digits, - or _');
70
+ }
71
+ if (new Set(workers).size !== workers.length) fail('--worker names must be unique');
72
+ if (parsed['--verify-cmd']?.length > 4096) fail('--verify-cmd is too long');
73
+ const gozarBin = parsed['--gozar-bin'] ?? env.GOZAR_BIN ?? 'gozar';
74
+ if (!gozarBin || gozarBin.startsWith('-')) fail('--gozar-bin must name a command');
75
+ return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
76
+ gozarBin, writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
77
+ }
78
+
79
+ function assertRealDirectoryPath(target, { owner = false } = {}) {
80
+ const absolute = path.resolve(target), root = path.parse(absolute).root;
81
+ let current = root, deepest = null;
82
+ for (const part of absolute.slice(root.length).split(path.sep).filter(Boolean)) {
83
+ current = path.join(current, part);
84
+ let info;
85
+ try { info = fs.lstatSync(current); } catch (error) { if (error.code === 'ENOENT') continue; throw error; }
86
+ if (info.isSymbolicLink() || !info.isDirectory() || fs.realpathSync(current) !== current) {
87
+ fail(`${current} is not a real directory; refusing to write through a symlink`);
88
+ }
89
+ deepest = { path: current, info };
90
+ }
91
+ if (owner && deepest && typeof process.getuid === 'function' && deepest.info.uid !== process.getuid()) fail(`${deepest.path} is not owned by the current user`);
92
+ }
93
+
94
+ function nodePath(execPath) {
95
+ let real;
96
+ try { real = fs.realpathSync(execPath); } catch { return execPath; }
97
+ const userHome = os.userInfo().homedir || os.homedir();
98
+ const candidates = ['/opt/homebrew/bin/node', '/usr/local/bin/node', path.join(userHome, '.local/share/mise/installs/node/lts/bin/node')];
99
+ for (const candidate of candidates) {
100
+ try { if (fs.realpathSync(candidate) === real) return candidate; } catch { /* candidate is not installed */ }
101
+ }
102
+ return execPath;
103
+ }
104
+
105
+ function unitName(home) { return `dalan-${createHash('sha256').update(home).digest('hex').slice(0, 10)}`; }
106
+
107
+ function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null } = {}) {
108
+ const name = unitName(home);
109
+ for (const [label, value] of [['home', home], ['repo', repo], ['node', node]]) {
110
+ if (!SAFE_PATH.test(value)) fail(`${label} contains characters that cannot be written safely in a systemd unit`);
111
+ }
112
+ const base = {
113
+ [`${name}.service`]: [
114
+ '[Unit]', 'Description=Dalan worker bridge', 'After=network-online.target', '', '[Service]',
115
+ `WorkingDirectory=${repo}`, `ExecStart=${node} ${path.join(repo, 'src/server.mjs')}`,
116
+ `Environment=HOME=${home}`, 'Environment=NODE_ENV=production', 'Environment=DALAN_AUTH_MODE=builtin',
117
+ 'Environment=DALAN_BIND_HOST=127.0.0.1', 'Environment=DALAN_GOZAR_SERVICE=1', 'Environment=DALAN_CATALOG_PROFILE=stable',
118
+ `Environment=DALAN_ENABLE_WORKSPACE=${o.enableWorkspace ? '1' : '0'}`, `Environment=DALAN_ENABLE_T3_TOOLS=${o.enableT3 ? '1' : '0'}`,
119
+ `Environment=DALAN_PORT=${o.port}`, `Environment=PATH=${[path.dirname(node), '/usr/local/bin', '/usr/bin', '/bin'].join(':')}`,
120
+ 'UnsetEnvironment=OPENAI_API_KEY ANTHROPIC_API_KEY DALAN_LOOPBACK DOT_BRIDGE_LOOPBACK DALAN_WORKERS_FILE DOT_BRIDGE_WORKERS_FILE', 'Restart=on-failure', 'RestartSec=3', 'UMask=0077', '',
121
+ '[Install]', 'WantedBy=default.target', '',
122
+ ].join('\n'),
123
+ };
124
+ const enable = [`${name}.service`];
125
+ const isDirect = o.target.host === '127.0.0.1' && o.target.port === o.port;
126
+ if (!isDirect) {
127
+ if (!proxy || !SAFE_PATH.test(proxy)) fail('systemd-socket-proxyd is required when --target is not 127.0.0.1:<port>');
128
+ base[`${name}-target.socket`] = [
129
+ '[Unit]', 'Description=Gozar target for Dalan', '', '[Socket]',
130
+ `ListenStream=${o.target.host}:${o.target.port}`, 'FreeBind=true', '', '[Install]', 'WantedBy=sockets.target', '',
131
+ ].join('\n');
132
+ base[`${name}-target.service`] = [
133
+ '[Unit]', 'Description=Forward Gozar target to the Dalan bridge', `Requires=${name}.service`, `After=${name}.service`, '', '[Service]',
134
+ `ExecStart=${proxy} 127.0.0.1:${o.port}`, 'Restart=on-failure', '',
135
+ ].join('\n');
136
+ enable.push(`${name}-target.socket`);
137
+ }
138
+ return { files: base, enable, name };
139
+ }
140
+
141
+ function findProxy() {
142
+ return ['/usr/lib/systemd/systemd-socket-proxyd', '/lib/systemd/systemd-socket-proxyd'].find(file => fs.existsSync(file)) ?? null;
143
+ }
144
+
145
+ function profileFor(home, workers) {
146
+ const file = path.join(defaultPath(home, '.config/dot-bridge'), 'workers.json');
147
+ if (fs.existsSync(file)) {
148
+ const stat = fs.lstatSync(file);
149
+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
150
+ let profile;
151
+ try { profile = parseWorkers(JSON.parse(fs.readFileSync(file, 'utf8')), { builtin: true }); }
152
+ catch (error) { fail(`${file} is not a built-in OAuth worker profile: ${error.message}`); }
153
+ if (!profile.workers.size || profile.legacy) fail(`${file} must contain a built-in OAuth worker profile`);
154
+ const configuredWorkers = [...profile.workers.keys()].sort();
155
+ if (workers.length && JSON.stringify([...workers].sort()) !== JSON.stringify(configuredWorkers)) {
156
+ fail(`${file} already exists; omit --worker or pass its exact worker set, and keep its workers and repository grants`);
157
+ }
158
+ return { file, workers: [...profile.workers.keys()], existing: true };
159
+ }
160
+ if (!workers.length) fail(`no ${file}; run dalan service migrate-workers first or pass --worker NAME`);
161
+ const value = { workers: Object.fromEntries(workers.map(name => [name, { repos: [] }])), default_execution: 'none' };
162
+ parseWorkers(value, { builtin: true });
163
+ return { file, workers, value, existing: false };
164
+ }
165
+
166
+ const POLICY_HOME_FILES = new Set([
167
+ 'service-migration.json', 'workers.json', 'workers-audit.jsonl', 'workers-audit-checkpoint.sqlite',
168
+ 'workers-audit-checkpoint.sqlite-wal', 'workers-audit-checkpoint.sqlite-shm', 'workers-repos.json',
169
+ ]);
170
+ const WORKSPACE_RUNTIME_DIRS = new Set(['artifacts', 'caches', 'host-receipts', 'mirrors', 'run', 'worktrees']);
171
+ const WORKSPACE_RUNTIME_FILES = new Map([['github-askpass', 0o700]]);
172
+
173
+ function installReceipt(home, configDir, o, workers) {
174
+ return { schema_version: 1, home, origin: o.origin, port: o.port, target: o.target.value, enable_workspace: !!o.enableWorkspace, enable_t3: !!o.enableT3,
175
+ unit: unitName(home), workers: [...workers].sort(), created_at: new Date().toISOString() };
176
+ }
177
+
178
+ function validateWorkspaceRuntime(home) {
179
+ const scratch = path.join(home, '.tmp');
180
+ const runtime = path.join(scratch, 'dalan');
181
+ for (const directory of [scratch, runtime]) assertRealDirectoryPath(directory, { owner: true });
182
+ const scratchEntries = fs.readdirSync(scratch);
183
+ if (scratchEntries.length !== 1 || scratchEntries[0] !== 'dalan') fail(`${scratch} contains data outside Dalan runtime scratch`);
184
+ if ((fs.lstatSync(runtime).mode & 0o777) !== 0o700) fail(`${runtime} must be private`);
185
+ const runtimeEntries = fs.readdirSync(runtime).sort();
186
+ for (const name of runtimeEntries) {
187
+ const entry = path.join(runtime, name);
188
+ if (!WORKSPACE_RUNTIME_DIRS.has(name) && !WORKSPACE_RUNTIME_FILES.has(name)) fail(`${runtime} contains an unknown Dalan workspace entry`);
189
+ const info = fs.lstatSync(entry);
190
+ if (WORKSPACE_RUNTIME_FILES.has(name)) {
191
+ const owned = typeof process.getuid !== 'function' || info.uid === process.getuid();
192
+ if (!info.isFile() || info.isSymbolicLink() || !owned || (info.mode & 0o777) !== WORKSPACE_RUNTIME_FILES.get(name)) {
193
+ fail(`${entry} must be a private regular Dalan file`);
194
+ }
195
+ continue;
196
+ }
197
+ assertRealDirectoryPath(entry, { owner: true });
198
+ if ((info.mode & 0o777) !== 0o700) fail(`${entry} must be private`);
199
+ }
200
+ }
201
+
202
+ function checkHomeScope(home, configDir, o, workers) {
203
+ if (!fs.existsSync(home)) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
204
+ const rootEntries = fs.readdirSync(home);
205
+ if (!rootEntries.length) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
206
+ const rootAllowed = ['.config', '.local', '.tmp', 'resource-url'];
207
+ if (rootEntries.some(name => !rootAllowed.includes(name))) fail(`${home} contains unrelated data; use a fresh home or one created by dalan service migrate-workers`);
208
+ if (!rootEntries.includes('.config')) fail(`${home} has no Dalan config directory; refusing to adopt it`);
209
+ const configRoot = path.join(home, '.config');
210
+ if (fs.lstatSync(configRoot).isSymbolicLink() || !fs.lstatSync(configRoot).isDirectory()) fail(`${configRoot} must be a real directory`);
211
+ const configEntries = fs.readdirSync(configRoot);
212
+ const configName = path.basename(configDir);
213
+ if (configEntries.some(name => name !== configName)) fail(`${home} contains config outside the service home; refusing to adopt it`);
214
+ if (!configEntries.length) {
215
+ if (rootEntries.includes('.local') || rootEntries.includes('.tmp') || rootEntries.includes('resource-url')) fail(`${home} already contains bridge data; use a fresh home or one created by dalan service migrate-workers`);
216
+ return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
217
+ }
218
+ const configInfo = fs.lstatSync(configDir);
219
+ if (configInfo.isSymbolicLink() || !configInfo.isDirectory()) fail(`${configDir} must be a real directory`);
220
+ const receiptFile = path.join(configDir, 'service-install.json');
221
+ const entries = fs.readdirSync(configDir);
222
+ const hasReceipt = entries.includes('service-install.json');
223
+ if (hasReceipt) {
224
+ const info = fs.lstatSync(receiptFile);
225
+ if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
226
+ let existing;
227
+ try { existing = JSON.parse(fs.readFileSync(receiptFile, 'utf8')); } catch { fail(`${receiptFile} is not valid JSON`); }
228
+ const wanted = installReceipt(home, configDir, o, workers);
229
+ for (const field of ['schema_version', 'home', 'origin', 'port', 'target', 'enable_workspace', 'enable_t3', 'unit', 'workers']) {
230
+ if (JSON.stringify(existing[field]) !== JSON.stringify(wanted[field])) fail(`${receiptFile} belongs to a different service configuration (${field}); refusing to change it`);
231
+ }
232
+ if (rootEntries.includes('.tmp')) validateWorkspaceRuntime(home);
233
+ if (rootEntries.includes('.local')) assertRealDirectoryPath(defaultPath(home, '.local/share/dot-bridge'));
234
+ return { receiptFile, hasReceipt };
235
+ }
236
+ if (rootEntries.includes('.local') || rootEntries.includes('.tmp') || rootEntries.includes('resource-url')) fail(`${home} already contains bridge data; use a fresh home or one created by dalan service migrate-workers`);
237
+ for (const name of entries) {
238
+ if (POLICY_HOME_FILES.has(name) || hasReceipt && name === 'service-install.json') continue;
239
+ fail(`${configDir}/${name} is outside a fresh or migrated policy-only home; refusing to adopt it`);
240
+ }
241
+ if (entries.length && !entries.includes('workers.json')) fail(`${configDir} has no worker policy; refusing to adopt it`);
242
+ return { receiptFile, hasReceipt };
243
+ }
244
+
245
+ function writePrivate(file, text) {
246
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
247
+ try { fs.writeFileSync(file, text, { mode: 0o600, flag: 'wx' }); }
248
+ catch (error) {
249
+ if (error.code !== 'EEXIST') throw error;
250
+ const info = fs.lstatSync(file);
251
+ if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600 || fs.readFileSync(file, 'utf8') !== text) {
252
+ fail(`${file} already exists with different or unsafe contents; refusing to replace it`);
253
+ }
254
+ }
255
+ }
256
+
257
+ function prepareHome(o, profile) {
258
+ fs.mkdirSync(o.home, { recursive: true, mode: 0o700 });
259
+ fs.chmodSync(o.home, 0o700);
260
+ const config = defaultPath(o.home, '.config/dot-bridge');
261
+ fs.mkdirSync(config, { recursive: true, mode: 0o700 });
262
+ if (!profile.existing) writePrivate(profile.file, `${JSON.stringify(profile.value, null, 2)}\n`);
263
+ initAsFiles(config, { publicUrl: o.origin });
264
+ const envFile = path.join(config, 'env');
265
+ if (!fs.existsSync(envFile)) writePrivate(envFile, `BRIDGE_PATH_SECRET=${randomBytes(32).toString('hex')}\n`);
266
+ const envInfo = fs.lstatSync(envFile);
267
+ const envText = fs.readFileSync(envFile, 'utf8');
268
+ const secret = /^BRIDGE_PATH_SECRET=([a-f0-9]{64})\n?$/.exec(envText)?.[1];
269
+ if (!envInfo.isFile() || envInfo.isSymbolicLink() || (envInfo.mode & 0o777) !== 0o600 || !secret) fail(`${envFile} is not a private bridge secret file`);
270
+ const resourceFile = path.join(o.home, 'resource-url');
271
+ writePrivate(resourceFile, `${o.origin}/${secret}/mcp\n`);
272
+ return { config, resourceFile, secret };
273
+ }
274
+
275
+ function writeUnits(dir, files) {
276
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
277
+ for (const [name, text] of Object.entries(files)) {
278
+ const file = path.join(dir, name);
279
+ try { fs.writeFileSync(file, text, { mode: 0o644, flag: 'wx' }); }
280
+ catch (error) {
281
+ if (error.code !== 'EEXIST') throw error;
282
+ if (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text) fail(`${file} already exists with different contents; refusing to replace it`);
283
+ }
284
+ }
285
+ }
286
+
287
+ function runCommand(command, args, { env, spawn = spawnSync, timeout = 30000 } = {}) {
288
+ const result = spawn(command, args, { encoding: 'utf8', env, timeout, maxBuffer: 1024 * 1024 });
289
+ if (result.error) throw new Error(`${command} ${args.join(' ')} could not run: ${result.error.message}`);
290
+ if (result.status !== 0) throw new Error(`${command} ${args.join(' ')} failed (exit ${result.status ?? result.signal}): ${(result.stderr || result.stdout || '').trim().slice(0, 1000)}`);
291
+ return result.stdout ?? '';
292
+ }
293
+
294
+ function socketIsReady(socketPath, timeoutMs = 30000) {
295
+ return new Promise(resolve => {
296
+ const started = Date.now();
297
+ const attempt = () => {
298
+ const probe = net.connect(socketPath);
299
+ const done = ready => { probe.destroy(); if (ready) resolve(true); else if (Date.now() - started >= timeoutMs) resolve(false); else setTimeout(attempt, 200); };
300
+ probe.once('connect', () => done(true));
301
+ probe.once('error', () => done(false));
302
+ probe.setTimeout(1000, () => done(false));
303
+ };
304
+ attempt();
305
+ });
306
+ }
307
+
308
+ export async function installService(o, seams = {}) {
309
+ const env = seams.env ?? process.env;
310
+ if ((seams.platform ?? process.platform) !== 'linux') fail('dalan service install currently requires Linux with a systemd user manager');
311
+ if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute systemd-safe path');
312
+ const target = parseTarget(typeof o.target === 'string' ? o.target : `${o.target?.host}:${o.target?.port}`);
313
+ o = { ...o, target };
314
+ validateTopology(o);
315
+ assertRealDirectoryPath(path.dirname(o.home), { owner: true });
316
+ assertRealDirectoryPath(o.home, { owner: true });
317
+ const profile = profileFor(o.home, o.workers ?? []);
318
+ assertRealDirectoryPath(path.dirname(profile.file));
319
+ 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');
320
+ assertRealDirectoryPath(unitDir, { owner: true });
321
+ const configDir = path.dirname(profile.file);
322
+ const homeScope = checkHomeScope(o.home, configDir, o, profile.workers);
323
+ const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
324
+ const { files, enable, name } = unitFiles(o, { home: o.home, repo: seams.repo ?? REPO, node: seams.node ?? nodePath(process.execPath), proxy });
325
+ // Check every collision before creating the bridge home or the first unit file.
326
+ for (const [filename, text] of Object.entries(files)) {
327
+ const file = path.join(unitDir, filename);
328
+ if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) fail(`${file} already exists with different contents; refusing to overwrite it`);
329
+ }
330
+ if (o.writeUnitsOnly) {
331
+ writeUnits(unitDir, files);
332
+ return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
333
+ }
334
+ const spawn = seams.spawn ?? spawnSync;
335
+ runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
336
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
337
+ if (!homeScope.hasReceipt) writePrivate(homeScope.receiptFile, `${JSON.stringify(installReceipt(o.home, configDir, o, profile.workers), null, 2)}\n`);
338
+ const homeFiles = prepareHome(o, profile);
339
+ writeUnits(unitDir, files);
340
+ runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
341
+ runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
342
+ const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
343
+ const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
344
+ if (!ready) fail(`Dalan did not start on its admin socket; the unit and home remain for inspection: systemctl --user status ${name}.service`);
345
+ const gozarArgs = ['service', 'add', '--origin', o.origin, '--target', o.target.value];
346
+ if (o.verifyCmd) gozarArgs.push('--verify-cmd', o.verifyCmd);
347
+ gozarArgs.push('--json');
348
+ const output = runCommand(o.gozarBin ?? env.GOZAR_BIN ?? 'gozar', gozarArgs, { env, spawn, timeout: 120000 });
349
+ let routeReply;
350
+ try { routeReply = JSON.parse(output); } catch { fail('Gozar returned invalid JSON for service add; the bridge is running but its route is unverified'); }
351
+ if (routeReply?.schemaVersion !== 1 || routeReply?.route?.origin !== o.origin || routeReply?.route?.target !== o.target.value) {
352
+ fail('Gozar returned a service route that does not match the requested origin and target; the bridge is running but its route is unverified');
353
+ }
354
+ if (routeReply.route.verification?.status !== 'verified') {
355
+ fail(`Gozar did not verify the service route; the bridge is running and the service route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
356
+ }
357
+ return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), port: o.port,
358
+ workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
359
+ target: o.target.value, started: true, route: routeReply.route };
360
+ }
361
+
362
+ export async function serviceMain(argv, seams = {}) {
363
+ const [action, ...args] = argv;
364
+ if (action === 'migrate-workers') {
365
+ const { migrationMain } = await import('./service-migrate-workers.mjs');
366
+ return migrationMain(args);
367
+ }
368
+ if (action === 'help' || action === '--help' || !action) {
369
+ (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] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]');
370
+ return null;
371
+ }
372
+ if (action !== 'install') fail('use dalan service install or dalan service migrate-workers');
373
+ const o = parseOptions(args, seams.env ?? process.env);
374
+ if (o.help) return serviceMain(['help'], seams);
375
+ const result = await installService(o, seams);
376
+ if (o.json) (seams.out ?? console.log)(JSON.stringify(result));
377
+ else {
378
+ (seams.out ?? console.log)(`Service: ${result.unit} (${result.started ? 'active' : 'unit files written'})`);
379
+ (seams.out ?? console.log)(`Home: ${result.home}`);
380
+ (seams.out ?? console.log)(`Public MCP URL: ${result.public_url ?? `${o.origin}/<secret>/mcp`}`);
381
+ (seams.out ?? console.log)(`Private URL file: ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
382
+ (seams.out ?? console.log)(`Gozar target: ${result.target}`);
383
+ if (result.route) (seams.out ?? console.log)(`Gozar route: ${result.route.verification.status}`);
384
+ }
385
+ return result;
386
+ }
387
+
388
+ export { parseOrigin, parseTarget, unitFiles };
package/src/setup.mjs ADDED
@@ -0,0 +1,63 @@
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.
4
+ 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';
7
+
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
+ 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.';
11
+
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] }; }
18
+ }
19
+
20
+ export async function runSetup({ env = process.env, out = process.stdout, input = process.stdin, interactive = Boolean(process.stdin.isTTY), detect = () => detectTailscale({ env }) } = {}) {
21
+ const say = line => out.write(`${line}\n`);
22
+ const found = detect();
23
+ const saved = readRouteSetting(env);
24
+ const lines = interactive ? readline.createInterface({ input }) : null;
25
+ const ask = question => new Promise(resolve => {
26
+ let done = false;
27
+ const finish = answer => { if (!done) { done = true; lines.off('close', onClose); resolve(answer); } };
28
+ const onClose = () => finish(null);
29
+ out.write(question); lines.once('line', finish); lines.once('close', onClose);
30
+ });
31
+ 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' };
55
+ }
56
+ say('Nothing saved. Install Tailscale, then run `dalan setup` again.');
57
+ return { route: saved, changed: false };
58
+ } finally { lines?.close(); }
59
+ }
60
+
61
+ export async function main() {
62
+ try { await runSetup(); } catch (error) { process.stderr.write(`dalan: ${error.message}\n`); process.exitCode = 1; }
63
+ }
@@ -0,0 +1,12 @@
1
+ // Say which signal stopped the bridge, then die by it as before. Node cannot see the sender, so the line names the signal only.
2
+ // Kept out of server.mjs: the owner-path test forbids process.kill in that file.
3
+ export function logShutdownSignals(log) {
4
+ for (const signalName of ['SIGTERM', 'SIGINT']) {
5
+ process.once(signalName, () => {
6
+ const entry = { kind: 'shutdown_signal', signal: signalName };
7
+ try { log(entry); } catch {}
8
+ console.error(JSON.stringify(entry));
9
+ process.kill(process.pid, signalName);
10
+ });
11
+ }
12
+ }
@@ -0,0 +1,56 @@
1
+ import json
2
+ import os
3
+ import signal
4
+ import sys
5
+
6
+
7
+ def process_fields(pid):
8
+ with open(f'/proc/{pid}/stat', encoding='utf-8') as stream:
9
+ text = stream.read()
10
+ fields = text[text.rfind(')') + 2:].split()
11
+ return fields[0], int(fields[2]), int(fields[19])
12
+
13
+
14
+ def in_scope(pid, start, group, scope):
15
+ init = scope.get('init') or {}
16
+ if pid == init.get('pid') and start == init.get('start'):
17
+ return True
18
+ sandbox_start = scope.get('sandboxStart')
19
+ if sandbox_start is not None and start < sandbox_start:
20
+ return False
21
+ namespace = scope.get('nsInode')
22
+ in_namespace = False
23
+ if namespace is not None:
24
+ try:
25
+ in_namespace = os.readlink(f'/proc/{pid}/ns/pid') == f'pid:[{namespace}]'
26
+ except OSError:
27
+ pass
28
+ return in_namespace or scope.get('pgid') is not None and group == scope['pgid']
29
+
30
+
31
+ def main():
32
+ request = json.load(sys.stdin)
33
+ signalled = []
34
+ for candidate in request['processes']:
35
+ pid = candidate['pid']
36
+ if pid == os.getpid():
37
+ continue
38
+ try:
39
+ fd = os.pidfd_open(pid, 0)
40
+ except (AttributeError, ProcessLookupError, PermissionError):
41
+ continue
42
+ try:
43
+ state, group, start = process_fields(pid)
44
+ if state in ('Z', 'X') or start != candidate['start'] or not in_scope(pid, start, group, request['scope']):
45
+ continue
46
+ signal.pidfd_send_signal(fd, signal.SIGKILL)
47
+ signalled.append(pid)
48
+ except (AttributeError, FileNotFoundError, ProcessLookupError, PermissionError):
49
+ pass
50
+ finally:
51
+ os.close(fd)
52
+ json.dump(signalled, sys.stdout)
53
+
54
+
55
+ if __name__ == '__main__':
56
+ main()