@juexibobi/private-desktop-mcp 0.5.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.
- package/AGENTS.md +41 -20
- package/README.md +52 -6
- package/bin/cli.mjs +581 -269
- package/bin/client-setup.mjs +40 -10
- package/bin/local-bridge.mjs +251 -0
- package/bin/logging.mjs +5 -1
- package/bin/policy.mjs +1 -1
- package/bin/proxy.mjs +44 -0
- package/bin/tailscale-hub.mjs +1951 -0
- package/bin/tailscale-node.mjs +351 -0
- package/bin/tailscale.mjs +605 -0
- package/core/mcp-hub.mjs +459 -0
- package/docs/agent-install.md +22 -1
- package/package.json +8 -3
- package/skills/private-desktop-mcp/SKILL.md +7 -2
package/bin/cli.mjs
CHANGED
|
@@ -9,33 +9,26 @@ import WebSocket from "ws";
|
|
|
9
9
|
import { ProxyAgent } from "undici";
|
|
10
10
|
import { HttpsProxyAgent } from "https-proxy-agent";
|
|
11
11
|
import { resolveProxyForUrl } from "./proxy.mjs";
|
|
12
|
-
import { logLine, sanitizeText } from "./logging.mjs";
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
requestDebug,
|
|
17
|
-
responseBrief,
|
|
18
|
-
safeTraceRequest,
|
|
19
|
-
safeTraceOutput,
|
|
20
|
-
shortCallId,
|
|
21
|
-
formatElapsed,
|
|
22
|
-
loggingOptions
|
|
23
|
-
} from "./activity.mjs";
|
|
24
|
-
import {
|
|
25
|
-
createPolicy,
|
|
26
|
-
evaluateToolCall,
|
|
27
|
-
filterToolsListBody,
|
|
28
|
-
redactOutboundResponse,
|
|
29
|
-
buildPolicyBlockedResponse
|
|
30
|
-
} from "./policy.mjs";
|
|
12
|
+
import { logLine, sanitizeText, setStdoutMode } from "./logging.mjs";
|
|
13
|
+
import { shortCallId, formatElapsed, loggingOptions } from "./activity.mjs";
|
|
14
|
+
import { createPolicy } from "./policy.mjs";
|
|
15
|
+
import { createLocalBridge } from "./local-bridge.mjs";
|
|
31
16
|
import { SUPPORTED_CLIENTS, configureMcpClient } from "./client-setup.mjs";
|
|
17
|
+
import {
|
|
18
|
+
DEFAULT_TAILSCALE_HTTPS_PORT,
|
|
19
|
+
DEFAULT_TAILSCALE_DIRECT_PORT,
|
|
20
|
+
getTailscaleStatus,
|
|
21
|
+
buildTailscaleNodeUrls
|
|
22
|
+
} from "./tailscale.mjs";
|
|
23
|
+
import { startTailscaleNodeServer } from "./tailscale-node.mjs";
|
|
24
|
+
import { DEFAULT_HUB_PORT, startTailnetMeshHubServer } from "./tailscale-hub.mjs";
|
|
32
25
|
|
|
33
26
|
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
34
27
|
const PKG_VERSION = (() => {
|
|
35
28
|
try {
|
|
36
|
-
return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.
|
|
29
|
+
return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.6.0";
|
|
37
30
|
} catch {
|
|
38
|
-
return "0.
|
|
31
|
+
return "0.6.0";
|
|
39
32
|
}
|
|
40
33
|
})();
|
|
41
34
|
|
|
@@ -43,11 +36,35 @@ const DEFAULT_RELAY = "https://private-desktop-device-relay.ljx2043979076.worker
|
|
|
43
36
|
const HEARTBEAT_INTERVAL_MS = 25000;
|
|
44
37
|
const MAX_GATEWAY_LOG_BYTES = 5 * 1024 * 1024;
|
|
45
38
|
|
|
39
|
+
function parseCsvList(raw) {
|
|
40
|
+
return String(raw || "")
|
|
41
|
+
.split(",")
|
|
42
|
+
.map((s) => s.trim())
|
|
43
|
+
.filter(Boolean);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
46
|
function parseArgs(argv) {
|
|
47
47
|
let command = "";
|
|
48
48
|
let subarg = "";
|
|
49
49
|
let relay = process.env.PCC_RELAY_URL || DEFAULT_RELAY;
|
|
50
|
+
let relayExplicit = Boolean(process.env.PCC_RELAY_URL);
|
|
51
|
+
let transport = String(process.env.PCC_TRANSPORT || "").trim().toLowerCase();
|
|
50
52
|
let port = Number(process.env.MCP_PORT || 8717);
|
|
53
|
+
let hubPort = Number(process.env.PCC_HUB_PORT || DEFAULT_HUB_PORT);
|
|
54
|
+
let tsHttpsPort = Number(process.env.PCC_TS_HTTPS_PORT || DEFAULT_TAILSCALE_HTTPS_PORT);
|
|
55
|
+
let tsDirectPort = Number(process.env.PCC_TS_PORT || DEFAULT_TAILSCALE_DIRECT_PORT);
|
|
56
|
+
let tsDirect = /^(1|true|yes)$/i.test(String(process.env.PCC_TS_DIRECT || ""));
|
|
57
|
+
let exposeTailscale = false;
|
|
58
|
+
let setupTailscale = false;
|
|
59
|
+
let setupHub = false;
|
|
60
|
+
let withLocal = false;
|
|
61
|
+
let includeSelf = false;
|
|
62
|
+
let discoverTailscale = true;
|
|
63
|
+
let allowAllTailnetPeers = false;
|
|
64
|
+
let defaultDevice = process.env.PCC_DEFAULT_DEVICE || "";
|
|
65
|
+
let sharedToken = process.env.PCC_TAILSCALE_TOKEN || "";
|
|
66
|
+
let peerToken = process.env.PCC_PEER_TOKEN || "";
|
|
67
|
+
let serverName = "";
|
|
51
68
|
let deviceName = os.hostname();
|
|
52
69
|
let readonly = /^(1|true|yes)$/i.test(String(process.env.PCC_READONLY || ""));
|
|
53
70
|
let dlp = !/^(0|false|no)$/i.test(String(process.env.PCC_DLP || "true"));
|
|
@@ -61,14 +78,12 @@ function parseArgs(argv) {
|
|
|
61
78
|
.split(path.delimiter)
|
|
62
79
|
.map((s) => s.trim())
|
|
63
80
|
.filter(Boolean);
|
|
64
|
-
const allowTools =
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
.map((s) => s.trim())
|
|
71
|
-
.filter(Boolean);
|
|
81
|
+
const allowTools = parseCsvList(process.env.PCC_ALLOW_TOOLS);
|
|
82
|
+
const denyTools = parseCsvList(process.env.PCC_DENY_TOOLS);
|
|
83
|
+
const allowTsUsers = parseCsvList(process.env.PCC_ALLOW_TS_USERS);
|
|
84
|
+
const allowTsTags = parseCsvList(process.env.PCC_ALLOW_TS_TAGS);
|
|
85
|
+
const peerTags = parseCsvList(process.env.PCC_PEER_TAGS);
|
|
86
|
+
const staticPeers = parseCsvList(process.env.PCC_PEERS);
|
|
72
87
|
|
|
73
88
|
for (let i = 0; i < argv.length; i++) {
|
|
74
89
|
const arg = argv[i];
|
|
@@ -83,8 +98,31 @@ function parseArgs(argv) {
|
|
|
83
98
|
const nextVal = () => (inlineVal !== null ? inlineVal : argv[++i] || "");
|
|
84
99
|
|
|
85
100
|
if (flag === "--help" || flag === "-h") command = "help";
|
|
86
|
-
else if (flag === "--relay")
|
|
87
|
-
|
|
101
|
+
else if (flag === "--relay") {
|
|
102
|
+
relay = nextVal().replace(/\/+$/, "");
|
|
103
|
+
relayExplicit = true;
|
|
104
|
+
} else if (flag === "--transport") transport = nextVal().trim().toLowerCase();
|
|
105
|
+
else if (flag === "--tailscale") {
|
|
106
|
+
if (!transport) transport = "tailscale";
|
|
107
|
+
setupTailscale = true;
|
|
108
|
+
} else if (flag === "--hybrid") {
|
|
109
|
+
transport = "hybrid";
|
|
110
|
+
} else if (flag === "--hub") {
|
|
111
|
+
setupHub = true;
|
|
112
|
+
} else if (flag === "--port") port = Number(nextVal());
|
|
113
|
+
else if (flag === "--hub-port") hubPort = Number(nextVal());
|
|
114
|
+
else if (flag === "--ts-https-port") tsHttpsPort = Number(nextVal());
|
|
115
|
+
else if (flag === "--ts-port") tsDirectPort = Number(nextVal());
|
|
116
|
+
else if (flag === "--ts-direct") tsDirect = true;
|
|
117
|
+
else if (flag === "--expose-tailscale") exposeTailscale = true;
|
|
118
|
+
else if (flag === "--with-local") withLocal = true;
|
|
119
|
+
else if (flag === "--include-self") includeSelf = true;
|
|
120
|
+
else if (flag === "--no-discover") discoverTailscale = false;
|
|
121
|
+
else if (flag === "--allow-all-tailnet-peers") allowAllTailnetPeers = true;
|
|
122
|
+
else if (flag === "--default-device") defaultDevice = nextVal();
|
|
123
|
+
else if (flag === "--token") sharedToken = nextVal();
|
|
124
|
+
else if (flag === "--peer-token") peerToken = nextVal();
|
|
125
|
+
else if (flag === "--server-name") serverName = nextVal();
|
|
88
126
|
else if (flag === "--name") deviceName = nextVal();
|
|
89
127
|
else if (flag === "--readonly") readonly = true;
|
|
90
128
|
else if (flag === "--no-dlp") dlp = false;
|
|
@@ -101,14 +139,44 @@ function parseArgs(argv) {
|
|
|
101
139
|
for (const item of nextVal().split(",")) if (item.trim()) allowTools.push(item.trim());
|
|
102
140
|
} else if (flag === "--deny-tools") {
|
|
103
141
|
for (const item of nextVal().split(",")) if (item.trim()) denyTools.push(item.trim());
|
|
142
|
+
} else if (flag === "--allow-ts-user") {
|
|
143
|
+
for (const item of nextVal().split(",")) if (item.trim()) allowTsUsers.push(item.trim());
|
|
144
|
+
} else if (flag === "--allow-ts-tag") {
|
|
145
|
+
for (const item of nextVal().split(",")) if (item.trim()) allowTsTags.push(item.trim());
|
|
146
|
+
} else if (flag === "--peer-tag") {
|
|
147
|
+
for (const item of nextVal().split(",")) if (item.trim()) peerTags.push(item.trim());
|
|
148
|
+
} else if (flag === "--peer") {
|
|
149
|
+
const v = nextVal().trim();
|
|
150
|
+
if (v) staticPeers.push(v);
|
|
104
151
|
}
|
|
105
152
|
}
|
|
106
153
|
|
|
154
|
+
const resolvedCommand = command || "connect";
|
|
155
|
+
const resolvedTransport =
|
|
156
|
+
transport || (resolvedCommand === "serve" ? "tailscale" : "cloudflare");
|
|
157
|
+
|
|
107
158
|
return {
|
|
108
|
-
command:
|
|
159
|
+
command: resolvedCommand,
|
|
109
160
|
subarg,
|
|
110
161
|
relay: relay.replace(/\/+$/, ""),
|
|
162
|
+
relayExplicit,
|
|
163
|
+
transport: resolvedTransport,
|
|
111
164
|
port,
|
|
165
|
+
hubPort,
|
|
166
|
+
tsHttpsPort,
|
|
167
|
+
tsDirectPort,
|
|
168
|
+
tsDirect,
|
|
169
|
+
exposeTailscale,
|
|
170
|
+
setupTailscale,
|
|
171
|
+
setupHub,
|
|
172
|
+
withLocal,
|
|
173
|
+
includeSelf,
|
|
174
|
+
discoverTailscale,
|
|
175
|
+
allowAllTailnetPeers,
|
|
176
|
+
defaultDevice,
|
|
177
|
+
sharedToken,
|
|
178
|
+
peerToken: peerToken || sharedToken,
|
|
179
|
+
serverName,
|
|
112
180
|
deviceName: deviceName || "Desktop",
|
|
113
181
|
readonly,
|
|
114
182
|
dlp,
|
|
@@ -120,14 +188,21 @@ function parseArgs(argv) {
|
|
|
120
188
|
serversConfig,
|
|
121
189
|
allowDirs,
|
|
122
190
|
allowTools,
|
|
123
|
-
denyTools
|
|
191
|
+
denyTools,
|
|
192
|
+
allowTsUsers,
|
|
193
|
+
allowTsTags,
|
|
194
|
+
peerTags,
|
|
195
|
+
staticPeers
|
|
124
196
|
};
|
|
125
197
|
}
|
|
126
198
|
|
|
127
199
|
const opts = parseArgs(process.argv.slice(2));
|
|
200
|
+
// In --json mode stdout is a machine-readable event stream; every human diagnostic goes to stderr.
|
|
201
|
+
setStdoutMode(opts.json ? "json" : "text");
|
|
128
202
|
const { trace, debug } = loggingOptions(process.argv.slice(2));
|
|
129
203
|
const configDir = path.join(process.env.APPDATA || path.join(os.homedir(), ".config"), "PrivateDesktopMCP");
|
|
130
204
|
const config = path.join(configDir, "device.json");
|
|
205
|
+
const hubStatePath = path.join(configDir, "hub-state.json");
|
|
131
206
|
const gatewayLogDir = path.join(configDir, "logs");
|
|
132
207
|
const gatewayLogPath = path.join(gatewayLogDir, "gateway.log");
|
|
133
208
|
const localBaseUrl = `http://127.0.0.1:${opts.port}/mcp`;
|
|
@@ -180,6 +255,8 @@ let gatewayHealthy = false;
|
|
|
180
255
|
let gatewayRestartCount = 0;
|
|
181
256
|
let gatewayRestartPromise = null;
|
|
182
257
|
let socket = null;
|
|
258
|
+
let tailscaleNodeHandle = null;
|
|
259
|
+
let tailnetHubHandle = null;
|
|
183
260
|
let activeCreds = null;
|
|
184
261
|
let connectionAttempt = 0;
|
|
185
262
|
let connectedSince = 0;
|
|
@@ -190,6 +267,25 @@ let allFails = 0;
|
|
|
190
267
|
let lastError = "";
|
|
191
268
|
const inflightControllers = new Map();
|
|
192
269
|
|
|
270
|
+
const localBridge = createLocalBridge({
|
|
271
|
+
localBaseUrl,
|
|
272
|
+
localGatewayToken,
|
|
273
|
+
policy,
|
|
274
|
+
isGatewayHealthy: () => gatewayHealthy,
|
|
275
|
+
getExtraSecrets: () => [activeCreds?.token || "", opts.sharedToken || "", opts.peerToken || ""],
|
|
276
|
+
debug,
|
|
277
|
+
trace,
|
|
278
|
+
inflightControllers,
|
|
279
|
+
onStats: ({ failed }) => {
|
|
280
|
+
allCalls++;
|
|
281
|
+
sessionCalls++;
|
|
282
|
+
if (failed) {
|
|
283
|
+
allFails++;
|
|
284
|
+
sessionFails++;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
|
|
193
289
|
function saved() {
|
|
194
290
|
try {
|
|
195
291
|
return JSON.parse(fs.readFileSync(config, "utf8"));
|
|
@@ -243,11 +339,19 @@ function tryOpenBrowser(url) {
|
|
|
243
339
|
} catch {}
|
|
244
340
|
}
|
|
245
341
|
|
|
246
|
-
function reportDevice(creds) {
|
|
342
|
+
function reportDevice(creds, { tsNode = null } = {}) {
|
|
247
343
|
logLine("info", "━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
|
|
248
344
|
logLine("info", "Computer: " + opts.deviceName + " | User: " + os.userInfo().username + " | Node: " + process.version);
|
|
249
|
-
|
|
250
|
-
|
|
345
|
+
if (creds?.deviceId) {
|
|
346
|
+
logLine("info", "Device ID: " + creds.deviceId + " | Gateway PID: " + (child?.pid || "unknown"));
|
|
347
|
+
logLine("info", "Cloudflare Relay: " + opts.relay);
|
|
348
|
+
} else {
|
|
349
|
+
logLine("info", "Gateway PID: " + (child?.pid || "unknown"));
|
|
350
|
+
}
|
|
351
|
+
if (tsNode) {
|
|
352
|
+
logLine("info", `Tailscale Node (${tsNode.mode}): ${tsNode.endpointUrl}`);
|
|
353
|
+
}
|
|
354
|
+
logLine("info", "Local MCP: " + localBaseUrl + " (Bearer+Host protected)");
|
|
251
355
|
logLine(
|
|
252
356
|
"info",
|
|
253
357
|
"Mode: " +
|
|
@@ -443,152 +547,26 @@ function stopGateway() {
|
|
|
443
547
|
}
|
|
444
548
|
|
|
445
549
|
async function respond(ws, msg) {
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
} catch {
|
|
462
|
-
parsedRpc = null;
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
// Enforce local tool policy before forwarding to gateway
|
|
466
|
-
if (parsedRpc) {
|
|
467
|
-
const verdict = evaluateToolCall(parsedRpc, policy);
|
|
468
|
-
if (!verdict.allowed) {
|
|
469
|
-
allFails++;
|
|
470
|
-
sessionFails++;
|
|
471
|
-
logLine("warn", "🛡️ [" + callId + "] Policy blocked " + name + ": " + verdict.reason);
|
|
472
|
-
const blockedResp = {
|
|
473
|
-
kind: "response",
|
|
474
|
-
id: msg.id,
|
|
475
|
-
status: 200,
|
|
476
|
-
headers: { "content-type": "application/json" },
|
|
477
|
-
body: buildPolicyBlockedResponse(parsedRpc.id, verdict.reason)
|
|
478
|
-
};
|
|
479
|
-
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(blockedResp));
|
|
480
|
-
return;
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
if (!gatewayHealthy) {
|
|
485
|
-
allFails++;
|
|
486
|
-
sessionFails++;
|
|
487
|
-
const unavailable = {
|
|
488
|
-
kind: "response",
|
|
489
|
-
id: msg.id,
|
|
490
|
-
status: 503,
|
|
491
|
-
headers: { "content-type": "application/json" },
|
|
492
|
-
body: JSON.stringify({ error: "Local MCP gateway is currently restarting; retry shortly." })
|
|
493
|
-
};
|
|
494
|
-
logLine("error", "❌ [" + callId + "] " + name + " | Local gateway unavailable");
|
|
495
|
-
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(unavailable));
|
|
496
|
-
return;
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
const headers = { authorization: "Bearer " + localGatewayToken };
|
|
500
|
-
for (const k of ["accept", "content-type", "mcp-session-id", "mcp-protocol-version", "last-event-id", "mcp-method", "mcp-name"]) {
|
|
501
|
-
if (msg.headers?.[k]) headers[k] = msg.headers[k];
|
|
502
|
-
}
|
|
503
|
-
if (parsedRpc && typeof parsedRpc.method === "string") {
|
|
504
|
-
headers["mcp-method"] = parsedRpc.method;
|
|
505
|
-
if (parsedRpc.method === "tools/call" && typeof parsedRpc.params?.name === "string") {
|
|
506
|
-
headers["mcp-name"] = parsedRpc.params.name;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
const controller = new AbortController();
|
|
511
|
-
const timeout = setTimeout(() => controller.abort(new Error("Local gateway timeout (70s)")), 70000);
|
|
512
|
-
inflightControllers.set(msg.id, controller);
|
|
513
|
-
|
|
514
|
-
let response;
|
|
515
|
-
try {
|
|
516
|
-
const fetchOpts = {
|
|
517
|
-
method: msg.method || "POST",
|
|
518
|
-
headers,
|
|
519
|
-
signal: controller.signal
|
|
520
|
-
};
|
|
521
|
-
if (fetchOpts.method !== "DELETE" && fetchOpts.method !== "GET" && fetchOpts.method !== "HEAD") {
|
|
522
|
-
fetchOpts.body = msg.body;
|
|
523
|
-
}
|
|
524
|
-
const r = await fetch(localBaseUrl, fetchOpts);
|
|
525
|
-
let body = await r.text();
|
|
526
|
-
const forward = {};
|
|
527
|
-
for (const k of ["content-type", "mcp-session-id", "mcp-protocol-version"]) {
|
|
528
|
-
if (r.headers.has(k)) forward[k] = r.headers.get(k);
|
|
529
|
-
}
|
|
530
|
-
const ct = forward["content-type"] || "";
|
|
531
|
-
|
|
532
|
-
// Filter disallowed tools from tools/list responses
|
|
533
|
-
if (call.method === "tools/list" && r.ok) {
|
|
534
|
-
body = filterToolsListBody(body, ct, policy);
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
// Outbound DLP secret redaction
|
|
538
|
-
const dlpResult = redactOutboundResponse(body, ct, {
|
|
539
|
-
enabled: policy.dlp,
|
|
540
|
-
extraSecrets: [activeCreds?.token || "", localGatewayToken]
|
|
541
|
-
});
|
|
542
|
-
if (dlpResult.redactedCount > 0) {
|
|
543
|
-
logLine("warn", `🛡️ [${callId}] DLP redacted ${dlpResult.redactedCount} secret(s) before returning response to relay`);
|
|
544
|
-
body = dlpResult.body;
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
response = { kind: "response", id: msg.id, status: r.status, headers: forward, body: body.slice(0, 8 * 1024 * 1024) };
|
|
548
|
-
} catch (e) {
|
|
549
|
-
const aborted = controller.signal.aborted;
|
|
550
|
-
const reason = controller.signal.reason?.message || e.message || "Local gateway error";
|
|
551
|
-
response = {
|
|
552
|
-
kind: "response",
|
|
553
|
-
id: msg.id,
|
|
554
|
-
status: aborted && /client/i.test(reason) ? 499 : 502,
|
|
555
|
-
headers: { "content-type": "application/json" },
|
|
556
|
-
body: JSON.stringify({ error: "Local gateway error", message: String(reason).slice(0, 180) })
|
|
557
|
-
};
|
|
558
|
-
} finally {
|
|
559
|
-
clearTimeout(timeout);
|
|
560
|
-
inflightControllers.delete(msg.id);
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
const result = responseBrief(response.body, response.headers?.["content-type"] || "", response.status);
|
|
564
|
-
const failed = result.failed;
|
|
565
|
-
if (failed) {
|
|
566
|
-
allFails++;
|
|
567
|
-
sessionFails++;
|
|
568
|
-
}
|
|
569
|
-
logLine(
|
|
570
|
-
failed ? "error" : "info",
|
|
571
|
-
(failed ? "❌" : "✅") +
|
|
572
|
-
" [" +
|
|
573
|
-
callId +
|
|
574
|
-
"] " +
|
|
575
|
-
name +
|
|
576
|
-
" | " +
|
|
577
|
-
result.kind +
|
|
578
|
-
" | HTTP " +
|
|
579
|
-
response.status +
|
|
580
|
-
" | " +
|
|
581
|
-
formatElapsed(Date.now() - started)
|
|
582
|
-
);
|
|
583
|
-
logLine(failed ? "warn" : "info", " ↳ " + result.summary);
|
|
584
|
-
if (result.error) logLine("error", " ↳ JSON-RPC: " + result.error);
|
|
585
|
-
if (debug) logLine("debug", " ↳ Response size: " + result.bytes + " bytes | Total calls: " + allCalls + " | Errors: " + allFails);
|
|
586
|
-
if (trace) logLine("warn", " ↳ Trace output (may contain private data): " + safeTraceOutput(result));
|
|
550
|
+
const result = await localBridge.forwardRequest({
|
|
551
|
+
id: msg.id,
|
|
552
|
+
method: msg.method || "POST",
|
|
553
|
+
headers: msg.headers || {},
|
|
554
|
+
body: msg.body || "",
|
|
555
|
+
timeoutMs: 70000,
|
|
556
|
+
maxBytes: 8 * 1024 * 1024
|
|
557
|
+
});
|
|
558
|
+
const response = {
|
|
559
|
+
kind: "response",
|
|
560
|
+
id: msg.id,
|
|
561
|
+
status: result.status,
|
|
562
|
+
headers: result.headers,
|
|
563
|
+
body: result.body
|
|
564
|
+
};
|
|
587
565
|
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(response));
|
|
588
566
|
else logLine("warn", " ↳ Response cannot be delivered: relay socket is not open");
|
|
589
567
|
}
|
|
590
568
|
|
|
591
|
-
async function connect(creds, { onHealthy } = {}) {
|
|
569
|
+
async function connect(creds, { onHealthy, tsNode = null } = {}) {
|
|
592
570
|
return new Promise((resolve) => {
|
|
593
571
|
const { wsAgent } = remoteTransport();
|
|
594
572
|
const attempt = ++connectionAttempt;
|
|
@@ -633,14 +611,11 @@ async function connect(creds, { onHealthy } = {}) {
|
|
|
633
611
|
lastError = "";
|
|
634
612
|
awaitingPong = false;
|
|
635
613
|
|
|
636
|
-
// Reset backoff retries once the connection proves stable for 10s
|
|
637
614
|
healthyTimer = setTimeout(() => {
|
|
638
615
|
if (ws.readyState === WebSocket.OPEN) onHealthy?.();
|
|
639
616
|
}, 10000);
|
|
640
617
|
healthyTimer.unref?.();
|
|
641
618
|
|
|
642
|
-
// RFC 6455 control-frame heartbeat: answered at the Cloudflare edge without waking hibernated DOs,
|
|
643
|
-
// and compatible with both legacy v0.3.x and v0.4.0 Workers.
|
|
644
619
|
heartbeatTimer = setInterval(() => {
|
|
645
620
|
if (ws.readyState !== WebSocket.OPEN) return;
|
|
646
621
|
if (awaitingPong) {
|
|
@@ -663,8 +638,10 @@ async function connect(creds, { onHealthy } = {}) {
|
|
|
663
638
|
heartbeatTimer.unref?.();
|
|
664
639
|
|
|
665
640
|
logLine("info", "✅ Cloudflare relay connected in " + formatElapsed(Date.now() - opening));
|
|
666
|
-
reportDevice(creds);
|
|
667
|
-
|
|
641
|
+
reportDevice(creds, { tsNode });
|
|
642
|
+
const connectedLine = "CONNECTED. Your AI client can now use this device. Ctrl+C to disconnect.";
|
|
643
|
+
if (opts.json) console.error(connectedLine);
|
|
644
|
+
else console.log(connectedLine);
|
|
668
645
|
});
|
|
669
646
|
|
|
670
647
|
ws.on("pong", () => {
|
|
@@ -681,9 +658,7 @@ async function connect(creds, { onHealthy } = {}) {
|
|
|
681
658
|
ws.on("message", (data) => {
|
|
682
659
|
awaitingPong = false;
|
|
683
660
|
const text = String(data);
|
|
684
|
-
if (text === "pong")
|
|
685
|
-
return;
|
|
686
|
-
}
|
|
661
|
+
if (text === "pong") return;
|
|
687
662
|
let m;
|
|
688
663
|
try {
|
|
689
664
|
m = JSON.parse(text);
|
|
@@ -746,40 +721,84 @@ async function connect(creds, { onHealthy } = {}) {
|
|
|
746
721
|
});
|
|
747
722
|
}
|
|
748
723
|
|
|
724
|
+
function summarizeTailscaleForDiagnostics(ts) {
|
|
725
|
+
if (!ts) return { installed: false, running: false };
|
|
726
|
+
const urls = ts.running
|
|
727
|
+
? buildTailscaleNodeUrls(ts, { httpsPort: opts.tsHttpsPort, directPort: opts.tsDirectPort })
|
|
728
|
+
: { httpsMcpUrl: "", directMcpUrl: "", preferredMcpUrl: "" };
|
|
729
|
+
const onlinePeers = (ts.peers || []).filter((p) => p.online);
|
|
730
|
+
const sameUserOnlinePeers = onlinePeers.filter((p) => p.isSameUser);
|
|
731
|
+
return {
|
|
732
|
+
installed: Boolean(ts.installed),
|
|
733
|
+
running: Boolean(ts.running),
|
|
734
|
+
backendState: ts.backendState || "Unknown",
|
|
735
|
+
magicDnsSuffix: ts.magicDnsSuffix || "",
|
|
736
|
+
httpsEnabled: Boolean(ts.httpsEnabled),
|
|
737
|
+
self: ts.self
|
|
738
|
+
? {
|
|
739
|
+
hostName: ts.self.hostName,
|
|
740
|
+
dnsName: ts.self.dnsName,
|
|
741
|
+
ipv4: ts.self.ipv4,
|
|
742
|
+
os: ts.self.os,
|
|
743
|
+
loginName: ts.self.loginName,
|
|
744
|
+
isTagged: ts.self.isTagged
|
|
745
|
+
}
|
|
746
|
+
: null,
|
|
747
|
+
onlinePeersCount: onlinePeers.length,
|
|
748
|
+
sameUserOnlinePeersCount: sameUserOnlinePeers.length,
|
|
749
|
+
suggestedNodeUrl: urls.preferredMcpUrl || null,
|
|
750
|
+
error: ts.error || null
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
|
|
749
754
|
async function runDoctor() {
|
|
755
|
+
const checkTailscaleOnly = opts.transport === "tailscale";
|
|
750
756
|
let healthy = true;
|
|
751
757
|
let proxyInfo = { mode: "unknown", source: "unknown" };
|
|
752
758
|
let transport = {};
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
759
|
+
|
|
760
|
+
if (!checkTailscaleOnly) {
|
|
761
|
+
try {
|
|
762
|
+
const p = resolveProxyForUrl(opts.relay);
|
|
763
|
+
proxyInfo = { mode: p.mode, source: p.source, description: p.description || "", reason: p.reason || "" };
|
|
764
|
+
if (p.mode === "unsupported") healthy = false;
|
|
765
|
+
else if (p.mode === "proxy") transport = { dispatcher: new ProxyAgent(p.url) };
|
|
766
|
+
} catch (e) {
|
|
767
|
+
proxyInfo = { mode: "error", source: "system", reason: e.message };
|
|
768
|
+
healthy = false;
|
|
769
|
+
}
|
|
770
|
+
} else {
|
|
771
|
+
proxyInfo = { mode: "direct", source: "tailscale-bypass" };
|
|
761
772
|
}
|
|
762
773
|
|
|
763
|
-
let relayStatus = { ok: false };
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
774
|
+
let relayStatus = checkTailscaleOnly ? { ok: true, skipped: true } : { ok: false };
|
|
775
|
+
if (!checkTailscaleOnly) {
|
|
776
|
+
try {
|
|
777
|
+
const t0 = Date.now();
|
|
778
|
+
const res = await fetch(opts.relay + "/relay/status", {
|
|
779
|
+
signal: AbortSignal.timeout(8000),
|
|
780
|
+
...transport
|
|
781
|
+
});
|
|
782
|
+
const body = await res.json();
|
|
783
|
+
relayStatus = {
|
|
784
|
+
ok: res.ok && Boolean(body?.ok),
|
|
785
|
+
httpStatus: res.status,
|
|
786
|
+
latencyMs: Date.now() - t0,
|
|
787
|
+
workerVersion: body?.version || "unknown",
|
|
788
|
+
protocol: body?.protocol || 1,
|
|
789
|
+
features: Array.isArray(body?.features) ? body.features : []
|
|
790
|
+
};
|
|
791
|
+
if (!relayStatus.ok) healthy = false;
|
|
792
|
+
} catch (e) {
|
|
793
|
+
relayStatus = { ok: false, error: sanitizeText(e.message, 140) };
|
|
794
|
+
healthy = false;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const tsRaw = getTailscaleStatus();
|
|
799
|
+
const tailscaleInfo = summarizeTailscaleForDiagnostics(tsRaw);
|
|
800
|
+
if (opts.transport === "tailscale" || opts.transport === "hybrid") {
|
|
801
|
+
if (!tailscaleInfo.running) healthy = false;
|
|
783
802
|
}
|
|
784
803
|
|
|
785
804
|
const creds = saved();
|
|
@@ -792,16 +811,24 @@ async function runDoctor() {
|
|
|
792
811
|
localPortOccupied = false;
|
|
793
812
|
}
|
|
794
813
|
|
|
814
|
+
const recommendedTransports = [];
|
|
815
|
+
if (tailscaleInfo.running) recommendedTransports.push("tailscale", "hub");
|
|
816
|
+
if (relayStatus.ok && !relayStatus.skipped) recommendedTransports.push("cloudflare");
|
|
817
|
+
if (tailscaleInfo.running && relayStatus.ok && !relayStatus.skipped) recommendedTransports.push("hybrid");
|
|
818
|
+
|
|
795
819
|
if (opts.json) {
|
|
796
820
|
console.log(
|
|
797
821
|
JSON.stringify(
|
|
798
822
|
{
|
|
799
823
|
ok: healthy,
|
|
800
824
|
version: PKG_VERSION,
|
|
825
|
+
transport: opts.transport,
|
|
801
826
|
runtime: { node: process.version, platform: process.platform, arch: process.arch },
|
|
802
827
|
relay: opts.relay,
|
|
803
828
|
proxy: proxyInfo,
|
|
804
829
|
relayStatus,
|
|
830
|
+
tailscale: tailscaleInfo,
|
|
831
|
+
recommendedTransports,
|
|
805
832
|
paired: Boolean(creds?.deviceId),
|
|
806
833
|
deviceId: creds?.deviceId ? String(creds.deviceId).slice(0, 8) + "…" : null,
|
|
807
834
|
localPort: opts.port,
|
|
@@ -830,12 +857,27 @@ async function runDoctor() {
|
|
|
830
857
|
? `${proxyInfo.source} (${proxyInfo.description})`
|
|
831
858
|
: `${proxyInfo.mode} (${proxyInfo.source}${proxyInfo.reason ? ": " + proxyInfo.reason : ""})`
|
|
832
859
|
);
|
|
833
|
-
if (relayStatus.
|
|
860
|
+
if (!relayStatus.skipped) {
|
|
861
|
+
if (relayStatus.ok) {
|
|
862
|
+
console.log(
|
|
863
|
+
`Relay Status: OK (HTTP ${relayStatus.httpStatus}, ${relayStatus.latencyMs}ms, worker v${relayStatus.workerVersion}, features: ${relayStatus.features.join(",") || "legacy"})`
|
|
864
|
+
);
|
|
865
|
+
} else {
|
|
866
|
+
console.log("Relay Status: UNREACHABLE -", relayStatus.error || `HTTP ${relayStatus.httpStatus || 0}`);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
if (tailscaleInfo.running) {
|
|
834
870
|
console.log(
|
|
835
|
-
`
|
|
871
|
+
`Tailscale: RUNNING (${tailscaleInfo.self?.dnsName || tailscaleInfo.self?.ipv4}, HTTPS: ${tailscaleInfo.httpsEnabled ? "ON" : "OFF"}, same-user online peers: ${tailscaleInfo.sameUserOnlinePeersCount}/${tailscaleInfo.onlinePeersCount})`
|
|
836
872
|
);
|
|
873
|
+
if (tailscaleInfo.suggestedNodeUrl) {
|
|
874
|
+
console.log("Tailscale Node URL:", tailscaleInfo.suggestedNodeUrl);
|
|
875
|
+
}
|
|
837
876
|
} else {
|
|
838
|
-
console.log(
|
|
877
|
+
console.log(
|
|
878
|
+
"Tailscale:",
|
|
879
|
+
tailscaleInfo.installed ? `NOT RUNNING (${tailscaleInfo.backendState})` : "not installed"
|
|
880
|
+
);
|
|
839
881
|
}
|
|
840
882
|
console.log("Device Pairing:", creds ? `paired (id=${String(creds.deviceId || "").slice(0, 8)}…)` : "not paired");
|
|
841
883
|
console.log(`Local Port ${opts.port}:`, localPortOccupied ? `occupied (HTTP ${localHttpStatus})` : "free");
|
|
@@ -846,6 +888,7 @@ async function runDoctor() {
|
|
|
846
888
|
function runReport() {
|
|
847
889
|
const p = resolveProxyForUrl(opts.relay);
|
|
848
890
|
const creds = saved();
|
|
891
|
+
const tsSummary = summarizeTailscaleForDiagnostics(getTailscaleStatus());
|
|
849
892
|
let gatewayLogTail = [];
|
|
850
893
|
try {
|
|
851
894
|
const raw = fs.readFileSync(gatewayLogPath, "utf8");
|
|
@@ -869,6 +912,7 @@ function runReport() {
|
|
|
869
912
|
description: p.description || "",
|
|
870
913
|
reason: p.reason || ""
|
|
871
914
|
},
|
|
915
|
+
tailscale: tsSummary,
|
|
872
916
|
policy: {
|
|
873
917
|
readonly: policy.readonly,
|
|
874
918
|
dlp: policy.dlp,
|
|
@@ -881,6 +925,36 @@ function runReport() {
|
|
|
881
925
|
console.log(JSON.stringify(report, null, 2));
|
|
882
926
|
}
|
|
883
927
|
|
|
928
|
+
function resolveSetupEndpoint() {
|
|
929
|
+
if (opts.relayExplicit) {
|
|
930
|
+
return { url: opts.relay, mode: "custom-relay" };
|
|
931
|
+
}
|
|
932
|
+
if (opts.setupHub) {
|
|
933
|
+
if (opts.exposeTailscale || opts.setupTailscale) {
|
|
934
|
+
const ts = getTailscaleStatus();
|
|
935
|
+
if (!ts.running) {
|
|
936
|
+
throw new Error(`Tailscale is not running (${ts.backendState}). Start Tailscale or omit --expose-tailscale.`);
|
|
937
|
+
}
|
|
938
|
+
const urls = buildTailscaleNodeUrls(ts, { httpsPort: opts.tsHttpsPort, directPort: opts.tsDirectPort });
|
|
939
|
+
const base = opts.tsDirect ? urls.directBase : urls.preferredBase;
|
|
940
|
+
if (!base) throw new Error("Unable to determine Tailscale hub URL.");
|
|
941
|
+
return { url: base, mode: "tailscale-hub" };
|
|
942
|
+
}
|
|
943
|
+
return { url: `http://127.0.0.1:${opts.hubPort}`, mode: "local-hub" };
|
|
944
|
+
}
|
|
945
|
+
if (opts.setupTailscale) {
|
|
946
|
+
const ts = getTailscaleStatus();
|
|
947
|
+
if (!ts.running) {
|
|
948
|
+
throw new Error(`Tailscale is not running (${ts.backendState}). Run \`tailscale up\` or pass --relay <url>.`);
|
|
949
|
+
}
|
|
950
|
+
const urls = buildTailscaleNodeUrls(ts, { httpsPort: opts.tsHttpsPort, directPort: opts.tsDirectPort });
|
|
951
|
+
const base = opts.tsDirect ? urls.directBase : urls.preferredBase;
|
|
952
|
+
if (!base) throw new Error("Unable to determine Tailscale node URL (no MagicDNS name or IPv4 found).");
|
|
953
|
+
return { url: base, mode: "tailscale-node" };
|
|
954
|
+
}
|
|
955
|
+
return { url: opts.relay, mode: "cloudflare" };
|
|
956
|
+
}
|
|
957
|
+
|
|
884
958
|
function runSetupClient() {
|
|
885
959
|
const target = String(opts.targetClient || "").toLowerCase().trim();
|
|
886
960
|
if (!target) {
|
|
@@ -891,17 +965,29 @@ function runSetupClient() {
|
|
|
891
965
|
return;
|
|
892
966
|
}
|
|
893
967
|
|
|
968
|
+
let resolvedEndpoint;
|
|
969
|
+
try {
|
|
970
|
+
resolvedEndpoint = resolveSetupEndpoint();
|
|
971
|
+
} catch (e) {
|
|
972
|
+
if (opts.json) console.log(JSON.stringify({ ok: false, error: e.message }, null, 2));
|
|
973
|
+
else console.error(`❌ ${e.message}`);
|
|
974
|
+
process.exitCode = 1;
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
|
|
894
978
|
const clients = target === "all" ? SUPPORTED_CLIENTS : [target];
|
|
895
979
|
const results = [];
|
|
896
980
|
for (const client of clients) {
|
|
897
981
|
try {
|
|
898
982
|
const res = configureMcpClient({
|
|
899
983
|
client,
|
|
900
|
-
relayUrl:
|
|
984
|
+
relayUrl: resolvedEndpoint.url,
|
|
985
|
+
serverName: opts.serverName || undefined,
|
|
986
|
+
bearerToken: opts.sharedToken || "",
|
|
901
987
|
configPath: clients.length === 1 && opts.clientConfigPath ? opts.clientConfigPath : undefined,
|
|
902
988
|
dryRun: opts.dryRun
|
|
903
989
|
});
|
|
904
|
-
results.push(res);
|
|
990
|
+
results.push({ ...res, endpointMode: resolvedEndpoint.mode });
|
|
905
991
|
} catch (e) {
|
|
906
992
|
results.push({ ok: false, client, error: e.message });
|
|
907
993
|
process.exitCode = 1;
|
|
@@ -918,13 +1004,189 @@ function runSetupClient() {
|
|
|
918
1004
|
console.error(`❌ [${r.client}] ${r.error}`);
|
|
919
1005
|
continue;
|
|
920
1006
|
}
|
|
921
|
-
console.log(`${r.dryRun ? "🔍 [DRY-RUN]" : "✅"} [${r.client}] ${r.action.toUpperCase()} → ${r.path}`);
|
|
1007
|
+
console.log(`${r.dryRun ? "🔍 [DRY-RUN]" : "✅"} [${r.client}] ${r.action.toUpperCase()} (${r.endpointMode}) → ${r.path}`);
|
|
922
1008
|
if (r.dryRun) {
|
|
923
1009
|
console.log(r.preview.trimEnd());
|
|
924
1010
|
}
|
|
925
1011
|
}
|
|
926
1012
|
}
|
|
927
1013
|
|
|
1014
|
+
async function startTailscaleTransport() {
|
|
1015
|
+
const tsStatus = getTailscaleStatus();
|
|
1016
|
+
const handle = await startTailscaleNodeServer({
|
|
1017
|
+
tsStatus,
|
|
1018
|
+
localBridge,
|
|
1019
|
+
deviceName: opts.deviceName,
|
|
1020
|
+
cliVersion: PKG_VERSION,
|
|
1021
|
+
policyMode: policy.readonly ? "READONLY" : "FULL",
|
|
1022
|
+
isGatewayHealthy: () => gatewayHealthy,
|
|
1023
|
+
preferDirect: opts.tsDirect,
|
|
1024
|
+
httpsPort: opts.tsHttpsPort,
|
|
1025
|
+
directPort: opts.tsDirectPort,
|
|
1026
|
+
allowedUsers: opts.allowTsUsers,
|
|
1027
|
+
allowedTags: opts.allowTsTags,
|
|
1028
|
+
sharedToken: opts.sharedToken
|
|
1029
|
+
});
|
|
1030
|
+
tailscaleNodeHandle = handle;
|
|
1031
|
+
logLine("info", `🔒 Tailscale node ready (${handle.mode}): ${handle.endpointUrl}`);
|
|
1032
|
+
if (opts.json) {
|
|
1033
|
+
console.log(
|
|
1034
|
+
JSON.stringify({
|
|
1035
|
+
event: "tailscale_node_ready",
|
|
1036
|
+
mode: handle.mode,
|
|
1037
|
+
deviceName: handle.name,
|
|
1038
|
+
nodeId: handle.nodeId,
|
|
1039
|
+
endpointUrl: handle.endpointUrl,
|
|
1040
|
+
policy: policy.readonly ? "READONLY" : "FULL"
|
|
1041
|
+
})
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
return handle;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
async function runServeOnly() {
|
|
1048
|
+
logLine("info", `╔══════════════ PCC TAILSCALE NODE v${PKG_VERSION} ══════════════╗`);
|
|
1049
|
+
logLine(
|
|
1050
|
+
"info",
|
|
1051
|
+
"Transport: TAILSCALE | Logging: " +
|
|
1052
|
+
(trace ? "TRACE" : debug ? "DEBUG" : "LIVE") +
|
|
1053
|
+
" | Policy: " +
|
|
1054
|
+
(policy.readonly ? "READONLY" : "FULL") +
|
|
1055
|
+
" | DLP: " +
|
|
1056
|
+
(policy.dlp ? "ON" : "OFF")
|
|
1057
|
+
);
|
|
1058
|
+
if (trace) logLine("warn", "TRACE mode can display private user content in this terminal; do not share these logs.");
|
|
1059
|
+
logLine("info", "╚═══════════════════════════════════════════════════════════╝");
|
|
1060
|
+
try {
|
|
1061
|
+
await startGateway();
|
|
1062
|
+
const tsNode = await startTailscaleTransport();
|
|
1063
|
+
reportDevice(null, { tsNode });
|
|
1064
|
+
const readyLine = `SERVING OVER TAILSCALE at ${tsNode.endpointUrl} (Ctrl+C to stop).`;
|
|
1065
|
+
if (opts.json) console.error(readyLine);
|
|
1066
|
+
else console.log(readyLine);
|
|
1067
|
+
await new Promise((resolve) => {
|
|
1068
|
+
const check = setInterval(() => {
|
|
1069
|
+
if (stopping) {
|
|
1070
|
+
clearInterval(check);
|
|
1071
|
+
resolve();
|
|
1072
|
+
}
|
|
1073
|
+
}, 250);
|
|
1074
|
+
});
|
|
1075
|
+
} catch (e) {
|
|
1076
|
+
logLine("error", "ERROR: " + sanitizeText(e.message, 250));
|
|
1077
|
+
process.exitCode = 1;
|
|
1078
|
+
} finally {
|
|
1079
|
+
await tailscaleNodeHandle?.close().catch(() => {});
|
|
1080
|
+
tailscaleNodeHandle = null;
|
|
1081
|
+
stopGateway();
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
async function runHub() {
|
|
1086
|
+
logLine("info", `╔══════════════ PCC TAILNET MESH HUB v${PKG_VERSION} ══════════════╗`);
|
|
1087
|
+
logLine(
|
|
1088
|
+
"info",
|
|
1089
|
+
"Mode: " +
|
|
1090
|
+
(opts.exposeTailscale ? "TAILSCALE-EXPOSED HUB" : "LOCAL LOOPBACK MESH HUB") +
|
|
1091
|
+
" | Auto-Discovery: " +
|
|
1092
|
+
(opts.discoverTailscale ? "ON" : "OFF") +
|
|
1093
|
+
(opts.withLocal ? " | Local Gateway: ON" : "")
|
|
1094
|
+
);
|
|
1095
|
+
logLine("info", "╚═══════════════════════════════════════════════════════════╝");
|
|
1096
|
+
|
|
1097
|
+
try {
|
|
1098
|
+
let localDevice = null;
|
|
1099
|
+
if (opts.withLocal) {
|
|
1100
|
+
await startGateway();
|
|
1101
|
+
localDevice = {
|
|
1102
|
+
id: "local:" + os.hostname().toLowerCase(),
|
|
1103
|
+
name: opts.deviceName,
|
|
1104
|
+
hostName: os.hostname(),
|
|
1105
|
+
platform: process.platform,
|
|
1106
|
+
arch: process.arch,
|
|
1107
|
+
mode: policy.readonly ? "READONLY" : "FULL",
|
|
1108
|
+
isGatewayHealthy: () => gatewayHealthy,
|
|
1109
|
+
localBridge
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
const handle = await startTailnetMeshHubServer({
|
|
1114
|
+
port: opts.hubPort,
|
|
1115
|
+
exposeTailscale: opts.exposeTailscale,
|
|
1116
|
+
preferDirect: opts.tsDirect,
|
|
1117
|
+
tsHttpsPort: opts.tsHttpsPort,
|
|
1118
|
+
tsDirectPort: opts.tsDirectPort,
|
|
1119
|
+
allowedUsers: opts.allowTsUsers,
|
|
1120
|
+
allowedTags: opts.allowTsTags,
|
|
1121
|
+
sharedToken: opts.sharedToken,
|
|
1122
|
+
hubOptions: {
|
|
1123
|
+
version: PKG_VERSION,
|
|
1124
|
+
statePath: hubStatePath,
|
|
1125
|
+
staticPeers: opts.staticPeers,
|
|
1126
|
+
localDevice,
|
|
1127
|
+
peerToken: opts.peerToken,
|
|
1128
|
+
tsHttpsPort: opts.tsHttpsPort,
|
|
1129
|
+
tsDirectPort: opts.tsDirectPort,
|
|
1130
|
+
preferDirect: opts.tsDirect,
|
|
1131
|
+
discoverTailscale: opts.discoverTailscale,
|
|
1132
|
+
includeSelfPeer: opts.includeSelf,
|
|
1133
|
+
peerTags: opts.peerTags,
|
|
1134
|
+
allowAllTailnetPeers: opts.allowAllTailnetPeers,
|
|
1135
|
+
defaultDevice: opts.defaultDevice
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
tailnetHubHandle = handle;
|
|
1139
|
+
|
|
1140
|
+
const devices = handle.hub.getDevicesList();
|
|
1141
|
+
const onlineCount = devices.filter((d) => d.online).length;
|
|
1142
|
+
logLine("info", `🕸️ Tailnet Mesh Hub listening (${handle.mode}): ${handle.endpointUrl}`);
|
|
1143
|
+
logLine("info", `📋 Admin Dashboard: ${handle.adminUrl}`);
|
|
1144
|
+
logLine("info", `🖥️ Discovered/Known Devices: ${onlineCount}/${devices.length} online`);
|
|
1145
|
+
for (const d of devices) {
|
|
1146
|
+
logLine("info", ` • ${d.name} (${d.transport}, ${d.online ? "ONLINE" : "offline"}, ${d.platform})`);
|
|
1147
|
+
}
|
|
1148
|
+
if (opts.json) {
|
|
1149
|
+
console.log(
|
|
1150
|
+
JSON.stringify({
|
|
1151
|
+
event: "tailnet_hub_ready",
|
|
1152
|
+
mode: handle.mode,
|
|
1153
|
+
endpointUrl: handle.endpointUrl,
|
|
1154
|
+
adminUrl: handle.adminUrl,
|
|
1155
|
+
onlineDevices: onlineCount,
|
|
1156
|
+
devices: devices.map((d) => ({
|
|
1157
|
+
id: d.id,
|
|
1158
|
+
name: d.name,
|
|
1159
|
+
transport: d.transport,
|
|
1160
|
+
online: d.online,
|
|
1161
|
+
platform: d.platform,
|
|
1162
|
+
readOnly: d.readOnly
|
|
1163
|
+
}))
|
|
1164
|
+
})
|
|
1165
|
+
);
|
|
1166
|
+
} else {
|
|
1167
|
+
console.log(`\nTAILNET MESH HUB READY: ${handle.endpointUrl}`);
|
|
1168
|
+
console.log("Configure your AI client with: private-desktop-mcp setup-client <client> --hub --dry-run");
|
|
1169
|
+
console.log("Ctrl+C to stop.\n");
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
await new Promise((resolve) => {
|
|
1173
|
+
const check = setInterval(() => {
|
|
1174
|
+
if (stopping) {
|
|
1175
|
+
clearInterval(check);
|
|
1176
|
+
resolve();
|
|
1177
|
+
}
|
|
1178
|
+
}, 250);
|
|
1179
|
+
});
|
|
1180
|
+
} catch (e) {
|
|
1181
|
+
logLine("error", "ERROR: " + sanitizeText(e.message, 250));
|
|
1182
|
+
process.exitCode = 1;
|
|
1183
|
+
} finally {
|
|
1184
|
+
await tailnetHubHandle?.close().catch(() => {});
|
|
1185
|
+
tailnetHubHandle = null;
|
|
1186
|
+
stopGateway();
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
|
|
928
1190
|
function stop() {
|
|
929
1191
|
if (stopping) return;
|
|
930
1192
|
stopping = true;
|
|
@@ -932,8 +1194,10 @@ function stop() {
|
|
|
932
1194
|
try {
|
|
933
1195
|
socket?.close(1000, "Manual disconnect");
|
|
934
1196
|
} catch {}
|
|
935
|
-
|
|
936
|
-
|
|
1197
|
+
Promise.allSettled([tailscaleNodeHandle?.close(), tailnetHubHandle?.close()]).finally(() => {
|
|
1198
|
+
stopGateway();
|
|
1199
|
+
setTimeout(() => process.exit(0), 200).unref();
|
|
1200
|
+
});
|
|
937
1201
|
}
|
|
938
1202
|
|
|
939
1203
|
process.on("SIGINT", stop);
|
|
@@ -941,18 +1205,39 @@ process.on("SIGTERM", stop);
|
|
|
941
1205
|
|
|
942
1206
|
if (opts.command === "help") {
|
|
943
1207
|
console.log(
|
|
944
|
-
`Private Desktop MCP v${PKG_VERSION}: connect | status | doctor | report | setup-client | reset\n` +
|
|
1208
|
+
`Private Desktop MCP v${PKG_VERSION}: connect | serve | hub | status | doctor | report | setup-client | reset\n` +
|
|
945
1209
|
"Subcommands:\n" +
|
|
946
|
-
" connect Pair
|
|
947
|
-
"
|
|
948
|
-
"
|
|
1210
|
+
" connect Pair & connect to Cloudflare relay (or --tailscale / --hybrid)\n" +
|
|
1211
|
+
" serve Serve this desktop over Tailscale P2P (zero Cloudflare required)\n" +
|
|
1212
|
+
" hub Start multi-device Tailnet Mesh Hub (auto-discovers Tailscale nodes)\n" +
|
|
1213
|
+
" status [--json] Check local pairing, gateway port, and Tailscale state\n" +
|
|
1214
|
+
" doctor [--json] End-to-end preflight check (proxy, relay, Tailscale, pairing, port)\n" +
|
|
949
1215
|
" report [--json] Generate sanitized JSON diagnostic bundle\n" +
|
|
950
1216
|
` setup-client <client|all> Configure MCP client (${SUPPORTED_CLIENTS.join(", ")})\n` +
|
|
951
1217
|
" reset [--json] Clear local device pairing credentials\n" +
|
|
952
|
-
"Options:\n" +
|
|
953
|
-
" --
|
|
1218
|
+
"Transport & Tailscale Options:\n" +
|
|
1219
|
+
" --transport <mode> cloudflare (default for connect) | tailscale | hybrid\n" +
|
|
1220
|
+
" --tailscale Use Tailscale transport (for connect/doctor/setup-client)\n" +
|
|
1221
|
+
" --hybrid Run BOTH Tailscale node AND Cloudflare relay simultaneously\n" +
|
|
1222
|
+
" --hub Configure client for local Tailnet Mesh Hub (for setup-client)\n" +
|
|
1223
|
+
" --hub-port <port> Tailnet Mesh Hub local port (default: 8720, env: PCC_HUB_PORT)\n" +
|
|
1224
|
+
" --expose-tailscale Expose the Mesh Hub over Tailscale (for hub / setup-client --hub)\n" +
|
|
1225
|
+
" --with-local Also register this computer inside `hub` as a local device\n" +
|
|
1226
|
+
" --peer <[name=]url> Add static peer node URL to `hub` (repeatable)\n" +
|
|
1227
|
+
" --peer-tag <tag> Also discover Tailscale peers with ACL tag (repeatable)\n" +
|
|
1228
|
+
" --ts-https-port <port> Tailscale Serve HTTPS port (default: 8443)\n" +
|
|
1229
|
+
" --ts-port <port> Direct Tailnet IP HTTP port (default: 8718)\n" +
|
|
1230
|
+
" --ts-direct Bind directly to Tailnet IPv4 with WhoIs auth instead of `tailscale serve`\n" +
|
|
1231
|
+
" --allow-ts-user <login> Allowed Tailscale user login (defaults to local Tailscale owner)\n" +
|
|
1232
|
+
" --allow-ts-tag <tag> Allowed Tailscale caller ACL tag (repeatable)\n" +
|
|
1233
|
+
" --token <secret> Optional defense-in-depth Bearer token for Tailscale node/hub\n" +
|
|
1234
|
+
" --peer-token <secret> Bearer token sent by `hub` to `--token`-protected peers\n" +
|
|
1235
|
+
" --default-device <name> Default target device name/ID for `hub`\n" +
|
|
1236
|
+
" --no-discover Disable automatic Tailscale peer discovery in `hub`\n" +
|
|
1237
|
+
"General Options:\n" +
|
|
1238
|
+
" --relay <url> Custom Cloudflare Worker or Tailnet Hub URL (env: PCC_RELAY_URL)\n" +
|
|
954
1239
|
" --port <port> Local MCP gateway port (default: 8717, env: MCP_PORT)\n" +
|
|
955
|
-
" --name <name> Device display name
|
|
1240
|
+
" --name <name> Device display name (default: hostname)\n" +
|
|
956
1241
|
" --readonly Allow read-only tools only and hide mutating tools\n" +
|
|
957
1242
|
" --allow-dir <dir> Restrict file tool paths to allowed directories (repeatable)\n" +
|
|
958
1243
|
" --allow-tools <csv> Explicit allowlist of MCP tool names\n" +
|
|
@@ -970,6 +1255,7 @@ if (opts.command === "help") {
|
|
|
970
1255
|
);
|
|
971
1256
|
} else if (opts.command === "status") {
|
|
972
1257
|
const creds = saved();
|
|
1258
|
+
const tsSummary = summarizeTailscaleForDiagnostics(getTailscaleStatus());
|
|
973
1259
|
let localHttpStatus = null;
|
|
974
1260
|
try {
|
|
975
1261
|
localHttpStatus = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(2000) })).status;
|
|
@@ -988,6 +1274,7 @@ if (opts.command === "help") {
|
|
|
988
1274
|
localPort: opts.port,
|
|
989
1275
|
localGatewayRunning: localHttpStatus !== null,
|
|
990
1276
|
localHttpStatus,
|
|
1277
|
+
tailscale: tsSummary,
|
|
991
1278
|
policy: { readonly: policy.readonly, dlp: policy.dlp }
|
|
992
1279
|
},
|
|
993
1280
|
null,
|
|
@@ -997,6 +1284,10 @@ if (opts.command === "help") {
|
|
|
997
1284
|
} else {
|
|
998
1285
|
console.log("Paired:", !!creds);
|
|
999
1286
|
console.log("Relay:", opts.relay);
|
|
1287
|
+
console.log(
|
|
1288
|
+
"Tailscale:",
|
|
1289
|
+
tsSummary.running ? `running (${tsSummary.suggestedNodeUrl || tsSummary.self?.ipv4})` : tsSummary.backendState
|
|
1290
|
+
);
|
|
1000
1291
|
if (localHttpStatus !== null) console.log("Local HTTP:", localHttpStatus);
|
|
1001
1292
|
else console.log("Local MCP offline");
|
|
1002
1293
|
}
|
|
@@ -1013,50 +1304,71 @@ if (opts.command === "help") {
|
|
|
1013
1304
|
} else {
|
|
1014
1305
|
console.log("Local credentials cleared. Revoke old credentials in the admin page too.");
|
|
1015
1306
|
}
|
|
1307
|
+
} else if (opts.command === "serve") {
|
|
1308
|
+
await runServeOnly();
|
|
1309
|
+
} else if (opts.command === "hub") {
|
|
1310
|
+
await runHub();
|
|
1016
1311
|
} else if (opts.command === "connect") {
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
"
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1312
|
+
if (!["cloudflare", "tailscale", "hybrid"].includes(opts.transport)) {
|
|
1313
|
+
console.error(`Invalid --transport "${opts.transport}". Expected cloudflare, tailscale, or hybrid.`);
|
|
1314
|
+
process.exitCode = 2;
|
|
1315
|
+
} else if (opts.transport === "tailscale") {
|
|
1316
|
+
await runServeOnly();
|
|
1317
|
+
} else {
|
|
1318
|
+
const isHybrid = opts.transport === "hybrid";
|
|
1319
|
+
logLine("info", `╔══════════════ PCC REMOTE v${PKG_VERSION}${isHybrid ? " (HYBRID)" : ""} ══════════════╗`);
|
|
1320
|
+
logLine(
|
|
1321
|
+
"info",
|
|
1322
|
+
"Transport: " +
|
|
1323
|
+
opts.transport.toUpperCase() +
|
|
1324
|
+
" | Logging: " +
|
|
1325
|
+
(trace ? "TRACE" : debug ? "DEBUG" : "LIVE") +
|
|
1326
|
+
" | Policy: " +
|
|
1327
|
+
(policy.readonly ? "READONLY" : "FULL") +
|
|
1328
|
+
" | DLP: " +
|
|
1329
|
+
(policy.dlp ? "ON" : "OFF") +
|
|
1330
|
+
" | Gateway: Desktop Commander MCP"
|
|
1331
|
+
);
|
|
1332
|
+
if (trace) logLine("warn", "TRACE mode can display private user content in this terminal; do not share these logs.");
|
|
1333
|
+
logLine("info", "╚═══════════════════════════════════════════════╝");
|
|
1334
|
+
try {
|
|
1335
|
+
const existing = saved();
|
|
1336
|
+
const credentials = existing || (await pair());
|
|
1337
|
+
activeCreds = credentials;
|
|
1338
|
+
if (existing) logLine("info", "💾 Stored device pairing found");
|
|
1339
|
+
await startGateway();
|
|
1340
|
+
let tsNode = null;
|
|
1341
|
+
if (isHybrid) {
|
|
1342
|
+
tsNode = await startTailscaleTransport();
|
|
1343
|
+
}
|
|
1344
|
+
let retries = 0;
|
|
1345
|
+
while (!stopping) {
|
|
1346
|
+
const r = await connect(credentials, {
|
|
1347
|
+
tsNode,
|
|
1348
|
+
onHealthy: () => {
|
|
1349
|
+
retries = 0;
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
if (r.unauthorized) {
|
|
1353
|
+
forget();
|
|
1354
|
+
logLine("error", "Credentials revoked; run again to pair.");
|
|
1355
|
+
break;
|
|
1041
1356
|
}
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1357
|
+
if (stopping) break;
|
|
1358
|
+
retries++;
|
|
1359
|
+
const baseMs = Math.min(30000, 1500 * 2 ** Math.min(5, retries));
|
|
1360
|
+
const jitterMs = Math.round(baseMs * (0.75 + Math.random() * 0.5));
|
|
1361
|
+
logLine("warn", "Reconnecting in " + (jitterMs / 1000).toFixed(1) + "s");
|
|
1362
|
+
await sleep(jitterMs);
|
|
1047
1363
|
}
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1364
|
+
} catch (e) {
|
|
1365
|
+
logLine("error", "ERROR: " + sanitizeText(e.message, 250));
|
|
1366
|
+
process.exitCode = 1;
|
|
1367
|
+
} finally {
|
|
1368
|
+
await tailscaleNodeHandle?.close().catch(() => {});
|
|
1369
|
+
tailscaleNodeHandle = null;
|
|
1370
|
+
stopGateway();
|
|
1054
1371
|
}
|
|
1055
|
-
} catch (e) {
|
|
1056
|
-
logLine("error", "ERROR: " + sanitizeText(e.message, 250));
|
|
1057
|
-
process.exitCode = 1;
|
|
1058
|
-
} finally {
|
|
1059
|
-
stopGateway();
|
|
1060
1372
|
}
|
|
1061
1373
|
} else {
|
|
1062
1374
|
console.error("Unknown command. Use help");
|