@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,908 @@
|
|
|
1
|
+
// The public route for `dalan try --public`: a loopback gate forwarded by Tailscale or a temporary relay. Cleanup attempts to
|
|
2
|
+
// remove resources owned by the trial and reports when removal is unconfirmed. Outside effects use injected seams in tests.
|
|
3
|
+
import { spawn, spawnSync, execFile } from 'node:child_process';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import http from 'node:http';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import {
|
|
11
|
+
ADMIN_ACL_URL, ADMIN_DNS_URL, choosePort, funnelOffArgs, funnelOnArgs, funnelRuleMatches, funnelStatusArgs,
|
|
12
|
+
preflight, publicUrl, removeExposure, whichOnPath, writeExposureRecord, recordPath,
|
|
13
|
+
} from '../scripts/lib/expose-tailscale.mjs';
|
|
14
|
+
import { childRegistry, registerChild, sweepChildren } from './child-registry.mjs';
|
|
15
|
+
import { safeDiagnostic } from './diagnostic.mjs';
|
|
16
|
+
import { processCommand } from './process-inspection.mjs';
|
|
17
|
+
export { processCommand } from './process-inspection.mjs';
|
|
18
|
+
|
|
19
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
20
|
+
// Cancellation: every wait in route startup ends when the caller's signal aborts, and an abort is never turned into a fallback.
|
|
21
|
+
const abortReason = signal => signal.reason ?? Object.assign(new Error('stopped'), { name: 'AbortError', code: 'ABORT_ERR' });
|
|
22
|
+
const raceAbort = (promise, signal) => !signal ? promise : Promise.race([promise, new Promise((_, reject) => {
|
|
23
|
+
if (signal.aborted) reject(abortReason(signal)); else signal.addEventListener('abort', () => reject(abortReason(signal)), { once: true });
|
|
24
|
+
})]);
|
|
25
|
+
// Complete lines from chunks that may split anywhere; `end()` hands over a last line that had no newline.
|
|
26
|
+
export function lineBuffer(onLine, max = 65_536) {
|
|
27
|
+
let buf = '';
|
|
28
|
+
const push = chunk => {
|
|
29
|
+
buf += chunk;
|
|
30
|
+
for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) { onLine(buf.slice(0, i).replace(/\r$/, '')); buf = buf.slice(i + 1); }
|
|
31
|
+
if (buf.length > max) buf = buf.slice(-max);
|
|
32
|
+
};
|
|
33
|
+
push.end = () => { if (buf) onLine(buf); buf = ''; };
|
|
34
|
+
return push;
|
|
35
|
+
}
|
|
36
|
+
const PROBE_TIMEOUT_MS = 10_000;
|
|
37
|
+
export const PUBLIC_READY_MS = { tailscale: 120_000, 'tailscale-node': 120_000, 'localhost.run': 60_000, gozar: 60_000 };
|
|
38
|
+
|
|
39
|
+
// ---- the gate ----------------------------------------------------------------------------------------------------------
|
|
40
|
+
// The route forwards to this listener, never to the bridge. A tunnel reports its address only after it starts, and the
|
|
41
|
+
// bridge needs that address at `init`, so the route must exist first. The gate answers 503 until the bridge is up, forwards to the
|
|
42
|
+
// one bridge port after that, and answers 503 again once closed. Nothing else on the computer is ever reachable through the route.
|
|
43
|
+
export async function createGate() {
|
|
44
|
+
let upstream = null, gozarHost = null;
|
|
45
|
+
// A fresh connection per request: a kept-alive socket that the bridge closed in the meantime would fail the next request with a 502
|
|
46
|
+
// that the bridge never sees.
|
|
47
|
+
const agent = new http.Agent({ keepAlive: false });
|
|
48
|
+
const server = http.createServer((req, res) => {
|
|
49
|
+
if (!upstream) { res.writeHead(503, { 'content-type': 'text/plain', 'retry-after': '2' }); res.end('starting\n'); return; }
|
|
50
|
+
// Gozar forwards with Host set to this loopback gate. Restore only that exact transport host to the
|
|
51
|
+
// configured public host; preserve other hosts and Origin for the bridge's identity checks.
|
|
52
|
+
const headers = gozarHost && req.headers.host === `127.0.0.1:${server.address().port}` ? { ...req.headers, host: gozarHost } : req.headers;
|
|
53
|
+
const forward = http.request({ agent, host: '127.0.0.1', port: upstream, method: req.method, path: req.url, headers }, answer => {
|
|
54
|
+
res.writeHead(answer.statusCode, answer.headers);
|
|
55
|
+
answer.pipe(res);
|
|
56
|
+
});
|
|
57
|
+
forward.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); });
|
|
58
|
+
res.on('close', () => forward.destroy());
|
|
59
|
+
req.pipe(forward);
|
|
60
|
+
});
|
|
61
|
+
server.headersTimeout = 10_000; server.requestTimeout = 60_000;
|
|
62
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
|
63
|
+
return {
|
|
64
|
+
port: server.address().port,
|
|
65
|
+
open(port, { gozarOrigin } = {}) { upstream = port; gozarHost = gozarOrigin ? new URL(gozarOrigin).host : null; },
|
|
66
|
+
shut() { upstream = null; },
|
|
67
|
+
async close() { upstream = null; server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); },
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ---- Tailscale Funnel --------------------------------------------------------------------------------------------------
|
|
72
|
+
const tailscaleRunner = (env = process.env) => args => spawnSync('tailscale', args, { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, env });
|
|
73
|
+
|
|
74
|
+
// A foreground Funnel (no --bg) is listed by `serve|funnel status --json` under Foreground.<session>.{TCP,Web,AllowFunnel}, not in
|
|
75
|
+
// the top-level maps read by the shared preflight and rule matching. Merge foreground sessions into the view used for rule matching.
|
|
76
|
+
export function mergeForeground(status) {
|
|
77
|
+
const sessions = Object.values(status?.Foreground ?? {});
|
|
78
|
+
if (!sessions.length) return status;
|
|
79
|
+
const merged = { ...status, TCP: { ...status.TCP }, Web: { ...status.Web }, AllowFunnel: { ...status.AllowFunnel } };
|
|
80
|
+
for (const session of sessions) for (const key of ['TCP', 'Web', 'AllowFunnel']) Object.assign(merged[key], session?.[key]);
|
|
81
|
+
return merged;
|
|
82
|
+
}
|
|
83
|
+
const seeForeground = run => args => {
|
|
84
|
+
const result = run(args);
|
|
85
|
+
if (!(args.includes('status') || args[0] === 'serve') || !args.includes('--json') || result.status !== 0 || !result.stdout) return result;
|
|
86
|
+
try { return { ...result, stdout: JSON.stringify(mergeForeground(JSON.parse(result.stdout))) }; } catch { return result; }
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
// One line for the first thing that stops Funnel, plus the owner's own fix.
|
|
90
|
+
export function explainTailscale(error) {
|
|
91
|
+
const text = String(error?.message ?? error);
|
|
92
|
+
const first = (line, fix) => ({ line, fix: fix ?? line });
|
|
93
|
+
if (/not installed|ENOENT/.test(text)) return first('Tailscale is not installed', 'Install Tailscale from https://tailscale.com/download, run `tailscale up`, then retry.');
|
|
94
|
+
if (/not running or not logged in/.test(text)) return first('Tailscale is not connected; run: tailscale up', 'Run `tailscale up`, then retry.');
|
|
95
|
+
if (/MagicDNS/.test(text)) return first('MagicDNS is off.', `Enable MagicDNS at ${ADMIN_DNS_URL}, then retry.`);
|
|
96
|
+
if (/HTTPS certificates/.test(text)) return first('Tailscale HTTPS is off.', `Enable HTTPS Certificates at ${ADMIN_DNS_URL} (it publishes your machine names on a public ledger), then retry.`);
|
|
97
|
+
if (/Funnel is not allowed/.test(text)) return first('Funnel is not allowed for this tailnet.', `A tailnet administrator can enable Funnel at ${ADMIN_ACL_URL}, then retry.`);
|
|
98
|
+
if (/no free Funnel port/.test(text)) return first('All permitted Funnel ports are occupied. Existing routes are unchanged.', 'Free one Funnel port (tailscale funnel status), then retry.');
|
|
99
|
+
const port = /--funnel-port (\d+) is (?:already used|not allowed)/.exec(text)?.[1];
|
|
100
|
+
if (port) return { ...first(`Tailscale port ${port} is not free for Funnel on this computer; its rules are unchanged.`, `Free Funnel port ${port} (tailscale funnel status shows what uses it), or make a public demo link with --route gozar.`), busy: /already used/.test(text) };
|
|
101
|
+
if (/macOS: the Tailscale/.test(text)) return first('The Tailscale app on this Mac cannot serve Funnel here', text.split('\n')[0]);
|
|
102
|
+
const line = safeDiagnostic(text.split('\n')[0], 160);
|
|
103
|
+
return first(`Tailscale Funnel is not usable (${line}).`, line);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Hosted trials use HTTPS port 443 for client compatibility. If this computer already uses 443, its existing rule is unchanged;
|
|
107
|
+
// an explicitly selected Tailscale route can use an isolated temporary node. Automatic trial relay selection uses Gozar.
|
|
108
|
+
export const TRIAL_PORT = 443;
|
|
109
|
+
export function tailscaleProvider({ port: wantedPort = TRIAL_PORT, name = 'tailscale', record: recordName = 'trial', tailscale: rawTailscale = tailscaleRunner(), env = process.env, platform = process.platform, spawnChild = spawn, clock = { sleep }, which = name => whichOnPath(name, env) } = {}) {
|
|
110
|
+
const tailscale = seeForeground(rawTailscale);
|
|
111
|
+
let plan = null, child = null, record = null, rule = null, cli = null;
|
|
112
|
+
return {
|
|
113
|
+
name,
|
|
114
|
+
// Read-only: inspects the daemon, DNS identity, capabilities and the ports other rules already use.
|
|
115
|
+
probe() {
|
|
116
|
+
const found = which('tailscale');
|
|
117
|
+
if (!found) return { ok: false, ...explainTailscale(new Error('Tailscale is not installed')) };
|
|
118
|
+
cli = typeof found === 'string' ? path.resolve(found) : null;
|
|
119
|
+
try {
|
|
120
|
+
const state = preflight({ tailscale, platform });
|
|
121
|
+
const port = choosePort({ requested: wantedPort, allowed: state.allowed, occupied: state.occupied });
|
|
122
|
+
plan = { dnsName: state.dnsName, port, origin: publicUrl(state.dnsName, port) };
|
|
123
|
+
return { ok: true, origin: plan.origin };
|
|
124
|
+
} catch (error) { return { ok: false, ...explainTailscale(error) }; }
|
|
125
|
+
},
|
|
126
|
+
// A foreground rule on a free port, exactly ours: it is removed by Tailscale itself when the child ends, and again by `stop`.
|
|
127
|
+
async start({ gatePort, home, signal }) {
|
|
128
|
+
signal?.throwIfAborted();
|
|
129
|
+
if (!plan) throw new Error('tailscale: probe() must succeed before start()');
|
|
130
|
+
// Re-read just before applying: a port another rule took since the probe is not ours to share.
|
|
131
|
+
const again = preflight({ tailscale, platform });
|
|
132
|
+
if (again.occupied.has(plan.port)) throw new Error(`Funnel port ${plan.port} was taken by another rule after the check; its rule is unchanged`);
|
|
133
|
+
record = recordPath(home, recordName);
|
|
134
|
+
recoverStaleFunnel(home, tailscale, recordName);
|
|
135
|
+
writeExposureRecord({ file: record, worker: 'trial', dnsName: plan.dnsName, port: plan.port, localPort: gatePort, url: plan.origin });
|
|
136
|
+
rule = { dnsName: plan.dnsName, port: plan.port, gatePort };
|
|
137
|
+
child = spawnChild(cli ?? 'tailscale', funnelOnArgs(plan.port, gatePort).filter(arg => arg !== '--bg'), { env, stdio: 'ignore' });
|
|
138
|
+
const exited = new Promise(resolve => { child.once('exit', resolve); child.once('error', resolve); });
|
|
139
|
+
for (let waited = 0; ; waited += 500) {
|
|
140
|
+
const status = JSON.parse(tailscale(funnelStatusArgs()).stdout || '{}');
|
|
141
|
+
if (funnelRuleMatches(status, plan.dnsName, plan.port, gatePort)) break;
|
|
142
|
+
if (waited >= 20_000 || child.exitCode !== null) throw new Error('tailscale funnel did not publish the rule');
|
|
143
|
+
await raceAbort(clock.sleep(500), signal);
|
|
144
|
+
}
|
|
145
|
+
return { origin: plan.origin, exited };
|
|
146
|
+
},
|
|
147
|
+
// Ends the child, then confirms the rule is gone. Only a rule that still matches ours is switched off.
|
|
148
|
+
async stop() {
|
|
149
|
+
if (!rule) return { removed: true };
|
|
150
|
+
if (child && child.exitCode === null) { child.kill('SIGTERM'); await Promise.race([new Promise(resolve => child.once('exit', resolve)), clock.sleep(5000)]); if (child.exitCode === null) child.kill('SIGKILL'); }
|
|
151
|
+
try { removeExposure({ tailscale, file: record, log: () => {} }); return { removed: true }; }
|
|
152
|
+
catch (error) {
|
|
153
|
+
const quote = value => "'" + String(value).replaceAll("'", "'\\''") + "'";
|
|
154
|
+
const keys = ['HOME', 'PATH', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_RUNTIME_DIR', 'TMPDIR'];
|
|
155
|
+
const assignments = keys.filter(key => env[key] !== undefined).map(key => `${key}=${quote(env[key])}`);
|
|
156
|
+
const command = cli && path.isAbsolute(cli)
|
|
157
|
+
? `(unset ${keys.join(' ')} && ${[...assignments, quote(cli), ...funnelOffArgs(rule.port).map(quote)].join(' ')})`
|
|
158
|
+
: null;
|
|
159
|
+
return { removed: false, detail: error.message, ...(command ? { command } : {}) };
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// A record from a trial that was killed: switch off exactly its rule if it is still ours, then drop the record.
|
|
166
|
+
function recoverStaleFunnel(home, tailscale, recordName = 'trial') {
|
|
167
|
+
const file = recordPath(home, recordName);
|
|
168
|
+
if (fs.existsSync(file)) removeExposure({ tailscale, file, log: () => {} });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ---- A Tailscale node of its own -----------------------------------------------------------------------------------------
|
|
172
|
+
// When this computer's Tailscale has a rule on 443, the trial starts a second, userspace `tailscaled`: its own socket and hostname
|
|
173
|
+
// (dalan-trial-<id>), so it has its own address and its own :443 Funnel. It touches nothing of the computer's Tailscale.
|
|
174
|
+
// The node is EPHEMERAL: `--state=mem:` keeps no state on disk and registers the machine as an ephemeral node, so Tailscale
|
|
175
|
+
// removes it by itself once the daemon is gone, even when this process was killed. `stop` ends the Funnel, logs out (which removes
|
|
176
|
+
// it at once), ends the daemon and deletes the socket directory.
|
|
177
|
+
// Every node is also listed in a registry that does not depend on the trial home. Any later trial sweeps it and ends daemons whose
|
|
178
|
+
// trial is gone.
|
|
179
|
+
const SOCKET_PATH_LIMIT = 100; // a unix socket path must fit sun_path (104 on macOS, 108 on Linux)
|
|
180
|
+
const nodeCli = (sock, env) => args => spawnSync('tailscale', [`--socket=${sock}`, ...args], { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, env });
|
|
181
|
+
const defaultRegistry = env => path.join(env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'dalan', 'trial-nodes');
|
|
182
|
+
// A key, a login link or a node key never reaches the daemon log.
|
|
183
|
+
export const maskNodeText = text => String(text).replace(/tskey-[A-Za-z0-9_-]+/g, '[key]').replace(/https:\/\/login\.tailscale\.com\/\S+/g, '[login link]').replace(/(nodekey|authkey)\S*/gi, '[secret]');
|
|
184
|
+
|
|
185
|
+
// Device and tailnet names identify the owner's tailnet. A kept log or a printed line carries neither: any *.ts.net name, the
|
|
186
|
+
// node's own DNS name and the tailnet's name (which can be an email address) become "[tailnet name]".
|
|
187
|
+
const readIdentity = run => {
|
|
188
|
+
try { const status = JSON.parse(run(['status', '--json']).stdout || '{}'); return { dnsName: String(status.Self?.DNSName ?? '').replace(/\.$/, ''), tailnet: String(status.CurrentTailnet?.Name ?? '') }; } catch { return { dnsName: '', tailnet: '' }; }
|
|
189
|
+
};
|
|
190
|
+
export const redactTailnetNames = (text, names = [], { strict = false } = {}) => {
|
|
191
|
+
let out = String(text).replace(/[A-Za-z0-9][A-Za-z0-9.-]*\.ts\.net\b/gi, '[tailnet name]');
|
|
192
|
+
for (const name of names.filter(n => n.length >= 3).sort((a, b) => b.length - a.length)) out = out.split(name).join('[tailnet name]');
|
|
193
|
+
// The tailnet's name is unknown (no status): fail closed, since it can be an email address.
|
|
194
|
+
return strict ? out.replace(/[^\s@()<>"',;]+@[^\s@()<>"',;]+\.[A-Za-z]{2,}/g, '[email]') : out;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
// Ends the daemons of trials that no longer run. A record is stale when its trial process is gone (or its PID now runs something
|
|
198
|
+
// else); the daemon is ended only if its command line still names the socket this trial started it with.
|
|
199
|
+
export async function sweepTrialNodes({ registry, processCmd = processCommand, kill = (pid, sig) => process.kill(pid, sig), clock = { sleep }, say = () => {} }) {
|
|
200
|
+
let names = []; try { names = fs.readdirSync(registry).filter(n => n.endsWith('.json')); } catch (error) { if (error.code === 'ENOENT') return { ended: [], retained: [] }; throw error; }
|
|
201
|
+
const ended = [], retained = [];
|
|
202
|
+
for (const name of names) {
|
|
203
|
+
const file = path.join(registry, name);
|
|
204
|
+
let rec; try { rec = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { retained.push({ home: null, sock: null }); continue; }
|
|
205
|
+
// Keep the ownership boundary even when a record cannot be safely reclaimed.
|
|
206
|
+
retained.push({ home: rec?.home ?? (typeof rec?.dir === 'string' ? path.dirname(rec.dir) : null), sock: rec?.sock ?? null });
|
|
207
|
+
if (!rec || typeof rec !== 'object' || Array.isArray(rec)) continue;
|
|
208
|
+
if (Number.isInteger(rec.pid) && (!Number.isInteger(rec.owner) || typeof rec.sock !== 'string' || !rec.sock)) continue;
|
|
209
|
+
if (Number.isInteger(rec.owner)) {
|
|
210
|
+
const owner = processCmd(rec.owner);
|
|
211
|
+
const reused = owner.state === 'present' && rec.ownerStart && owner.start && owner.start !== rec.ownerStart;
|
|
212
|
+
if (owner.state !== 'absent' && !reused) continue; // a missing command is not evidence that its trial ended
|
|
213
|
+
}
|
|
214
|
+
const daemonMatches = () => { const daemon = processCmd(rec.pid); return daemon.state === 'present' && daemon.command?.includes(rec.sock); };
|
|
215
|
+
if (Number.isInteger(rec.pid) && rec.sock && daemonMatches()) {
|
|
216
|
+
try { kill(rec.pid, 'SIGTERM'); } catch { /* gone */ }
|
|
217
|
+
for (let i = 0; i < 20 && daemonMatches(); i++) await clock.sleep(100);
|
|
218
|
+
if (daemonMatches()) { try { kill(rec.pid, 'SIGKILL'); } catch { /* gone */ } }
|
|
219
|
+
}
|
|
220
|
+
// A failed check or signal must keep the daemon's files and recovery record.
|
|
221
|
+
if (Number.isInteger(rec.pid)) {
|
|
222
|
+
const daemon = processCmd(rec.pid);
|
|
223
|
+
if (daemon.state === 'unknown' || (daemon.state === 'present' && daemon.command?.includes(rec.sock))) continue;
|
|
224
|
+
}
|
|
225
|
+
// Missing identities (including older records) cannot prove PID reuse. Unknown inspection keeps all files and the debt.
|
|
226
|
+
if (rec.certOut) {
|
|
227
|
+
const cert = processCmd(rec.certPid);
|
|
228
|
+
const different = cert.state === 'present' && rec.certStart && cert.start && cert.start !== rec.certStart;
|
|
229
|
+
if (cert.state !== 'absent' && !different) {
|
|
230
|
+
const unknown = cert.state !== 'present' || !cert.start || !rec.certStart;
|
|
231
|
+
say(`TLS certificate cleanup deferred: ${unknown ? 'process identity unknown' : 'child still running'} (${rec.hostname ?? name}).`);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (rec.dir && path.basename(rec.dir) === 'tsnode') fs.rmSync(rec.dir, { recursive: true, force: true });
|
|
236
|
+
fs.rmSync(file, { force: true });
|
|
237
|
+
ended.push(rec.hostname ?? name);
|
|
238
|
+
retained.pop();
|
|
239
|
+
}
|
|
240
|
+
return { ended, retained };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function tailscaleNodeProvider({
|
|
244
|
+
env = process.env, platform = process.platform, spawnChild = spawn, runCli = nodeCli, clock = { sleep }, which = name => whichOnPath(name, env),
|
|
245
|
+
newId = () => randomBytes(3).toString('hex'), loginWaitMs = 600_000, daemonWaitMs = 20_000, certWaitMs = 60_000, killGraceMs = 2000, registry = defaultRegistry(env), processCmd = processCommand,
|
|
246
|
+
} = {}) {
|
|
247
|
+
let node = null; // { dir, sock, hostname, daemon, daemonExited, run, inner, recordFile, signedIn }
|
|
248
|
+
// The credential never reaches a child's environment: it travels only in a file read by `tailscale up`.
|
|
249
|
+
const childEnv = Object.fromEntries(Object.entries(env).filter(([k]) => k !== 'DALAN_TS_AUTHKEY'));
|
|
250
|
+
return {
|
|
251
|
+
name: 'tailscale-node',
|
|
252
|
+
probe() {
|
|
253
|
+
if (!which('tailscaled') || !which('tailscale')) return { ok: false, line: 'tailscaled is not installed, so a separate Tailscale node cannot be started', fix: 'Install Tailscale (it includes tailscaled) from https://tailscale.com/download, or free Funnel port 443 on this computer.' };
|
|
254
|
+
return { ok: true };
|
|
255
|
+
},
|
|
256
|
+
recover: ({ say } = {}) => sweepTrialNodes({ registry, processCmd, clock, say }),
|
|
257
|
+
async start({ gatePort, home, say = () => {}, signal }) {
|
|
258
|
+
signal?.throwIfAborted();
|
|
259
|
+
const { retained } = await sweepTrialNodes({ registry, processCmd, clock, say });
|
|
260
|
+
const dir = path.join(home, 'tsnode'), sock = path.join(dir, 'tailscaled.sock'), hostname = `dalan-trial-${newId()}`;
|
|
261
|
+
if (retained.some(debt => debt.home === home || debt.sock === sock || (!debt.home && !debt.sock))) {
|
|
262
|
+
throw Object.assign(new Error(`Cannot confirm that the earlier Tailscale node in ${home} has stopped; its files are retained.`), { tryKind: 'node_retained' });
|
|
263
|
+
}
|
|
264
|
+
if (Buffer.byteLength(sock) > SOCKET_PATH_LIMIT) throw new Error('the trial home path is too long for a Tailscale socket; choose a shorter --home');
|
|
265
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
266
|
+
// tailscaled keeps its TLS certificates under its var root (--statedir). --state=mem: gives it none, so without this directory
|
|
267
|
+
// every first TLS hello fails ("no TailscaleVarRoot") and the public address answers with a TLS internal error. It lives inside
|
|
268
|
+
// `tsnode`, so it goes with the node.
|
|
269
|
+
const stateDir = path.join(dir, 'state');
|
|
270
|
+
fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
271
|
+
fs.mkdirSync(registry, { recursive: true, mode: 0o700 });
|
|
272
|
+
const recordFile = path.join(registry, `${hostname}.json`);
|
|
273
|
+
const owner = processCmd(process.pid);
|
|
274
|
+
const writeRecord = pid => fs.writeFileSync(recordFile, JSON.stringify({ dir, sock, hostname, pid, home, owner: process.pid, ownerCmd: owner.command ?? null, ownerStart: owner.start ?? null, created_at: new Date().toISOString() }), { mode: 0o600 });
|
|
275
|
+
writeRecord(null); // ownership is recorded before the first process exists
|
|
276
|
+
const run = runCli(sock, childEnv);
|
|
277
|
+
const logFile = path.join(dir, 'tailscaled.log');
|
|
278
|
+
const daemon = spawnChild('tailscaled', ['--tun=userspace-networking', '--state=mem:', `--statedir=${stateDir}`, `--socket=${sock}`, '--port=0'], { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
279
|
+
const daemonLog = lineBuffer(line => { try { fs.appendFileSync(logFile, `${maskNodeText(line)}\n`, { mode: 0o600 }); } catch { /* the directory is gone */ } });
|
|
280
|
+
for (const stream of [daemon.stdout, daemon.stderr]) { stream?.setEncoding?.('utf8'); stream?.on('data', daemonLog); stream?.on('end', () => daemonLog.end()); }
|
|
281
|
+
const daemonExited = new Promise(resolve => { daemon.once('exit', resolve); daemon.once('error', resolve); });
|
|
282
|
+
node = { dir, sock, hostname, daemon, daemonExited, run, recordFile, inner: null, signedIn: false };
|
|
283
|
+
writeRecord(daemon.pid ?? null);
|
|
284
|
+
for (let waited = 0; ; waited += 250) {
|
|
285
|
+
let up = false; try { up = Boolean(JSON.parse(run(['status', '--json']).stdout || '{}').BackendState); } catch { /* not ready */ }
|
|
286
|
+
if (up) break;
|
|
287
|
+
if (daemon.exitCode !== null || waited >= daemonWaitMs) throw new Error('tailscaled did not start for the trial node');
|
|
288
|
+
await raceAbort(clock.sleep(250), signal);
|
|
289
|
+
}
|
|
290
|
+
// One-time sign-in of the new node: a login URL on a terminal, or an auth key from DALAN_TS_AUTHKEY. The key is in a 0600 file
|
|
291
|
+
// only while `tailscale up` runs.
|
|
292
|
+
const keyFile = path.join(dir, 'authkey');
|
|
293
|
+
const upArgs = ['up', `--hostname=${hostname}`, '--accept-dns=false', '--accept-routes=false'];
|
|
294
|
+
if (env.DALAN_TS_AUTHKEY) { fs.writeFileSync(keyFile, env.DALAN_TS_AUTHKEY, { mode: 0o600 }); upArgs.push(`--auth-key=file:${keyFile}`); }
|
|
295
|
+
const upChild = spawnChild('tailscale', [`--socket=${sock}`, ...upArgs], { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
296
|
+
let announced = false, timer = null;
|
|
297
|
+
const scan = lineBuffer(line => {
|
|
298
|
+
const url = !announced && /https:\/\/login\.tailscale\.com\/\S+/.exec(line)?.[0];
|
|
299
|
+
if (url) { announced = true; say(`This temporary Tailscale node needs a one-time sign-in. Open: ${url}`); say('Waiting for the sign-in…'); }
|
|
300
|
+
});
|
|
301
|
+
for (const stream of [upChild.stdout, upChild.stderr]) { stream?.on('data', scan); stream?.on('end', () => scan.end()); }
|
|
302
|
+
const upDone = new Promise(resolve => { upChild.once('exit', code => { scan.end(); resolve(code); }); upChild.once('error', () => resolve(-1)); });
|
|
303
|
+
const timedOut = new Promise(resolve => { timer = setTimeout(() => resolve('timeout'), loginWaitMs); });
|
|
304
|
+
let code;
|
|
305
|
+
try { code = await raceAbort(Promise.race([upDone, timedOut]), signal); }
|
|
306
|
+
finally { clearTimeout(timer); fs.rmSync(keyFile, { force: true }); if (upChild.exitCode === null && upChild.signalCode === null) upChild.kill('SIGTERM'); }
|
|
307
|
+
if (code !== 0) throw new Error(code === 'timeout' ? 'the one-time Tailscale sign-in was not completed in time' : 'the Tailscale node could not sign in');
|
|
308
|
+
node.signedIn = true;
|
|
309
|
+
node.identity = readIdentity(run); // kept now: at diagnose time the node may no longer answer status
|
|
310
|
+
const wrapSpawn = (cmd, args, opts) => spawnChild(cmd, [`--socket=${sock}`, ...args], opts);
|
|
311
|
+
const inner = tailscaleProvider({ tailscale: run, env: childEnv, platform: 'linux', spawnChild: wrapSpawn, clock, which: () => true, name: 'tailscale-node', record: 'trial-node' });
|
|
312
|
+
node.inner = inner;
|
|
313
|
+
const probe = inner.probe();
|
|
314
|
+
if (!probe.ok) throw new Error(probe.fix);
|
|
315
|
+
const started = await inner.start({ gatePort, home, signal });
|
|
316
|
+
return { origin: started.origin, exited: Promise.race([started.exited, daemonExited]) };
|
|
317
|
+
},
|
|
318
|
+
// Called when the public address never answered: one bounded certificate request on the node's own socket says whether the
|
|
319
|
+
// node can get a TLS certificate at all, and a copy of the daemon log survives the node's directory.
|
|
320
|
+
// Output: one line, never a key. The certificate files go to a private directory inside `tsnode` (so the sweep of an
|
|
321
|
+
// abandoned trial removes them too) and are deleted once the child has exited. Names that identify the tailnet are redacted
|
|
322
|
+
// from the line and from the kept log.
|
|
323
|
+
async diagnose({ home, say = () => {}, signal } = {}) {
|
|
324
|
+
if (!node) return;
|
|
325
|
+
const now = readIdentity(node.run), cached = node.identity ?? { dnsName: '', tailnet: '' };
|
|
326
|
+
const dnsName = now.dnsName || cached.dnsName, tailnet = now.tailnet || cached.tailnet;
|
|
327
|
+
if (dnsName || tailnet) node.identity = { dnsName, tailnet };
|
|
328
|
+
const redact = text => redactTailnetNames(text, [dnsName, tailnet], { strict: !tailnet });
|
|
329
|
+
let verdict;
|
|
330
|
+
if (!dnsName) verdict = 'error (the node has no DNS name)';
|
|
331
|
+
else {
|
|
332
|
+
const out = fs.mkdtempSync(path.join(node.dir, 'tlscheck-'));
|
|
333
|
+
let timer = null, child = null, gone = true, exited = null;
|
|
334
|
+
const recordCert = fields => {
|
|
335
|
+
const rec = JSON.parse(fs.readFileSync(node.recordFile, 'utf8'));
|
|
336
|
+
const pending = node.recordFile + '.cert-tmp';
|
|
337
|
+
try {
|
|
338
|
+
fs.writeFileSync(pending, JSON.stringify({ ...rec, ...fields }), { mode: 0o600 });
|
|
339
|
+
fs.renameSync(pending, node.recordFile);
|
|
340
|
+
} finally { fs.rmSync(pending, { force: true }); }
|
|
341
|
+
};
|
|
342
|
+
try {
|
|
343
|
+
// Persist the folder before spawning. If later identity persistence fails, this marker still prevents a sweep deleting it.
|
|
344
|
+
recordCert({ certOut: out, certPid: null, certCmd: null, certStart: null });
|
|
345
|
+
child = spawnChild('tailscale', [`--socket=${node.sock}`, 'cert', `--cert-file=${path.join(out, 'cert')}`, `--key-file=${path.join(out, 'key')}`, dnsName], { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
346
|
+
let said = '';
|
|
347
|
+
for (const stream of [child.stdout, child.stderr]) { stream?.setEncoding?.('utf8'); stream?.on('data', chunk => { if (said.length < 2000) said += chunk; }); }
|
|
348
|
+
gone = false;
|
|
349
|
+
exited = new Promise(resolve => child.once('exit', code => { gone = true; resolve(code); }));
|
|
350
|
+
const failed = new Promise(resolve => child.once('error', () => { if (!child.pid) gone = true; resolve(-1); }));
|
|
351
|
+
node.certChild = { out, exited };
|
|
352
|
+
const identity = processCmd(child.pid);
|
|
353
|
+
recordCert({ certPid: child.pid ?? null, certCmd: identity.command ?? null, certStart: identity.start ?? null });
|
|
354
|
+
const aborted = new Promise(resolve => { if (signal?.aborted) resolve('aborted'); else signal?.addEventListener('abort', () => resolve('aborted'), { once: true }); });
|
|
355
|
+
const code = await Promise.race([exited, failed, aborted, new Promise(resolve => { timer = setTimeout(() => resolve('timeout'), certWaitMs); })]);
|
|
356
|
+
const first = said.split('\n').map(l => l.trim()).find(Boolean);
|
|
357
|
+
verdict = code === 0 ? 'ok' : code === 'aborted' ? 'error (cancelled)' : code === 'timeout' ? `error (no answer in ${Math.round(certWaitMs / 1000)} s)` : `error (${first ? redact(safeDiagnostic(first, 120)) : `exit ${code}`})`;
|
|
358
|
+
} catch (error) { verdict = `error (${redact(safeDiagnostic(error.message, 120))})`; }
|
|
359
|
+
finally {
|
|
360
|
+
clearTimeout(timer);
|
|
361
|
+
// Every path, including a record-write or process-control error, attempts termination before handing off cleanup debt.
|
|
362
|
+
for (const sig of ['SIGTERM', 'SIGKILL']) {
|
|
363
|
+
if (gone) break;
|
|
364
|
+
try { child.kill(sig); } catch { /* a failed signal does not prove exit */ }
|
|
365
|
+
await Promise.race([exited, clock.sleep(killGraceMs)]);
|
|
366
|
+
}
|
|
367
|
+
// The files go only after confirmed exit. Otherwise stop and the sweep retain them as cleanup debt.
|
|
368
|
+
if (gone) {
|
|
369
|
+
fs.rmSync(out, { recursive: true, force: true });
|
|
370
|
+
node.certChild = null;
|
|
371
|
+
try { recordCert({ certOut: null, certPid: null, certCmd: null, certStart: null }); }
|
|
372
|
+
catch { say('TLS certificate cleanup record could not be cleared; a later sweep may retain it.'); }
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
node.certChild = { out, exited }; // the node's stop keeps owning it
|
|
376
|
+
say(`TLS certificate check did not stop (termination not confirmed); its files stay in ${out} until exit is confirmed.`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
say(`TLS certificate: ${verdict}`);
|
|
381
|
+
try {
|
|
382
|
+
const kept = path.join(home, 'tailscaled.log');
|
|
383
|
+
fs.writeFileSync(kept, fs.readFileSync(path.join(node.dir, 'tailscaled.log'), 'utf8').split('\n').map(redact).join('\n'), { mode: 0o600 });
|
|
384
|
+
fs.chmodSync(kept, 0o600);
|
|
385
|
+
} catch { /* no log to keep */ }
|
|
386
|
+
},
|
|
387
|
+
async stop() {
|
|
388
|
+
if (!node) return { removed: true };
|
|
389
|
+
const { dir, hostname, daemon, run, recordFile, inner } = node;
|
|
390
|
+
let result = { removed: true };
|
|
391
|
+
if (inner) result = await inner.stop();
|
|
392
|
+
let loggedOut = true;
|
|
393
|
+
if (node.signedIn) { try { loggedOut = run(['logout']).status === 0; } catch { loggedOut = false; } }
|
|
394
|
+
const daemonGone = () => daemon.exitCode !== null || daemon.signalCode != null || !Number.isInteger(daemon.pid);
|
|
395
|
+
if (!daemonGone()) {
|
|
396
|
+
const gone = new Promise(resolve => daemon.once('exit', resolve));
|
|
397
|
+
try { daemon.kill('SIGTERM'); } catch { /* only exit confirms cleanup */ }
|
|
398
|
+
await Promise.race([gone, clock.sleep(5000)]);
|
|
399
|
+
if (!daemonGone()) {
|
|
400
|
+
try { daemon.kill('SIGKILL'); } catch { /* keep recovery debt */ }
|
|
401
|
+
await Promise.race([gone, clock.sleep(killGraceMs)]);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const daemonConfirmed = daemonGone();
|
|
405
|
+
// A certificate child that diagnose could not stop still holds its files: wait once more for its exit. Without a confirmed
|
|
406
|
+
// exit, everything else goes, the child's directory stays, and the record stays so the next sweep removes it.
|
|
407
|
+
const pendingCert = node.certChild;
|
|
408
|
+
let certConfirmed = true;
|
|
409
|
+
if (pendingCert) {
|
|
410
|
+
let exitedNow = false; pendingCert.exited.then(() => { exitedNow = true; });
|
|
411
|
+
await Promise.race([pendingCert.exited, clock.sleep(killGraceMs)]);
|
|
412
|
+
certConfirmed = exitedNow;
|
|
413
|
+
}
|
|
414
|
+
if (daemonConfirmed && certConfirmed) { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(recordFile, { force: true }); }
|
|
415
|
+
else if (daemonConfirmed) {
|
|
416
|
+
for (const entry of fs.readdirSync(dir)) if (path.join(dir, entry) !== pendingCert.out) fs.rmSync(path.join(dir, entry), { recursive: true, force: true });
|
|
417
|
+
}
|
|
418
|
+
node = null;
|
|
419
|
+
// keepNode tells the caller not to delete the node's directory: a certificate child still holds files there.
|
|
420
|
+
const keep = daemonConfirmed && certConfirmed ? {} : { keepNode: true };
|
|
421
|
+
if (!daemonConfirmed) return { removed: false, ...keep, detail: `the trial's Tailscale daemon did not exit; its files and recovery record are retained` };
|
|
422
|
+
if (!result.removed) return { ...result, ...keep };
|
|
423
|
+
// Logout removes the node at once. If it failed, the node is still registered until Tailscale drops the ephemeral machine.
|
|
424
|
+
return loggedOut ? { removed: true, ...keep } : { ...keep, removed: false, detail: `the trial's Tailscale node ${hostname} could not be logged out. It is ephemeral, so Tailscale removes it on its own once offline; to remove it now, delete ${hostname} in the Tailscale admin console` };
|
|
425
|
+
},
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ---- localhost.run (explicit legacy route) -------------------------------------------------------------------------------
|
|
430
|
+
// An explicit legacy option. The relay ends TLS and can see traffic. A changed address cannot keep the OAuth identity, so the trial
|
|
431
|
+
// stops instead of restarting.
|
|
432
|
+
export const LHR_ORIGIN = /^https:\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.lhr\.life$/;
|
|
433
|
+
const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
434
|
+
// Every origin the relay names on one line of its session output. Banner links (admin.localhost.run, docs) are not tunnels: only
|
|
435
|
+
// a single-label name under lhr.life counts.
|
|
436
|
+
export function parseLocalhostRunOrigins(line) {
|
|
437
|
+
const found = [];
|
|
438
|
+
for (const token of String(line).replace(ANSI, '').split(/[\s,]+/)) {
|
|
439
|
+
const match = /^https:\/\/[^/?#]+/.exec(token);
|
|
440
|
+
if (match && LHR_ORIGIN.test(match[0]) && token === match[0]) found.push(match[0]);
|
|
441
|
+
}
|
|
442
|
+
return [...new Set(found)];
|
|
443
|
+
}
|
|
444
|
+
export const LOCALHOST_RUN_FIX = 'ssh is not installed. Install OpenSSH (macOS and most Linux systems include it; on Debian or Ubuntu: sudo apt install openssh-client) and run this again.';
|
|
445
|
+
export function localhostRunProvider({ env = process.env, spawnChild = spawn, which = name => whichOnPath(name, env), clock = { sleep }, startMs = 30_000, killGraceMs = 2000 } = {}) {
|
|
446
|
+
let child = null, reason = null, forget = () => {};
|
|
447
|
+
const registry = childRegistry(env);
|
|
448
|
+
return {
|
|
449
|
+
name: 'localhost.run',
|
|
450
|
+
// An ssh left by a trial whose process was killed without cleanup is ended by the next trial.
|
|
451
|
+
recover: () => sweepChildren({ registry, clock }).then(pids => pids.length ? ['ssh'] : []),
|
|
452
|
+
probe: () => which('ssh') ? { ok: true } : { ok: false, line: LOCALHOST_RUN_FIX, fix: LOCALHOST_RUN_FIX },
|
|
453
|
+
// Why the route ended, when the provider knows: 'rotated' (the relay named a new address), else null.
|
|
454
|
+
endedBecause: () => reason,
|
|
455
|
+
async start({ gatePort, home, signal }) {
|
|
456
|
+
if (!Number.isInteger(gatePort) || gatePort < 1 || gatePort > 65535) throw new Error('the local gate port is not valid');
|
|
457
|
+
signal?.throwIfAborted();
|
|
458
|
+
// A known_hosts file of the trial's own: the relay's key is trusted at first use and then pinned for this trial. The user's
|
|
459
|
+
// ssh configuration, agent and keys are not used (the relay needs no key).
|
|
460
|
+
const dir = path.join(home, 'localhost-run');
|
|
461
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
462
|
+
const childEnv = Object.fromEntries(['PATH', 'TMPDIR', 'LANG'].filter(k => env[k] !== undefined).map(k => [k, env[k]]));
|
|
463
|
+
const args = ['-F', '/dev/null', '-T', '-o', 'BatchMode=yes', '-o', 'ExitOnForwardFailure=yes', '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=2',
|
|
464
|
+
'-o', 'StrictHostKeyChecking=accept-new', '-o', `UserKnownHostsFile=${path.join(dir, 'known_hosts')}`, '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-o', 'PasswordAuthentication=no',
|
|
465
|
+
'-R', `80:127.0.0.1:${gatePort}`, 'nokey@localhost.run'];
|
|
466
|
+
child = spawnChild('ssh', args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
467
|
+
forget = registerChild({ registry, child });
|
|
468
|
+
child.once('exit', () => forget());
|
|
469
|
+
let first = null, tail = '';
|
|
470
|
+
let onRotate = () => {};
|
|
471
|
+
const exited = new Promise(resolve => { child.once('exit', resolve); child.once('error', resolve); });
|
|
472
|
+
const origin = await new Promise((resolve, reject) => {
|
|
473
|
+
const timer = setTimeout(() => finish(reject)(new Error('localhost.run did not report a public address in time')), startMs);
|
|
474
|
+
const onAbort = () => finish(reject)(abortReason(signal));
|
|
475
|
+
if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });
|
|
476
|
+
let settled = false;
|
|
477
|
+
const finish = fn => value => { if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener('abort', onAbort); fn(value); };
|
|
478
|
+
const onLine = line => {
|
|
479
|
+
tail = `${tail}${String(line).replace(ANSI, '')}\n`.slice(-2000);
|
|
480
|
+
for (const found of parseLocalhostRunOrigins(line)) {
|
|
481
|
+
if (first === null) { first = found; finish(resolve)(found); }
|
|
482
|
+
else if (found !== first && reason === null) { reason = 'rotated'; onRotate(); }
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
const sinks = [child.stdout, child.stderr].map(stream => { const buffer = lineBuffer(onLine); stream?.setEncoding?.('utf8'); stream?.on('data', buffer); stream?.on('end', () => buffer.end()); return buffer; });
|
|
486
|
+
exited.then(() => { for (const sink of sinks) sink.end(); finish(reject)(new Error(`ssh to localhost.run ended before the tunnel was ready: ${safeDiagnostic(tail.trim().split('\n').filter(Boolean).slice(-2).join(' '), 200)}`)); });
|
|
487
|
+
});
|
|
488
|
+
// A new address after the first one ends the route: the sign-in identity is tied to the first.
|
|
489
|
+
const ended = new Promise(resolve => { exited.then(resolve); onRotate = () => { child.kill('SIGTERM'); resolve('rotated'); }; });
|
|
490
|
+
if (reason === 'rotated') onRotate();
|
|
491
|
+
return { origin, exited: ended };
|
|
492
|
+
},
|
|
493
|
+
async stop() {
|
|
494
|
+
if (!child) return { removed: true };
|
|
495
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
496
|
+
const gone = new Promise(resolve => child.once('exit', resolve));
|
|
497
|
+
child.kill('SIGTERM');
|
|
498
|
+
await Promise.race([gone, clock.sleep(killGraceMs)]);
|
|
499
|
+
if (child.exitCode === null && child.signalCode === null) { child.kill('SIGKILL'); await Promise.race([gone, clock.sleep(killGraceMs)]); }
|
|
500
|
+
}
|
|
501
|
+
return child.exitCode !== null || child.signalCode !== null ? { removed: true } : { removed: false, detail: 'the ssh process did not exit', command: `kill ${child.pid}` };
|
|
502
|
+
},
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// ---- Gozar (transport only; Dalan still owns sign-in and identity) --------------------------------------------------------
|
|
507
|
+
const require = createRequire(import.meta.url);
|
|
508
|
+
const bundledGozar = () => {
|
|
509
|
+
try { return require.resolve('@tnunamak/gozar/bin/gozar.mjs'); } catch (error) {
|
|
510
|
+
if (error.code === 'MODULE_NOT_FOUND') return null;
|
|
511
|
+
throw error;
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
|
|
515
|
+
export function gozarProvider({ env = process.env, which = name => whichOnPath(name, env), resolveBundled = bundledGozar, run = execFile, pollMs = 3000, now = Date.now } = {}) {
|
|
516
|
+
let binary = null, bundled = null, commandCwd = null, port = null, sessionId = null;
|
|
517
|
+
let endReason = null;
|
|
518
|
+
let watching = false, timer = null, wakeWatcher = () => {}, watcher = Promise.resolve();
|
|
519
|
+
const command = (args, { status = false } = {}) => new Promise((resolve, reject) => {
|
|
520
|
+
run(binary, [...(bundled ? [bundled] : []), ...args], { cwd: commandCwd, env, encoding: 'utf8', timeout: status ? 15_000 : 120_000, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
|
|
521
|
+
let reply;
|
|
522
|
+
try { reply = JSON.parse(stdout); } catch { reject(new Error('Gozar did not return valid JSON')); return; }
|
|
523
|
+
if (status && !validStatus(reply?.snapshot)) { reject(new Error('Gozar did not return valid status JSON')); return; }
|
|
524
|
+
// Status exits 1 with valid, withdrawn-readiness JSON when no controller is running.
|
|
525
|
+
if ((error && !(status && error.code === 1 && withdrawn(reply?.snapshot))) || reply?.error) {
|
|
526
|
+
reject(Object.assign(new Error(`Gozar: ${safeDiagnostic(reply?.error ?? 'command failed', 240)}`), { gozarReply: reply })); return;
|
|
527
|
+
}
|
|
528
|
+
resolve(reply);
|
|
529
|
+
});
|
|
530
|
+
});
|
|
531
|
+
// Recovery may be pasted into another shell: retain the selected executable and
|
|
532
|
+
// directory lookup context, without printing unrelated environment secrets.
|
|
533
|
+
const recoveryCommand = target => {
|
|
534
|
+
const quote = value => "'" + String(value).replaceAll("'", "'\\''") + "'";
|
|
535
|
+
const keys = ['HOME', 'PATH', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_RUNTIME_DIR', 'TMPDIR', 'GOZAR_HOME'];
|
|
536
|
+
const assignments = keys.filter(key => env[key] !== undefined).map(key => `${key}=${quote(env[key])}`);
|
|
537
|
+
const argv = [binary, ...(bundled ? [bundled] : []), 'stop', '--port', String(target)];
|
|
538
|
+
return `(cd ${quote(commandCwd ?? process.cwd())} && unset ${keys.join(' ')} && ${[...assignments, ...argv.map(quote)].join(' ')})`;
|
|
539
|
+
};
|
|
540
|
+
const status = target => command(['status', '--port', String(target), '--json'], { status: true });
|
|
541
|
+
const validResources = snapshot => snapshot.resources === undefined || (Array.isArray(snapshot.resources) &&
|
|
542
|
+
snapshot.resources.every(resource => resource && typeof resource === 'object' && !Array.isArray(resource) && typeof resource.cleanup === 'string' && resource.cleanup.length > 0));
|
|
543
|
+
const validStatus = snapshot => snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) &&
|
|
544
|
+
typeof snapshot.phase === 'string' && snapshot.phase.length > 0 &&
|
|
545
|
+
(snapshot.published === null || (typeof snapshot.published === 'string' && snapshot.published.length > 0)) &&
|
|
546
|
+
(snapshot.candidate === null || (typeof snapshot.candidate === 'string' && snapshot.candidate.length > 0)) && validResources(snapshot);
|
|
547
|
+
const withdrawn = snapshot => validStatus(snapshot) &&
|
|
548
|
+
snapshot.published === null && snapshot.candidate === null &&
|
|
549
|
+
['unknown', 'stopped', 'stopping', 'cleanup-pending'].includes(snapshot.phase);
|
|
550
|
+
const removed = snapshot => withdrawn(snapshot) && (snapshot.resources ?? []).every(resource => resource.cleanup === 'removed') &&
|
|
551
|
+
(snapshot.phase === 'stopped' || (snapshot.phase === 'unknown' && Array.isArray(snapshot.limitations) && snapshot.limitations.some(line => typeof line === 'string' && /^Controller unavailable:.*\b(?:ENOENT|ECONNREFUSED)\b/.test(line))));
|
|
552
|
+
const stopWatcher = async () => {
|
|
553
|
+
watching = false;
|
|
554
|
+
clearTimeout(timer);
|
|
555
|
+
wakeWatcher();
|
|
556
|
+
await watcher;
|
|
557
|
+
};
|
|
558
|
+
return {
|
|
559
|
+
name: 'gozar',
|
|
560
|
+
probe() {
|
|
561
|
+
commandCwd = process.cwd();
|
|
562
|
+
bundled = resolveBundled();
|
|
563
|
+
binary = bundled ? process.execPath : null;
|
|
564
|
+
if (!binary && env.GOZAR_BIN) {
|
|
565
|
+
try { fs.accessSync(env.GOZAR_BIN, fs.constants.X_OK); binary = env.GOZAR_BIN; } catch { /* unavailable */ }
|
|
566
|
+
}
|
|
567
|
+
binary ??= which('gozar');
|
|
568
|
+
return binary ? { ok: true } : { ok: false, line: 'Gozar is not installed', fix: 'Install gozar on PATH or set GOZAR_BIN to its executable path.' };
|
|
569
|
+
},
|
|
570
|
+
async start({ gatePort, signal, lifetimeEndsAt }) {
|
|
571
|
+
signal?.throwIfAborted();
|
|
572
|
+
if (!binary) throw new Error('gozar: probe() must succeed before start()');
|
|
573
|
+
if (!Number.isInteger(gatePort) || gatePort < 1 || gatePort > 65535) throw new Error('the local gate port is not valid');
|
|
574
|
+
// Expose silently reuses an existing controller. Refuse it before acquiring any cleanup responsibility.
|
|
575
|
+
const before = await status(gatePort);
|
|
576
|
+
if (!removed(before.snapshot)) throw new Error(`port ${gatePort} already has a Gozar route; Dalan cannot confirm ownership and is leaving it untouched. Choose a different --port and --home for another trial.`);
|
|
577
|
+
signal?.throwIfAborted();
|
|
578
|
+
port = gatePort;
|
|
579
|
+
// Pin the trial adapter; never let auto recommendation select the machine's Tailscale.
|
|
580
|
+
// Let expose settle before cleanup: it starts a background controller even if the caller cancels.
|
|
581
|
+
let reply;
|
|
582
|
+
const lifetimeArgs = lifetimeEndsAt === undefined ? [] : ['--lifetime-ms', String(Math.max(1, Math.floor(lifetimeEndsAt - now())))];
|
|
583
|
+
try { reply = await command(['expose', ...lifetimeArgs, '--port', String(port), '--client-reach', 'internet', '--yes', '--json', '--transport', 'https', '--sse', '--adapter', 'tunnl-gg']); }
|
|
584
|
+
catch (error) { sessionId = error.gozarReply?.snapshot?.sessionId ?? null; throw error; }
|
|
585
|
+
sessionId = reply?.snapshot?.sessionId ?? null;
|
|
586
|
+
signal?.throwIfAborted();
|
|
587
|
+
const origin = reply?.snapshot?.published;
|
|
588
|
+
let url; try { url = new URL(origin); } catch { /* rejected below */ }
|
|
589
|
+
if (typeof sessionId !== 'string' || !sessionId || reply?.snapshot?.phase !== 'published-ready' || !url || url.protocol !== 'https:' || url.origin !== origin) throw new Error('Gozar did not publish a ready HTTPS origin with a session identity');
|
|
590
|
+
let ended;
|
|
591
|
+
const exited = new Promise(resolve => { ended = resolve; });
|
|
592
|
+
const ownedPort = port, ownedSession = sessionId;
|
|
593
|
+
watching = true;
|
|
594
|
+
watcher = (async () => {
|
|
595
|
+
while (watching) {
|
|
596
|
+
await new Promise(resolve => { wakeWatcher = resolve; timer = setTimeout(resolve, pollMs); timer.unref?.(); });
|
|
597
|
+
if (!watching) break;
|
|
598
|
+
try {
|
|
599
|
+
const current = (await status(ownedPort)).snapshot;
|
|
600
|
+
if (current?.sessionId === ownedSession && current.phase === 'published-ready' && current.published === origin) continue;
|
|
601
|
+
endReason = current?.sessionId === ownedSession && current.phase === 'published-ready' && current.published && current.published !== origin ? 'rotated' : 'lost';
|
|
602
|
+
} catch { /* Unobservable readiness cannot keep the trial alive. */ }
|
|
603
|
+
if (watching) ended();
|
|
604
|
+
break;
|
|
605
|
+
}
|
|
606
|
+
})();
|
|
607
|
+
return { origin, exited, endedBecause: () => endReason };
|
|
608
|
+
},
|
|
609
|
+
async stop() {
|
|
610
|
+
await stopWatcher();
|
|
611
|
+
if (port === null) return { removed: true };
|
|
612
|
+
let current;
|
|
613
|
+
try {
|
|
614
|
+
current = (await status(port)).snapshot;
|
|
615
|
+
} catch (error) {
|
|
616
|
+
return { removed: false, detail: `Gozar session ownership could not be confirmed (${error.message}); leaving the route untouched. Choose a different --port and --home for another trial.` };
|
|
617
|
+
}
|
|
618
|
+
if (sessionId && current?.sessionId && current.sessionId !== sessionId) {
|
|
619
|
+
return { removed: false, detail: 'Gozar now reports a different session for this port; cleanup of this trial could not be confirmed. The replacement was left untouched. Choose a different --port and --home for another trial.' };
|
|
620
|
+
}
|
|
621
|
+
if (removed(current)) {
|
|
622
|
+
const noController = current.phase === 'unknown' && Array.isArray(current.limitations) && current.limitations.some(line => typeof line === 'string' && /^Controller unavailable:.*\b(?:ENOENT|ECONNREFUSED)\b/.test(line));
|
|
623
|
+
if (!noController && (!sessionId || current.sessionId !== sessionId)) {
|
|
624
|
+
return { removed: false, detail: 'Gozar reports no active route, but cleanup of this trial could not be confirmed because its session identity is missing. Choose a different --port and --home for another trial.' };
|
|
625
|
+
}
|
|
626
|
+
port = null; sessionId = null;
|
|
627
|
+
return { removed: true };
|
|
628
|
+
}
|
|
629
|
+
// This avoids stopping a session already known to be unowned; Gozar can still race a replacement after this check.
|
|
630
|
+
if (!sessionId || current?.phase === 'unknown' || current?.sessionId !== sessionId) {
|
|
631
|
+
return { removed: false, detail: 'Gozar session ownership could not be confirmed; leaving the route untouched. Choose a different --port and --home for another trial.' };
|
|
632
|
+
}
|
|
633
|
+
const cleanupCommand = recoveryCommand(port);
|
|
634
|
+
let reply;
|
|
635
|
+
try {
|
|
636
|
+
reply = await command(['stop', '--port', String(port), '--json']);
|
|
637
|
+
} catch (error) {
|
|
638
|
+
return { removed: false, detail: `Gozar route cleanup is unconfirmed (${error.message}); its current owner could not be confirmed. Choose a different --port and --home for another trial.` };
|
|
639
|
+
}
|
|
640
|
+
const stopped = reply?.snapshot;
|
|
641
|
+
if (!validStatus(stopped) || stopped.sessionId !== sessionId || stopped.phase === 'unknown') {
|
|
642
|
+
return { removed: false, detail: 'Gozar route cleanup is unconfirmed; its current owner could not be confirmed. Choose a different --port and --home for another trial.' };
|
|
643
|
+
}
|
|
644
|
+
if (removed(stopped) && !reply.localCleanupFailures?.length) {
|
|
645
|
+
port = null; sessionId = null;
|
|
646
|
+
return { removed: true };
|
|
647
|
+
}
|
|
648
|
+
if (stopped.phase === 'cleanup-pending' && stopped.published === null && stopped.candidate === null) {
|
|
649
|
+
return { removed: false, detail: 'Gozar reports cleanup pending for this session. Its recovery command stops by port and can race a route replacement; inspect the route before you run it.', command: cleanupCommand };
|
|
650
|
+
}
|
|
651
|
+
return { removed: false, detail: 'Gozar route cleanup is unconfirmed; its current owner could not be confirmed. Choose a different --port and --home for another trial.' };
|
|
652
|
+
},
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// ---- choosing a route --------------------------------------------------------------------------------------------------
|
|
657
|
+
// `tailscale` uses the computer's HTTPS route, or an isolated node when that route is busy. `gozar` is the temporary demo relay.
|
|
658
|
+
// An explicit route shows its own failure and never falls back to the other. Existing Tailscale rules are never changed.
|
|
659
|
+
export function selectRouteProvider({ route = 'gozar', providers, say = () => {}, signal }) {
|
|
660
|
+
const named = name => providers.find(p => p.name === name);
|
|
661
|
+
signal?.throwIfAborted();
|
|
662
|
+
if (route === 'localhost.run' || route === 'gozar') {
|
|
663
|
+
const provider = named(route), probe = provider.probe();
|
|
664
|
+
if (!probe.ok) throw new Error(probe.fix);
|
|
665
|
+
return provider;
|
|
666
|
+
}
|
|
667
|
+
if (route !== 'tailscale') throw new Error(`unknown route ${route}`);
|
|
668
|
+
const host = named('tailscale').probe();
|
|
669
|
+
let choice = null, why = host.fix;
|
|
670
|
+
if (host.ok) choice = named('tailscale');
|
|
671
|
+
else if (host.busy && named('tailscale-node')) {
|
|
672
|
+
const node = named('tailscale-node').probe();
|
|
673
|
+
if (node.ok) { say(`${host.line} Starting a separate Tailscale node for this trial.`); choice = named('tailscale-node'); }
|
|
674
|
+
else { say(host.line); why = `${host.fix} (${node.fix})`; }
|
|
675
|
+
} else say(host.line);
|
|
676
|
+
if (!choice) throw new Error(why);
|
|
677
|
+
return choice;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
export async function startRoute({ route = 'gozar', providers, selectedProvider, gatePort, home, say, signal, lifetimeEndsAt }) {
|
|
681
|
+
// Clean a failed start before returning, and carry any retained files/debt to the caller's final cleanup.
|
|
682
|
+
const attempt = async provider => {
|
|
683
|
+
signal?.throwIfAborted();
|
|
684
|
+
try {
|
|
685
|
+
const started = await provider.start({ gatePort, home, say, signal, lifetimeEndsAt });
|
|
686
|
+
return { provider, origin: started.origin, exited: started.exited, endedBecause: started.endedBecause, stop: () => provider.stop() };
|
|
687
|
+
} catch (error) {
|
|
688
|
+
const cleaned = await provider.stop().catch(e => ({ removed: false, keepNode: true, detail: e.message }));
|
|
689
|
+
if (!cleaned.removed) throw Object.assign(new Error(`${provider.name} failed (${error.message}) and could not be removed: ${cleaned.detail}${cleaned.command ? `\nRemove it with:\n ${cleaned.command}` : ''}`), { cleanupFailed: true, routeCleanup: cleaned });
|
|
690
|
+
throw Object.assign(error, { routeCleanup: cleaned });
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
return attempt(selectedProvider ?? selectRouteProvider({ route, providers, say, signal }));
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// A trial constraint, not an OAuth rule: RFC 8414 lets an authorization server live on another origin. A trial's bridge serves its own
|
|
697
|
+
// authorization server, so the check requires the issuer and every endpoint on the trial's public origin (a bare root issuer counts).
|
|
698
|
+
export const TRIAL_ORIGIN_RULE = 'a trial constraint: the bridge serves its own authorization server on the public origin';
|
|
699
|
+
export const onOrigin = (origin, value) => value === origin || value.startsWith(`${origin}/`);
|
|
700
|
+
// RFC 8414 section 3.1: the well-known segment goes between the host and the issuer's path, and a terminal slash of that path is
|
|
701
|
+
// dropped. The metadata's `issuer` is still compared to the issuer exactly as written.
|
|
702
|
+
export function authorizationServerMetadataUrl(issuer) {
|
|
703
|
+
let url; try { url = new URL(issuer); } catch { url = null; }
|
|
704
|
+
if (!url || url.search || url.hash || issuer.includes('?') || issuer.includes('#')) throw new Error('the issuer is not a plain address (it has a query or fragment, or is not a URL)');
|
|
705
|
+
return `${url.origin}/.well-known/oauth-authorization-server${url.pathname.replace(/\/$/, '')}`;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// ---- readiness ---------------------------------------------------------------------------------------------------------
|
|
709
|
+
// The public address answers as this bridge: trusted TLS (the platform's fetch checks it), discovery that names this origin and
|
|
710
|
+
// resource, an OAuth challenge on an unauthenticated MCP request, and no owner route. The secret path is known only to this bridge,
|
|
711
|
+
// so a matching discovery document also shows that the route reaches it and not another program.
|
|
712
|
+
export async function verifyPublicReady({ origin, secret, fetchImpl = fetch, clock = { now: Date.now, sleep }, timeoutMs, say = () => {}, signal }) {
|
|
713
|
+
const within = ms => signal ? AbortSignal.any([AbortSignal.timeout(ms), signal]) : AbortSignal.timeout(ms);
|
|
714
|
+
const resource = `${origin}/${secret}/mcp`;
|
|
715
|
+
const check = async () => {
|
|
716
|
+
const meta = await fetchImpl(`${origin}/.well-known/oauth-protected-resource/${secret}/mcp`, { redirect: 'manual', signal: within(10_000) });
|
|
717
|
+
if (meta.status !== 200) return `discovery returned HTTP ${meta.status}`;
|
|
718
|
+
const doc = await meta.json().catch(() => null);
|
|
719
|
+
if (doc?.resource !== resource) return 'discovery names a different resource';
|
|
720
|
+
if (!Array.isArray(doc.authorization_servers) || doc.authorization_servers.length === 0) return 'discovery names no authorization server';
|
|
721
|
+
if (!doc.authorization_servers.every(s => onOrigin(origin, String(s)))) return `discovery names an issuer outside this origin (${TRIAL_ORIGIN_RULE})`;
|
|
722
|
+
// The issuer's own metadata: the exact issuer, and https endpoints for sign-in, tokens and registration on this origin.
|
|
723
|
+
const issuer = String(doc.authorization_servers[0]);
|
|
724
|
+
let asUrl; try { asUrl = authorizationServerMetadataUrl(issuer); } catch (error) { return error.message; }
|
|
725
|
+
const asMeta = await fetchImpl(asUrl, { redirect: 'manual', signal: within(10_000) });
|
|
726
|
+
if (asMeta.status !== 200) return `authorization-server metadata returned HTTP ${asMeta.status}`;
|
|
727
|
+
const as = await asMeta.json().catch(() => null);
|
|
728
|
+
if (as?.issuer !== issuer) return 'the authorization-server issuer does not match the issuer in discovery';
|
|
729
|
+
for (const key of ['authorization_endpoint', 'token_endpoint', 'registration_endpoint']) {
|
|
730
|
+
if (typeof as[key] !== 'string' || !onOrigin(origin, as[key])) return `the authorization server's ${key} is missing or is not an address on this origin (${TRIAL_ORIGIN_RULE})`;
|
|
731
|
+
}
|
|
732
|
+
const challenge = await fetchImpl(resource, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: '{"jsonrpc":"2.0","id":1,"method":"ping"}', signal: within(10_000) });
|
|
733
|
+
const isChallenge = challenge.status === 401 && /^Bearer/i.test(challenge.headers.get('www-authenticate') ?? '');
|
|
734
|
+
void challenge.body?.cancel().catch(() => {});
|
|
735
|
+
if (!isChallenge) return `an unauthenticated MCP request returned HTTP ${challenge.status}, not an OAuth challenge`;
|
|
736
|
+
for (const owner of ['/admin', '/connect/pending', '/connect/list']) {
|
|
737
|
+
const res = await fetchImpl(`${origin}${owner}`, { redirect: 'manual', signal: within(10_000) });
|
|
738
|
+
const status = res.status;
|
|
739
|
+
void res.body?.cancel().catch(() => {});
|
|
740
|
+
if (status === 200) return `${owner} answers on the public address`;
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
resource: doc.resource,
|
|
744
|
+
authorizationServers: doc.authorization_servers,
|
|
745
|
+
issuer,
|
|
746
|
+
authorizationServer: as,
|
|
747
|
+
};
|
|
748
|
+
};
|
|
749
|
+
const end = clock.now() + timeoutMs;
|
|
750
|
+
let last = 'no answer yet', nextSay = clock.now() + 15_000;
|
|
751
|
+
for (;;) {
|
|
752
|
+
signal?.throwIfAborted();
|
|
753
|
+
try { last = await check(); if (last && typeof last === 'object') return { ready: true, identity: last }; }
|
|
754
|
+
catch (error) { if (signal?.aborted) throw error; last = safeDiagnostic(error.cause?.code ?? error.message, 120); }
|
|
755
|
+
if (clock.now() >= end) return { ready: false, last };
|
|
756
|
+
if (clock.now() >= nextSay) { say(`Still waiting for the public address to answer (${last})…`); nextSay += 15_000; }
|
|
757
|
+
await raceAbort(clock.sleep(2000), signal);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const identityMatches = (actual, expected) => actual.resource === expected.resource &&
|
|
762
|
+
JSON.stringify(actual.authorizationServers) === JSON.stringify(expected.authorizationServers) &&
|
|
763
|
+
actual.issuer === expected.issuer &&
|
|
764
|
+
['issuer', 'authorization_endpoint', 'token_endpoint', 'registration_endpoint'].every(key => actual.authorizationServer[key] === expected.authorizationServer[key]);
|
|
765
|
+
|
|
766
|
+
async function readIdentityJson(response, signal, label, maxBytes = 65_536) {
|
|
767
|
+
if (response.status >= 300 && response.status < 400) return { kind: 'identity_changed', detail: `${label} redirected` };
|
|
768
|
+
if (response.status !== 200) return { kind: 'unresponsive', detail: `${label} returned HTTP ${response.status}` };
|
|
769
|
+
if (!response.body) return { kind: 'unresponsive', detail: `${label} returned no body` };
|
|
770
|
+
const reader = response.body.getReader();
|
|
771
|
+
const chunks = [];
|
|
772
|
+
let size = 0;
|
|
773
|
+
try {
|
|
774
|
+
for (;;) {
|
|
775
|
+
if (signal.aborted) throw signal.reason ?? new Error('identity check timed out');
|
|
776
|
+
const { done, value } = await raceSignal(reader.read(), signal, () => reader.cancel().catch(() => {}));
|
|
777
|
+
if (done) break;
|
|
778
|
+
size += value.byteLength;
|
|
779
|
+
if (size > maxBytes) {
|
|
780
|
+
void reader.cancel().catch(() => {});
|
|
781
|
+
return { kind: 'identity_changed', detail: `${label} returned an oversized identity document` };
|
|
782
|
+
}
|
|
783
|
+
chunks.push(Buffer.from(value));
|
|
784
|
+
}
|
|
785
|
+
let value;
|
|
786
|
+
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
787
|
+
catch { return { kind: 'identity_changed', detail: `${label} returned invalid JSON` }; }
|
|
788
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return { kind: 'identity_changed', detail: `${label} returned invalid JSON` };
|
|
789
|
+
return { value };
|
|
790
|
+
} finally { try { reader.releaseLock(); } catch { /* A timed-out stream may still be cancelling. */ } }
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
function raceSignal(promise, signal, onAbort = () => {}) {
|
|
794
|
+
if (signal.aborted) {
|
|
795
|
+
const failed = Promise.reject(signal.reason ?? new Error('identity check timed out'));
|
|
796
|
+
onAbort();
|
|
797
|
+
return failed;
|
|
798
|
+
}
|
|
799
|
+
let listener;
|
|
800
|
+
const aborted = new Promise((_, reject) => {
|
|
801
|
+
listener = () => { reject(signal.reason ?? new Error('identity check timed out')); onAbort(); };
|
|
802
|
+
signal.addEventListener('abort', listener, { once: true });
|
|
803
|
+
});
|
|
804
|
+
return Promise.race([promise, aborted]).finally(() => signal.removeEventListener('abort', listener));
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// One bounded identity check: one deadline covers TLS, all response bodies and every endpoint.
|
|
808
|
+
export async function checkPublicIdentity({ origin, secret, fetchImpl = fetch, signal, timeoutMs = 5000 }) {
|
|
809
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
810
|
+
const checkSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
811
|
+
const request = (url, init = {}) => raceSignal(fetchImpl(url, { ...init, redirect: 'manual', signal: checkSignal }), checkSignal);
|
|
812
|
+
const resource = `${origin}/${secret}/mcp`;
|
|
813
|
+
try {
|
|
814
|
+
const meta = await request(`${origin}/.well-known/oauth-protected-resource/${secret}/mcp`);
|
|
815
|
+
const docResult = await readIdentityJson(meta, checkSignal, 'protected-resource metadata');
|
|
816
|
+
if (docResult.kind) return docResult;
|
|
817
|
+
const doc = docResult.value;
|
|
818
|
+
if (doc.resource !== resource || !Array.isArray(doc.authorization_servers) || !doc.authorization_servers.length ||
|
|
819
|
+
doc.authorization_servers.some(value => typeof value !== 'string' || !onOrigin(origin, value))) {
|
|
820
|
+
return { kind: 'identity_changed', detail: 'protected-resource identity changed' };
|
|
821
|
+
}
|
|
822
|
+
const issuer = doc.authorization_servers[0];
|
|
823
|
+
let asUrl;
|
|
824
|
+
try { asUrl = authorizationServerMetadataUrl(issuer); }
|
|
825
|
+
catch { return { kind: 'identity_changed', detail: 'authorization-server identity changed' }; }
|
|
826
|
+
const asResponse = await request(asUrl);
|
|
827
|
+
const asResult = await readIdentityJson(asResponse, checkSignal, 'authorization-server metadata');
|
|
828
|
+
if (asResult.kind) return asResult;
|
|
829
|
+
const as = asResult.value;
|
|
830
|
+
if (as.issuer !== issuer || !['authorization_endpoint', 'token_endpoint', 'registration_endpoint'].every(key =>
|
|
831
|
+
typeof as[key] === 'string' && onOrigin(origin, as[key]))) {
|
|
832
|
+
return { kind: 'identity_changed', detail: 'authorization-server identity changed' };
|
|
833
|
+
}
|
|
834
|
+
const challenge = await request(resource, {
|
|
835
|
+
method: 'POST',
|
|
836
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
|
|
837
|
+
body: '{"jsonrpc":"2.0","id":1,"method":"ping"}',
|
|
838
|
+
});
|
|
839
|
+
try {
|
|
840
|
+
if (challenge.status >= 300 && challenge.status < 400) return { kind: 'identity_changed', detail: 'MCP endpoint redirected' };
|
|
841
|
+
if (challenge.status !== 401 || !/^Bearer/i.test(challenge.headers.get('www-authenticate') ?? '')) {
|
|
842
|
+
return { kind: 'unresponsive', detail: `MCP identity probe returned HTTP ${challenge.status}` };
|
|
843
|
+
}
|
|
844
|
+
} finally { void challenge.body?.cancel().catch(() => {}); }
|
|
845
|
+
const actual = { resource: doc.resource, authorizationServers: doc.authorization_servers, issuer, authorizationServer: as };
|
|
846
|
+
return { kind: 'ready', identity: actual };
|
|
847
|
+
} catch (error) {
|
|
848
|
+
if (signal?.aborted) return { kind: 'stopped' };
|
|
849
|
+
return { kind: 'unresponsive', detail: safeDiagnostic(error?.cause?.code ?? error?.message ?? 'probe failed', 160) };
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
const sleepOrAbort = (ms, signal) => new Promise(resolve => {
|
|
854
|
+
if (signal.aborted) { resolve(); return; }
|
|
855
|
+
const timer = setTimeout(done, ms);
|
|
856
|
+
function done() { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); }
|
|
857
|
+
signal.addEventListener('abort', done, { once: true });
|
|
858
|
+
});
|
|
859
|
+
|
|
860
|
+
// The URL is also the OAuth identity. A replacement or two consecutive failed public checks ends this trial.
|
|
861
|
+
export async function watchPublicIdentity({ origin, secret, identity, fetchImpl = fetch, intervalMs = 10_000, retryMs = 5000, timeoutMs = 5000, onStatus = () => {} }) {
|
|
862
|
+
const controller = new AbortController();
|
|
863
|
+
let resolveReady, resolveLost;
|
|
864
|
+
const ready = new Promise(resolve => { resolveReady = resolve; });
|
|
865
|
+
const lost = new Promise(resolve => { resolveLost = resolve; });
|
|
866
|
+
let stopped = false, failure = null;
|
|
867
|
+
const check = async () => checkPublicIdentity({ origin, secret, fetchImpl, signal: controller.signal, timeoutMs });
|
|
868
|
+
const run = (async () => {
|
|
869
|
+
const initial = await check();
|
|
870
|
+
if (initial.kind === 'identity_changed' || (initial.kind === 'ready' && !identityMatches(initial.identity, identity))) {
|
|
871
|
+
resolveLost({ origin, reason: 'identity_changed', detail: initial.detail });
|
|
872
|
+
resolveReady(false);
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
if (initial.kind !== 'ready') {
|
|
876
|
+
failure = initial;
|
|
877
|
+
try { onStatus('retrying', initial.detail); } catch { /* A status message cannot keep a dead route alive. */ }
|
|
878
|
+
}
|
|
879
|
+
resolveReady(true);
|
|
880
|
+
for (;;) {
|
|
881
|
+
await sleepOrAbort(failure ? retryMs : intervalMs, controller.signal);
|
|
882
|
+
if (stopped) return;
|
|
883
|
+
const result = await check();
|
|
884
|
+
if (result.kind === 'stopped' || stopped) return;
|
|
885
|
+
if (result.kind === 'identity_changed' || (result.kind === 'ready' && !identityMatches(result.identity, identity))) {
|
|
886
|
+
resolveLost({ origin, reason: 'identity_changed', detail: result.detail });
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
if (result.kind === 'ready') {
|
|
890
|
+
failure = null;
|
|
891
|
+
try { onStatus('ready'); } catch { /* A status message cannot keep a dead route alive. */ }
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
if (!failure) {
|
|
895
|
+
failure = result;
|
|
896
|
+
try { onStatus('retrying', result.detail); } catch { /* A status message cannot keep a dead route alive. */ }
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
resolveLost({ origin, reason: 'unresponsive', detail: result.detail ?? failure.detail });
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
})();
|
|
903
|
+
return {
|
|
904
|
+
ready,
|
|
905
|
+
lost,
|
|
906
|
+
async stop() { stopped = true; controller.abort(); await run; },
|
|
907
|
+
};
|
|
908
|
+
}
|