@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.
package/bin/cli.mjs CHANGED
@@ -9,32 +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";
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";
16
+ import { SUPPORTED_CLIENTS, configureMcpClient } from "./client-setup.mjs";
13
17
  import {
14
- callInfo,
15
- requestBrief,
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";
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";
31
25
 
32
26
  const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
33
27
  const PKG_VERSION = (() => {
34
28
  try {
35
- return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.4.0";
29
+ return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.6.0";
36
30
  } catch {
37
- return "0.4.0";
31
+ return "0.6.0";
38
32
  }
39
33
  })();
40
34
 
@@ -42,32 +36,60 @@ const DEFAULT_RELAY = "https://private-desktop-device-relay.ljx2043979076.worker
42
36
  const HEARTBEAT_INTERVAL_MS = 25000;
43
37
  const MAX_GATEWAY_LOG_BYTES = 5 * 1024 * 1024;
44
38
 
39
+ function parseCsvList(raw) {
40
+ return String(raw || "")
41
+ .split(",")
42
+ .map((s) => s.trim())
43
+ .filter(Boolean);
44
+ }
45
+
45
46
  function parseArgs(argv) {
46
47
  let command = "";
48
+ let subarg = "";
47
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();
48
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 = "";
49
68
  let deviceName = os.hostname();
50
69
  let readonly = /^(1|true|yes)$/i.test(String(process.env.PCC_READONLY || ""));
51
70
  let dlp = !/^(0|false|no)$/i.test(String(process.env.PCC_DLP || "true"));
52
71
  let autoOpen = true;
72
+ let jsonOutput = false;
73
+ let dryRun = false;
74
+ let targetClient = "";
75
+ let clientConfigPath = "";
53
76
  let serversConfig = process.env.PCC_MCP_CONFIG || "";
54
77
  const allowDirs = String(process.env.PCC_ALLOW_DIRS || "")
55
78
  .split(path.delimiter)
56
79
  .map((s) => s.trim())
57
80
  .filter(Boolean);
58
- const allowTools = String(process.env.PCC_ALLOW_TOOLS || "")
59
- .split(",")
60
- .map((s) => s.trim())
61
- .filter(Boolean);
62
- const denyTools = String(process.env.PCC_DENY_TOOLS || "")
63
- .split(",")
64
- .map((s) => s.trim())
65
- .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);
66
87
 
67
88
  for (let i = 0; i < argv.length; i++) {
68
89
  const arg = argv[i];
69
90
  if (!arg.startsWith("-")) {
70
91
  if (!command) command = arg;
92
+ else if (!subarg) subarg = arg;
71
93
  continue;
72
94
  }
73
95
  const eq = arg.indexOf("=");
@@ -76,12 +98,39 @@ function parseArgs(argv) {
76
98
  const nextVal = () => (inlineVal !== null ? inlineVal : argv[++i] || "");
77
99
 
78
100
  if (flag === "--help" || flag === "-h") command = "help";
79
- else if (flag === "--relay") relay = nextVal().replace(/\/+$/, "");
80
- else if (flag === "--port") port = Number(nextVal());
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();
81
126
  else if (flag === "--name") deviceName = nextVal();
82
127
  else if (flag === "--readonly") readonly = true;
83
128
  else if (flag === "--no-dlp") dlp = false;
84
129
  else if (flag === "--no-open") autoOpen = false;
130
+ else if (flag === "--json") jsonOutput = true;
131
+ else if (flag === "--dry-run") dryRun = true;
132
+ else if (flag === "--client") targetClient = nextVal();
133
+ else if (flag === "--config") clientConfigPath = nextVal();
85
134
  else if (flag === "--servers") serversConfig = nextVal();
86
135
  else if (flag === "--allow-dir") {
87
136
  const v = nextVal().trim();
@@ -90,28 +139,70 @@ function parseArgs(argv) {
90
139
  for (const item of nextVal().split(",")) if (item.trim()) allowTools.push(item.trim());
91
140
  } else if (flag === "--deny-tools") {
92
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);
93
151
  }
94
152
  }
95
153
 
154
+ const resolvedCommand = command || "connect";
155
+ const resolvedTransport =
156
+ transport || (resolvedCommand === "serve" ? "tailscale" : "cloudflare");
157
+
96
158
  return {
97
- command: command || "connect",
159
+ command: resolvedCommand,
160
+ subarg,
98
161
  relay: relay.replace(/\/+$/, ""),
162
+ relayExplicit,
163
+ transport: resolvedTransport,
99
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,
100
180
  deviceName: deviceName || "Desktop",
101
181
  readonly,
102
182
  dlp,
103
183
  autoOpen,
184
+ json: jsonOutput,
185
+ dryRun,
186
+ targetClient: targetClient || subarg,
187
+ clientConfigPath,
104
188
  serversConfig,
105
189
  allowDirs,
106
190
  allowTools,
107
- denyTools
191
+ denyTools,
192
+ allowTsUsers,
193
+ allowTsTags,
194
+ peerTags,
195
+ staticPeers
108
196
  };
109
197
  }
110
198
 
111
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");
112
202
  const { trace, debug } = loggingOptions(process.argv.slice(2));
113
203
  const configDir = path.join(process.env.APPDATA || path.join(os.homedir(), ".config"), "PrivateDesktopMCP");
114
204
  const config = path.join(configDir, "device.json");
205
+ const hubStatePath = path.join(configDir, "hub-state.json");
115
206
  const gatewayLogDir = path.join(configDir, "logs");
116
207
  const gatewayLogPath = path.join(gatewayLogDir, "gateway.log");
117
208
  const localBaseUrl = `http://127.0.0.1:${opts.port}/mcp`;
@@ -164,6 +255,8 @@ let gatewayHealthy = false;
164
255
  let gatewayRestartCount = 0;
165
256
  let gatewayRestartPromise = null;
166
257
  let socket = null;
258
+ let tailscaleNodeHandle = null;
259
+ let tailnetHubHandle = null;
167
260
  let activeCreds = null;
168
261
  let connectionAttempt = 0;
169
262
  let connectedSince = 0;
@@ -174,6 +267,25 @@ let allFails = 0;
174
267
  let lastError = "";
175
268
  const inflightControllers = new Map();
176
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
+
177
289
  function saved() {
178
290
  try {
179
291
  return JSON.parse(fs.readFileSync(config, "utf8"));
@@ -227,11 +339,19 @@ function tryOpenBrowser(url) {
227
339
  } catch {}
228
340
  }
229
341
 
230
- function reportDevice(creds) {
342
+ function reportDevice(creds, { tsNode = null } = {}) {
231
343
  logLine("info", "━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
232
344
  logLine("info", "Computer: " + opts.deviceName + " | User: " + os.userInfo().username + " | Node: " + process.version);
233
- logLine("info", "Device ID: " + creds.deviceId + " | Gateway PID: " + (child?.pid || "unknown"));
234
- logLine("info", "Relay: " + opts.relay + " | Local MCP: " + localBaseUrl + " (Bearer+Host protected)");
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)");
235
355
  logLine(
236
356
  "info",
237
357
  "Mode: " +
@@ -263,15 +383,28 @@ async function post(route, data) {
263
383
  async function pair() {
264
384
  const v = await post("/relay/pair/start", { name: opts.deviceName });
265
385
  logLine("info", "🔑 New device pairing requested");
266
- console.log(
267
- "\nNEW DEVICE: " +
268
- opts.deviceName +
269
- "\nPAIRING CODE: " +
270
- v.code +
271
- "\nPlease visit " +
272
- v.approvalUrl +
273
- " and approve the matching code.\nWaiting for approval (60 minutes)...\n"
274
- );
386
+ if (opts.json) {
387
+ console.log(
388
+ JSON.stringify({
389
+ event: "pairing_required",
390
+ deviceName: opts.deviceName,
391
+ code: v.code,
392
+ approvalUrl: v.approvalUrl,
393
+ pairId: v.pairId,
394
+ expiresIn: v.expiresIn || 3600
395
+ })
396
+ );
397
+ } else {
398
+ console.log(
399
+ "\nNEW DEVICE: " +
400
+ opts.deviceName +
401
+ "\nPAIRING CODE: " +
402
+ v.code +
403
+ "\nPlease visit " +
404
+ v.approvalUrl +
405
+ " and approve the matching code.\nWaiting for approval (60 minutes)...\n"
406
+ );
407
+ }
275
408
  tryOpenBrowser(v.approvalUrl);
276
409
  for (let i = 0; i < 720 && !stopping; i++) {
277
410
  await sleep(5000);
@@ -286,6 +419,9 @@ async function pair() {
286
419
  const credentials = { deviceId: r.deviceId, token: r.token };
287
420
  store(credentials);
288
421
  logLine("info", "✅ Device approved; credentials saved locally.");
422
+ if (opts.json) {
423
+ console.log(JSON.stringify({ event: "pairing_approved", deviceId: r.deviceId, deviceName: opts.deviceName }));
424
+ }
289
425
  return credentials;
290
426
  }
291
427
  }
@@ -411,152 +547,26 @@ function stopGateway() {
411
547
  }
412
548
 
413
549
  async function respond(ws, msg) {
414
- const started = Date.now();
415
- const call = callInfo(msg.body, msg.id);
416
- const callId = shortCallId(call.requestId);
417
- const name = call.label;
418
- const isTool = call.method === "tools/call";
419
- allCalls++;
420
- sessionCalls++;
421
-
422
- logLine("info", "🔧 [" + callId + "] " + (isTool ? "Tool: " : "MCP: ") + name + " | " + requestBrief(call));
423
- if (debug) logLine("debug", " ↳ Metadata: " + requestDebug(call));
424
- if (trace) logLine("warn", " ↳ Trace args (locally visible): " + safeTraceRequest(call));
425
-
426
- let parsedRpc = null;
427
- try {
428
- parsedRpc = JSON.parse(String(msg.body || ""));
429
- } catch {
430
- parsedRpc = null;
431
- }
432
-
433
- // Enforce local tool policy before forwarding to gateway
434
- if (parsedRpc) {
435
- const verdict = evaluateToolCall(parsedRpc, policy);
436
- if (!verdict.allowed) {
437
- allFails++;
438
- sessionFails++;
439
- logLine("warn", "🛡️ [" + callId + "] Policy blocked " + name + ": " + verdict.reason);
440
- const blockedResp = {
441
- kind: "response",
442
- id: msg.id,
443
- status: 200,
444
- headers: { "content-type": "application/json" },
445
- body: buildPolicyBlockedResponse(parsedRpc.id, verdict.reason)
446
- };
447
- if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(blockedResp));
448
- return;
449
- }
450
- }
451
-
452
- if (!gatewayHealthy) {
453
- allFails++;
454
- sessionFails++;
455
- const unavailable = {
456
- kind: "response",
457
- id: msg.id,
458
- status: 503,
459
- headers: { "content-type": "application/json" },
460
- body: JSON.stringify({ error: "Local MCP gateway is currently restarting; retry shortly." })
461
- };
462
- logLine("error", "❌ [" + callId + "] " + name + " | Local gateway unavailable");
463
- if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(unavailable));
464
- return;
465
- }
466
-
467
- const headers = { authorization: "Bearer " + localGatewayToken };
468
- for (const k of ["accept", "content-type", "mcp-session-id", "mcp-protocol-version", "last-event-id", "mcp-method", "mcp-name"]) {
469
- if (msg.headers?.[k]) headers[k] = msg.headers[k];
470
- }
471
- if (parsedRpc && typeof parsedRpc.method === "string") {
472
- headers["mcp-method"] = parsedRpc.method;
473
- if (parsedRpc.method === "tools/call" && typeof parsedRpc.params?.name === "string") {
474
- headers["mcp-name"] = parsedRpc.params.name;
475
- }
476
- }
477
-
478
- const controller = new AbortController();
479
- const timeout = setTimeout(() => controller.abort(new Error("Local gateway timeout (70s)")), 70000);
480
- inflightControllers.set(msg.id, controller);
481
-
482
- let response;
483
- try {
484
- const fetchOpts = {
485
- method: msg.method || "POST",
486
- headers,
487
- signal: controller.signal
488
- };
489
- if (fetchOpts.method !== "DELETE" && fetchOpts.method !== "GET" && fetchOpts.method !== "HEAD") {
490
- fetchOpts.body = msg.body;
491
- }
492
- const r = await fetch(localBaseUrl, fetchOpts);
493
- let body = await r.text();
494
- const forward = {};
495
- for (const k of ["content-type", "mcp-session-id", "mcp-protocol-version"]) {
496
- if (r.headers.has(k)) forward[k] = r.headers.get(k);
497
- }
498
- const ct = forward["content-type"] || "";
499
-
500
- // Filter disallowed tools from tools/list responses
501
- if (call.method === "tools/list" && r.ok) {
502
- body = filterToolsListBody(body, ct, policy);
503
- }
504
-
505
- // Outbound DLP secret redaction
506
- const dlpResult = redactOutboundResponse(body, ct, {
507
- enabled: policy.dlp,
508
- extraSecrets: [activeCreds?.token || "", localGatewayToken]
509
- });
510
- if (dlpResult.redactedCount > 0) {
511
- logLine("warn", `🛡️ [${callId}] DLP redacted ${dlpResult.redactedCount} secret(s) before returning response to relay`);
512
- body = dlpResult.body;
513
- }
514
-
515
- response = { kind: "response", id: msg.id, status: r.status, headers: forward, body: body.slice(0, 8 * 1024 * 1024) };
516
- } catch (e) {
517
- const aborted = controller.signal.aborted;
518
- const reason = controller.signal.reason?.message || e.message || "Local gateway error";
519
- response = {
520
- kind: "response",
521
- id: msg.id,
522
- status: aborted && /client/i.test(reason) ? 499 : 502,
523
- headers: { "content-type": "application/json" },
524
- body: JSON.stringify({ error: "Local gateway error", message: String(reason).slice(0, 180) })
525
- };
526
- } finally {
527
- clearTimeout(timeout);
528
- inflightControllers.delete(msg.id);
529
- }
530
-
531
- const result = responseBrief(response.body, response.headers?.["content-type"] || "", response.status);
532
- const failed = result.failed;
533
- if (failed) {
534
- allFails++;
535
- sessionFails++;
536
- }
537
- logLine(
538
- failed ? "error" : "info",
539
- (failed ? "❌" : "✅") +
540
- " [" +
541
- callId +
542
- "] " +
543
- name +
544
- " | " +
545
- result.kind +
546
- " | HTTP " +
547
- response.status +
548
- " | " +
549
- formatElapsed(Date.now() - started)
550
- );
551
- logLine(failed ? "warn" : "info", " ↳ " + result.summary);
552
- if (result.error) logLine("error", " ↳ JSON-RPC: " + result.error);
553
- if (debug) logLine("debug", " ↳ Response size: " + result.bytes + " bytes | Total calls: " + allCalls + " | Errors: " + allFails);
554
- 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
+ };
555
565
  if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(response));
556
566
  else logLine("warn", " ↳ Response cannot be delivered: relay socket is not open");
557
567
  }
558
568
 
559
- async function connect(creds, { onHealthy } = {}) {
569
+ async function connect(creds, { onHealthy, tsNode = null } = {}) {
560
570
  return new Promise((resolve) => {
561
571
  const { wsAgent } = remoteTransport();
562
572
  const attempt = ++connectionAttempt;
@@ -601,14 +611,11 @@ async function connect(creds, { onHealthy } = {}) {
601
611
  lastError = "";
602
612
  awaitingPong = false;
603
613
 
604
- // Reset backoff retries once the connection proves stable for 10s
605
614
  healthyTimer = setTimeout(() => {
606
615
  if (ws.readyState === WebSocket.OPEN) onHealthy?.();
607
616
  }, 10000);
608
617
  healthyTimer.unref?.();
609
618
 
610
- // RFC 6455 control-frame heartbeat: answered at the Cloudflare edge without waking hibernated DOs,
611
- // and compatible with both legacy v0.3.x and v0.4.0 Workers.
612
619
  heartbeatTimer = setInterval(() => {
613
620
  if (ws.readyState !== WebSocket.OPEN) return;
614
621
  if (awaitingPong) {
@@ -631,8 +638,10 @@ async function connect(creds, { onHealthy } = {}) {
631
638
  heartbeatTimer.unref?.();
632
639
 
633
640
  logLine("info", "✅ Cloudflare relay connected in " + formatElapsed(Date.now() - opening));
634
- reportDevice(creds);
635
- console.log("CONNECTED. Your AI client can now use this device. Ctrl+C to disconnect.");
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);
636
645
  });
637
646
 
638
647
  ws.on("pong", () => {
@@ -649,9 +658,7 @@ async function connect(creds, { onHealthy } = {}) {
649
658
  ws.on("message", (data) => {
650
659
  awaitingPong = false;
651
660
  const text = String(data);
652
- if (text === "pong") {
653
- return;
654
- }
661
+ if (text === "pong") return;
655
662
  let m;
656
663
  try {
657
664
  m = JSON.parse(text);
@@ -714,47 +721,166 @@ async function connect(creds, { onHealthy } = {}) {
714
721
  });
715
722
  }
716
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
+
717
754
  async function runDoctor() {
755
+ const checkTailscaleOnly = opts.transport === "tailscale";
718
756
  let healthy = true;
719
- console.log(`Private Desktop MCP Doctor (v${PKG_VERSION})`);
720
- console.log("─".repeat(48));
721
- console.log("Node.js:", process.version, `(${process.platform}/${process.arch})`);
722
- console.log("Relay URL:", opts.relay);
723
-
757
+ let proxyInfo = { mode: "unknown", source: "unknown" };
724
758
  let transport = {};
725
- try {
726
- const p = resolveProxyForUrl(opts.relay);
727
- console.log("Proxy:", p.mode === "proxy" ? `${p.source} (${p.description})` : `${p.mode} (${p.source}${p.reason ? ": " + p.reason : ""})`);
728
- if (p.mode === "unsupported") healthy = false;
729
- else if (p.mode === "proxy") transport = { dispatcher: new ProxyAgent(p.url) };
730
- } catch (e) {
731
- console.log("Proxy: error -", e.message);
732
- healthy = false;
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" };
733
772
  }
734
773
 
735
- try {
736
- const t0 = Date.now();
737
- const res = await fetch(opts.relay + "/relay/status", {
738
- signal: AbortSignal.timeout(8000),
739
- ...transport
740
- });
741
- const body = await res.json();
742
- console.log(
743
- `Relay Status: OK (HTTP ${res.status}, ${Date.now() - t0}ms, worker v${body.version || "unknown"}, features: ${(body.features || []).join(",") || "legacy"})`
744
- );
745
- } catch (e) {
746
- console.log("Relay Status: UNREACHABLE -", sanitizeText(e.message, 140));
747
- healthy = false;
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;
748
802
  }
749
803
 
750
804
  const creds = saved();
751
- console.log("Device Pairing:", creds ? `paired (id=${String(creds.deviceId || "").slice(0, 8)}…)` : "not paired");
805
+ let localPortOccupied = false;
806
+ let localHttpStatus = 0;
752
807
  try {
753
- const st = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) })).status;
754
- console.log(`Local Port ${opts.port}: occupied (HTTP ${st})`);
808
+ localHttpStatus = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) })).status;
809
+ localPortOccupied = localHttpStatus > 0;
755
810
  } catch {
756
- console.log(`Local Port ${opts.port}: free`);
811
+ localPortOccupied = false;
812
+ }
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
+
819
+ if (opts.json) {
820
+ console.log(
821
+ JSON.stringify(
822
+ {
823
+ ok: healthy,
824
+ version: PKG_VERSION,
825
+ transport: opts.transport,
826
+ runtime: { node: process.version, platform: process.platform, arch: process.arch },
827
+ relay: opts.relay,
828
+ proxy: proxyInfo,
829
+ relayStatus,
830
+ tailscale: tailscaleInfo,
831
+ recommendedTransports,
832
+ paired: Boolean(creds?.deviceId),
833
+ deviceId: creds?.deviceId ? String(creds.deviceId).slice(0, 8) + "…" : null,
834
+ localPort: opts.port,
835
+ localPortOccupied,
836
+ policy: {
837
+ readonly: policy.readonly,
838
+ dlp: policy.dlp,
839
+ allowDirsCount: policy.allowDirs.length
840
+ }
841
+ },
842
+ null,
843
+ 2
844
+ )
845
+ );
846
+ if (!healthy) process.exitCode = 1;
847
+ return;
848
+ }
849
+
850
+ console.log(`Private Desktop MCP Doctor (v${PKG_VERSION})`);
851
+ console.log("─".repeat(48));
852
+ console.log("Node.js:", process.version, `(${process.platform}/${process.arch})`);
853
+ console.log("Relay URL:", opts.relay);
854
+ console.log(
855
+ "Proxy:",
856
+ proxyInfo.mode === "proxy"
857
+ ? `${proxyInfo.source} (${proxyInfo.description})`
858
+ : `${proxyInfo.mode} (${proxyInfo.source}${proxyInfo.reason ? ": " + proxyInfo.reason : ""})`
859
+ );
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) {
870
+ console.log(
871
+ `Tailscale: RUNNING (${tailscaleInfo.self?.dnsName || tailscaleInfo.self?.ipv4}, HTTPS: ${tailscaleInfo.httpsEnabled ? "ON" : "OFF"}, same-user online peers: ${tailscaleInfo.sameUserOnlinePeersCount}/${tailscaleInfo.onlinePeersCount})`
872
+ );
873
+ if (tailscaleInfo.suggestedNodeUrl) {
874
+ console.log("Tailscale Node URL:", tailscaleInfo.suggestedNodeUrl);
875
+ }
876
+ } else {
877
+ console.log(
878
+ "Tailscale:",
879
+ tailscaleInfo.installed ? `NOT RUNNING (${tailscaleInfo.backendState})` : "not installed"
880
+ );
757
881
  }
882
+ console.log("Device Pairing:", creds ? `paired (id=${String(creds.deviceId || "").slice(0, 8)}…)` : "not paired");
883
+ console.log(`Local Port ${opts.port}:`, localPortOccupied ? `occupied (HTTP ${localHttpStatus})` : "free");
758
884
  console.log("Policy:", policy.readonly ? "READONLY" : "FULL", "| DLP:", policy.dlp ? "ON" : "OFF");
759
885
  if (!healthy) process.exitCode = 1;
760
886
  }
@@ -762,6 +888,7 @@ async function runDoctor() {
762
888
  function runReport() {
763
889
  const p = resolveProxyForUrl(opts.relay);
764
890
  const creds = saved();
891
+ const tsSummary = summarizeTailscaleForDiagnostics(getTailscaleStatus());
765
892
  let gatewayLogTail = [];
766
893
  try {
767
894
  const raw = fs.readFileSync(gatewayLogPath, "utf8");
@@ -785,6 +912,7 @@ function runReport() {
785
912
  description: p.description || "",
786
913
  reason: p.reason || ""
787
914
  },
915
+ tailscale: tsSummary,
788
916
  policy: {
789
917
  readonly: policy.readonly,
790
918
  dlp: policy.dlp,
@@ -797,6 +925,268 @@ function runReport() {
797
925
  console.log(JSON.stringify(report, null, 2));
798
926
  }
799
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
+
958
+ function runSetupClient() {
959
+ const target = String(opts.targetClient || "").toLowerCase().trim();
960
+ if (!target) {
961
+ const msg = `Specify a target client: ${SUPPORTED_CLIENTS.join(", ")} or "all"`;
962
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: msg, supportedClients: SUPPORTED_CLIENTS }, null, 2));
963
+ else console.error(msg);
964
+ process.exitCode = 2;
965
+ return;
966
+ }
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
+
978
+ const clients = target === "all" ? SUPPORTED_CLIENTS : [target];
979
+ const results = [];
980
+ for (const client of clients) {
981
+ try {
982
+ const res = configureMcpClient({
983
+ client,
984
+ relayUrl: resolvedEndpoint.url,
985
+ serverName: opts.serverName || undefined,
986
+ bearerToken: opts.sharedToken || "",
987
+ configPath: clients.length === 1 && opts.clientConfigPath ? opts.clientConfigPath : undefined,
988
+ dryRun: opts.dryRun
989
+ });
990
+ results.push({ ...res, endpointMode: resolvedEndpoint.mode });
991
+ } catch (e) {
992
+ results.push({ ok: false, client, error: e.message });
993
+ process.exitCode = 1;
994
+ }
995
+ }
996
+
997
+ if (opts.json) {
998
+ console.log(JSON.stringify(clients.length === 1 ? results[0] : { ok: results.every((r) => r.ok), results }, null, 2));
999
+ return;
1000
+ }
1001
+
1002
+ for (const r of results) {
1003
+ if (!r.ok) {
1004
+ console.error(`❌ [${r.client}] ${r.error}`);
1005
+ continue;
1006
+ }
1007
+ console.log(`${r.dryRun ? "🔍 [DRY-RUN]" : "✅"} [${r.client}] ${r.action.toUpperCase()} (${r.endpointMode}) → ${r.path}`);
1008
+ if (r.dryRun) {
1009
+ console.log(r.preview.trimEnd());
1010
+ }
1011
+ }
1012
+ }
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
+
800
1190
  function stop() {
801
1191
  if (stopping) return;
802
1192
  stopping = true;
@@ -804,8 +1194,10 @@ function stop() {
804
1194
  try {
805
1195
  socket?.close(1000, "Manual disconnect");
806
1196
  } catch {}
807
- stopGateway();
808
- setTimeout(() => process.exit(0), 200).unref();
1197
+ Promise.allSettled([tailscaleNodeHandle?.close(), tailnetHubHandle?.close()]).finally(() => {
1198
+ stopGateway();
1199
+ setTimeout(() => process.exit(0), 200).unref();
1200
+ });
809
1201
  }
810
1202
 
811
1203
  process.on("SIGINT", stop);
@@ -813,82 +1205,170 @@ process.on("SIGTERM", stop);
813
1205
 
814
1206
  if (opts.command === "help") {
815
1207
  console.log(
816
- `Private Desktop MCP v${PKG_VERSION}: connect | status | doctor | report | reset\n` +
817
- "Options:\n" +
818
- " --relay <url> Custom Cloudflare Worker relay URL (env: PCC_RELAY_URL)\n" +
819
- " --port <port> Local MCP gateway port (default: 8717, env: MCP_PORT)\n" +
820
- " --name <name> Device display name when pairing (default: hostname)\n" +
821
- " --readonly Allow read-only tools only and hide mutating tools\n" +
822
- " --allow-dir <dir> Restrict file tool paths to allowed directories (repeatable)\n" +
823
- " --allow-tools <csv> Explicit allowlist of MCP tool names\n" +
824
- " --deny-tools <csv> Explicit denylist of MCP tool names\n" +
825
- " --servers <file.json> Aggregate additional local stdio MCP servers (env: PCC_MCP_CONFIG)\n" +
826
- " --no-dlp Disable outbound secret redaction on responses (enabled by default)\n" +
827
- " --no-open Do not auto-open browser during device pairing\n" +
828
- " --safe | --debug | --trace Terminal logging verbosity (default: TRACE)\n" +
1208
+ `Private Desktop MCP v${PKG_VERSION}: connect | serve | hub | status | doctor | report | setup-client | reset\n` +
1209
+ "Subcommands:\n" +
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" +
1215
+ " report [--json] Generate sanitized JSON diagnostic bundle\n" +
1216
+ ` setup-client <client|all> Configure MCP client (${SUPPORTED_CLIENTS.join(", ")})\n` +
1217
+ " reset [--json] Clear local device pairing credentials\n" +
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" +
1239
+ " --port <port> Local MCP gateway port (default: 8717, env: MCP_PORT)\n" +
1240
+ " --name <name> Device display name (default: hostname)\n" +
1241
+ " --readonly Allow read-only tools only and hide mutating tools\n" +
1242
+ " --allow-dir <dir> Restrict file tool paths to allowed directories (repeatable)\n" +
1243
+ " --allow-tools <csv> Explicit allowlist of MCP tool names\n" +
1244
+ " --deny-tools <csv> Explicit denylist of MCP tool names\n" +
1245
+ " --servers <file.json> Aggregate additional local stdio MCP servers (env: PCC_MCP_CONFIG)\n" +
1246
+ " --no-dlp Disable outbound secret redaction on responses (enabled by default)\n" +
1247
+ " --no-open Do not auto-open browser during device pairing\n" +
1248
+ " --dry-run Preview client config changes without writing to disk (for setup-client)\n" +
1249
+ " --config <path> Custom client config file path override (for setup-client)\n" +
1250
+ " --json Emit machine-readable JSON output for agents\n" +
1251
+ " --safe | --debug | --trace Terminal logging verbosity (default: TRACE)\n" +
829
1252
  `Default relay: ${DEFAULT_RELAY}\n` +
830
1253
  `Approval page: ${opts.relay}/admin/devices\n` +
831
1254
  "Ctrl+C to disconnect. No automatic startup."
832
1255
  );
833
1256
  } else if (opts.command === "status") {
834
- console.log("Paired:", !!saved());
835
- console.log("Relay:", opts.relay);
1257
+ const creds = saved();
1258
+ const tsSummary = summarizeTailscaleForDiagnostics(getTailscaleStatus());
1259
+ let localHttpStatus = null;
836
1260
  try {
837
- console.log("Local HTTP:", (await fetch(localBaseUrl, { signal: AbortSignal.timeout(2000) })).status);
1261
+ localHttpStatus = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(2000) })).status;
838
1262
  } catch {
839
- console.log("Local MCP offline");
1263
+ localHttpStatus = null;
1264
+ }
1265
+ if (opts.json) {
1266
+ console.log(
1267
+ JSON.stringify(
1268
+ {
1269
+ ok: true,
1270
+ version: PKG_VERSION,
1271
+ paired: Boolean(creds?.deviceId),
1272
+ deviceId: creds?.deviceId ? String(creds.deviceId).slice(0, 8) + "…" : null,
1273
+ relay: opts.relay,
1274
+ localPort: opts.port,
1275
+ localGatewayRunning: localHttpStatus !== null,
1276
+ localHttpStatus,
1277
+ tailscale: tsSummary,
1278
+ policy: { readonly: policy.readonly, dlp: policy.dlp }
1279
+ },
1280
+ null,
1281
+ 2
1282
+ )
1283
+ );
1284
+ } else {
1285
+ console.log("Paired:", !!creds);
1286
+ console.log("Relay:", opts.relay);
1287
+ console.log(
1288
+ "Tailscale:",
1289
+ tsSummary.running ? `running (${tsSummary.suggestedNodeUrl || tsSummary.self?.ipv4})` : tsSummary.backendState
1290
+ );
1291
+ if (localHttpStatus !== null) console.log("Local HTTP:", localHttpStatus);
1292
+ else console.log("Local MCP offline");
840
1293
  }
841
1294
  } else if (opts.command === "doctor") {
842
1295
  await runDoctor();
843
1296
  } else if (opts.command === "report") {
844
1297
  runReport();
1298
+ } else if (opts.command === "setup-client") {
1299
+ runSetupClient();
845
1300
  } else if (opts.command === "reset") {
846
1301
  forget();
847
- console.log("Local credentials cleared. Revoke old credentials in the admin page too.");
1302
+ if (opts.json) {
1303
+ console.log(JSON.stringify({ ok: true, cleared: true, configPath: config }, null, 2));
1304
+ } else {
1305
+ console.log("Local credentials cleared. Revoke old credentials in the admin page too.");
1306
+ }
1307
+ } else if (opts.command === "serve") {
1308
+ await runServeOnly();
1309
+ } else if (opts.command === "hub") {
1310
+ await runHub();
848
1311
  } else if (opts.command === "connect") {
849
- logLine("info", `╔══════════════ PCC REMOTE v${PKG_VERSION} ══════════════╗`);
850
- logLine(
851
- "info",
852
- "Logging: " +
853
- (trace ? "TRACE" : debug ? "DEBUG" : "LIVE") +
854
- " | Policy: " +
855
- (policy.readonly ? "READONLY" : "FULL") +
856
- " | DLP: " +
857
- (policy.dlp ? "ON" : "OFF") +
858
- " | Gateway: Desktop Commander MCP"
859
- );
860
- if (trace) logLine("warn", "TRACE mode can display private user content in this terminal; do not share these logs.");
861
- logLine("info", "╚═══════════════════════════════════════════════╝");
862
- try {
863
- const existing = saved();
864
- const credentials = existing || (await pair());
865
- activeCreds = credentials;
866
- if (existing) logLine("info", "💾 Stored device pairing found");
867
- await startGateway();
868
- let retries = 0;
869
- while (!stopping) {
870
- const r = await connect(credentials, {
871
- onHealthy: () => {
872
- retries = 0;
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;
873
1356
  }
874
- });
875
- if (r.unauthorized) {
876
- forget();
877
- logLine("error", "Credentials revoked; run again to pair.");
878
- break;
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);
879
1363
  }
880
- if (stopping) break;
881
- retries++;
882
- const baseMs = Math.min(30000, 1500 * 2 ** Math.min(5, retries));
883
- const jitterMs = Math.round(baseMs * (0.75 + Math.random() * 0.5));
884
- logLine("warn", "Reconnecting in " + (jitterMs / 1000).toFixed(1) + "s");
885
- await sleep(jitterMs);
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();
886
1371
  }
887
- } catch (e) {
888
- logLine("error", "ERROR: " + sanitizeText(e.message, 250));
889
- process.exitCode = 1;
890
- } finally {
891
- stopGateway();
892
1372
  }
893
1373
  } else {
894
1374
  console.error("Unknown command. Use help");