@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.
- package/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,925 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { defaultPath } from '../src/paths.mjs';
|
|
3
|
+
import { readEnv } from '../src/env.mjs';
|
|
4
|
+
// One command that turns a fresh worker bridge into a durable service: a systemd user service on Linux, a launchd
|
|
5
|
+
// LaunchAgent on macOS. Separate from scripts/live-trial/setup.mjs on purpose: that script starts a throwaway process
|
|
6
|
+
// and a manifest that teardown deletes. This one leaves a permanent HOME, unit or plist files and (with --start) a
|
|
7
|
+
// running service. --remove undoes it; it only touches files this script wrote (marker line).
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { spawnSync } from 'node:child_process';
|
|
12
|
+
import { randomBytes } from 'node:crypto';
|
|
13
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { parseArgs } from './live-trial/common.mjs';
|
|
16
|
+
import { loadKeys } from '../src/as-files.mjs';
|
|
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';
|
|
20
|
+
|
|
21
|
+
const REPO = fileURLToPath(new URL('..', import.meta.url));
|
|
22
|
+
const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/; // no space, quote, %, $ or newline: the value goes into a unit or plist as is
|
|
23
|
+
const PROXYD = ['/usr/lib/systemd/systemd-socket-proxyd', '/lib/systemd/systemd-socket-proxyd'];
|
|
24
|
+
const MARKER = 'Generated by scripts/worker-bridge-setup.mjs'; // --remove only deletes files that carry this text
|
|
25
|
+
class SetupRefusal extends Error {
|
|
26
|
+
constructor(message) { super(message); this.name = 'SetupRefusal'; this.code = 'SETUP_REFUSED'; }
|
|
27
|
+
}
|
|
28
|
+
const fail = message => { throw new SetupRefusal(message); };
|
|
29
|
+
const launchLabel = worker => `org.dalan.dot-bridge-${worker}`;
|
|
30
|
+
// New services load into the user's launchd domain, not the GUI domain. A GUI domain whose session is idle or locked can be in
|
|
31
|
+
// "on-demand-only" mode: launchd then neither runs an agent at load nor restarts it after it is killed (KeepAlive has no effect).
|
|
32
|
+
// The user domain has no such mode. Agents that an older release loaded into the GUI domain are still found when they are removed.
|
|
33
|
+
const SESSION_TYPES = ['Aqua', 'Background']; // the user domain accepts an agent only if its plist allows the Background session
|
|
34
|
+
const launchDomains = uid => [`user/${uid}`, `gui/${uid}`];
|
|
35
|
+
|
|
36
|
+
// A version-pinned interpreter path (Homebrew Cellar, mise installs/node/<version>) breaks the unit on upgrade. Prefer a stable
|
|
37
|
+
// launcher path that resolves to the same binary.
|
|
38
|
+
function stableNode(execPath) {
|
|
39
|
+
const real = fs.realpathSync(execPath);
|
|
40
|
+
const userHome = os.userInfo().homedir || os.homedir();
|
|
41
|
+
for (const candidate of ['/opt/homebrew/bin/node', '/usr/local/bin/node', path.join(userHome, '.local/share/mise/installs/node/lts/bin/node')]) {
|
|
42
|
+
try { if (fs.realpathSync(candidate) === real) return candidate; } catch { /* not present */ }
|
|
43
|
+
}
|
|
44
|
+
return execPath;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parseOptions(argv, platform) {
|
|
48
|
+
const args = parseArgs(argv, {
|
|
49
|
+
values: ['--worker', '--public-url', '--port', '--home', '--lan-forward', '--expose', '--funnel-port', '--ngrok-domain'],
|
|
50
|
+
flags: ['--persistent', '--write-units-only', '--no-repo-tools', '--start', '--help', '--remove', '--purge-home', '--retry-public-check', '--repoint'],
|
|
51
|
+
});
|
|
52
|
+
if (args._.length) fail(`unexpected argument ${args._[0]}`);
|
|
53
|
+
if (args['--help']) return { help: true };
|
|
54
|
+
const worker = args['--worker'];
|
|
55
|
+
if (!worker || !/^[a-z][a-z0-9_-]{0,31}$/.test(worker)) fail('--worker NAME is required (lowercase letters, digits, - and _; up to 32 characters)');
|
|
56
|
+
const home = path.resolve(args['--home'] ?? path.join(os.homedir(), '.local/share/dbm'));
|
|
57
|
+
if (args['--retry-public-check'] && args['--remove']) fail('--retry-public-check cannot be combined with --remove');
|
|
58
|
+
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);
|
|
60
|
+
if (others.length) fail(`--repoint takes only --worker; remove ${others.join(' ')}`);
|
|
61
|
+
const repo = REPO.replace(/\/$/, '');
|
|
62
|
+
if (!SAFE_PATH.test(repo)) fail(`repo path contains a character that is not safe in a unit file: ${JSON.stringify(repo)}`);
|
|
63
|
+
return { repoint: true, worker, repo };
|
|
64
|
+
}
|
|
65
|
+
if (args['--remove']) {
|
|
66
|
+
// 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);
|
|
68
|
+
if (ignored.length) console.error(`worker-bridge-setup: ignoring install-only flags with --remove: ${ignored.join(' ')}`);
|
|
69
|
+
return { remove: true, worker, home, purge: !!args['--purge-home'] };
|
|
70
|
+
}
|
|
71
|
+
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']);
|
|
84
|
+
const port = Number(args['--port']);
|
|
85
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port N is required (1024-65535)');
|
|
86
|
+
const node = stableNode(process.execPath);
|
|
87
|
+
const repo = REPO.replace(/\/$/, '');
|
|
88
|
+
// Unix socket paths are limited (104 bytes on macOS, 108 on Linux); the owner socket lives under the bridge home.
|
|
89
|
+
const socketPath = defaultPath(home,'.local/share/dot-bridge/admin.sock');
|
|
90
|
+
if (Buffer.byteLength(socketPath) >= 104) fail(`--home is too long: the owner socket path would be ${Buffer.byteLength(socketPath)} bytes (limit 103); choose a shorter home`);
|
|
91
|
+
for (const [label, value] of [['--home', home], ['node path', node], ['repo path', repo]]) {
|
|
92
|
+
if (!SAFE_PATH.test(value)) fail(`${label} contains a character that is not safe in a unit file: ${JSON.stringify(value)}`);
|
|
93
|
+
}
|
|
94
|
+
let lan = null;
|
|
95
|
+
if (args['--lan-forward']) {
|
|
96
|
+
if (platform === 'darwin') fail('--lan-forward is Linux only (it needs a systemd socket); it is not supported on macOS');
|
|
97
|
+
const m = /^(\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})$/.exec(args['--lan-forward']);
|
|
98
|
+
const lanPort = m && Number(m[2]);
|
|
99
|
+
if (!m || m[1].split('.').some(n => Number(n) > 255) || lanPort < 1 || lanPort > 65535) fail('--lan-forward must look like 198.51.100.10:8789');
|
|
100
|
+
if (lanPort === port && ['127.0.0.1', '0.0.0.0'].includes(m[1])) fail('--lan-forward would collide with the bridge port');
|
|
101
|
+
lan = { address: m[1], port: lanPort };
|
|
102
|
+
}
|
|
103
|
+
if (args['--write-units-only'] && args['--start']) fail('--start and --write-units-only exclude each other');
|
|
104
|
+
return {
|
|
105
|
+
worker, publicUrl, port, home, socketPath, node, repo, lan, writeUnitsOnly: !!args['--write-units-only'], start: !!args['--start'],
|
|
106
|
+
repoTools: !args['--no-repo-tools'], retryPublicCheck: !!args['--retry-public-check'],
|
|
107
|
+
expose: mode === 'tailscale' ? { mode, funnelPort } : mode === 'ngrok' ? { mode, domain: ngrokDomain } : null,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function parsePublicUrl(value) {
|
|
112
|
+
if (!value) fail('--public-url https://HOST is required');
|
|
113
|
+
let url;
|
|
114
|
+
try { url = new URL(value); } catch { fail('--public-url must be an origin URL'); }
|
|
115
|
+
if (url.protocol !== 'https:') fail('--public-url must use https');
|
|
116
|
+
const withoutDefaultPort = value.replace(/:443(?=\/|$)/, '');
|
|
117
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || (withoutDefaultPort !== url.origin && withoutDefaultPort !== `${url.origin}/`)) {
|
|
118
|
+
fail('--public-url must contain only scheme, host and optional port');
|
|
119
|
+
}
|
|
120
|
+
return url.origin;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function shellQuote(value) {
|
|
124
|
+
return `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function setupLockPath(rootOverride) {
|
|
128
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : 'user';
|
|
129
|
+
const root = rootOverride || path.join(fs.realpathSync('/tmp'), `dot-bridge-setup-locks-${uid}`);
|
|
130
|
+
assertNoSymlinkInCreationPath(root, 'setup lock directory');
|
|
131
|
+
try { fs.mkdirSync(root, { recursive: true, mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
132
|
+
const info = fs.lstatSync(root);
|
|
133
|
+
if (info.isSymbolicLink() || !info.isDirectory() || fs.realpathSync(root) !== root || (typeof process.getuid === 'function' && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0) {
|
|
134
|
+
fail('setup lock directory is not a private directory owned by the current user');
|
|
135
|
+
}
|
|
136
|
+
return path.join(root, 'install.lock');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function assertNoSymlinkInCreationPath(target, description, requireCurrentOwner = false) {
|
|
140
|
+
let existing = path.resolve(target);
|
|
141
|
+
while (!fs.existsSync(existing)) {
|
|
142
|
+
const parent = path.dirname(existing);
|
|
143
|
+
if (parent === existing) fail(`${description} has no existing parent directory`);
|
|
144
|
+
existing = parent;
|
|
145
|
+
}
|
|
146
|
+
let info;
|
|
147
|
+
try { info = fs.lstatSync(existing); } catch { fail(`${description} cannot be inspected safely`); }
|
|
148
|
+
if (info.isSymbolicLink() || !info.isDirectory() || fs.realpathSync(existing) !== existing) {
|
|
149
|
+
fail(`${description} crosses a symbolic link or is not a real directory; refusing to write through it`);
|
|
150
|
+
}
|
|
151
|
+
if (requireCurrentOwner && typeof process.getuid === 'function' && info.uid !== process.getuid()) {
|
|
152
|
+
fail(`${description} is not owned by the current user; refusing to write there`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function acquireSetupLock(rootOverride) {
|
|
157
|
+
const file = setupLockPath(rootOverride);
|
|
158
|
+
try {
|
|
159
|
+
const fd = fs.openSync(file, 'wx', 0o600);
|
|
160
|
+
fs.closeSync(fd);
|
|
161
|
+
} catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
162
|
+
const info = fs.lstatSync(file);
|
|
163
|
+
if (!info.isFile() || info.isSymbolicLink() || (typeof process.getuid === 'function' && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0) {
|
|
164
|
+
fail('setup lock is not a private regular file owned by the current user; refusing to use it');
|
|
165
|
+
}
|
|
166
|
+
const db = new DatabaseSync(file);
|
|
167
|
+
try {
|
|
168
|
+
// An empty SQLite file needs no schema or owner record. Its kernel lock is
|
|
169
|
+
// acquired atomically and released on process death, including SIGKILL.
|
|
170
|
+
db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE');
|
|
171
|
+
} catch (error) {
|
|
172
|
+
db.close();
|
|
173
|
+
if (error.errcode === 5 || error.errcode === 6) fail('another worker-bridge setup is running; wait for it to finish, then retry');
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
let released = false;
|
|
177
|
+
return () => {
|
|
178
|
+
if (released) return;
|
|
179
|
+
released = true;
|
|
180
|
+
try { db.exec('ROLLBACK'); } finally { db.close(); }
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function unitDirFor(platform, env) {
|
|
185
|
+
if (platform === 'linux') {
|
|
186
|
+
const configHome = env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(os.homedir(), '.config');
|
|
187
|
+
return path.join(configHome, 'systemd/user');
|
|
188
|
+
}
|
|
189
|
+
if (platform === 'darwin') return path.join(env.HOME || os.homedir(), 'Library/LaunchAgents');
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function unitFiles(o) {
|
|
194
|
+
const name = `dot-bridge-${o.worker}`;
|
|
195
|
+
const files = { [`${name}.service`]: [
|
|
196
|
+
`# ${MARKER}. Remove with --remove.`,
|
|
197
|
+
'[Unit]',
|
|
198
|
+
`Description=Worker Bridge instance for worker ${o.worker} (built-in OAuth, loopback)`,
|
|
199
|
+
'After=network-online.target',
|
|
200
|
+
'',
|
|
201
|
+
'[Service]',
|
|
202
|
+
`WorkingDirectory=${o.repo}`,
|
|
203
|
+
`ExecStart=${o.node} src/server.mjs`,
|
|
204
|
+
`Environment=HOME=${o.home}`,
|
|
205
|
+
'Environment=NODE_ENV=production',
|
|
206
|
+
'Environment=DALAN_AUTH_MODE=builtin',
|
|
207
|
+
...(o.repoTools ? ['Environment=DALAN_ENABLE_WORKSPACE=1'] : []),
|
|
208
|
+
`Environment=DALAN_PORT=${o.port}`,
|
|
209
|
+
`Environment=PATH=${servicePath(o.node)}`,
|
|
210
|
+
'UnsetEnvironment=OPENAI_API_KEY ANTHROPIC_API_KEY',
|
|
211
|
+
'Restart=on-failure',
|
|
212
|
+
'RestartSec=3',
|
|
213
|
+
'UMask=0077',
|
|
214
|
+
'',
|
|
215
|
+
'[Install]',
|
|
216
|
+
'WantedBy=default.target',
|
|
217
|
+
'',
|
|
218
|
+
].join('\n') };
|
|
219
|
+
const enable = [`${name}.service`];
|
|
220
|
+
if (o.lan) {
|
|
221
|
+
const proxyd = PROXYD.find(f => fs.existsSync(f)) ?? PROXYD[0];
|
|
222
|
+
files[`${name}-lan.socket`] = [
|
|
223
|
+
`# ${MARKER}. Remove with --remove.`,
|
|
224
|
+
'[Unit]',
|
|
225
|
+
`Description=LAN listener for the ${o.worker} bridge (a reverse proxy on another host forwards here)`,
|
|
226
|
+
'',
|
|
227
|
+
'[Socket]',
|
|
228
|
+
`ListenStream=${o.lan.address}:${o.lan.port}`,
|
|
229
|
+
'FreeBind=true',
|
|
230
|
+
'',
|
|
231
|
+
'[Install]',
|
|
232
|
+
'WantedBy=sockets.target',
|
|
233
|
+
'',
|
|
234
|
+
].join('\n');
|
|
235
|
+
files[`${name}-lan.service`] = [
|
|
236
|
+
`# ${MARKER}. Remove with --remove.`,
|
|
237
|
+
'[Unit]',
|
|
238
|
+
`Description=Forward ${o.lan.address}:${o.lan.port} to the ${o.worker} bridge on 127.0.0.1:${o.port}`,
|
|
239
|
+
`Requires=${name}-lan.socket`,
|
|
240
|
+
`After=${name}-lan.socket ${name}.service`,
|
|
241
|
+
'',
|
|
242
|
+
'[Service]',
|
|
243
|
+
`ExecStart=${proxyd} 127.0.0.1:${o.port}`,
|
|
244
|
+
'',
|
|
245
|
+
].join('\n');
|
|
246
|
+
enable.push(`${name}-lan.socket`);
|
|
247
|
+
}
|
|
248
|
+
return { files, enable };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function servicePath(node) {
|
|
252
|
+
return [...new Set([path.dirname(node), '/opt/homebrew/bin', '/home/linuxbrew/.linuxbrew/bin', '/usr/local/bin', '/usr/bin', '/bin'])].join(':');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// LaunchAgent. Every value is a path or a fixed word that passed SAFE_PATH or is a literal, so no XML escaping is needed.
|
|
256
|
+
function plistText(o) {
|
|
257
|
+
const name = `dot-bridge-${o.worker}`;
|
|
258
|
+
const logs = path.join(o.home, 'logs');
|
|
259
|
+
const env = { HOME: o.home, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', ...(o.repoTools ? { DALAN_ENABLE_WORKSPACE: '1' } : {}), DALAN_PORT: String(o.port), PATH: servicePath(o.node) };
|
|
260
|
+
return [
|
|
261
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
262
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
263
|
+
`<!-- ${MARKER}. Remove with --remove --worker ${o.worker}. -->`,
|
|
264
|
+
'<plist version="1.0">',
|
|
265
|
+
'<dict>',
|
|
266
|
+
' <key>Label</key>',
|
|
267
|
+
` <string>${launchLabel(o.worker)}</string>`,
|
|
268
|
+
' <key>ProgramArguments</key>',
|
|
269
|
+
' <array>',
|
|
270
|
+
` <string>${o.node}</string>`,
|
|
271
|
+
` <string>${path.join(o.repo, 'src/server.mjs')}</string>`,
|
|
272
|
+
' </array>',
|
|
273
|
+
' <key>WorkingDirectory</key>',
|
|
274
|
+
` <string>${o.repo}</string>`,
|
|
275
|
+
' <key>EnvironmentVariables</key>',
|
|
276
|
+
' <dict>',
|
|
277
|
+
...Object.entries(env).flatMap(([key, value]) => [` <key>${key}</key>`, ` <string>${value}</string>`]),
|
|
278
|
+
' </dict>',
|
|
279
|
+
' <key>RunAtLoad</key>',
|
|
280
|
+
' <true/>',
|
|
281
|
+
' <key>KeepAlive</key>',
|
|
282
|
+
' <true/>',
|
|
283
|
+
' <key>LimitLoadToSessionType</key>',
|
|
284
|
+
' <array>',
|
|
285
|
+
...SESSION_TYPES.map(type => ` <string>${type}</string>`),
|
|
286
|
+
' </array>',
|
|
287
|
+
' <key>UMask</key>',
|
|
288
|
+
' <integer>63</integer>', // 0077 octal
|
|
289
|
+
' <key>StandardOutPath</key>',
|
|
290
|
+
` <string>${path.join(logs, `${name}.out.log`)}</string>`,
|
|
291
|
+
' <key>StandardErrorPath</key>',
|
|
292
|
+
` <string>${path.join(logs, `${name}.err.log`)}</string>`,
|
|
293
|
+
'</dict>',
|
|
294
|
+
'</plist>',
|
|
295
|
+
'',
|
|
296
|
+
].join('\n');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Lint the generated text before anything is written. Returns false when plutil is not installed (skipped).
|
|
300
|
+
function lintPlist(text, env) {
|
|
301
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dbm-plist-'));
|
|
302
|
+
try {
|
|
303
|
+
const file = path.join(dir, 'check.plist');
|
|
304
|
+
fs.writeFileSync(file, text, { mode: 0o600 });
|
|
305
|
+
const r = spawnSync('plutil', ['-lint', file], { encoding: 'utf8', env });
|
|
306
|
+
if (r.error?.code === 'ENOENT') return false;
|
|
307
|
+
if (r.status !== 0) fail(`plutil -lint rejected the generated plist: ${`${r.stdout}${r.stderr}`.trim()}`);
|
|
308
|
+
return true;
|
|
309
|
+
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function runDotWorkerInit(options) {
|
|
313
|
+
return spawnSync(options.node, [path.join(options.repo, 'bin/dalan.mjs'), 'init', '--worker', options.worker, ...(options.repoTools?['--enable-workspace']:[]), '--public-url', options.publicUrl, '--json'], {
|
|
314
|
+
cwd: options.repo, env: { ...process.env, HOME: options.home, NODE_ENV: 'production' }, encoding: 'utf8',
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function writeHome(o, platform, initHome = runDotWorkerInit) {
|
|
319
|
+
const parent = path.dirname(o.home);
|
|
320
|
+
fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
|
|
321
|
+
const stage = path.join(parent, `.${path.basename(o.home)}.dot-bridge-${randomBytes(8).toString('hex')}.stage`);
|
|
322
|
+
fs.mkdirSync(stage, { mode: 0o700 });
|
|
323
|
+
fs.chmodSync(stage, 0o700);
|
|
324
|
+
try {
|
|
325
|
+
if (platform === 'darwin') fs.mkdirSync(path.join(stage, 'logs'), { recursive: true, mode: 0o700 });
|
|
326
|
+
const configDir = defaultPath(stage,'.config/dot-bridge');
|
|
327
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
328
|
+
const init = initHome({ ...o, home: stage });
|
|
329
|
+
if (init.status !== 0) fail(`dalan init failed (exit ${init.status}): ${String(init.stderr).trim().split('\n').at(-1)}`);
|
|
330
|
+
// Create the path secret now so the private resource URL file exists before the first start. The server keeps an existing env file.
|
|
331
|
+
const envFile = path.join(configDir, 'env');
|
|
332
|
+
if (!fs.existsSync(envFile)) writeExclusive(envFile, `BRIDGE_PATH_SECRET=${randomBytes(32).toString('hex')}\n`, 0o600, 'bridge environment file');
|
|
333
|
+
fs.chmodSync(envFile, 0o600);
|
|
334
|
+
const secret = /^BRIDGE_PATH_SECRET=([a-f0-9]{64})$/m.exec(fs.readFileSync(envFile, 'utf8'))?.[1];
|
|
335
|
+
if (!secret) fail('bridge path secret is missing or invalid');
|
|
336
|
+
const urlFile = path.join(stage, 'resource-url');
|
|
337
|
+
fs.writeFileSync(urlFile, `${o.publicUrl}/${secret}/mcp\n`, { mode: 0o600 });
|
|
338
|
+
fs.chmodSync(urlFile, 0o600);
|
|
339
|
+
writeWorkerInstructions(stage);
|
|
340
|
+
try { fs.mkdirSync(o.home, { mode: 0o700 }); }
|
|
341
|
+
catch (error) {
|
|
342
|
+
if (error.code === 'EEXIST' || error.code === 'ENOTEMPTY') fail(`${o.home} appeared during setup; refusing to replace the existing path`);
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
// Reserve the final path with mkdir (which cannot replace an existing directory), then copy the complete staged tree.
|
|
347
|
+
// A process kill during this copy can leave a partial home; it never authorizes overwriting a foreign destination.
|
|
348
|
+
for (const name of fs.readdirSync(stage)) {
|
|
349
|
+
fs.cpSync(path.join(stage, name), path.join(o.home, name), { recursive: true, errorOnExist: true, force: false });
|
|
350
|
+
}
|
|
351
|
+
fs.chmodSync(o.home, 0o700);
|
|
352
|
+
// fs.cp creates destination directories with the process umask; restore the
|
|
353
|
+
// private mode required before the authorization server can read its keys.
|
|
354
|
+
fs.chmodSync(defaultPath(o.home,'.config/dot-bridge'),0o700);
|
|
355
|
+
fs.rmSync(stage, { recursive: true });
|
|
356
|
+
} catch (error) {
|
|
357
|
+
fail(`${o.home} was reserved by this setup but staging could not be fully copied; inspect the path before retrying (${error.message})`);
|
|
358
|
+
}
|
|
359
|
+
return path.join(o.home, 'resource-url');
|
|
360
|
+
} catch (error) {
|
|
361
|
+
fs.rmSync(stage, { recursive: true, force: true });
|
|
362
|
+
throw error;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function systemctl(args, env, spawn = spawnSync, o) {
|
|
367
|
+
const r = spawn('systemctl', ['--user', ...args], { stdio: 'inherit', env });
|
|
368
|
+
if (r.status !== 0) fail(`systemctl --user ${args.join(' ')} failed (exit ${r.status ?? r.signal}). Generated state is left in place; remove this install with: ${recoveryCommand(o)}`);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function launchctl(args, env, spawn = spawnSync) {
|
|
372
|
+
return spawn('launchctl', args, { encoding: 'utf8', env });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function checkStartReadiness(platform, env) {
|
|
376
|
+
if (platform === 'linux') {
|
|
377
|
+
const manager = spawnSync('systemctl', ['--user', 'show-environment'], { stdio: 'ignore', env });
|
|
378
|
+
if (manager.status !== 0) fail('systemd user manager is unavailable; start a user session with an active systemd --user manager, then retry --start. Use --write-units-only to generate files offline.');
|
|
379
|
+
} else {
|
|
380
|
+
const uid = process.getuid?.();
|
|
381
|
+
const domain = uid === undefined ? null : spawnSync('launchctl', ['print', `user/${uid}`], { stdio: 'ignore', env });
|
|
382
|
+
if (!domain || domain.status !== 0) fail('launchd user domain is unavailable; log in to this Mac as the user that owns the bridge, then retry --start. Generate files without --start for offline setup.');
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function warnIfLingeringDisabled(platform, env, log, spawn = spawnSync) {
|
|
387
|
+
if (platform !== 'linux') return;
|
|
388
|
+
const uid = typeof process.getuid === 'function' ? String(process.getuid()) : '';
|
|
389
|
+
if (!uid) return;
|
|
390
|
+
const result = spawn('loginctl', ['show-user', uid, '--property=Linger', '--value'], { encoding: 'utf8', timeout: 2000, env });
|
|
391
|
+
if (result.status === 0 && result.stdout.trim() === 'no') {
|
|
392
|
+
log(`WARN user lingering is disabled. A user service can stop when the user manager stops. If you choose to run services outside your login session, an administrator can enable it with: loginctl enable-linger ${uid}`);
|
|
393
|
+
} else if (result.error?.code === 'ENOENT' || result.status !== 0) {
|
|
394
|
+
log('WARN could not check systemd user lingering (read-only loginctl probe unavailable); inspect it with loginctl show-user USER -p Linger. No setting was changed.');
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function isBridgeHome(home, worker) {
|
|
399
|
+
try {
|
|
400
|
+
const cfg = JSON.parse(fs.readFileSync(defaultPath(home,'.config/dot-bridge/workers.json'), 'utf8'));
|
|
401
|
+
return Object.hasOwn(cfg.workers ?? {}, worker);
|
|
402
|
+
} catch { return false; }
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Validate only the user-owned tree that retry will trust. System ancestors such as /home and /Users are
|
|
406
|
+
// intentionally outside this walk; HOME and every bridge-owned descendant must be real, owned objects.
|
|
407
|
+
function assertOwnedPath(root, target, expectedType, description) {
|
|
408
|
+
const relative = path.relative(root, target);
|
|
409
|
+
if (relative.startsWith('..') || path.isAbsolute(relative)) fail(`--retry-public-check refused: ${description} is outside its owned root`);
|
|
410
|
+
let current = root;
|
|
411
|
+
const parts = relative ? relative.split(path.sep) : [];
|
|
412
|
+
for (let index = 0; index <= parts.length; index++) {
|
|
413
|
+
if (index > 0) current = path.join(current, parts[index - 1]);
|
|
414
|
+
let info;
|
|
415
|
+
try { info = fs.lstatSync(current); } catch { fail(`--retry-public-check refused: ${description} is missing (${current})`); }
|
|
416
|
+
if (info.isSymbolicLink()) fail(`--retry-public-check refused: ${description} contains a symbolic link (${current})`);
|
|
417
|
+
const isTarget = index === parts.length;
|
|
418
|
+
const typeOk = isTarget ? (expectedType === 'directory' ? info.isDirectory() : info.isFile()) : info.isDirectory();
|
|
419
|
+
if (!typeOk) fail(`--retry-public-check refused: ${description} has an unexpected file type (${current})`);
|
|
420
|
+
if (typeof process.getuid === 'function' && info.uid !== process.getuid()) fail(`--retry-public-check refused: ${description} is not owned by the current user (${current})`);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function readOwnedFile(root, file, description) {
|
|
425
|
+
assertOwnedPath(root, file, 'file', description);
|
|
426
|
+
return fs.readFileSync(file, 'utf8');
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function assertNoSystemdOverrides(unit,env) {
|
|
430
|
+
const dropDir=unit+'.d';
|
|
431
|
+
if(fs.existsSync(dropDir)&&fs.readdirSync(dropDir).some(name=>name.endsWith('.conf'))) fail('--retry-public-check refused: the service has systemd drop-ins; inspect them with systemctl --user cat '+path.basename(unit));
|
|
432
|
+
// The user manager also knows about global and transient drop-ins outside the generated unit directory.
|
|
433
|
+
const effective=spawnSync('systemctl',['--user','show',path.basename(unit),'--property=DropInPaths','--value'],{env,encoding:'utf8',timeout:5000,maxBuffer:65536});
|
|
434
|
+
if(effective.error||effective.status!==0) fail('--retry-public-check refused: cannot inspect the effective systemd service; check its status with systemctl --user status '+path.basename(unit));
|
|
435
|
+
if(effective.stdout.trim()) fail('--retry-public-check refused: the effective service has systemd drop-ins; inspect them with systemctl --user cat '+path.basename(unit));
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function publicRetryCommand(o,url) {
|
|
439
|
+
return `node ${path.join(o.repo,'scripts/worker-bridge-setup.mjs')} --retry-public-check --worker ${o.worker} --public-url ${url} --port ${o.port} --home ${o.home}${o.repoTools?'':' --no-repo-tools'}`;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function recoveryCommand(o) {
|
|
443
|
+
return `node ${path.join(o.repo, 'scripts/worker-bridge-setup.mjs')} --remove --worker ${o.worker} --home ${o.home} --purge-home`;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function writeExclusive(file, value, mode, kind, o) {
|
|
447
|
+
try { fs.writeFileSync(file, value, { mode, flag: 'wx' }); }
|
|
448
|
+
catch (error) {
|
|
449
|
+
if (error.code === 'EEXIST') {
|
|
450
|
+
const recovery = o ? ` Generated state is left in place; remove this install with: ${recoveryCommand(o)}` : '';
|
|
451
|
+
fail(`${file} already exists; refusing to overwrite the existing ${kind}.${recovery}`);
|
|
452
|
+
}
|
|
453
|
+
throw error;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// The real location of a path: the real path of its deepest existing ancestor, followed by the rest of the path.
|
|
458
|
+
function canonicalPath(target) {
|
|
459
|
+
let head = path.resolve(target), tail = '';
|
|
460
|
+
for (;;) {
|
|
461
|
+
try { return path.join(fs.realpathSync(head), tail); } catch { /* not there (yet), or unreadable: try the parent */ }
|
|
462
|
+
const parent = path.dirname(head);
|
|
463
|
+
if (parent === head) return path.resolve(target);
|
|
464
|
+
tail = path.join(path.basename(head), tail); head = parent;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// Every path a unit or plist could name without quoting. A path that setup writes uses only SAFE_PATH characters, and = : ,
|
|
469
|
+
// are both path characters and separators (HOME=/a, PATH=/a:/b), so every way to cut a run of those characters at them is
|
|
470
|
+
// a candidate: it starts at any /, since a unit may put a prefix such as - + or @ before a path (WorkingDirectory=-/a), and
|
|
471
|
+
// ends at the end of the run or before = : or ,. A start inside a path only adds a shorter candidate, which can refuse a
|
|
472
|
+
// purge but never hides a match. Returns null past a fixed number of candidates, so a crafted file cannot make the check slow.
|
|
473
|
+
const UNIT_PATH_CANDIDATES_MAX = 20000;
|
|
474
|
+
function unitPathCandidates(text) {
|
|
475
|
+
const out = [];
|
|
476
|
+
for (const [run] of text.matchAll(/[A-Za-z0-9_@+=:,./-]+/g)) {
|
|
477
|
+
const starts = [], ends = [];
|
|
478
|
+
for (let i = 0; i < run.length; i += 1) {
|
|
479
|
+
if (run[i] === '/') starts.push(i);
|
|
480
|
+
if ('=:,'.includes(run[i])) ends.push(i);
|
|
481
|
+
}
|
|
482
|
+
ends.push(run.length);
|
|
483
|
+
let first = 0; // starts and ends both ascend, so the ends after each start begin at a moving index
|
|
484
|
+
for (const s of starts) {
|
|
485
|
+
while (ends[first] <= s) first += 1;
|
|
486
|
+
for (let k = first; k < ends.length; k += 1) {
|
|
487
|
+
if (out.length >= UNIT_PATH_CANDIDATES_MAX) return null;
|
|
488
|
+
out.push(run.slice(s, ends[k]));
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return out;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// Files in the user's unit directory (other than the ones --remove is about to delete) that name this home. Such a file is
|
|
496
|
+
// a service that still uses the home, whatever its name or the release that wrote it. A symlink is followed: a unit linked
|
|
497
|
+
// into the directory is as live as one written there. Returns { named, unreadable }: a file that cannot be read is not
|
|
498
|
+
// evidence that it is unrelated, so the caller refuses on it. A link to nothing, or to something that is not a file (such as
|
|
499
|
+
// /dev/null, which masks a unit), cannot name a home and is skipped.
|
|
500
|
+
function unitsNamingHome(unitDir, home, skip) {
|
|
501
|
+
const escaped = home.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
502
|
+
const literal = new RegExp(`(?<![\\w./-])${escaped}(?![\\w.-])`);
|
|
503
|
+
// A unit can name the home through another spelling of the same directory, such as a symlinked parent. Every absolute
|
|
504
|
+
// path in the unit is compared by its real location as well.
|
|
505
|
+
const real = canonicalPath(home);
|
|
506
|
+
const namesHome = text => {
|
|
507
|
+
if (literal.test(text)) return true;
|
|
508
|
+
const candidates = unitPathCandidates(text);
|
|
509
|
+
if (candidates === null) return null;
|
|
510
|
+
return candidates.some(candidate => {
|
|
511
|
+
const resolved = canonicalPath(candidate);
|
|
512
|
+
return resolved === real || resolved.startsWith(real + '/');
|
|
513
|
+
});
|
|
514
|
+
};
|
|
515
|
+
const named = [], unreadable = [];
|
|
516
|
+
let entries;
|
|
517
|
+
try { entries = fs.readdirSync(unitDir, { withFileTypes: true }); }
|
|
518
|
+
catch (error) { return { named, unreadable: error.code === 'ENOENT' ? [] : [unitDir] }; }
|
|
519
|
+
for (const entry of entries) {
|
|
520
|
+
const file = path.join(unitDir, entry.name);
|
|
521
|
+
if (skip.includes(file) || !(entry.isFile() || entry.isSymbolicLink())) continue;
|
|
522
|
+
try {
|
|
523
|
+
const stat = fs.statSync(file); // follows a link
|
|
524
|
+
if (!stat.isFile()) continue;
|
|
525
|
+
if (stat.size >= 1048576) { unreadable.push(file); continue; }
|
|
526
|
+
const names = namesHome(fs.readFileSync(file, 'utf8'));
|
|
527
|
+
if (names === null) unreadable.push(file); // too many possible paths to check: not evidence that it is unrelated
|
|
528
|
+
else if (names) named.push(file);
|
|
529
|
+
} catch (error) {
|
|
530
|
+
if (entry.isSymbolicLink() && error.code === 'ENOENT') continue; // a dangling link
|
|
531
|
+
unreadable.push(file);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return { named, unreadable };
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// Processes (other than this one) that hold a bridge database of this home open: { holders: [{ pid, command }], unknown }.
|
|
538
|
+
// `unknown` is null when the probe ran to the end, or a reason when it could not tell. An empty `holders` with a reason
|
|
539
|
+
// is NOT "nobody holds it": the caller must not act on it.
|
|
540
|
+
export function bridgeDatabaseHolders(home, { spawn = spawnSync, platform = process.platform, procRoot = '/proc' } = {}) {
|
|
541
|
+
const isDb = file => file.startsWith(`${home}${path.sep}`) && /(^|\/)bridge\.db(-wal|-shm)?$/.test(file);
|
|
542
|
+
const holders = new Map();
|
|
543
|
+
let unknown = null;
|
|
544
|
+
if (platform === 'linux') {
|
|
545
|
+
let pids = [];
|
|
546
|
+
try { pids = fs.readdirSync(procRoot).filter(n => /^\d+$/.test(n) && Number(n) !== process.pid); }
|
|
547
|
+
catch (error) { return { holders: [], unknown: `${procRoot} could not be read (${error.code ?? error.message})` }; }
|
|
548
|
+
// A process that exited while we looked is gone (ENOENT/ESRCH). One that refuses us (EACCES/EPERM: another user's, or a
|
|
549
|
+
// same-user process that dropped its dumpable flag, such as ssh-agent) is not a bridge: the bridge is a plain node
|
|
550
|
+
// process. Any other failure to read is a gap in the answer.
|
|
551
|
+
const skippable = error => ['ENOENT', 'ESRCH', 'EACCES', 'EPERM'].includes(error.code);
|
|
552
|
+
for (const pid of pids) {
|
|
553
|
+
let fds;
|
|
554
|
+
try { fds = fs.readdirSync(`${procRoot}/${pid}/fd`); }
|
|
555
|
+
catch (error) { if (!skippable(error)) unknown ??= `the open files of process ${pid} could not be read (${error.code ?? error.message})`; continue; }
|
|
556
|
+
for (const fd of fds) {
|
|
557
|
+
let target;
|
|
558
|
+
try { target = fs.readlinkSync(`${procRoot}/${pid}/fd/${fd}`); }
|
|
559
|
+
catch (error) { if (!skippable(error)) unknown ??= `the open files of process ${pid} could not be read (${error.code ?? error.message})`; continue; }
|
|
560
|
+
if (isDb(target)) { let command = ''; try { command = fs.readFileSync(`${procRoot}/${pid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim(); } catch {} holders.set(pid, command); break; }
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
} else {
|
|
564
|
+
const r = spawn('lsof', ['-nP', '-F', 'pcn', '+D', home], { encoding: 'utf8', timeout: 10000, maxBuffer: 1 << 20 });
|
|
565
|
+
let pid = null, command = '';
|
|
566
|
+
for (const line of String(r.stdout ?? '').split('\n')) {
|
|
567
|
+
if (line.startsWith('p')) { pid = line.slice(1); command = ''; }
|
|
568
|
+
else if (line.startsWith('c')) command = line.slice(1);
|
|
569
|
+
else if (line.startsWith('n') && pid && Number(pid) !== process.pid && isDb(line.slice(1))) holders.set(pid, command);
|
|
570
|
+
}
|
|
571
|
+
// lsof exits 1 with no output when nothing matched; any other failure leaves the answer incomplete.
|
|
572
|
+
const cleanNone = r.status === 1 && !String(r.stdout ?? '').trim() && !String(r.stderr ?? '').trim();
|
|
573
|
+
if (r.error) unknown = `lsof could not be run (${r.error.code ?? r.error.message})`;
|
|
574
|
+
else if (r.signal) unknown = `lsof was stopped by ${r.signal}`;
|
|
575
|
+
else if (r.status !== 0 && !cleanNone) unknown = `lsof failed (exit ${r.status}${String(r.stderr ?? '').trim() ? `: ${String(r.stderr).trim().slice(0, 120)}` : ''})`;
|
|
576
|
+
}
|
|
577
|
+
return { holders: [...holders].map(([pid, command]) => ({ pid, command })), unknown };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// Stop, then delete, only files that carry the marker. The refusals that need the unit directory and the bridge home
|
|
581
|
+
// happen before the first stop or delete; the check for a process that still holds the database follows the stop, because
|
|
582
|
+
// the service that was just stopped needs a moment to exit.
|
|
583
|
+
function removeUnit(o, { platform, env, log, spawn = spawnSync, holderProbe = home => bridgeDatabaseHolders(home, { spawn }) }) {
|
|
584
|
+
const unitDir = unitDirFor(platform, env);
|
|
585
|
+
if (!unitDir) fail('--remove is not supported on this platform (only Linux and macOS have units)');
|
|
586
|
+
const linux = platform === 'linux';
|
|
587
|
+
const name = `dot-bridge-${o.worker}`;
|
|
588
|
+
const names = linux ? [`${name}.service`, `${name}-lan.socket`, `${name}-lan.service`] : [`${launchLabel(o.worker)}.plist`];
|
|
589
|
+
const present = names.map(n => path.join(unitDir, n)).filter(f => fs.existsSync(f));
|
|
590
|
+
for (const f of present) if (!fs.readFileSync(f, 'utf8').includes(MARKER)) fail(`${f} was not created by worker-bridge-setup; refusing to remove it`);
|
|
591
|
+
const homeExists = fs.existsSync(o.home);
|
|
592
|
+
// The checks below compare paths: the units name the real home and lsof reports the real path. A --home that reaches the
|
|
593
|
+
// home through a symbolic link would pass them and then delete the real home, so purge only the real path.
|
|
594
|
+
if (o.purge && homeExists) {
|
|
595
|
+
const real = fs.realpathSync(o.home);
|
|
596
|
+
if (real !== path.resolve(o.home)) fail(`${o.home} passes through a symbolic link (its real path is ${real}); nothing was removed. Run the same command with --home ${real}`);
|
|
597
|
+
}
|
|
598
|
+
if (o.purge && homeExists && !isBridgeHome(o.home, o.worker)) fail(`${o.home} is not a bridge home for worker ${o.worker}; refusing to purge it`);
|
|
599
|
+
if (!present.length && !(o.purge && homeExists)) { log(`Nothing to remove for worker ${o.worker}.`); return; }
|
|
600
|
+
if (o.purge && homeExists) {
|
|
601
|
+
const { named: users, unreadable } = unitsNamingHome(unitDir, o.home, present);
|
|
602
|
+
if (unreadable.length) fail(`${unreadable.join(', ')} could not be read, so it is not known whether a service that uses ${o.home} is defined there. Nothing was removed. Make ${unreadable.length > 1 ? 'them' : 'it'} readable (or delete ${unreadable.length > 1 ? 'them' : 'it'} once the service is stopped), then run this command again.`);
|
|
603
|
+
if (users.length) {
|
|
604
|
+
const stop = linux
|
|
605
|
+
? users.map(f => `systemctl --user disable --now ${path.basename(f)}`).join('; ')
|
|
606
|
+
: users.map(f => `launchctl bootout ${launchDomains(process.getuid())[0]} ${f} (or ${launchDomains(process.getuid())[1]} for an agent that an earlier release loaded)`).join('; ');
|
|
607
|
+
fail(`${o.home} is still named by ${users.join(', ')}; a service that uses this home may be running. Nothing was removed. Stop it (${stop}), delete that file, then run this command again.`);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
if (present.length && linux) systemctl(['disable', '--now', ...present.map(f => path.basename(f))], env, spawn, o);
|
|
612
|
+
if (!linux) for (const plist of present) {
|
|
613
|
+
const label = path.basename(plist, '.plist'), uid = process.getuid();
|
|
614
|
+
const [userDomain, guiDomain] = launchDomains(uid);
|
|
615
|
+
const r = launchctl(['bootout', userDomain, plist], env, spawn);
|
|
616
|
+
const g = r.status === 0 ? r : launchctl(['bootout', guiDomain, plist], env, spawn); // loaded by an older release
|
|
617
|
+
if (r.status === 0 || g.status === 0) log(`Stopped ${label}`);
|
|
618
|
+
else if (launchDomains(uid).some(domain => launchctl(['print', `${domain}/${label}`], env, spawn).status === 0)) {
|
|
619
|
+
fail(`launchctl bootout ${guiDomain} ${plist} failed (exit ${g.status ?? g.signal}) and the agent is still loaded: ${String(g.stderr).trim()}. Nothing was removed.`);
|
|
620
|
+
} else log(`${label} was not loaded; nothing to stop`);
|
|
621
|
+
}
|
|
622
|
+
for (const f of present) { fs.rmSync(f); log(`Removed ${f}`); }
|
|
623
|
+
if (present.length && linux) systemctl(['daemon-reload'], env, spawn, o);
|
|
624
|
+
if (o.purge && homeExists) {
|
|
625
|
+
// The service that was just stopped needs a moment to exit.
|
|
626
|
+
const waitMs = Number(env.DALAN_PURGE_WAIT_MS ?? 5000);
|
|
627
|
+
let probe = holderProbe(o.home);
|
|
628
|
+
for (let waited = 0; (probe.holders.length || probe.unknown) && waited < waitMs; waited += 100) {
|
|
629
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
630
|
+
probe = holderProbe(o.home);
|
|
631
|
+
}
|
|
632
|
+
const retry = `--remove --worker ${o.worker} --home ${o.home} --purge-home`;
|
|
633
|
+
if (probe.holders.length) {
|
|
634
|
+
fail(`The service is removed, but ${o.home} is kept: ${probe.holders.map(h => `process ${h.pid}${h.command ? ` (${h.command.slice(0, 80)})` : ''}`).join(', ')} still hold(s) its bridge database open. Stop ${probe.holders.length > 1 ? 'them' : 'it'}, then run the same command again: ${retry}`);
|
|
635
|
+
}
|
|
636
|
+
if (probe.unknown) {
|
|
637
|
+
fail(`The service is removed, but ${o.home} is kept: it could not be checked whether a process still holds its bridge database open (${probe.unknown}). Make sure nothing uses ${o.home}, fix that check (for example install lsof), then run the same command again: ${retry}`);
|
|
638
|
+
}
|
|
639
|
+
fs.rmSync(o.home, { recursive: true, force: true }); log(`Removed bridge home ${o.home}`);
|
|
640
|
+
}
|
|
641
|
+
else if (o.purge) log(`No bridge home at ${o.home}`);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// Point an existing service at the code that runs this script. An npm install of a renamed package, or a moved checkout,
|
|
645
|
+
// leaves the unit naming the old directory. Only the old directory text changes; port, home and environment stay as they are.
|
|
646
|
+
function repointUnit(o, { platform, env, log }) {
|
|
647
|
+
const unitDir = unitDirFor(platform, env);
|
|
648
|
+
if (!unitDir) fail('--repoint is not supported on this platform (only Linux and macOS have units)');
|
|
649
|
+
const linux = platform === 'linux';
|
|
650
|
+
const names = linux ? [`dot-bridge-${o.worker}.service`] : [`${launchLabel(o.worker)}.plist`];
|
|
651
|
+
const present = names.map(n => path.join(unitDir, n)).filter(f => fs.existsSync(f));
|
|
652
|
+
if (!present.length) fail(`no service unit for worker ${o.worker} in ${unitDir}; nothing to repoint`);
|
|
653
|
+
const changes = present.map(file => {
|
|
654
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
655
|
+
if (!text.includes(MARKER)) fail(`${file} was not created by worker-bridge-setup; refusing to change it`);
|
|
656
|
+
const match = linux ? /^WorkingDirectory=(\S+)$/m.exec(text) : /<key>WorkingDirectory<\/key>\s*<string>([^<]+)<\/string>/.exec(text);
|
|
657
|
+
if (!match) fail(`${file} has no WorkingDirectory; refusing to guess the old code directory`);
|
|
658
|
+
if (!linux && match[1] !== o.repo && !text.includes(`<string>${path.join(match[1], 'src/server.mjs')}</string>`)) fail(`${file} runs a script other than ${path.join(match[1], 'src/server.mjs')}; refusing to guess what to change`);
|
|
659
|
+
return { file, text, old: match[1] };
|
|
660
|
+
});
|
|
661
|
+
for (const { file, text, old } of changes) {
|
|
662
|
+
let next = text;
|
|
663
|
+
// Change the code directory and the script argument only. HOME, the environment, the interpreter and the log paths can
|
|
664
|
+
// name a path below the old code directory; they are not code paths and stay as they are.
|
|
665
|
+
if (old !== o.repo) {
|
|
666
|
+
next = linux
|
|
667
|
+
? next.replace(/^WorkingDirectory=.*$/m, () => `WorkingDirectory=${o.repo}`)
|
|
668
|
+
: next.replace(/(<key>WorkingDirectory<\/key>\s*<string>)[^<]*(<\/string>)/, (_, head, tail) => `${head}${o.repo}${tail}`)
|
|
669
|
+
.replace(`<string>${path.join(old, 'src/server.mjs')}</string>`, () => `<string>${path.join(o.repo, 'src/server.mjs')}</string>`);
|
|
670
|
+
}
|
|
671
|
+
// A plist from an older release lacks the session types that let launchd load it into the user domain.
|
|
672
|
+
const addSessionTypes = !linux && !next.includes('<key>LimitLoadToSessionType</key>');
|
|
673
|
+
if (addSessionTypes) {
|
|
674
|
+
next = next.replace(/( <key>KeepAlive<\/key>\s*<true\/>\n)/, `$1 <key>LimitLoadToSessionType</key>\n <array>\n${SESSION_TYPES.map(type => ` <string>${type}</string>\n`).join('')} </array>\n`);
|
|
675
|
+
}
|
|
676
|
+
if (next === text) { log(`${file} already points at ${o.repo}`); continue; }
|
|
677
|
+
if (!fs.existsSync(path.join(o.repo, 'src/server.mjs'))) fail(`${o.repo}/src/server.mjs does not exist; run this from the installed package`);
|
|
678
|
+
const tmp = `${file}.repoint-${process.pid}`;
|
|
679
|
+
fs.writeFileSync(tmp, next, { mode: fs.statSync(file).mode & 0o777, flag: 'wx' });
|
|
680
|
+
fs.renameSync(tmp, file);
|
|
681
|
+
log(old === o.repo ? `Updated ${file}: added the launchd session types (${SESSION_TYPES.join(', ')})` : `Repointed ${file}: ${old} -> ${o.repo}${addSessionTypes ? '; added the launchd session types' : ''}`);
|
|
682
|
+
}
|
|
683
|
+
const [userDomain] = launchDomains(process.getuid?.());
|
|
684
|
+
log(linux
|
|
685
|
+
? `Restart it: systemctl --user daemon-reload && systemctl --user restart dot-bridge-${o.worker}.service`
|
|
686
|
+
: `Load it again: launchctl bootstrap ${userDomain} PLIST && launchctl kickstart -k ${userDomain}/LABEL (stop it first with launchctl bootout ${userDomain} PLIST, or bootout gui/${process.getuid()} PLIST for an agent that an older release loaded)`);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function verifyRetryTarget(o, { platform, env }) {
|
|
690
|
+
const configDir=defaultPath(o.home,'.config/dot-bridge');
|
|
691
|
+
const workersFile=defaultPath(o.home,'.config/dot-bridge/workers.json');
|
|
692
|
+
const asFile=defaultPath(o.home,'.config/dot-bridge/as.json');
|
|
693
|
+
const envFile=path.join(configDir,'env');
|
|
694
|
+
const keysFile=path.join(configDir,'as-jwks.json');
|
|
695
|
+
const cookieKeysFile=path.join(configDir,'as-cookie-keys.json');
|
|
696
|
+
const urlFile=path.join(o.home,'resource-url');
|
|
697
|
+
assertOwnedPath(o.home, o.home, 'directory', 'bridge home');
|
|
698
|
+
assertOwnedPath(o.home, path.join(o.home,'.config'), 'directory', 'bridge config path');
|
|
699
|
+
assertOwnedPath(o.home, configDir, 'directory', 'bridge config path');
|
|
700
|
+
const workers=JSON.parse(readOwnedFile(o.home,workersFile,'worker profile'));
|
|
701
|
+
const as=JSON.parse(readOwnedFile(o.home,asFile,'issuer config'));
|
|
702
|
+
const envText=readOwnedFile(o.home,envFile,'bridge environment');
|
|
703
|
+
const resource=readOwnedFile(o.home,urlFile,'resource URL').trim();
|
|
704
|
+
readOwnedFile(o.home,keysFile,'signing key');
|
|
705
|
+
readOwnedFile(o.home,cookieKeysFile,'cookie keys');
|
|
706
|
+
const secretMatch=/^BRIDGE_PATH_SECRET=([a-f0-9]{64})\n?$/.exec(envText);
|
|
707
|
+
if(!secretMatch) fail('--retry-public-check refused: the saved bridge path secret is missing or invalid');
|
|
708
|
+
loadKeys(configDir);
|
|
709
|
+
if(!Object.hasOwn(workers.workers??{},o.worker)) fail(`--retry-public-check refused: ${o.home} has no worker profile named ${o.worker}`);
|
|
710
|
+
let saved;
|
|
711
|
+
try { saved=new URL(resource); } catch { fail('--retry-public-check refused: the saved resource URL is invalid'); }
|
|
712
|
+
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
|
+
if(saved.pathname!==`/${secretMatch[1]}/mcp`) fail('--retry-public-check refused: the saved resource URL does not match this home path secret');
|
|
714
|
+
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
|
+
const dir=unitDirFor(platform,env), unit=platform==='darwin'?path.join(dir,`${launchLabel(o.worker)}.plist`):path.join(dir,`dot-bridge-${o.worker}.service`);
|
|
727
|
+
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
|
+
assertOwnedPath(configRoot,dir,'directory','service unit directory');
|
|
729
|
+
const text=readOwnedFile(configRoot,unit,'service unit');
|
|
730
|
+
const expected=platform==='darwin'?plistText(o):unitFiles(o).files[`dot-bridge-${o.worker}.service`];
|
|
731
|
+
// Accept only the previous generator's equivalent setting names; retain every
|
|
732
|
+
// other byte check so a customized service cannot become a retry target.
|
|
733
|
+
const compatibleText=text.replace(/^Environment=DOT_BRIDGE_(AUTH_MODE|ENABLE_WORKSPACE|PORT)=/gm,'Environment=DALAN_$1=').replace(/<key>DOT_BRIDGE_(AUTH_MODE|ENABLE_WORKSPACE|PORT)<\/key>/g,'<key>DALAN_$1</key>');
|
|
734
|
+
if(compatibleText!==expected) fail(`--retry-public-check refused: ${unit} does not exactly match the generated worker, HOME, executable, working directory and port`);
|
|
735
|
+
if(platform==='linux') assertNoSystemdOverrides(unit,env);
|
|
736
|
+
return { url:o.publicUrl, dnsName:saved.hostname };
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// `--start` returns as soon as the service manager accepts the unit, but the bridge needs a moment more before its admin
|
|
740
|
+
// socket answers. Commands run in that gap fail with `connect ENOENT .../admin.sock`, so --start waits for a real connection.
|
|
741
|
+
const connectsOnce = socketPath => spawnSync(process.execPath, ['-e',
|
|
742
|
+
"const s=require('node:net').connect(process.argv[1]);s.on('connect',()=>process.exit(0));s.on('error',()=>process.exit(1));setTimeout(()=>process.exit(1),2000)", socketPath], { stdio: 'ignore' }).status === 0;
|
|
743
|
+
export function waitForAdminSocket({ socketPath, timeoutMs = 30000, intervalMs = 250, probe = connectsOnce, now = Date.now, sleep = ms => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }) {
|
|
744
|
+
const deadline = now() + timeoutMs;
|
|
745
|
+
for (;;) {
|
|
746
|
+
if (probe(socketPath)) return true;
|
|
747
|
+
if (now() >= deadline) return false;
|
|
748
|
+
sleep(intervalMs);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
function waitForStartedBridge(o, env, platform, waitForSocket) {
|
|
752
|
+
// Only an explicit "0" skips the wait (tests that replace the service manager have no bridge to wait for);
|
|
753
|
+
// an empty or invalid value keeps the 30 s default.
|
|
754
|
+
const raw = readEnv('DALAN_SETUP_SOCKET_WAIT_MS', env);
|
|
755
|
+
if (String(raw ?? '').trim() === '0') return;
|
|
756
|
+
const requested = Number(raw);
|
|
757
|
+
const budget = raw != null && String(raw).trim() !== '' && Number.isFinite(requested) && requested > 0 ? requested : 30000;
|
|
758
|
+
if (waitForSocket({ socketPath: o.socketPath, timeoutMs: budget })) return;
|
|
759
|
+
const where = platform === 'darwin' ? `the log files under ${path.join(o.home, 'logs')}` : `journalctl --user -u dot-bridge-${o.worker}.service`;
|
|
760
|
+
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
|
+
}
|
|
762
|
+
|
|
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) {
|
|
764
|
+
const o = parsed ?? parseOptions(argv, platform);
|
|
765
|
+
if (o.help) {
|
|
766
|
+
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]');
|
|
769
|
+
log(' node scripts/worker-bridge-setup.mjs --retry-public-check --worker NAME --public-url https://HOST --port N [--home DIR]');
|
|
770
|
+
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)');
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
if (o.repoint) return repointUnit(o, { platform, env, log });
|
|
775
|
+
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 } : {}) });
|
|
779
|
+
return removeUnit(o, { platform, env, log, spawn, ...(holderProbe ? { holderProbe } : {}) });
|
|
780
|
+
}
|
|
781
|
+
const linux = platform === 'linux', darwin = platform === 'darwin';
|
|
782
|
+
if (o.start && !linux && !darwin) fail('--start is not supported on this platform: only Linux (systemd) and macOS (launchd) have a service unit');
|
|
783
|
+
const unitDir = unitDirFor(platform, env);
|
|
784
|
+
const { files, enable } = linux ? unitFiles(o) : { files: darwin ? { [`${launchLabel(o.worker)}.plist`]: plistText(o) } : {}, enable: [] };
|
|
785
|
+
|
|
786
|
+
if(o.retryPublicCheck) {
|
|
787
|
+
const {url,dnsName}=verifyRetryTarget(o,{platform,env});
|
|
788
|
+
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=>{
|
|
793
|
+
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
|
+
});
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// Check everything before the first write so a refusal leaves nothing behind.
|
|
800
|
+
if (!o.writeUnitsOnly) assertNoSymlinkInCreationPath(path.dirname(o.home), '--home parent');
|
|
801
|
+
if (unitDir) assertNoSymlinkInCreationPath(unitDir, 'service unit directory', true);
|
|
802
|
+
if (!o.writeUnitsOnly) {
|
|
803
|
+
try { fs.lstatSync(o.home); fail(`${o.home} already exists; refusing to reuse or change it. Pick a new --home or remove it yourself`); }
|
|
804
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
805
|
+
}
|
|
806
|
+
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
|
+
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
|
+
}
|
|
821
|
+
|
|
822
|
+
if (o.start) checkStartReadiness(platform, env);
|
|
823
|
+
if (o.start) warnIfLingeringDisabled(platform, env, log, spawn);
|
|
824
|
+
|
|
825
|
+
let urlFile = path.join(o.home, 'resource-url');
|
|
826
|
+
if (!o.writeUnitsOnly) { urlFile = writeHome(o, platform, initHome); log(`Home ready: ${o.home} (mode 0700), worker ${o.worker}, issuer ${o.publicUrl}`); }
|
|
827
|
+
|
|
828
|
+
const uid = process.getuid?.();
|
|
829
|
+
if (!unitDir) {
|
|
830
|
+
log('service unit: not supported on this platform. Home and init are done; start `node src/server.mjs` yourself with');
|
|
831
|
+
log(` HOME=${o.home} NODE_ENV=production DALAN_AUTH_MODE=builtin${o.repoTools ? ' DALAN_ENABLE_WORKSPACE=1' : ''} DALAN_PORT=${o.port}`);
|
|
832
|
+
} else if (linux) {
|
|
833
|
+
fs.mkdirSync(unitDir, { recursive: true });
|
|
834
|
+
for (const [f, text] of Object.entries(files)) { writeExclusive(path.join(unitDir, f), text, 0o644, 'service unit', o); log(`Wrote ${path.join(unitDir, f)}`); }
|
|
835
|
+
const command = `systemctl --user daemon-reload && systemctl --user enable --now ${enable.join(' ')}`;
|
|
836
|
+
if (o.start) { systemctl(['daemon-reload'], env, spawn, o); systemctl(['enable', '--now', ...enable], env, spawn, o); waitForStartedBridge(o, env, platform, waitForSocket); log(`Started: ${enable.join(' ')}`); }
|
|
837
|
+
else log(`Not started. To start:\n ${command}`);
|
|
838
|
+
} else {
|
|
839
|
+
fs.mkdirSync(unitDir, { recursive: true });
|
|
840
|
+
const plist = path.join(unitDir, `${launchLabel(o.worker)}.plist`);
|
|
841
|
+
writeExclusive(plist, files[`${launchLabel(o.worker)}.plist`], 0o644, 'launch agent', o);
|
|
842
|
+
log(`Wrote ${plist}`);
|
|
843
|
+
const domain = launchDomains(uid)[0];
|
|
844
|
+
const stop = `launchctl bootout ${domain} ${plist}`;
|
|
845
|
+
if (o.start) {
|
|
846
|
+
const r = launchctl(['bootstrap', domain, plist], env, spawn);
|
|
847
|
+
if (r.status !== 0) fail(`launchctl bootstrap ${domain} ${plist} failed (exit ${r.status ?? r.signal}): ${String(r.stderr).trim()}. The plist and home are left in place; remove this install with: ${recoveryCommand(o)}`);
|
|
848
|
+
// On macOS 26 a bootstrapped agent can stay loaded but never spawn. Ask launchd to start it, then check that it runs.
|
|
849
|
+
const kick = launchctl(['kickstart', `${domain}/${launchLabel(o.worker)}`], env, spawn);
|
|
850
|
+
if (kick.status !== 0) log(`Warning: launchctl kickstart failed (exit ${kick.status ?? kick.signal}): ${String(kick.stderr).trim()}. The agent is loaded; if the bridge does not answer, check ${path.join(o.home, 'logs')}.`);
|
|
851
|
+
waitForStartedBridge(o, env, platform, waitForSocket);
|
|
852
|
+
log(`Started: ${launchLabel(o.worker)}`);
|
|
853
|
+
log(`To stop: ${stop}`);
|
|
854
|
+
} else log(`Not started. To start:\n launchctl bootstrap ${domain} ${plist}\nTo stop:\n ${stop}`);
|
|
855
|
+
}
|
|
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
|
+
}
|
|
876
|
+
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
|
+
log(`Resource URL file (private, mode 0600): ${urlFile}`);
|
|
878
|
+
const dw = `dalan() { HOME=${shellQuote(o.home)} ${shellQuote(o.node)} ${shellQuote(path.join(o.repo, 'bin/dalan.mjs'))} "$@"; }`;
|
|
879
|
+
log('Owner commands (run after the service is up):');
|
|
880
|
+
log(` ${dw}`);
|
|
881
|
+
log(` dalan connect start --worker ${o.worker}`);
|
|
882
|
+
log(' dalan connect pending');
|
|
883
|
+
log(` dalan connect approve CODE --worker ${o.worker}`);
|
|
884
|
+
log(' dalan connect signal-token # save wake URL privately for hook-driven workers; print path; --rotate replaces it');
|
|
885
|
+
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
|
+
// Public check only after the bridge starts. Returns a promise; the entry point awaits it and exits 1 on failure.
|
|
891
|
+
const { dnsName, url } = exposure;
|
|
892
|
+
if (!o.start) {
|
|
893
|
+
log(`Public check runs with --start. By hand: dig @8.8.8.8 ${dnsName} A (or @1.1.1.1, @9.9.9.9) ; curl -sS -o /dev/null -w '%{http_code}' ${url}/admin (expect 404)`);
|
|
894
|
+
return undefined;
|
|
895
|
+
}
|
|
896
|
+
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 => {
|
|
898
|
+
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
|
+
});
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
export function run(argv, seams = {}) {
|
|
903
|
+
if (argv.includes('--help')) return runUnlocked(argv, seams);
|
|
904
|
+
// Reject malformed arguments before creating the per-home lock directory.
|
|
905
|
+
const parsed = parseOptions(argv, seams.platform ?? process.platform);
|
|
906
|
+
// The lock is per user and host-wide by default, so installers with different HOME values still serialize on one unit directory.
|
|
907
|
+
// DALAN_SETUP_LOCK_DIR (an absolute path) moves it, for example so concurrent test runs do not collide.
|
|
908
|
+
const envRoot = (seams.env ?? process.env).DALAN_SETUP_LOCK_DIR;
|
|
909
|
+
if (envRoot && !path.isAbsolute(envRoot)) fail('DALAN_SETUP_LOCK_DIR must be an absolute path');
|
|
910
|
+
const release = acquireSetupLock(seams.setupLockRoot ?? (envRoot || undefined));
|
|
911
|
+
try {
|
|
912
|
+
const result = runUnlocked(argv, seams, parsed);
|
|
913
|
+
if (result && typeof result.then === 'function') return result.finally(release);
|
|
914
|
+
release();
|
|
915
|
+
return result;
|
|
916
|
+
} catch (error) {
|
|
917
|
+
release();
|
|
918
|
+
throw error;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
923
|
+
try { await run(process.argv.slice(2)); }
|
|
924
|
+
catch (e) { console.error(`worker-bridge-setup: ${e.message}`); process.exit(1); }
|
|
925
|
+
}
|