@juexibobi/private-desktop-mcp 0.4.0 → 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.
@@ -0,0 +1,1951 @@
1
+ import http from "node:http";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { WebSocketServer, WebSocket } from "ws";
6
+ import { Agent as UndiciDirectAgent } from "undici";
7
+ import {
8
+ HUB_PROTOCOL_VERSION,
9
+ SUPPORTED_PROTOCOL_VERSIONS,
10
+ READONLY_UPSTREAM_TOOLS,
11
+ RELAY_META_TOOLS,
12
+ RELAY_META_NAMES,
13
+ RELAY_RESOURCES,
14
+ RELAY_PROMPTS,
15
+ RELAY_PROMPT_NAMES,
16
+ constantTimeEqual,
17
+ sanitizeLabel,
18
+ sanitizeShort,
19
+ sanitizeDeviceId,
20
+ injectMetaToolsIntoBody,
21
+ enrichInitializeBody,
22
+ injectRelayResourcesIntoBody,
23
+ injectRelayPromptsIntoBody,
24
+ resolveDeviceFromList,
25
+ buildEdgeInitializePayload,
26
+ buildRelayPromptText,
27
+ buildSelfHealingDeviceErrorPayload
28
+ } from "../core/mcp-hub.mjs";
29
+ import { isTailscaleIp, isTailscaleTarget } from "./proxy.mjs";
30
+ import { logLine } from "./logging.mjs";
31
+ import {
32
+ DEFAULT_TAILSCALE_HTTPS_PORT,
33
+ DEFAULT_TAILSCALE_DIRECT_PORT,
34
+ authorizeTailscaleRequest,
35
+ buildTailscaleNodeUrls,
36
+ createWhoIsResolver,
37
+ getTailscaleStatus,
38
+ isLoopbackIp,
39
+ spawnTailscaleServe,
40
+ stripTrailingDot
41
+ } from "./tailscale.mjs";
42
+ import { readIncomingBody } from "./tailscale-node.mjs";
43
+
44
+ export const DEFAULT_HUB_PORT = 8720;
45
+ const DEFAULT_MAX_REQUEST_BYTES = 16 * 1024 * 1024;
46
+ const DEFAULT_UPSTREAM_TIMEOUT_MS = 300000;
47
+ const DISCOVERY_DEBOUNCE_MS = 3000;
48
+ const PROBE_TIMEOUT_MS = 1800;
49
+ const PROBE_CONCURRENCY = 8;
50
+
51
+ let sharedDirectAgent = null;
52
+ function defaultMeshFetch(url, init = {}) {
53
+ if (isTailscaleTarget(url) && !init.dispatcher) {
54
+ if (!sharedDirectAgent) sharedDirectAgent = new UndiciDirectAgent({ keepAliveTimeout: 5000 });
55
+ return fetch(url, { ...init, dispatcher: sharedDirectAgent });
56
+ }
57
+ return fetch(url, init);
58
+ }
59
+
60
+ const esc = (s) =>
61
+ String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
62
+
63
+ const sha256Hex = (s) => crypto.createHash("sha256").update(String(s)).digest("hex");
64
+ const randomHex = (n) => crypto.randomBytes(n).toString("hex");
65
+
66
+ export function parseStaticPeerSpec(rawSpec) {
67
+ const raw = String(rawSpec || "").trim();
68
+ if (!raw) return null;
69
+ let explicitName = "";
70
+ let rawUrl = raw;
71
+ const eq = raw.indexOf("=");
72
+ if (eq > 0 && !raw.slice(0, eq).includes("://")) {
73
+ explicitName = raw.slice(0, eq).trim();
74
+ rawUrl = raw.slice(eq + 1).trim();
75
+ }
76
+ let parsed;
77
+ try {
78
+ parsed = new URL(rawUrl);
79
+ } catch {
80
+ throw new Error(`Invalid peer URL "${rawSpec}"`);
81
+ }
82
+ if (!["http:", "https:"].includes(parsed.protocol)) {
83
+ throw new Error(`Unsupported peer URL protocol "${parsed.protocol}" in "${rawSpec}"`);
84
+ }
85
+ const baseUrl = parsed.origin + parsed.pathname.replace(/\/mcp\/?$/i, "").replace(/\/+$/, "");
86
+ const name = sanitizeLabel(explicitName || parsed.hostname.split(".")[0], "Peer", 40);
87
+ const id = `peer:${sha256Hex(baseUrl).slice(0, 16)}`;
88
+ return {
89
+ id,
90
+ name,
91
+ hasExplicitName: Boolean(explicitName),
92
+ baseUrl,
93
+ mcpUrl: `${baseUrl}/mcp`,
94
+ nodeInfoUrl: `${baseUrl}/pcc/node-info`,
95
+ hostName: parsed.hostname,
96
+ dnsName: parsed.hostname.endsWith(".ts.net") ? parsed.hostname : "",
97
+ ipv4: isTailscaleIp(parsed.hostname) ? parsed.hostname : "",
98
+ transport: parsed.protocol === "https:" ? "tailscale-https" : isTailscaleIp(parsed.hostname) ? "tailscale-direct" : "static-http"
99
+ };
100
+ }
101
+
102
+ function sendJson(res, status, payload, extraHeaders = {}) {
103
+ if (res.writableEnded) return;
104
+ res.writeHead(status, {
105
+ "content-type": "application/json",
106
+ "cache-control": "no-store",
107
+ ...extraHeaders
108
+ });
109
+ res.end(JSON.stringify(payload));
110
+ }
111
+
112
+ function sendHtml(res, status, markup) {
113
+ if (res.writableEnded) return;
114
+ res.writeHead(status, {
115
+ "content-type": "text/html;charset=utf-8",
116
+ "cache-control": "no-store",
117
+ "content-security-policy": "default-src 'none';style-src 'unsafe-inline';form-action 'self';frame-ancestors 'none'"
118
+ });
119
+ res.end(markup);
120
+ }
121
+
122
+ function jsonRpcPayload(id, payload, isError = false) {
123
+ return {
124
+ jsonrpc: "2.0",
125
+ id: id ?? null,
126
+ result: {
127
+ content: [{ type: "text", text: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2) }],
128
+ ...(typeof payload === "object" && payload !== null ? { structuredContent: payload } : {}),
129
+ isError
130
+ }
131
+ };
132
+ }
133
+
134
+ function isAllowedLocalhostHeader(hostHeader, port) {
135
+ const host = String(hostHeader || "").trim().toLowerCase();
136
+ if (!host) return false;
137
+ const p = String(port);
138
+ return host === `127.0.0.1:${p}` || host === `localhost:${p}` || host === `[::1]:${p}`;
139
+ }
140
+
141
+ async function runWithConcurrency(items, limit, worker) {
142
+ const results = new Array(items.length);
143
+ let next = 0;
144
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
145
+ while (next < items.length) {
146
+ const idx = next++;
147
+ results[idx] = await worker(items[idx], idx);
148
+ }
149
+ });
150
+ await Promise.all(runners);
151
+ return results;
152
+ }
153
+
154
+ /**
155
+ * Multi-device Tailnet Mesh Hub.
156
+ * Unifies:
157
+ * - Zero-pairing Tailscale peer auto-discovery (`private-desktop-mcp serve` nodes)
158
+ * - Explicit static peer URLs (`--peer`)
159
+ * - Optional in-process local gateway (`--with-local`)
160
+ * - Optional paired WebSocket relay devices (`connect --relay <hub-url>`)
161
+ */
162
+ export class TailnetMeshHub {
163
+ constructor({
164
+ version = "0.6.0",
165
+ statePath = "",
166
+ staticPeers = [],
167
+ localDevice = null,
168
+ peerToken = "",
169
+ tsHttpsPort = DEFAULT_TAILSCALE_HTTPS_PORT,
170
+ tsDirectPort = DEFAULT_TAILSCALE_DIRECT_PORT,
171
+ preferDirect = false,
172
+ discoverTailscale = true,
173
+ includeSelfPeer = false,
174
+ peerTags = [],
175
+ allowAllTailnetPeers = false,
176
+ defaultDevice = "",
177
+ getTailscaleStatusFn = getTailscaleStatus,
178
+ fetcher = defaultMeshFetch,
179
+ upstreamTimeoutMs = DEFAULT_UPSTREAM_TIMEOUT_MS,
180
+ probeTimeoutMs = PROBE_TIMEOUT_MS,
181
+ log = logLine
182
+ } = {}) {
183
+ this.version = version;
184
+ this.statePath = statePath;
185
+ this.peerToken = String(peerToken || "");
186
+ this.tsHttpsPort = Number(tsHttpsPort) || DEFAULT_TAILSCALE_HTTPS_PORT;
187
+ this.tsDirectPort = Number(tsDirectPort) || DEFAULT_TAILSCALE_DIRECT_PORT;
188
+ this.preferDirect = Boolean(preferDirect);
189
+ this.discoverTailscale = Boolean(discoverTailscale);
190
+ this.includeSelfPeer = Boolean(includeSelfPeer);
191
+ this.peerTags = new Set(
192
+ (peerTags || [])
193
+ .map((t) => {
194
+ const s = String(t || "").trim().toLowerCase();
195
+ return s ? (s.startsWith("tag:") ? s : `tag:${s}`) : "";
196
+ })
197
+ .filter(Boolean)
198
+ );
199
+ this.allowAllTailnetPeers = Boolean(allowAllTailnetPeers);
200
+ this.defaultDevice = String(defaultDevice || "").trim();
201
+ this.getTailscaleStatusFn = getTailscaleStatusFn;
202
+ this.fetcher = fetcher;
203
+ this.upstreamTimeoutMs = upstreamTimeoutMs;
204
+ this.probeTimeoutMs = probeTimeoutMs;
205
+ this.log = log;
206
+
207
+ this.localDevice = localDevice; // { id, name, platform, arch, mode, isGatewayHealthy, localBridge }
208
+ this.staticPeers = (staticPeers || []).map((p) => (typeof p === "string" ? parseStaticPeerSpec(p) : p)).filter(Boolean);
209
+
210
+ // Persisted / runtime state
211
+ this.selectedDeviceId = "";
212
+ this.policyOverrides = new Map(); // deviceId -> { readOnly?: boolean, name?: string }
213
+ this.pairedDevices = new Map(); // deviceId -> { id, name, hash, approvedAt, readOnly, platform, arch, cliVersion, clientMode, lastSeen }
214
+ this.pendingPairs = new Map(); // pairId -> { id, proof, code, name, expires, approved, deviceId, token }
215
+ this.wsConnections = new Map(); // deviceId -> { ws, meta }
216
+ this.wsInflight = new Map(); // reqId -> { ws, resolve }
217
+ this.wsPings = new Map(); // pingId -> { ws, resolve }
218
+
219
+ // Live discovered HTTP mesh devices & per-device upstream MCP sessions
220
+ this.discoveredDevices = new Map(); // deviceId -> device record with endpointBase/mcpUrl/nodeInfoUrl
221
+ this.upstreamSessions = new Map(); // deviceId -> { sessionId, protocolVersion }
222
+ this.lastDiscoveryAt = 0;
223
+ this.discoveryPromise = null;
224
+ this.lastTailscaleStatus = null;
225
+ this.audits = [];
226
+
227
+ this.loadState();
228
+ }
229
+
230
+ loadState() {
231
+ if (!this.statePath) return;
232
+ try {
233
+ const raw = JSON.parse(fs.readFileSync(this.statePath, "utf8"));
234
+ if (typeof raw.selectedDeviceId === "string") this.selectedDeviceId = raw.selectedDeviceId;
235
+ if (raw.policyOverrides && typeof raw.policyOverrides === "object") {
236
+ for (const [id, ov] of Object.entries(raw.policyOverrides)) {
237
+ if (ov && typeof ov === "object") this.policyOverrides.set(id, { ...ov });
238
+ }
239
+ }
240
+ if (raw.pairedDevices && typeof raw.pairedDevices === "object") {
241
+ for (const [id, dev] of Object.entries(raw.pairedDevices)) {
242
+ if (dev && typeof dev === "object" && dev.id && dev.hash) {
243
+ this.pairedDevices.set(id, dev);
244
+ }
245
+ }
246
+ }
247
+ } catch {
248
+ // First run or unreadable state: start clean
249
+ }
250
+ }
251
+
252
+ saveState() {
253
+ if (!this.statePath) return;
254
+ try {
255
+ fs.mkdirSync(path.dirname(this.statePath), { recursive: true, mode: 0o700 });
256
+ const payload = {
257
+ selectedDeviceId: this.selectedDeviceId,
258
+ policyOverrides: Object.fromEntries(this.policyOverrides),
259
+ pairedDevices: Object.fromEntries(this.pairedDevices)
260
+ };
261
+ fs.writeFileSync(this.statePath, JSON.stringify(payload, null, 2), { mode: 0o600 });
262
+ } catch (err) {
263
+ this.log("warn", "Failed to save hub state: " + (err?.message || err));
264
+ }
265
+ }
266
+
267
+ recordAudit({
268
+ actor = "",
269
+ deviceId = "",
270
+ deviceName = "",
271
+ mcpMethod = "",
272
+ mcpName = "",
273
+ status = 200,
274
+ durationMs = 0,
275
+ ok = true,
276
+ error = ""
277
+ }) {
278
+ this.audits.unshift({
279
+ ts: new Date().toISOString(),
280
+ actor: String(actor || "local-owner").slice(0, 120),
281
+ deviceId: String(deviceId || "").slice(0, 64),
282
+ deviceName: String(deviceName || "").slice(0, 64),
283
+ mcpMethod: String(mcpMethod || "").slice(0, 80),
284
+ mcpName: String(mcpName || "").slice(0, 80),
285
+ status: Number(status) || 0,
286
+ durationMs: Math.max(0, Math.round(Number(durationMs) || 0)),
287
+ ok: Boolean(ok),
288
+ error: String(error || "").slice(0, 180)
289
+ });
290
+ if (this.audits.length > 500) this.audits.length = 500;
291
+ }
292
+
293
+ listAudit(limit = 20) {
294
+ const n = Math.min(50, Math.max(1, Number(limit) || 20));
295
+ return this.audits.slice(0, n);
296
+ }
297
+
298
+ peerAuthHeaders() {
299
+ const h = { accept: "application/json" };
300
+ if (this.peerToken) h.authorization = `Bearer ${this.peerToken}`;
301
+ return h;
302
+ }
303
+
304
+ async probeNodeInfo(baseUrl, transportLabel) {
305
+ const started = Date.now();
306
+ const url = `${baseUrl.replace(/\/+$/, "")}/pcc/node-info`;
307
+ try {
308
+ const res = await this.fetcher(url, {
309
+ method: "GET",
310
+ headers: this.peerAuthHeaders(),
311
+ signal: AbortSignal.timeout(this.probeTimeoutMs)
312
+ });
313
+ if (!res.ok) return { ok: false, status: res.status, rttMs: Date.now() - started };
314
+ const body = await res.json();
315
+ if (!body || body.ok !== true || body.kind !== "private-desktop-mcp-node") {
316
+ return { ok: false, status: res.status, rttMs: Date.now() - started };
317
+ }
318
+ return {
319
+ ok: true,
320
+ rttMs: Date.now() - started,
321
+ transport: transportLabel,
322
+ baseUrl: baseUrl.replace(/\/+$/, ""),
323
+ mcpUrl: `${baseUrl.replace(/\/+$/, "")}/mcp`,
324
+ info: body
325
+ };
326
+ } catch (e) {
327
+ return { ok: false, error: e?.message || "Probe failed", rttMs: Date.now() - started };
328
+ }
329
+ }
330
+
331
+ async probeTailscalePeer(peer) {
332
+ const candidates = [];
333
+ const dnsName = stripTrailingDot(peer.dnsName || "");
334
+ const ipv4 = String(peer.ipv4 || "").trim();
335
+
336
+ if (!this.preferDirect && dnsName) {
337
+ const httpsBase = `https://${dnsName}${this.tsHttpsPort === 443 ? "" : `:${this.tsHttpsPort}`}`;
338
+ candidates.push({ baseUrl: httpsBase, transport: "tailscale-https" });
339
+ }
340
+ if (ipv4 && isTailscaleIp(ipv4)) {
341
+ candidates.push({ baseUrl: `http://${ipv4}:${this.tsDirectPort}`, transport: "tailscale-direct" });
342
+ }
343
+ if (this.preferDirect && dnsName) {
344
+ const httpsBase = `https://${dnsName}${this.tsHttpsPort === 443 ? "" : `:${this.tsHttpsPort}`}`;
345
+ candidates.push({ baseUrl: httpsBase, transport: "tailscale-https" });
346
+ }
347
+
348
+ for (const c of candidates) {
349
+ const probe = await this.probeNodeInfo(c.baseUrl, c.transport);
350
+ if (probe.ok) return { peer, probe };
351
+ }
352
+ return null;
353
+ }
354
+
355
+ isPeerEligibleForDiscovery(peer) {
356
+ if (!peer || !peer.online) return false;
357
+ if (this.allowAllTailnetPeers) return true;
358
+ if (peer.isSameUser) return true;
359
+ if (this.peerTags.size > 0 && Array.isArray(peer.tags)) {
360
+ return peer.tags.some((t) => this.peerTags.has(String(t).toLowerCase()));
361
+ }
362
+ return false;
363
+ }
364
+
365
+ async refreshDiscovery({ force = false } = {}) {
366
+ const now = Date.now();
367
+ if (!force && now - this.lastDiscoveryAt < DISCOVERY_DEBOUNCE_MS) {
368
+ return;
369
+ }
370
+ if (this.discoveryPromise) {
371
+ return this.discoveryPromise;
372
+ }
373
+
374
+ this.discoveryPromise = (async () => {
375
+ const nextDiscovered = new Map();
376
+
377
+ // 1. Auto-discover Tailscale peers running `private-desktop-mcp serve`
378
+ if (this.discoverTailscale) {
379
+ try {
380
+ const tsStatus = this.getTailscaleStatusFn();
381
+ this.lastTailscaleStatus = tsStatus;
382
+ if (tsStatus?.running) {
383
+ const candidates = (tsStatus.peers || []).filter((p) => this.isPeerEligibleForDiscovery(p));
384
+ if (this.includeSelfPeer && tsStatus.self) {
385
+ candidates.unshift({ ...tsStatus.self, online: true, isSameUser: true });
386
+ }
387
+ const results = await runWithConcurrency(candidates, PROBE_CONCURRENCY, (peer) => this.probeTailscalePeer(peer));
388
+ for (const hit of results) {
389
+ if (!hit) continue;
390
+ const { peer, probe } = hit;
391
+ const info = probe.info;
392
+ const id = sanitizeDeviceId(info.nodeId || `ts:${peer.id || peer.dnsName || peer.ipv4}`, 64);
393
+ nextDiscovered.set(id, {
394
+ id,
395
+ name: sanitizeLabel(info.name || peer.hostName, "TailscalePC", 40),
396
+ hostName: peer.hostName || info.tailscale?.hostName || "",
397
+ dnsName: peer.dnsName || info.tailscale?.dnsName || "",
398
+ ipv4: peer.ipv4 || info.tailscale?.ipv4 || "",
399
+ platform: sanitizeShort(info.platform || peer.os || "unknown", 24),
400
+ arch: sanitizeShort(info.arch || "", 16),
401
+ cliVersion: sanitizeShort(info.cliVersion || "", 24),
402
+ clientMode: sanitizeShort(info.mode || "FULL", 24),
403
+ gatewayReady: Boolean(info.gatewayReady),
404
+ uptimeMs: Number(info.uptimeMs) || 0,
405
+ transport: probe.transport,
406
+ endpointBase: probe.baseUrl,
407
+ mcpUrl: probe.mcpUrl,
408
+ online: true,
409
+ lastSeen: new Date().toISOString(),
410
+ source: "tailscale-discovery"
411
+ });
412
+ }
413
+ }
414
+ } catch (err) {
415
+ this.log("warn", "Tailscale peer discovery error: " + (err?.message || err));
416
+ }
417
+ }
418
+
419
+ // 2. Probe explicit static peers (`--peer`)
420
+ if (this.staticPeers.length > 0) {
421
+ const staticResults = await runWithConcurrency(this.staticPeers, PROBE_CONCURRENCY, async (spec) => {
422
+ const probe = await this.probeNodeInfo(spec.baseUrl, spec.transport);
423
+ return { spec, probe };
424
+ });
425
+ for (const { spec, probe } of staticResults) {
426
+ if (probe.ok) {
427
+ const info = probe.info;
428
+ const id = sanitizeDeviceId(info.nodeId || spec.id, 64);
429
+ nextDiscovered.set(id, {
430
+ id,
431
+ name: sanitizeLabel(spec.hasExplicitName ? spec.name : info.name || spec.name, "Peer", 40),
432
+ hostName: spec.hostName,
433
+ dnsName: spec.dnsName || info.tailscale?.dnsName || "",
434
+ ipv4: spec.ipv4 || info.tailscale?.ipv4 || "",
435
+ platform: sanitizeShort(info.platform || "unknown", 24),
436
+ arch: sanitizeShort(info.arch || "", 16),
437
+ cliVersion: sanitizeShort(info.cliVersion || "", 24),
438
+ clientMode: sanitizeShort(info.mode || "FULL", 24),
439
+ gatewayReady: Boolean(info.gatewayReady),
440
+ uptimeMs: Number(info.uptimeMs) || 0,
441
+ transport: spec.transport,
442
+ endpointBase: spec.baseUrl,
443
+ mcpUrl: spec.mcpUrl,
444
+ online: true,
445
+ lastSeen: new Date().toISOString(),
446
+ source: "static-peer"
447
+ });
448
+ } else {
449
+ // Keep static peer visible as offline so users/agents can diagnose it
450
+ nextDiscovered.set(spec.id, {
451
+ id: spec.id,
452
+ name: spec.name,
453
+ hostName: spec.hostName,
454
+ dnsName: spec.dnsName,
455
+ ipv4: spec.ipv4,
456
+ platform: "unknown",
457
+ arch: "",
458
+ cliVersion: "",
459
+ clientMode: "FULL",
460
+ gatewayReady: false,
461
+ uptimeMs: 0,
462
+ transport: spec.transport,
463
+ endpointBase: spec.baseUrl,
464
+ mcpUrl: spec.mcpUrl,
465
+ online: false,
466
+ lastSeen: null,
467
+ source: "static-peer"
468
+ });
469
+ }
470
+ }
471
+ }
472
+
473
+ // Preserve previously discovered devices that went offline temporarily so agents see them as offline
474
+ for (const [id, prev] of this.discoveredDevices) {
475
+ if (!nextDiscovered.has(id) && prev.source === "tailscale-discovery") {
476
+ nextDiscovered.set(id, { ...prev, online: false, gatewayReady: false });
477
+ }
478
+ }
479
+
480
+ this.discoveredDevices = nextDiscovered;
481
+ this.lastDiscoveryAt = Date.now();
482
+ })();
483
+
484
+ try {
485
+ await this.discoveryPromise;
486
+ } finally {
487
+ this.discoveryPromise = null;
488
+ }
489
+ }
490
+
491
+ getDevicesList() {
492
+ const out = [];
493
+ const seen = new Set();
494
+
495
+ const applyOverlay = (dev) => {
496
+ const ov = this.policyOverrides.get(dev.id) || {};
497
+ return {
498
+ ...dev,
499
+ name: ov.name || dev.name,
500
+ readOnly: ov.readOnly !== undefined ? Boolean(ov.readOnly) : Boolean(dev.readOnly),
501
+ selected: this.selectedDeviceId === dev.id
502
+ };
503
+ };
504
+
505
+ // 1. Optional in-process local device
506
+ if (this.localDevice) {
507
+ const id = this.localDevice.id || "local";
508
+ seen.add(id);
509
+ out.push(
510
+ applyOverlay({
511
+ id,
512
+ name: this.localDevice.name || "Local",
513
+ hostName: this.localDevice.hostName || "",
514
+ dnsName: this.localDevice.dnsName || "",
515
+ ipv4: this.localDevice.ipv4 || "127.0.0.1",
516
+ platform: this.localDevice.platform || process.platform,
517
+ arch: this.localDevice.arch || process.arch,
518
+ cliVersion: this.version,
519
+ clientMode: this.localDevice.mode || "FULL",
520
+ readOnly: false,
521
+ transport: "local",
522
+ online: Boolean(this.localDevice.isGatewayHealthy?.()),
523
+ lastSeen: new Date().toISOString(),
524
+ source: "local"
525
+ })
526
+ );
527
+ }
528
+
529
+ // 2. Tailscale-discovered and static HTTP mesh peers
530
+ for (const dev of this.discoveredDevices.values()) {
531
+ if (seen.has(dev.id)) continue;
532
+ seen.add(dev.id);
533
+ out.push(applyOverlay({ ...dev, readOnly: false }));
534
+ }
535
+
536
+ // 3. Push-connected WebSocket devices (self-hosted relay)
537
+ for (const d of this.pairedDevices.values()) {
538
+ if (seen.has(d.id)) continue;
539
+ seen.add(d.id);
540
+ const conn = this.wsConnections.get(d.id);
541
+ const online = Boolean(conn && conn.ws.readyState === WebSocket.OPEN);
542
+ out.push(
543
+ applyOverlay({
544
+ id: d.id,
545
+ name: d.name,
546
+ approvedAt: d.approvedAt,
547
+ lastSeen: online ? new Date().toISOString() : d.lastSeen || d.approvedAt,
548
+ platform: conn?.meta?.platform || d.platform || "unknown",
549
+ arch: conn?.meta?.arch || d.arch || "",
550
+ cliVersion: conn?.meta?.cliVersion || d.cliVersion || "",
551
+ clientMode: conn?.meta?.clientMode || d.clientMode || "FULL",
552
+ readOnly: Boolean(d.readOnly),
553
+ transport: "relay-ws",
554
+ online,
555
+ source: "ws-relay"
556
+ })
557
+ );
558
+ }
559
+
560
+ // Apply defaultDevice automatically if none selected yet
561
+ if (!this.selectedDeviceId && this.defaultDevice) {
562
+ const resolved = resolveDeviceFromList(out, this.defaultDevice);
563
+ if (resolved.device) {
564
+ this.selectedDeviceId = resolved.device.id;
565
+ for (const item of out) item.selected = item.id === this.selectedDeviceId;
566
+ }
567
+ }
568
+
569
+ return out;
570
+ }
571
+
572
+ async ensureUpstreamSession(device, requestedProtocolVersion = SUPPORTED_PROTOCOL_VERSIONS[0], signal = null) {
573
+ const existing = this.upstreamSessions.get(device.id);
574
+ if (existing?.sessionId) return existing;
575
+
576
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedProtocolVersion)
577
+ ? requestedProtocolVersion
578
+ : SUPPORTED_PROTOCOL_VERSIONS[0];
579
+
580
+ const headers = {
581
+ "content-type": "application/json",
582
+ accept: "application/json, text/event-stream",
583
+ ...this.peerAuthHeaders()
584
+ };
585
+
586
+ const initRes = await this.fetcher(device.mcpUrl, {
587
+ method: "POST",
588
+ headers,
589
+ body: JSON.stringify({
590
+ jsonrpc: "2.0",
591
+ id: `hub-init-${crypto.randomUUID()}`,
592
+ method: "initialize",
593
+ params: {
594
+ protocolVersion,
595
+ capabilities: {},
596
+ clientInfo: { name: "private-desktop-mcp-tailscale-hub", version: this.version }
597
+ }
598
+ }),
599
+ signal: signal || AbortSignal.timeout(15000)
600
+ });
601
+
602
+ if (!initRes.ok) {
603
+ return { sessionId: "", protocolVersion };
604
+ }
605
+ const sessionId = initRes.headers.get("mcp-session-id") || "";
606
+ const negotiated = initRes.headers.get("mcp-protocol-version") || protocolVersion;
607
+ try {
608
+ await initRes.text();
609
+ } catch {}
610
+
611
+ if (sessionId) {
612
+ // Complete MCP handshake with notifications/initialized
613
+ try {
614
+ await this.fetcher(device.mcpUrl, {
615
+ method: "POST",
616
+ headers: {
617
+ ...headers,
618
+ "mcp-session-id": sessionId,
619
+ "mcp-protocol-version": negotiated
620
+ },
621
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
622
+ signal: AbortSignal.timeout(5000)
623
+ });
624
+ } catch {}
625
+ }
626
+
627
+ const session = { sessionId, protocolVersion: negotiated };
628
+ if (sessionId) this.upstreamSessions.set(device.id, session);
629
+ return session;
630
+ }
631
+
632
+ async forwardToHttpPeer(device, { method, headers, body, mcpMethod, signal }) {
633
+ const sendOnce = async (sessionId, protocolVersion) => {
634
+ const outHeaders = {
635
+ accept: headers["accept"] || "application/json, text/event-stream",
636
+ ...this.peerAuthHeaders()
637
+ };
638
+ if (headers["content-type"]) outHeaders["content-type"] = headers["content-type"];
639
+ else if (method === "POST") outHeaders["content-type"] = "application/json";
640
+ if (sessionId) outHeaders["mcp-session-id"] = sessionId;
641
+ if (protocolVersion || headers["mcp-protocol-version"]) {
642
+ outHeaders["mcp-protocol-version"] = protocolVersion || headers["mcp-protocol-version"];
643
+ }
644
+ if (headers["last-event-id"]) outHeaders["last-event-id"] = headers["last-event-id"];
645
+
646
+ const controller = new AbortController();
647
+ const timer = setTimeout(() => controller.abort(new Error("Upstream peer timeout")), this.upstreamTimeoutMs);
648
+ const onAbort = () => controller.abort(new Error("Client aborted"));
649
+ if (signal) {
650
+ if (signal.aborted) {
651
+ clearTimeout(timer);
652
+ onAbort();
653
+ } else {
654
+ signal.addEventListener("abort", onAbort, { once: true });
655
+ }
656
+ }
657
+
658
+ try {
659
+ const fetchOpts = { method, headers: outHeaders, signal: controller.signal };
660
+ if (method !== "DELETE" && method !== "GET" && method !== "HEAD") {
661
+ fetchOpts.body = body;
662
+ }
663
+ const r = await this.fetcher(device.mcpUrl, fetchOpts);
664
+ const text = [202, 204].includes(r.status) ? "" : await r.text();
665
+ const resHeaders = {};
666
+ for (const k of ["content-type", "mcp-session-id", "mcp-protocol-version"]) {
667
+ if (r.headers.has(k)) resHeaders[k] = r.headers.get(k);
668
+ }
669
+ return { status: r.status, headers: resHeaders, body: text };
670
+ } catch (err) {
671
+ const aborted = controller.signal.aborted;
672
+ const reason = controller.signal.reason?.message || err?.message || "Peer unreachable";
673
+ return {
674
+ status: aborted && /client/i.test(reason) ? 499 : 502,
675
+ headers: { "content-type": "application/json" },
676
+ body: JSON.stringify({ error: "Tailscale peer error", message: String(reason).slice(0, 180) })
677
+ };
678
+ } finally {
679
+ clearTimeout(timer);
680
+ if (signal) {
681
+ try {
682
+ signal.removeEventListener("abort", onAbort);
683
+ } catch {}
684
+ }
685
+ }
686
+ };
687
+
688
+ if (mcpMethod === "initialize") {
689
+ // Fresh initialize: send directly and capture any new session ID
690
+ const res = await sendOnce("", headers["mcp-protocol-version"] || "");
691
+ if (res.headers["mcp-session-id"]) {
692
+ this.upstreamSessions.set(device.id, {
693
+ sessionId: res.headers["mcp-session-id"],
694
+ protocolVersion: res.headers["mcp-protocol-version"] || SUPPORTED_PROTOCOL_VERSIONS[0]
695
+ });
696
+ }
697
+ return res;
698
+ }
699
+
700
+ if (method === "DELETE") {
701
+ const existing = this.upstreamSessions.get(device.id);
702
+ this.upstreamSessions.delete(device.id);
703
+ if (!existing?.sessionId) return { status: 204, headers: {}, body: "" };
704
+ return sendOnce(existing.sessionId, existing.protocolVersion);
705
+ }
706
+
707
+ // For normal MCP calls (tools/list, tools/call, etc.), ensure peer has an initialized session
708
+ const session = await this.ensureUpstreamSession(device, headers["mcp-protocol-version"], signal);
709
+ let res = await sendOnce(session.sessionId, session.protocolVersion);
710
+
711
+ // Auto-recover if peer gateway restarted and rejected the cached session ID
712
+ if ((res.status === 400 || res.status === 404) && session.sessionId) {
713
+ this.upstreamSessions.delete(device.id);
714
+ const refreshed = await this.ensureUpstreamSession(device, headers["mcp-protocol-version"], signal);
715
+ if (refreshed.sessionId) {
716
+ res = await sendOnce(refreshed.sessionId, refreshed.protocolVersion);
717
+ }
718
+ } else if (res.status === 502) {
719
+ this.upstreamSessions.delete(device.id);
720
+ }
721
+ return res;
722
+ }
723
+
724
+ async forwardToWsDevice(deviceId, { method, headers, body, signal }) {
725
+ const conn = this.wsConnections.get(deviceId);
726
+ if (!conn || conn.ws.readyState !== WebSocket.OPEN) {
727
+ return { status: 503, headers: { "content-type": "application/json" }, body: '{"error":"Device offline"}' };
728
+ }
729
+ const ws = conn.ws;
730
+ const reqId = crypto.randomUUID();
731
+ const cleanHeaders = {};
732
+ for (const k of ["accept", "content-type", "mcp-session-id", "mcp-protocol-version", "last-event-id", "mcp-method", "mcp-name"]) {
733
+ if (headers[k]) cleanHeaders[k] = headers[k];
734
+ }
735
+
736
+ return new Promise((resolve) => {
737
+ const cleanup = () => {
738
+ clearTimeout(timer);
739
+ this.wsInflight.delete(reqId);
740
+ if (signal) {
741
+ try {
742
+ signal.removeEventListener("abort", onAbort);
743
+ } catch {}
744
+ }
745
+ };
746
+ const timer = setTimeout(() => {
747
+ cleanup();
748
+ try {
749
+ ws.send(JSON.stringify({ kind: "cancel", id: reqId }));
750
+ } catch {}
751
+ resolve({ status: 504, headers: { "content-type": "application/json" }, body: '{"error":"Timeout"}' });
752
+ }, this.upstreamTimeoutMs);
753
+ const onAbort = () => {
754
+ cleanup();
755
+ try {
756
+ ws.send(JSON.stringify({ kind: "cancel", id: reqId }));
757
+ } catch {}
758
+ resolve({ status: 499, headers: { "content-type": "application/json" }, body: '{"error":"Client aborted"}' });
759
+ };
760
+ if (signal) {
761
+ if (signal.aborted) {
762
+ onAbort();
763
+ return;
764
+ }
765
+ signal.addEventListener("abort", onAbort, { once: true });
766
+ }
767
+
768
+ this.wsInflight.set(reqId, {
769
+ ws,
770
+ resolve: (v) => {
771
+ cleanup();
772
+ resolve(v);
773
+ }
774
+ });
775
+
776
+ try {
777
+ ws.send(JSON.stringify({ kind: "request", id: reqId, method, headers: cleanHeaders, body }));
778
+ } catch {
779
+ cleanup();
780
+ resolve({ status: 503, headers: { "content-type": "application/json" }, body: '{"error":"Disconnected"}' });
781
+ }
782
+ });
783
+ }
784
+
785
+ async pingDevice(device) {
786
+ const started = Date.now();
787
+ if (device.source === "local" && this.localDevice) {
788
+ const ready = Boolean(this.localDevice.isGatewayHealthy?.());
789
+ return {
790
+ ok: ready,
791
+ deviceId: device.id,
792
+ transport: "local",
793
+ rttMs: Date.now() - started,
794
+ gatewayReady: ready,
795
+ mode: this.localDevice.mode || "FULL",
796
+ cliVersion: this.version
797
+ };
798
+ }
799
+
800
+ if (device.endpointBase) {
801
+ const probe = await this.probeNodeInfo(device.endpointBase, device.transport);
802
+ if (!probe.ok) {
803
+ return {
804
+ ok: false,
805
+ deviceId: device.id,
806
+ transport: device.transport,
807
+ rttMs: probe.rttMs,
808
+ error: probe.error || `HTTP ${probe.status || 0}`
809
+ };
810
+ }
811
+ return {
812
+ ok: true,
813
+ deviceId: device.id,
814
+ transport: device.transport,
815
+ rttMs: probe.rttMs,
816
+ gatewayReady: Boolean(probe.info.gatewayReady),
817
+ uptimeMs: probe.info.uptimeMs || 0,
818
+ mode: probe.info.mode || "FULL",
819
+ cliVersion: probe.info.cliVersion || ""
820
+ };
821
+ }
822
+
823
+ const conn = this.wsConnections.get(device.id);
824
+ if (!conn || conn.ws.readyState !== WebSocket.OPEN) {
825
+ return { ok: false, deviceId: device.id, transport: "relay-ws", error: "Device offline", rttMs: 0 };
826
+ }
827
+ const pingId = crypto.randomUUID();
828
+ return new Promise((resolve) => {
829
+ const timer = setTimeout(() => {
830
+ this.wsPings.delete(pingId);
831
+ resolve({ ok: false, deviceId: device.id, transport: "relay-ws", error: "Ping timed out", rttMs: Date.now() - started });
832
+ }, 8000);
833
+ this.wsPings.set(pingId, {
834
+ ws: conn.ws,
835
+ resolve: (payload) => {
836
+ clearTimeout(timer);
837
+ resolve({ ok: true, deviceId: device.id, transport: "relay-ws", rttMs: Date.now() - started, ...payload });
838
+ }
839
+ });
840
+ try {
841
+ conn.ws.send(JSON.stringify({ kind: "ping", id: pingId }));
842
+ } catch {
843
+ clearTimeout(timer);
844
+ this.wsPings.delete(pingId);
845
+ resolve({ ok: false, deviceId: device.id, transport: "relay-ws", error: "WebSocket send failed", rttMs: Date.now() - started });
846
+ }
847
+ });
848
+ }
849
+
850
+ async handleMetaToolCall(rpc, actor) {
851
+ const started = Date.now();
852
+ const name = rpc.params?.name;
853
+ const args = rpc.params?.arguments && typeof rpc.params.arguments === "object" ? rpc.params.arguments : {};
854
+
855
+ if (name === "relay_list_devices") {
856
+ await this.refreshDiscovery({ force: true });
857
+ const devices = this.getDevicesList();
858
+ const onlineCount = devices.filter((d) => d.online).length;
859
+ const selected = devices.find((d) => d.selected)?.id || null;
860
+ this.recordAudit({ actor, mcpMethod: "tools/call", mcpName: name, status: 200, durationMs: Date.now() - started, ok: true });
861
+ return jsonRpcPayload(rpc.id, {
862
+ hubMode: "tailscale-mesh",
863
+ workerVersion: this.version,
864
+ onlineCount,
865
+ selectedDeviceId: selected,
866
+ devices
867
+ });
868
+ }
869
+
870
+ if (name === "relay_select_device") {
871
+ await this.refreshDiscovery();
872
+ const devices = this.getDevicesList();
873
+ const query = args.device_id || args.device_name || "";
874
+ const resolved = resolveDeviceFromList(devices, query);
875
+ if (resolved.error) {
876
+ this.recordAudit({ actor, mcpMethod: "tools/call", mcpName: name, status: resolved.status, durationMs: Date.now() - started, ok: false, error: resolved.error });
877
+ return jsonRpcPayload(rpc.id, { error: resolved.error }, true);
878
+ }
879
+ this.selectedDeviceId = resolved.device.id;
880
+ this.saveState();
881
+ this.recordAudit({
882
+ actor,
883
+ deviceId: resolved.device.id,
884
+ deviceName: resolved.device.name,
885
+ mcpMethod: "tools/call",
886
+ mcpName: name,
887
+ status: 200,
888
+ durationMs: Date.now() - started,
889
+ ok: true
890
+ });
891
+ return jsonRpcPayload(rpc.id, {
892
+ selected: resolved.device.id,
893
+ name: resolved.device.name,
894
+ transport: resolved.device.transport,
895
+ online: resolved.device.online,
896
+ readOnly: resolved.device.readOnly
897
+ });
898
+ }
899
+
900
+ if (name === "relay_ping_device") {
901
+ await this.refreshDiscovery();
902
+ const devices = this.getDevicesList();
903
+ let target = null;
904
+ if (args.device_id || args.device_name) {
905
+ const resolved = resolveDeviceFromList(devices, args.device_id || args.device_name);
906
+ if (resolved.error) return jsonRpcPayload(rpc.id, { error: resolved.error }, true);
907
+ target = resolved.device;
908
+ } else {
909
+ const online = devices.filter((d) => d.online);
910
+ target = devices.find((d) => d.id === this.selectedDeviceId) || (online.length === 1 ? online[0] : null);
911
+ }
912
+ if (!target || !target.online) {
913
+ return jsonRpcPayload(rpc.id, { ok: false, error: "Target device is offline or unselected" }, true);
914
+ }
915
+ const pingRes = await this.pingDevice(target);
916
+ this.recordAudit({
917
+ actor,
918
+ deviceId: target.id,
919
+ deviceName: target.name,
920
+ mcpMethod: "tools/call",
921
+ mcpName: name,
922
+ status: pingRes.ok ? 200 : 504,
923
+ durationMs: Date.now() - started,
924
+ ok: pingRes.ok,
925
+ error: pingRes.error || ""
926
+ });
927
+ return jsonRpcPayload(rpc.id, pingRes, !pingRes.ok);
928
+ }
929
+
930
+ if (name === "relay_set_device_policy") {
931
+ await this.refreshDiscovery();
932
+ const devices = this.getDevicesList();
933
+ const query = args.device_id || args.device_name || this.selectedDeviceId || "";
934
+ const resolved = resolveDeviceFromList(devices, query);
935
+ if (resolved.error) {
936
+ this.recordAudit({ actor, mcpMethod: "tools/call", mcpName: name, status: resolved.status, durationMs: Date.now() - started, ok: false, error: resolved.error });
937
+ return jsonRpcPayload(rpc.id, { error: resolved.error }, true);
938
+ }
939
+ const id = resolved.device.id;
940
+ const existing = this.policyOverrides.get(id) || {};
941
+ const nextOverride = { ...existing };
942
+ if (typeof args.read_only === "boolean") nextOverride.readOnly = args.read_only;
943
+ if (typeof args.new_name === "string" && args.new_name.trim()) {
944
+ nextOverride.name = sanitizeLabel(args.new_name, resolved.device.name, 40);
945
+ }
946
+ this.policyOverrides.set(id, nextOverride);
947
+ if (this.pairedDevices.has(id)) {
948
+ const stored = this.pairedDevices.get(id);
949
+ this.pairedDevices.set(id, {
950
+ ...stored,
951
+ ...(nextOverride.readOnly !== undefined ? { readOnly: nextOverride.readOnly } : {}),
952
+ ...(nextOverride.name ? { name: nextOverride.name } : {})
953
+ });
954
+ }
955
+ this.saveState();
956
+ const updatedName = nextOverride.name || resolved.device.name;
957
+ const updatedReadOnly = nextOverride.readOnly !== undefined ? Boolean(nextOverride.readOnly) : Boolean(resolved.device.readOnly);
958
+ this.recordAudit({
959
+ actor,
960
+ deviceId: id,
961
+ deviceName: updatedName,
962
+ mcpMethod: "tools/call",
963
+ mcpName: name,
964
+ status: 200,
965
+ durationMs: Date.now() - started,
966
+ ok: true
967
+ });
968
+ return jsonRpcPayload(rpc.id, {
969
+ deviceId: id,
970
+ name: updatedName,
971
+ readOnly: updatedReadOnly,
972
+ online: resolved.device.online
973
+ });
974
+ }
975
+
976
+ if (name === "relay_recent_activity") {
977
+ const entries = this.listAudit(args.limit ?? 20);
978
+ this.recordAudit({ actor, mcpMethod: "tools/call", mcpName: name, status: 200, durationMs: Date.now() - started, ok: true });
979
+ return jsonRpcPayload(rpc.id, { count: entries.length, entries });
980
+ }
981
+
982
+ return jsonRpcPayload(rpc.id, { error: "Unknown relay tool" }, true);
983
+ }
984
+
985
+ async handleResourceRead(rpc, actor, authMeta = {}) {
986
+ const started = Date.now();
987
+ const uri = String(rpc?.params?.uri || "");
988
+ await this.refreshDiscovery();
989
+ const devices = this.getDevicesList();
990
+ let payload = null;
991
+
992
+ if (uri === "relay://devices") {
993
+ payload = {
994
+ hubMode: "tailscale-mesh",
995
+ workerVersion: this.version,
996
+ onlineCount: devices.filter((d) => d.online).length,
997
+ selectedDeviceId: devices.find((d) => d.selected)?.id || null,
998
+ devices
999
+ };
1000
+ } else if (uri === "relay://status") {
1001
+ payload = {
1002
+ ok: true,
1003
+ hubMode: "tailscale-mesh",
1004
+ workerVersion: this.version,
1005
+ protocol: HUB_PROTOCOL_VERSION,
1006
+ authMode: authMeta.transport || "loopback",
1007
+ verified: Boolean(authMeta.verified),
1008
+ actor,
1009
+ tailscaleRunning: Boolean(this.lastTailscaleStatus?.running),
1010
+ magicDnsSuffix: this.lastTailscaleStatus?.magicDnsSuffix || "",
1011
+ onlineCount: devices.filter((d) => d.online).length,
1012
+ pairedCount: devices.length,
1013
+ selectedDeviceId: devices.find((d) => d.selected)?.id || null
1014
+ };
1015
+ } else if (uri === "relay://audit") {
1016
+ const entries = this.listAudit(30);
1017
+ payload = { count: entries.length, entries };
1018
+ } else {
1019
+ return null;
1020
+ }
1021
+
1022
+ this.recordAudit({ actor, mcpMethod: "resources/read", mcpName: uri, status: 200, durationMs: Date.now() - started, ok: true });
1023
+ return {
1024
+ jsonrpc: "2.0",
1025
+ id: rpc?.id ?? null,
1026
+ result: {
1027
+ contents: [
1028
+ {
1029
+ uri,
1030
+ mimeType: "application/json",
1031
+ text: JSON.stringify(payload, null, 2)
1032
+ }
1033
+ ]
1034
+ }
1035
+ };
1036
+ }
1037
+
1038
+ async handlePromptGet(rpc, actor) {
1039
+ const started = Date.now();
1040
+ const name = String(rpc?.params?.name || "");
1041
+ if (!RELAY_PROMPT_NAMES.has(name)) return null;
1042
+ const args = rpc?.params?.arguments && typeof rpc.params.arguments === "object" ? rpc.params.arguments : {};
1043
+ await this.refreshDiscovery();
1044
+ const devices = this.getDevicesList();
1045
+ const promptText = buildRelayPromptText(name, args, devices, {
1046
+ version: this.version,
1047
+ hubLabel: "Private Desktop MCP Tailnet Hub"
1048
+ });
1049
+ this.recordAudit({ actor, mcpMethod: "prompts/get", mcpName: name, status: 200, durationMs: Date.now() - started, ok: true });
1050
+ return {
1051
+ jsonrpc: "2.0",
1052
+ id: rpc?.id ?? null,
1053
+ result: {
1054
+ description: RELAY_PROMPTS.find((p) => p.name === name)?.description || name,
1055
+ messages: [{ role: "user", content: { type: "text", text: promptText } }]
1056
+ }
1057
+ };
1058
+ }
1059
+
1060
+ async handleMcpRequest({ method, headers, body, actor = "local-owner", authMeta = {}, signal = null }) {
1061
+ const started = Date.now();
1062
+ let rpc = null;
1063
+ if (body) {
1064
+ try {
1065
+ rpc = JSON.parse(body);
1066
+ } catch {
1067
+ rpc = null;
1068
+ }
1069
+ }
1070
+
1071
+ const mcpMethod = typeof rpc?.method === "string" ? rpc.method : headers["mcp-method"] || method;
1072
+ const mcpName =
1073
+ mcpMethod === "tools/call" && typeof rpc?.params?.name === "string" ? rpc.params.name : headers["mcp-name"] || "";
1074
+
1075
+ // 1. Built-in Hub meta-tools, resources, prompts
1076
+ if (mcpMethod === "tools/call" && RELAY_META_NAMES.has(mcpName)) {
1077
+ const payload = await this.handleMetaToolCall(rpc, actor);
1078
+ return { status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify(payload) };
1079
+ }
1080
+ if (mcpMethod === "resources/read" && String(rpc?.params?.uri || "").startsWith("relay://")) {
1081
+ const payload = await this.handleResourceRead(rpc, actor, authMeta);
1082
+ if (payload) return { status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify(payload) };
1083
+ }
1084
+ if (mcpMethod === "prompts/get" && RELAY_PROMPT_NAMES.has(String(rpc?.params?.name || ""))) {
1085
+ const payload = await this.handlePromptGet(rpc, actor);
1086
+ if (payload) return { status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify(payload) };
1087
+ }
1088
+
1089
+ // 2. Refresh Tailscale discovery and resolve target device
1090
+ await this.refreshDiscovery();
1091
+ const devices = this.getDevicesList();
1092
+ const onlineDevices = devices.filter((d) => d.online);
1093
+ const byId = new Map(devices.map((d) => [d.id, d]));
1094
+
1095
+ let forwardedBody = body;
1096
+ let targetQuery = String(headers["x-target-device"] || "").trim();
1097
+ if (
1098
+ mcpMethod === "tools/call" &&
1099
+ rpc?.params?.arguments &&
1100
+ typeof rpc.params.arguments === "object" &&
1101
+ typeof rpc.params.arguments._device === "string"
1102
+ ) {
1103
+ targetQuery = rpc.params.arguments._device.trim();
1104
+ const cleanedArgs = { ...rpc.params.arguments };
1105
+ delete cleanedArgs._device;
1106
+ forwardedBody = JSON.stringify({
1107
+ ...rpc,
1108
+ params: { ...rpc.params, arguments: cleanedArgs }
1109
+ });
1110
+ }
1111
+
1112
+ let targetDevice = null;
1113
+ if (targetQuery) {
1114
+ const resolved = resolveDeviceFromList(devices, targetQuery);
1115
+ if (resolved.error) {
1116
+ this.recordAudit({ actor, mcpMethod, mcpName, status: resolved.status, durationMs: Date.now() - started, ok: false, error: resolved.error });
1117
+ const errRes = buildSelfHealingDeviceErrorPayload({
1118
+ rpc,
1119
+ devices,
1120
+ reasonCode: "DEVICE_TARGET_ERROR",
1121
+ humanMessage: resolved.error,
1122
+ status: resolved.status,
1123
+ connectCommand: "npx --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp serve"
1124
+ });
1125
+ return { status: errRes.status, headers: { "content-type": "application/json" }, body: await errRes.text() };
1126
+ }
1127
+ targetDevice = resolved.device;
1128
+ } else {
1129
+ if (this.selectedDeviceId && byId.has(this.selectedDeviceId)) {
1130
+ targetDevice = byId.get(this.selectedDeviceId);
1131
+ }
1132
+ if ((!targetDevice || !targetDevice.online) && onlineDevices.length === 1) {
1133
+ targetDevice = onlineDevices[0];
1134
+ }
1135
+ }
1136
+
1137
+ // 3. Hub-native lifecycle fallback when no single online device is active
1138
+ const hubMeta = {
1139
+ serverName: "private-desktop-mcp-tailnet-hub",
1140
+ version: this.version,
1141
+ hubLabel: "Private Desktop MCP Tailnet Hub",
1142
+ extraHint: "Devices on your Tailscale network are discovered automatically when running `private-desktop-mcp serve`."
1143
+ };
1144
+
1145
+ if (!targetDevice || !targetDevice.online) {
1146
+ if (mcpMethod === "initialize" || mcpMethod === "server/discover") {
1147
+ this.recordAudit({ actor, mcpMethod, mcpName, status: 200, durationMs: Date.now() - started, ok: true });
1148
+ return {
1149
+ status: 200,
1150
+ headers: { "content-type": "application/json" },
1151
+ body: JSON.stringify(buildEdgeInitializePayload(rpc, devices, hubMeta))
1152
+ };
1153
+ }
1154
+ if (mcpMethod === "notifications/initialized") {
1155
+ this.recordAudit({ actor, mcpMethod, mcpName: "", status: 202, durationMs: Date.now() - started, ok: true });
1156
+ return { status: 202, headers: {}, body: "" };
1157
+ }
1158
+ if (mcpMethod === "ping") {
1159
+ return { status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: rpc?.id ?? null, result: {} }) };
1160
+ }
1161
+ if (mcpMethod === "tools/list") {
1162
+ this.recordAudit({ actor, mcpMethod, mcpName, status: 200, durationMs: Date.now() - started, ok: true });
1163
+ return {
1164
+ status: 200,
1165
+ headers: { "content-type": "application/json" },
1166
+ body: JSON.stringify({ jsonrpc: "2.0", id: rpc?.id ?? null, result: { tools: RELAY_META_TOOLS } })
1167
+ };
1168
+ }
1169
+ if (mcpMethod === "resources/list") {
1170
+ this.recordAudit({ actor, mcpMethod, mcpName, status: 200, durationMs: Date.now() - started, ok: true });
1171
+ return {
1172
+ status: 200,
1173
+ headers: { "content-type": "application/json" },
1174
+ body: JSON.stringify({ jsonrpc: "2.0", id: rpc?.id ?? null, result: { resources: RELAY_RESOURCES } })
1175
+ };
1176
+ }
1177
+ if (mcpMethod === "prompts/list") {
1178
+ this.recordAudit({ actor, mcpMethod, mcpName, status: 200, durationMs: Date.now() - started, ok: true });
1179
+ return {
1180
+ status: 200,
1181
+ headers: { "content-type": "application/json" },
1182
+ body: JSON.stringify({ jsonrpc: "2.0", id: rpc?.id ?? null, result: { prompts: RELAY_PROMPTS } })
1183
+ };
1184
+ }
1185
+ }
1186
+
1187
+ const serveHint = "npx --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp serve";
1188
+ if (targetDevice && !targetDevice.online) {
1189
+ this.recordAudit({ actor, deviceId: targetDevice.id, deviceName: targetDevice.name, mcpMethod, mcpName, status: 503, durationMs: Date.now() - started, ok: false, error: "Selected device offline" });
1190
+ const errRes = buildSelfHealingDeviceErrorPayload({
1191
+ rpc,
1192
+ devices,
1193
+ reasonCode: "SELECTED_DEVICE_OFFLINE",
1194
+ humanMessage: `Device "${targetDevice.name}" is offline; call relay_list_devices to refresh Tailscale peers.`,
1195
+ status: 503,
1196
+ connectCommand: serveHint
1197
+ });
1198
+ return { status: errRes.status, headers: { "content-type": "application/json" }, body: await errRes.text() };
1199
+ }
1200
+ if (!targetDevice) {
1201
+ if (onlineDevices.length === 0) {
1202
+ this.recordAudit({ actor, mcpMethod, mcpName, status: 503, durationMs: Date.now() - started, ok: false, error: "No device online" });
1203
+ const errRes = buildSelfHealingDeviceErrorPayload({
1204
+ rpc,
1205
+ devices,
1206
+ reasonCode: "NO_DEVICE_ONLINE",
1207
+ humanMessage: "No Tailscale or relay desktop device is currently online.",
1208
+ status: 503,
1209
+ connectCommand: serveHint
1210
+ });
1211
+ return { status: errRes.status, headers: { "content-type": "application/json" }, body: await errRes.text() };
1212
+ }
1213
+ if (onlineDevices.length > 1) {
1214
+ this.recordAudit({ actor, mcpMethod, mcpName, status: 409, durationMs: Date.now() - started, ok: false, error: "Multiple devices online" });
1215
+ const errRes = buildSelfHealingDeviceErrorPayload({
1216
+ rpc,
1217
+ devices,
1218
+ reasonCode: "MULTIPLE_DEVICES_ONLINE",
1219
+ humanMessage: "Multiple devices online; call relay_select_device or pass _device on the tool call.",
1220
+ status: 409,
1221
+ connectCommand: serveHint
1222
+ });
1223
+ return { status: errRes.status, headers: { "content-type": "application/json" }, body: await errRes.text() };
1224
+ }
1225
+ targetDevice = onlineDevices[0];
1226
+ }
1227
+
1228
+ // 4. Hub-level read-only lock check before crossing the network
1229
+ if (targetDevice.readOnly && mcpMethod === "tools/call" && !READONLY_UPSTREAM_TOOLS.has(mcpName)) {
1230
+ const msg = `Blocked by Tailnet Hub: device "${targetDevice.name}" is locked in read-only mode (call relay_set_device_policy to unlock).`;
1231
+ this.recordAudit({ actor, deviceId: targetDevice.id, deviceName: targetDevice.name, mcpMethod, mcpName, status: 403, durationMs: Date.now() - started, ok: false, error: "Device read-only lock" });
1232
+ return { status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify(jsonRpcPayload(rpc?.id ?? null, msg, true)) };
1233
+ }
1234
+
1235
+ // 5. Route to the target device via its active transport (local, Tailscale HTTP, or WS relay)
1236
+ let res;
1237
+ if (targetDevice.source === "local" && this.localDevice?.localBridge) {
1238
+ res = await this.localDevice.localBridge.forwardRequest({
1239
+ id: crypto.randomUUID(),
1240
+ method,
1241
+ headers,
1242
+ body: forwardedBody,
1243
+ signal,
1244
+ timeoutMs: this.upstreamTimeoutMs,
1245
+ sourceLabel: "hub-local"
1246
+ });
1247
+ } else if (targetDevice.mcpUrl) {
1248
+ res = await this.forwardToHttpPeer(targetDevice, {
1249
+ method,
1250
+ headers,
1251
+ body: forwardedBody,
1252
+ mcpMethod,
1253
+ signal
1254
+ });
1255
+ } else {
1256
+ res = await this.forwardToWsDevice(targetDevice.id, {
1257
+ method,
1258
+ headers,
1259
+ body: forwardedBody,
1260
+ signal
1261
+ });
1262
+ }
1263
+
1264
+ let responseBody = [202, 204].includes(res.status) ? "" : String(res.body || "");
1265
+ const resContentType = res.headers?.["content-type"] || "";
1266
+ if (responseBody && res.status >= 200 && res.status < 300) {
1267
+ if (mcpMethod === "tools/list") {
1268
+ responseBody = injectMetaToolsIntoBody(responseBody, resContentType);
1269
+ } else if (mcpMethod === "initialize" || mcpMethod === "server/discover") {
1270
+ responseBody = enrichInitializeBody(responseBody, resContentType, devices, hubMeta);
1271
+ } else if (mcpMethod === "resources/list") {
1272
+ responseBody = injectRelayResourcesIntoBody(responseBody, resContentType);
1273
+ } else if (mcpMethod === "prompts/list") {
1274
+ responseBody = injectRelayPromptsIntoBody(responseBody, resContentType);
1275
+ }
1276
+ }
1277
+
1278
+ const ok = res.status >= 200 && res.status < 400;
1279
+ this.recordAudit({
1280
+ actor,
1281
+ deviceId: targetDevice.id,
1282
+ deviceName: targetDevice.name,
1283
+ mcpMethod,
1284
+ mcpName,
1285
+ status: res.status || 502,
1286
+ durationMs: Date.now() - started,
1287
+ ok,
1288
+ error: ok ? "" : `HTTP ${res.status || 502}`
1289
+ });
1290
+
1291
+ const outHeaders = { "cache-control": "no-store" };
1292
+ for (const k of ["content-type", "mcp-session-id", "mcp-protocol-version"]) {
1293
+ if (res.headers?.[k]) outHeaders[k] = res.headers[k];
1294
+ }
1295
+ return { status: res.status || 502, headers: outHeaders, body: responseBody };
1296
+ }
1297
+
1298
+ // --- Self-hosted WebSocket Relay compatibility (/relay/* + /admin/*) ---
1299
+
1300
+ handlePairStart(bodyObj, approvalBaseUrl) {
1301
+ const name = sanitizeLabel(bodyObj?.name, "Desktop", 40);
1302
+ const now = Date.now();
1303
+ for (const [k, v] of this.pendingPairs) {
1304
+ if (v.expires < now) this.pendingPairs.delete(k);
1305
+ }
1306
+ if (this.pendingPairs.size > 20) {
1307
+ return { status: 429, body: { error: "Too many pending devices" } };
1308
+ }
1309
+ const id = crypto.randomUUID();
1310
+ const proof = randomHex(32);
1311
+ const code = randomHex(5).toUpperCase();
1312
+ this.pendingPairs.set(id, { id, proof, code, name, expires: now + 3600000, approved: false });
1313
+ return {
1314
+ status: 200,
1315
+ body: {
1316
+ pairId: id,
1317
+ proof,
1318
+ code,
1319
+ approvalUrl: `${approvalBaseUrl}/admin/devices`,
1320
+ expiresIn: 3600
1321
+ }
1322
+ };
1323
+ }
1324
+
1325
+ handlePairPoll(bodyObj) {
1326
+ const r = this.pendingPairs.get(String(bodyObj?.pairId || ""));
1327
+ if (!r || !constantTimeEqual(r.proof, String(bodyObj?.proof || "")) || r.expires < Date.now()) {
1328
+ return { status: 404, body: { error: "Pairing expired" } };
1329
+ }
1330
+ if (!r.approved) return { status: 200, body: { status: "pending" } };
1331
+ this.pendingPairs.delete(r.id);
1332
+ return { status: 200, body: { status: "approved", deviceId: r.deviceId, token: r.token } };
1333
+ }
1334
+
1335
+ approvePair(pairId) {
1336
+ const p = this.pendingPairs.get(String(pairId || ""));
1337
+ if (!p || p.expires < Date.now() || p.approved) return false;
1338
+ const deviceId = crypto.randomUUID();
1339
+ const token = randomHex(32);
1340
+ this.pairedDevices.set(deviceId, {
1341
+ id: deviceId,
1342
+ name: p.name,
1343
+ hash: sha256Hex(token),
1344
+ approvedAt: new Date().toISOString(),
1345
+ readOnly: false
1346
+ });
1347
+ this.pendingPairs.set(p.id, { ...p, approved: true, deviceId, token, expires: Date.now() + 600000 });
1348
+ this.saveState();
1349
+ return true;
1350
+ }
1351
+
1352
+ authenticateWsDevice(headers) {
1353
+ const id = String(headers["x-device-id"] || "");
1354
+ const auth = String(headers["authorization"] || "");
1355
+ if (!id || !/^Bearer [a-f0-9]{64}$/.test(auth)) return null;
1356
+ const dev = this.pairedDevices.get(id);
1357
+ if (!dev) return null;
1358
+ if (!constantTimeEqual(dev.hash, sha256Hex(auth.slice(7)))) return null;
1359
+ return dev;
1360
+ }
1361
+
1362
+ attachWsDevice(ws, device, headers) {
1363
+ const prev = this.wsConnections.get(device.id);
1364
+ if (prev && prev.ws !== ws) {
1365
+ try {
1366
+ prev.ws.close(1000, "Reconnected");
1367
+ } catch {}
1368
+ }
1369
+ const nowIso = new Date().toISOString();
1370
+ const meta = {
1371
+ deviceId: device.id,
1372
+ name: device.name,
1373
+ platform: sanitizeShort(headers["x-device-platform"] || device.platform || "unknown", 24),
1374
+ arch: sanitizeShort(headers["x-device-arch"] || device.arch || "", 16),
1375
+ cliVersion: sanitizeShort(headers["x-device-version"] || device.cliVersion || "", 24),
1376
+ clientMode: sanitizeShort(headers["x-device-mode"] || device.clientMode || "FULL", 24),
1377
+ connectedAt: nowIso
1378
+ };
1379
+ this.pairedDevices.set(device.id, { ...device, ...meta, lastSeen: nowIso });
1380
+ this.saveState();
1381
+ this.wsConnections.set(device.id, { ws, meta });
1382
+
1383
+ ws.on("message", (raw) => {
1384
+ const text = String(raw);
1385
+ if (text === "ping") {
1386
+ try {
1387
+ ws.send("pong");
1388
+ } catch {}
1389
+ return;
1390
+ }
1391
+ let d;
1392
+ try {
1393
+ d = JSON.parse(text);
1394
+ } catch {
1395
+ return;
1396
+ }
1397
+ if (d?.kind === "ping") {
1398
+ try {
1399
+ ws.send(JSON.stringify({ kind: "pong", id: d.id, ts: Date.now() }));
1400
+ } catch {}
1401
+ return;
1402
+ }
1403
+ if (d?.kind === "pong" && d.id && this.wsPings.has(d.id)) {
1404
+ const slot = this.wsPings.get(d.id);
1405
+ if (slot.ws === ws) {
1406
+ this.wsPings.delete(d.id);
1407
+ slot.resolve({
1408
+ uptimeMs: d.uptimeMs,
1409
+ gatewayReady: d.gatewayReady,
1410
+ mode: d.mode,
1411
+ cliVersion: d.version
1412
+ });
1413
+ }
1414
+ return;
1415
+ }
1416
+ const slot = d?.id && this.wsInflight.get(d.id);
1417
+ if (d?.kind === "response" && slot && slot.ws === ws) {
1418
+ this.wsInflight.delete(d.id);
1419
+ slot.resolve({
1420
+ status: Number(d.status) || 500,
1421
+ headers: d.headers || {},
1422
+ body: String(d.body || "")
1423
+ });
1424
+ }
1425
+ });
1426
+
1427
+ const onDisconnect = () => {
1428
+ const current = this.wsConnections.get(device.id);
1429
+ if (current?.ws === ws) this.wsConnections.delete(device.id);
1430
+ for (const [reqId, p] of this.wsInflight) {
1431
+ if (p.ws === ws) {
1432
+ this.wsInflight.delete(reqId);
1433
+ p.resolve({ status: 503, headers: { "content-type": "application/json" }, body: '{"error":"Device disconnected"}' });
1434
+ }
1435
+ }
1436
+ for (const [pingId, p] of this.wsPings) {
1437
+ if (p.ws === ws) {
1438
+ this.wsPings.delete(pingId);
1439
+ p.resolve({ ok: false, error: "Device disconnected" });
1440
+ }
1441
+ }
1442
+ };
1443
+ ws.on("close", onDisconnect);
1444
+ ws.on("error", onDisconnect);
1445
+ }
1446
+
1447
+ renderDashboardHtml(actor, authMode) {
1448
+ const devices = this.getDevicesList();
1449
+ const audits = this.listAudit(30);
1450
+ const now = Date.now();
1451
+ const form = (act, id, label, extra = "") =>
1452
+ `<form action="/admin/${act}" method="post"><input type="hidden" name="id" value="${esc(id)}">${extra}<button>${esc(label)}</button></form>`;
1453
+
1454
+ const pRows =
1455
+ [...this.pendingPairs.values()]
1456
+ .filter((x) => !x.approved && x.expires > now)
1457
+ .map((x) => `<li><b>${esc(x.name)}</b> — 配对码 <code>${esc(x.code)}</code> ${form("approve", x.id, "批准设备")}</li>`)
1458
+ .join("") || "<li>暂无待批准的 WebSocket 设备(Tailscale Serve 节点会自动发现,无需配对)</li>";
1459
+
1460
+ const dRows =
1461
+ devices
1462
+ .map((x) => {
1463
+ const badges = [
1464
+ x.online ? '<span class="b ok">在线</span>' : '<span class="b off">离线</span>',
1465
+ `<span class="b tr">${esc(x.transport || "mesh")}</span>`,
1466
+ x.selected ? '<span class="b sel">当前选中</span>' : "",
1467
+ x.readOnly ? '<span class="b ro">Hub 只读锁定</span>' : "",
1468
+ x.clientMode === "READONLY" ? '<span class="b ro">节点只读</span>' : ""
1469
+ ]
1470
+ .filter(Boolean)
1471
+ .join(" ");
1472
+ const meta = [x.platform, x.arch, x.dnsName || x.ipv4 || "", x.cliVersion ? "v" + x.cliVersion : ""]
1473
+ .filter(Boolean)
1474
+ .join(" · ");
1475
+ return (
1476
+ `<li><div><b>${esc(x.name)}</b> ${badges}<div class="meta">${esc(x.id)} · ${esc(meta)}</div></div>` +
1477
+ `<div class="actions">` +
1478
+ form("select", x.id, "选择此设备") +
1479
+ form("readonly", x.id, x.readOnly ? "解除只读锁定" : "锁定为只读") +
1480
+ form("rename", x.id, "重命名", '<input name="name" placeholder="新名称" maxlength="40">') +
1481
+ (x.source === "ws-relay" ? form("revoke", x.id, "撤销授权") : "") +
1482
+ `</div></li>`
1483
+ );
1484
+ })
1485
+ .join("") || "<li>暂无已发现或已配对的设备</li>";
1486
+
1487
+ const aRows =
1488
+ audits
1489
+ .map(
1490
+ (a) =>
1491
+ `<tr><td>${esc(a.ts.slice(11, 19))}</td><td>${esc(a.deviceName || a.deviceId.slice(0, 8))}</td><td><code>${esc(a.mcpName || a.mcpMethod)}</code></td><td>${a.ok ? "OK" : "ERR"} (${esc(a.status)})</td><td>${esc(a.durationMs)}ms</td><td>${esc(a.actor)}</td></tr>`
1492
+ )
1493
+ .join("") || '<tr><td colspan="6">暂无审计记录</td></tr>';
1494
+
1495
+ return (
1496
+ '<!doctype html><html lang="zh"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
1497
+ "<title>Private Desktop MCP · Tailnet Hub</title>" +
1498
+ "<style>" +
1499
+ "body{font:15px/1.5 system-ui;max-width:920px;margin:2rem auto;padding:1rem;background:#f6f7f9;color:#111}" +
1500
+ "ul{list-style:none;padding:0}li{margin:.8rem 0;padding:1rem;background:#fff;border-radius:12px;box-shadow:0 1px 3px rgba(0,0,0,.06)}" +
1501
+ ".meta{color:#666;font-size:12px;margin-top:.2rem}.actions{margin-top:.6rem;display:flex;flex-wrap:wrap;gap:.4rem;align-items:center}" +
1502
+ "form{display:inline-flex;gap:.3rem;align-items:center}button{padding:.35rem .7rem;border-radius:6px;border:1px solid #ccc;background:#fff;cursor:pointer}" +
1503
+ "input{padding:.3rem .5rem;border-radius:6px;border:1px solid #ccc;width:120px}" +
1504
+ ".b{display:inline-block;padding:.1rem .45rem;border-radius:999px;font-size:12px;margin-left:.3rem}" +
1505
+ ".b.ok{background:#dcfce7;color:#166534}.b.off{background:#e5e7eb;color:#374151}.b.sel{background:#dbeafe;color:#1e40af}.b.ro{background:#fef3c7;color:#92400e}.b.tr{background:#ede9fe;color:#5b21b6}" +
1506
+ ".banner{padding:.6rem .9rem;border-radius:8px;font-size:13px;background:#ecfdf5;color:#065f46}" +
1507
+ "table{width:100%;border-collapse:collapse;background:#fff;border-radius:12px;overflow:hidden;font-size:13px}th,td{padding:.5rem .7rem;border-bottom:1px solid #eee;text-align:left}" +
1508
+ "</style>" +
1509
+ `<h1>Private Desktop MCP · Tailnet Mesh Hub <small>v${esc(this.version)}</small></h1>` +
1510
+ `<p class="banner">认证模式:${esc(authMode)} · 当前身份:${esc(actor)}</p>` +
1511
+ `<h2>待批准(WebSocket 中继设备)</h2><ul>${pRows}</ul>` +
1512
+ `<h2>在线与已知设备(Tailscale 自动发现 + 中继)</h2><ul>${dRows}</ul>` +
1513
+ `<h2>最近调用审计(仅元数据)</h2><table><thead><tr><th>UTC</th><th>设备</th><th>工具/方法</th><th>状态</th><th>耗时</th><th>操作者</th></tr></thead><tbody>${aRows}</tbody></table>` +
1514
+ '<p><a href="/admin/devices">刷新</a></p></html>'
1515
+ );
1516
+ }
1517
+ }
1518
+
1519
+ /**
1520
+ * Starts the Tailnet Mesh Hub HTTP/WS server.
1521
+ * - Default (`exposeTailscale: false`): listens strictly on `127.0.0.1:<port>` (Host + Origin guarded, optional Bearer token).
1522
+ * - Exposed (`exposeTailscale: true`): serves over Tailscale (`serve` HTTPS or `direct` Tailnet IP) with fail-closed Tailscale identity verification.
1523
+ */
1524
+ export async function startTailnetMeshHubServer({
1525
+ hub = null,
1526
+ hubOptions = {},
1527
+ port = DEFAULT_HUB_PORT,
1528
+ exposeTailscale = false,
1529
+ tsStatus = null,
1530
+ preferDirect = false,
1531
+ tsHttpsPort = DEFAULT_TAILSCALE_HTTPS_PORT,
1532
+ tsDirectPort = DEFAULT_TAILSCALE_DIRECT_PORT,
1533
+ allowedUsers = [],
1534
+ allowedTags = [],
1535
+ sharedToken = "",
1536
+ maxRequestBytes = DEFAULT_MAX_REQUEST_BYTES,
1537
+ whoisFn = null,
1538
+ spawnServeFn = spawnTailscaleServe,
1539
+ skipServeSpawn = false,
1540
+ log = logLine
1541
+ } = {}) {
1542
+ const meshHub = hub || new TailnetMeshHub(hubOptions);
1543
+ let mode = "loopback";
1544
+ let bindHost = "127.0.0.1";
1545
+ let listenPort = port;
1546
+ let effectiveTsStatus = tsStatus;
1547
+
1548
+ if (exposeTailscale) {
1549
+ effectiveTsStatus = effectiveTsStatus || getTailscaleStatus();
1550
+ if (!effectiveTsStatus?.running || !effectiveTsStatus?.self) {
1551
+ throw new Error("Tailscale is not running; cannot start Hub with --expose-tailscale.");
1552
+ }
1553
+ const urls = buildTailscaleNodeUrls(effectiveTsStatus, { httpsPort: tsHttpsPort, directPort: tsDirectPort });
1554
+ mode = !preferDirect && urls.httpsEnabled ? "serve" : "direct";
1555
+ bindHost = mode === "serve" ? "127.0.0.1" : effectiveTsStatus.self.ipv4;
1556
+ listenPort = mode === "serve" ? port : tsDirectPort;
1557
+ }
1558
+
1559
+ const resolvedWhois =
1560
+ exposeTailscale ? whoisFn || createWhoIsResolver({ bin: effectiveTsStatus?.bin || "tailscale" }) : null;
1561
+
1562
+ let actualPort = listenPort;
1563
+ let allowedHosts = [];
1564
+ let endpointBase = "";
1565
+ let serveHandle = null;
1566
+
1567
+ const authorizeOwner = async (req, { allowSameOrigin = false } = {}) => {
1568
+ if (exposeTailscale) {
1569
+ return authorizeTailscaleRequest({
1570
+ mode,
1571
+ headers: req.headers,
1572
+ remoteAddress: req.socket?.remoteAddress || "",
1573
+ selfStatus: effectiveTsStatus,
1574
+ allowedUsers,
1575
+ allowedTags,
1576
+ sharedToken,
1577
+ allowedHosts,
1578
+ allowSameOrigin,
1579
+ whoisFn: resolvedWhois
1580
+ });
1581
+ }
1582
+
1583
+ // Strict loopback guard (anti-DNS-rebinding, anti-CSRF, optional Bearer token)
1584
+ if (!isLoopbackIp(req.socket?.remoteAddress || "")) {
1585
+ return { ok: false, status: 403, error: "Forbidden: local hub accepts loopback connections only" };
1586
+ }
1587
+ if (!isAllowedLocalhostHeader(req.headers.host, actualPort)) {
1588
+ return { ok: false, status: 403, error: "Forbidden: invalid Host header" };
1589
+ }
1590
+ if (req.headers.origin) {
1591
+ if (!allowSameOrigin) {
1592
+ return { ok: false, status: 403, error: "Forbidden: browser Origin not allowed on local hub" };
1593
+ }
1594
+ let originHost = "";
1595
+ try {
1596
+ originHost = new URL(req.headers.origin).host.toLowerCase();
1597
+ } catch {
1598
+ originHost = "";
1599
+ }
1600
+ if (!originHost || originHost !== String(req.headers.host || "").trim().toLowerCase()) {
1601
+ return { ok: false, status: 403, error: "Forbidden: cross-origin admin POST rejected" };
1602
+ }
1603
+ }
1604
+ if (sharedToken) {
1605
+ const auth = String(req.headers.authorization || "");
1606
+ const prefix = "Bearer ";
1607
+ if (!auth.startsWith(prefix) || !constantTimeEqual(auth.slice(prefix.length), sharedToken)) {
1608
+ return { ok: false, status: 401, error: "Unauthorized: invalid hub bearer token" };
1609
+ }
1610
+ }
1611
+ return { ok: true, verified: true, transport: "loopback", actor: "local-owner" };
1612
+ };
1613
+
1614
+ const validateRelayTransportBoundary = (req) => {
1615
+ const remote = req.socket?.remoteAddress || "";
1616
+ const host = String(req.headers.host || "").trim().toLowerCase();
1617
+ if (req.headers.origin) {
1618
+ return { ok: false, status: 403, error: "Forbidden: browser Origin not allowed on relay endpoints" };
1619
+ }
1620
+ if (allowedHosts.length > 0 && !allowedHosts.includes(host)) {
1621
+ return { ok: false, status: 403, error: "Forbidden: invalid Host header" };
1622
+ }
1623
+ if (mode === "direct") {
1624
+ if (!isTailscaleIp(remote)) {
1625
+ return { ok: false, status: 403, error: "Forbidden: relay endpoint requires Tailscale source IP" };
1626
+ }
1627
+ } else if (!isLoopbackIp(remote)) {
1628
+ return { ok: false, status: 403, error: "Forbidden: relay endpoint requires loopback transport" };
1629
+ }
1630
+ return { ok: true };
1631
+ };
1632
+
1633
+ const wss = new WebSocketServer({ noServer: true });
1634
+
1635
+ const server = http.createServer(async (req, res) => {
1636
+ const parsedUrl = new URL(req.url || "/", "http://localhost");
1637
+ const pathname = parsedUrl.pathname;
1638
+ const method = req.method || "GET";
1639
+
1640
+ try {
1641
+ // Relay compatibility endpoints for push-WS devices
1642
+ if (pathname === "/relay/status" && method === "GET") {
1643
+ const boundary = validateRelayTransportBoundary(req);
1644
+ if (!boundary.ok) {
1645
+ sendJson(res, boundary.status, { error: boundary.error });
1646
+ return;
1647
+ }
1648
+ sendJson(res, 200, {
1649
+ ok: true,
1650
+ kind: "tailscale-mesh-hub",
1651
+ version: meshHub.version,
1652
+ protocol: HUB_PROTOCOL_VERSION,
1653
+ features: [
1654
+ "tailscale-discovery",
1655
+ "heartbeat",
1656
+ "meta-tools",
1657
+ "device-targeting",
1658
+ "cancel",
1659
+ "audit",
1660
+ "readonly-lock",
1661
+ "agent-native-discovery",
1662
+ "mcp-resources",
1663
+ "mcp-prompts",
1664
+ "self-healing-errors"
1665
+ ]
1666
+ });
1667
+ return;
1668
+ }
1669
+
1670
+ if (pathname === "/relay/pair/start" && method === "POST") {
1671
+ const boundary = validateRelayTransportBoundary(req);
1672
+ if (!boundary.ok) {
1673
+ sendJson(res, boundary.status, { error: boundary.error });
1674
+ return;
1675
+ }
1676
+ const raw = await readIncomingBody(req, 65536);
1677
+ const bodyObj = JSON.parse(raw || "{}");
1678
+ const out = meshHub.handlePairStart(bodyObj, endpointBase);
1679
+ sendJson(res, out.status, out.body);
1680
+ return;
1681
+ }
1682
+
1683
+ if (pathname === "/relay/pair/poll" && method === "POST") {
1684
+ const boundary = validateRelayTransportBoundary(req);
1685
+ if (!boundary.ok) {
1686
+ sendJson(res, boundary.status, { error: boundary.error });
1687
+ return;
1688
+ }
1689
+ const raw = await readIncomingBody(req, 65536);
1690
+ const bodyObj = JSON.parse(raw || "{}");
1691
+ const out = meshHub.handlePairPoll(bodyObj);
1692
+ sendJson(res, out.status, out.body);
1693
+ return;
1694
+ }
1695
+
1696
+ // Owner-protected endpoints: /healthz, /mcp, /admin/*
1697
+ const isAdmin = pathname.startsWith("/admin/");
1698
+ const auth = await authorizeOwner(req, { allowSameOrigin: isAdmin && method === "POST" });
1699
+ if (!auth.ok) {
1700
+ sendJson(res, auth.status || 403, { error: auth.error });
1701
+ return;
1702
+ }
1703
+
1704
+ if (pathname === "/healthz" && method === "GET") {
1705
+ const devices = meshHub.getDevicesList();
1706
+ sendJson(res, 200, {
1707
+ ok: true,
1708
+ kind: "tailscale-mesh-hub",
1709
+ mode,
1710
+ onlineCount: devices.filter((d) => d.online).length,
1711
+ deviceCount: devices.length
1712
+ });
1713
+ return;
1714
+ }
1715
+
1716
+ if (pathname === "/mcp") {
1717
+ if (method === "GET") {
1718
+ res.writeHead(405, { allow: "POST, DELETE", "cache-control": "no-store" });
1719
+ res.end("POST/DELETE only");
1720
+ return;
1721
+ }
1722
+ if (method !== "POST" && method !== "DELETE") {
1723
+ res.writeHead(405, { allow: "POST, DELETE", "cache-control": "no-store" });
1724
+ res.end("Method not allowed");
1725
+ return;
1726
+ }
1727
+
1728
+ const body = method === "DELETE" ? "" : await readIncomingBody(req, maxRequestBytes);
1729
+ const ac = new AbortController();
1730
+ const onClose = () => {
1731
+ if (!res.writableEnded) {
1732
+ try {
1733
+ ac.abort(new Error("Client aborted"));
1734
+ } catch {}
1735
+ }
1736
+ };
1737
+ res.on("close", onClose);
1738
+ try {
1739
+ const out = await meshHub.handleMcpRequest({
1740
+ method,
1741
+ headers: req.headers,
1742
+ body,
1743
+ actor: auth.actor,
1744
+ authMeta: auth,
1745
+ signal: ac.signal
1746
+ });
1747
+ if (!res.writableEnded) {
1748
+ res.writeHead(out.status || 200, { "cache-control": "no-store", ...(out.headers || {}) });
1749
+ if (out.status === 202 || out.status === 204) res.end();
1750
+ else res.end(out.body || "");
1751
+ }
1752
+ } finally {
1753
+ res.off("close", onClose);
1754
+ }
1755
+ return;
1756
+ }
1757
+
1758
+ if (pathname === "/admin/devices" && method === "GET") {
1759
+ await meshHub.refreshDiscovery();
1760
+ sendHtml(res, 200, meshHub.renderDashboardHtml(auth.actor, auth.transport));
1761
+ return;
1762
+ }
1763
+
1764
+ if (isAdmin && method === "POST") {
1765
+ const raw = await readIncomingBody(req, 65536);
1766
+ const ct = String(req.headers["content-type"] || "");
1767
+ const params = ct.includes("form-urlencoded")
1768
+ ? Object.fromEntries(new URLSearchParams(raw))
1769
+ : JSON.parse(raw || "{}");
1770
+ const id = String(params.id || "");
1771
+
1772
+ if (pathname === "/admin/approve") {
1773
+ if (!meshHub.approvePair(id)) {
1774
+ res.writeHead(400).end("Expired");
1775
+ return;
1776
+ }
1777
+ } else if (pathname === "/admin/select") {
1778
+ if (!meshHub.getDevicesList().some((d) => d.id === id)) {
1779
+ res.writeHead(404).end("Unknown");
1780
+ return;
1781
+ }
1782
+ meshHub.selectedDeviceId = id;
1783
+ meshHub.saveState();
1784
+ } else if (pathname === "/admin/readonly") {
1785
+ const current = meshHub.getDevicesList().find((d) => d.id === id);
1786
+ if (!current) {
1787
+ res.writeHead(404).end("Unknown");
1788
+ return;
1789
+ }
1790
+ const ov = meshHub.policyOverrides.get(id) || {};
1791
+ meshHub.policyOverrides.set(id, { ...ov, readOnly: !current.readOnly });
1792
+ meshHub.saveState();
1793
+ } else if (pathname === "/admin/rename") {
1794
+ const current = meshHub.getDevicesList().find((d) => d.id === id);
1795
+ if (!current) {
1796
+ res.writeHead(404).end("Unknown");
1797
+ return;
1798
+ }
1799
+ const ov = meshHub.policyOverrides.get(id) || {};
1800
+ const nextName = sanitizeLabel(params.name, current.name || "Device", 40);
1801
+ meshHub.policyOverrides.set(id, { ...ov, name: nextName });
1802
+ meshHub.saveState();
1803
+ } else if (pathname === "/admin/revoke") {
1804
+ meshHub.pairedDevices.delete(id);
1805
+ if (meshHub.selectedDeviceId === id) meshHub.selectedDeviceId = "";
1806
+ const conn = meshHub.wsConnections.get(id);
1807
+ if (conn) {
1808
+ try {
1809
+ conn.ws.close(1008, "Revoked");
1810
+ } catch {}
1811
+ }
1812
+ meshHub.saveState();
1813
+ } else {
1814
+ sendJson(res, 404, { error: "Not found" });
1815
+ return;
1816
+ }
1817
+ res.writeHead(303, { location: "/admin/devices" }).end();
1818
+ return;
1819
+ }
1820
+
1821
+ sendJson(res, 404, { error: "Not found" });
1822
+ } catch (err) {
1823
+ sendJson(res, err?.statusCode || 500, { error: String(err?.message || err).slice(0, 180) });
1824
+ }
1825
+ });
1826
+
1827
+ server.on("upgrade", (req, socket, head) => {
1828
+ const pathname = new URL(req.url || "/", "http://localhost").pathname;
1829
+ if (pathname !== "/relay/ws") {
1830
+ socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
1831
+ socket.destroy();
1832
+ return;
1833
+ }
1834
+ const boundary = validateRelayTransportBoundary(req);
1835
+ if (!boundary.ok) {
1836
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
1837
+ socket.destroy();
1838
+ return;
1839
+ }
1840
+ const dev = meshHub.authenticateWsDevice(req.headers);
1841
+ if (!dev) {
1842
+ socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
1843
+ socket.destroy();
1844
+ return;
1845
+ }
1846
+ wss.handleUpgrade(req, socket, head, (ws) => {
1847
+ meshHub.attachWsDevice(ws, dev, req.headers);
1848
+ });
1849
+ });
1850
+
1851
+ await new Promise((resolve, reject) => {
1852
+ server.once("error", reject);
1853
+ server.listen(listenPort, bindHost, () => {
1854
+ server.off("error", reject);
1855
+ resolve();
1856
+ });
1857
+ });
1858
+
1859
+ const addr = server.address();
1860
+ actualPort = typeof addr === "object" && addr ? addr.port : listenPort;
1861
+
1862
+ if (exposeTailscale && effectiveTsStatus?.self) {
1863
+ const dns = stripTrailingDot(effectiveTsStatus.self.dnsName || "").toLowerCase();
1864
+ const shortHost = String(effectiveTsStatus.self.hostName || "").trim().toLowerCase();
1865
+ const ipv4 = String(effectiveTsStatus.self.ipv4 || "").trim();
1866
+ const hostSet = new Set();
1867
+ if (mode === "serve") {
1868
+ hostSet.add(`127.0.0.1:${actualPort}`);
1869
+ hostSet.add(`localhost:${actualPort}`);
1870
+ hostSet.add(`[::1]:${actualPort}`);
1871
+ if (dns) {
1872
+ hostSet.add(dns);
1873
+ hostSet.add(`${dns}:${tsHttpsPort}`);
1874
+ }
1875
+ if (shortHost) {
1876
+ hostSet.add(shortHost);
1877
+ hostSet.add(`${shortHost}:${tsHttpsPort}`);
1878
+ }
1879
+ if (ipv4) {
1880
+ hostSet.add(ipv4);
1881
+ hostSet.add(`${ipv4}:${tsHttpsPort}`);
1882
+ }
1883
+ const urls = buildTailscaleNodeUrls(effectiveTsStatus, { httpsPort: tsHttpsPort, directPort: tsDirectPort });
1884
+ endpointBase = urls.httpsBase || `http://127.0.0.1:${actualPort}`;
1885
+ if (!skipServeSpawn) {
1886
+ let earlyExit = null;
1887
+ serveHandle = spawnServeFn({
1888
+ bin: effectiveTsStatus.bin || "tailscale",
1889
+ localPort: actualPort,
1890
+ httpsPort: tsHttpsPort,
1891
+ onLog: log,
1892
+ onExit: (code) => {
1893
+ earlyExit = code;
1894
+ }
1895
+ });
1896
+ await new Promise((r) => setTimeout(r, 350));
1897
+ if (earlyExit !== null && earlyExit !== 0) {
1898
+ await new Promise((r) => server.close(() => r()));
1899
+ throw new Error(
1900
+ `tailscale serve failed for hub (exit ${earlyExit}). Enable Tailscale Serve/HTTPS in your tailnet or pass --ts-direct.`
1901
+ );
1902
+ }
1903
+ }
1904
+ } else {
1905
+ hostSet.add(`${bindHost}:${actualPort}`);
1906
+ if (dns) hostSet.add(`${dns}:${actualPort}`);
1907
+ if (shortHost) hostSet.add(`${shortHost}:${actualPort}`);
1908
+ endpointBase = `http://${bindHost}:${actualPort}`;
1909
+ }
1910
+ allowedHosts = [...hostSet];
1911
+ } else {
1912
+ endpointBase = `http://127.0.0.1:${actualPort}`;
1913
+ allowedHosts = [`127.0.0.1:${actualPort}`, `localhost:${actualPort}`, `[::1]:${actualPort}`];
1914
+ }
1915
+
1916
+ // Trigger initial Tailscale peer discovery before advertising readiness
1917
+ await meshHub.refreshDiscovery({ force: true });
1918
+
1919
+ const close = async () => {
1920
+ try {
1921
+ serveHandle?.stop();
1922
+ } catch {}
1923
+ for (const { ws } of meshHub.wsConnections.values()) {
1924
+ try {
1925
+ ws.close(1001, "Hub shutting down");
1926
+ } catch {}
1927
+ }
1928
+ try {
1929
+ wss.close();
1930
+ } catch {}
1931
+ await new Promise((resolve) => {
1932
+ try {
1933
+ server.close(() => resolve());
1934
+ } catch {
1935
+ resolve();
1936
+ }
1937
+ });
1938
+ };
1939
+
1940
+ return {
1941
+ hub: meshHub,
1942
+ server,
1943
+ mode,
1944
+ bindHost,
1945
+ port: actualPort,
1946
+ endpointBase,
1947
+ endpointUrl: `${endpointBase}/mcp`,
1948
+ adminUrl: `${endpointBase}/admin/devices`,
1949
+ close
1950
+ };
1951
+ }