@juexibobi/private-desktop-mcp 0.3.6 → 0.5.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
@@ -1,144 +1,1064 @@
1
1
  #!/usr/bin/env node
2
+ import crypto from "node:crypto";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
5
  import os from "node:os";
5
- import {spawn,spawnSync} from "node:child_process";
6
- import {fileURLToPath} from "node:url";
6
+ import { spawn, spawnSync } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
7
8
  import WebSocket from "ws";
8
9
  import { ProxyAgent } from "undici";
9
- import { resolveProxyForUrl } from "./proxy.mjs";
10
10
  import { HttpsProxyAgent } from "https-proxy-agent";
11
+ import { resolveProxyForUrl } from "./proxy.mjs";
11
12
  import { logLine, sanitizeText } from "./logging.mjs";
12
- import { callInfo, requestBrief, requestDebug, responseBrief, safeTraceRequest, safeTraceOutput, shortCallId, formatElapsed, loggingOptions } from "./activity.mjs";
13
-
14
- const root=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
15
- const command=process.argv.slice(2).find(a=>!a.startsWith("--"))||"connect",relay="https://private-desktop-device-relay.ljx2043979076.workers.dev";
16
- const {trace,debug}=loggingOptions(process.argv.slice(2));
17
- const config=path.join(process.env.APPDATA||path.join(os.homedir(),".config"),"PrivateDesktopMCP","device.json");
18
- const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
19
- let currentProxy=null,proxyCheckedAt=0,lastProxyNotice="";
20
- const agents=new Map();
21
- function remoteTransport(){
22
- if(!currentProxy||Date.now()-proxyCheckedAt>10000){
23
- currentProxy=resolveProxyForUrl(relay);
24
- proxyCheckedAt=Date.now();
25
- if(currentProxy.mode==="unsupported")throw Error(currentProxy.reason+" (use an HTTP/Mixed port via system settings or HTTPS_PROXY)");
26
- const notice=currentProxy.mode==="proxy"?"🌐 Proxy: "+currentProxy.source+" ("+currentProxy.description+")":
27
- currentProxy.mode==="unavailable"?"⚠️ Proxy detection unavailable: "+currentProxy.reason+"; trying direct":
28
- "🌐 Direct connection ("+currentProxy.source+")";
29
- if(notice!==lastProxyNotice){logLine(currentProxy.mode==="unavailable"?"warn":"info",notice);lastProxyNotice=notice}
30
- }
31
- if(currentProxy.mode!=="proxy")return {};
32
- let transport=agents.get(currentProxy.url);
33
- if(!transport){
34
- transport={dispatcher:new ProxyAgent(currentProxy.url),wsAgent:new HttpsProxyAgent(currentProxy.url)};
35
- agents.set(currentProxy.url,transport);
36
- }
37
- return transport;
38
- }
39
- let stopping=false,child=null,socket=null;
40
- let connectionAttempt=0,connectedSince=0,sessionCalls=0,sessionFails=0,allCalls=0,allFails=0,lastError="";
41
- function reportDevice(creds){
42
- logLine("info","━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
43
- logLine("info","Computer: "+os.hostname()+" | User: "+os.userInfo().username+" | Node: "+process.version);
44
- logLine("info","Device ID: "+creds.deviceId+" | Gateway PID: "+(child?.pid||"unknown"));
45
- logLine("info","Relay: "+relay+" | Local MCP: http://127.0.0.1:8717/mcp");
46
- logLine("info","Mode: "+(trace?"TRACE":debug?"DEBUG":"LIVE"));
47
- logLine("info","Return to ChatGPT; keep this terminal running. Ctrl+C to disconnect.");
48
- logLine("info","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
49
- }
50
- function saved(){try{return JSON.parse(fs.readFileSync(config,"utf8"))}catch{return null}}
51
- function store(x){fs.mkdirSync(path.dirname(config),{recursive:true,mode:0o700});fs.writeFileSync(config,JSON.stringify(x,null,2),{mode:0o600});}
52
- function forget(){try{fs.unlinkSync(config)}catch{}}
53
- async function post(route,data){const {dispatcher}=remoteTransport();const r=await fetch(relay+route,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(data),signal:AbortSignal.timeout(12000),...(dispatcher?{dispatcher}:{})});const j=await r.json();if(!r.ok)throw Error(j.error||"HTTP "+r.status);return j;}
54
- async function pair(){
55
- const v=await post("/relay/pair/start",{name:os.hostname()});
56
- logLine("info","🔑 New device pairing requested");
57
- console.log("\nNEW DEVICE: "+os.hostname()+"\nPAIRING CODE: "+v.code+"\nPlease visit "+v.approvalUrl+" and approve the matching code.\nWaiting for approval (60 minutes)...\n");
58
- for(let i=0;i<720&&!stopping;i++){
59
- await sleep(5000);let r;try{r=await post("/relay/pair/poll",{pairId:v.pairId,proof:v.proof})}catch(e){if(/expired|invalid/i.test(e.message))throw e;continue}
60
- if(r.status==="approved"){const credentials={deviceId:r.deviceId,token:r.token};store(credentials);logLine("info","✅ Device approved; credentials saved locally.");return credentials}
61
- }
62
- throw Error("Pairing timed out. Re-run the command.");
63
- }
64
- async function portOpen(){const r=await fetch("http://127.0.0.1:8717/mcp",{signal:AbortSignal.timeout(1500)});return r.status>0;}
65
- async function startGateway(){
66
- try{if(await portOpen())throw Error("Port 8717 is already occupied. Stop the other MCP gateway before connecting.")}catch(e){if(/occupied/.test(e.message))throw e}
67
- logLine("info","🚀 Starting local Desktop Commander gateway...");
68
- const fd=fs.openSync(path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"),"a");
69
- child=spawn(process.execPath,[path.join(root,"gateway.mjs")],{cwd:root,stdio:["ignore",fd,fd],windowsHide:true});fs.closeSync(fd);
70
- logLine("info","Gateway PID: "+child.pid+" | diagnostic log: "+path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"));
71
- for(let i=0;i<40;i++){if(child.exitCode!==null)throw Error("Gateway exited unexpectedly. See private-desktop-mcp-device.log");try{if(await portOpen()){logLine("info","🔌 Local Desktop Commander gateway ready (127.0.0.1:8717)");return}}catch{}await sleep(500)}
72
- throw Error("Gateway failed to listen on port 8717.");
73
- }
74
- function stopGateway(){if(child?.pid){if(process.platform==="win32")spawnSync("taskkill.exe",["/PID",String(child.pid),"/T","/F"],{windowsHide:true,timeout:8000});else child.kill("SIGTERM");child=null;}}
75
- async function respond(ws,msg){
76
- const started=Date.now(),call=callInfo(msg.body,msg.id),callId=shortCallId(call.requestId);
77
- const name=call.label,isTool=call.method==="tools/call";
78
- allCalls++;sessionCalls++;
79
- logLine("info","🔧 ["+callId+"] "+(isTool?"Tool: ":"MCP: ")+name+" | "+requestBrief(call));
80
- if(debug)logLine("debug"," ↳ Metadata: "+requestDebug(call));
81
- if(trace)logLine("warn"," ↳ Trace args (locally visible): "+safeTraceRequest(call));
82
- const headers={};for(const k of ["accept","content-type","mcp-session-id","mcp-protocol-version","last-event-id","mcp-method","mcp-name"])if(msg.headers?.[k])headers[k]=msg.headers[k];
83
- try{const rpc=JSON.parse(String(msg.body||""));if(typeof rpc.method==="string"){headers["mcp-method"]=rpc.method;if(rpc.method==="tools/call"&&typeof rpc.params?.name==="string")headers["mcp-name"]=rpc.params.name;}}catch{}
84
- let response;
85
- try{
86
- const r=await fetch("http://127.0.0.1:8717/mcp",{method:msg.method||"POST",headers,body:msg.body,signal:AbortSignal.timeout(70000)});
87
- const body=await r.text(),forward={};for(const k of ["content-type","mcp-session-id","mcp-protocol-version"])if(r.headers.has(k))forward[k]=r.headers.get(k);
88
- response={kind:"response",id:msg.id,status:r.status,headers:forward,body:body.slice(0,8*1024*1024)};
89
- }catch(e){response={kind:"response",id:msg.id,status:502,headers:{"content-type":"application/json"},body:JSON.stringify({error:"Local gateway error",message:String(e.message).slice(0,180)})}}
90
- const result=responseBrief(response.body,response.headers?.["content-type"]||"",response.status);
91
- const failed=result.failed;
92
- if(failed){allFails++;sessionFails++;}
93
- logLine(failed?"error":"info",(failed?"❌":"✅")+" ["+callId+"] "+name+
94
- " | "+result.kind+" | HTTP "+response.status+" | "+formatElapsed(Date.now()-started));
95
- logLine(failed?"warn":"info"," ↳ "+result.summary);
96
- if(result.error)logLine("error"," ↳ JSON-RPC: "+result.error);
97
- if(debug)logLine("debug"," ↳ Response size: "+result.bytes+" bytes | Total calls: "+allCalls+" | Errors: "+allFails);
98
- if(trace)logLine("warn"," ↳ Trace output (may contain private data): "+safeTraceOutput(result));
99
- if(ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify(response));
100
- else logLine("warn"," ↳ Response cannot be delivered: relay socket is not open");
101
- }
102
- async function connect(creds){return new Promise(resolve=>{
103
- const {wsAgent}=remoteTransport();
104
- const attempt=++connectionAttempt,opening=Date.now();
105
- logLine("info","🌐 Connecting to Cloudflare relay (attempt #"+attempt+")...");
106
- const ws=new WebSocket(relay.replace(/^https:/,"wss:")+"/relay/ws",{headers:{"Authorization":"Bearer "+creds.token,"X-Device-ID":creds.deviceId},handshakeTimeout:15000,...(wsAgent?{agent:wsAgent}:{})});socket=ws;
107
- let status=0;
108
- ws.on("open",()=>{
109
- connectedSince=Date.now();sessionCalls=0;sessionFails=0;lastError="";
110
- logLine("info","✅ Cloudflare relay connected in "+formatElapsed(Date.now()-opening));
111
- reportDevice(creds);
112
- console.log("CONNECTED. ChatGPT can now use this device. Ctrl+C to disconnect.");
113
- });
114
- ws.on("unexpected-response",(_req,res)=>{status=res.statusCode;res.resume();lastError="HTTP "+status;logLine("error","Relay handshake rejected: HTTP "+status)});
115
- ws.on("message",data=>{
116
- let m;try{m=JSON.parse(String(data))}catch{if(debug)logLine("debug","Ignored invalid relay JSON message");return}
117
- if(m.kind==="request")respond(ws,m).catch(e=>logLine("error","Request handler: "+sanitizeText(e.message,240)));
118
- });
119
- ws.on("error",e=>{lastError=sanitizeText(e.message,180);logLine("error","Relay network error: "+lastError)});
120
- ws.on("close",(code,reason)=>{
121
- socket=null;
122
- const uptime=connectedSince?formatElapsed(Date.now()-connectedSince):"not established";
123
- logLine("warn","🔌 Relay disconnected | code="+code+" | session uptime="+uptime+
124
- " | calls="+sessionCalls+" | failures="+sessionFails);
125
- if(lastError)logLine("warn"," ↳ Last network error: "+lastError);
126
- if(reason?.length)logLine("warn"," ↳ Close reason: "+sanitizeText(reason.toString(),100));
127
- connectedSince=0;
128
- resolve({unauthorized:status===401});
129
- });
130
- })}
131
- function stop(){if(stopping)return;stopping=true;logLine("info","Disconnecting PCC...");try{socket?.close(1000,"Manual disconnect")}catch{}stopGateway();setTimeout(()=>process.exit(0),200).unref();}
132
- process.on("SIGINT",stop);process.on("SIGTERM",stop);
133
- if(["help","--help","-h"].includes(command)){console.log("Private Desktop MCP: connect | status | reset [--safe | --debug | --trace]\nDefault: TRACE logs with redacted/truncated command and response previews (may contain private data).\nUse --safe for compact metadata-only logs, or --debug for detailed metadata without content previews.\nFirst connect requires approval at https://private-desktop-device-relay.ljx2043979076.workers.dev/admin/devices\nCtrl+C to disconnect. No automatic startup.");}
134
- else if(command==="status"){console.log("Paired:",!!saved());try{console.log("Local HTTP:",(await fetch("http://127.0.0.1:8717/mcp",{signal:AbortSignal.timeout(2000)})).status)}catch{console.log("Local MCP offline")}}
135
- else if(command==="reset"){forget();console.log("Local credentials cleared. Revoke old credentials in the admin page too.");}
136
- else if(command==="connect"){
137
- logLine("info","╔══════════════ PCC REMOTE v0.3.6 ══════════════╗");
138
- logLine("info","Logging: "+(trace?"TRACE":debug?"DEBUG":"LIVE")+" | Gateway: Desktop Commander MCP");
139
- if(trace)logLine("warn","TRACE mode can display private user content in this terminal; do not share these logs.");
140
- logLine("info","╚═══════════════════════════════════════════════╝");
141
- try{const credentials=saved()||await pair();if(saved())logLine("info","💾 Stored device pairing found");await startGateway();let retries=0;
142
- while(!stopping){const r=await connect(credentials);if(r.unauthorized){forget();logLine("error","Credentials revoked; run again to pair.");break}if(stopping)break;retries++;const ms=Math.min(30000,1500*2**Math.min(5,retries));logLine("warn","Reconnecting in "+Math.ceil(ms/1000)+"s");await sleep(ms);}
143
- }catch(e){logLine("error","ERROR: "+sanitizeText(e.message,250));process.exitCode=1}finally{stopGateway()}
144
- }else{console.error("Unknown command. Use help");process.exitCode=2}
13
+ 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";
31
+ import { SUPPORTED_CLIENTS, configureMcpClient } from "./client-setup.mjs";
32
+
33
+ const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
34
+ const PKG_VERSION = (() => {
35
+ try {
36
+ return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.5.0";
37
+ } catch {
38
+ return "0.5.0";
39
+ }
40
+ })();
41
+
42
+ const DEFAULT_RELAY = "https://private-desktop-device-relay.ljx2043979076.workers.dev";
43
+ const HEARTBEAT_INTERVAL_MS = 25000;
44
+ const MAX_GATEWAY_LOG_BYTES = 5 * 1024 * 1024;
45
+
46
+ function parseArgs(argv) {
47
+ let command = "";
48
+ let subarg = "";
49
+ let relay = process.env.PCC_RELAY_URL || DEFAULT_RELAY;
50
+ let port = Number(process.env.MCP_PORT || 8717);
51
+ let deviceName = os.hostname();
52
+ let readonly = /^(1|true|yes)$/i.test(String(process.env.PCC_READONLY || ""));
53
+ let dlp = !/^(0|false|no)$/i.test(String(process.env.PCC_DLP || "true"));
54
+ let autoOpen = true;
55
+ let jsonOutput = false;
56
+ let dryRun = false;
57
+ let targetClient = "";
58
+ let clientConfigPath = "";
59
+ let serversConfig = process.env.PCC_MCP_CONFIG || "";
60
+ const allowDirs = String(process.env.PCC_ALLOW_DIRS || "")
61
+ .split(path.delimiter)
62
+ .map((s) => s.trim())
63
+ .filter(Boolean);
64
+ const allowTools = String(process.env.PCC_ALLOW_TOOLS || "")
65
+ .split(",")
66
+ .map((s) => s.trim())
67
+ .filter(Boolean);
68
+ const denyTools = String(process.env.PCC_DENY_TOOLS || "")
69
+ .split(",")
70
+ .map((s) => s.trim())
71
+ .filter(Boolean);
72
+
73
+ for (let i = 0; i < argv.length; i++) {
74
+ const arg = argv[i];
75
+ if (!arg.startsWith("-")) {
76
+ if (!command) command = arg;
77
+ else if (!subarg) subarg = arg;
78
+ continue;
79
+ }
80
+ const eq = arg.indexOf("=");
81
+ const flag = eq > 0 ? arg.slice(0, eq) : arg;
82
+ const inlineVal = eq > 0 ? arg.slice(eq + 1) : null;
83
+ const nextVal = () => (inlineVal !== null ? inlineVal : argv[++i] || "");
84
+
85
+ if (flag === "--help" || flag === "-h") command = "help";
86
+ else if (flag === "--relay") relay = nextVal().replace(/\/+$/, "");
87
+ else if (flag === "--port") port = Number(nextVal());
88
+ else if (flag === "--name") deviceName = nextVal();
89
+ else if (flag === "--readonly") readonly = true;
90
+ else if (flag === "--no-dlp") dlp = false;
91
+ else if (flag === "--no-open") autoOpen = false;
92
+ else if (flag === "--json") jsonOutput = true;
93
+ else if (flag === "--dry-run") dryRun = true;
94
+ else if (flag === "--client") targetClient = nextVal();
95
+ else if (flag === "--config") clientConfigPath = nextVal();
96
+ else if (flag === "--servers") serversConfig = nextVal();
97
+ else if (flag === "--allow-dir") {
98
+ const v = nextVal().trim();
99
+ if (v) allowDirs.push(v);
100
+ } else if (flag === "--allow-tools") {
101
+ for (const item of nextVal().split(",")) if (item.trim()) allowTools.push(item.trim());
102
+ } else if (flag === "--deny-tools") {
103
+ for (const item of nextVal().split(",")) if (item.trim()) denyTools.push(item.trim());
104
+ }
105
+ }
106
+
107
+ return {
108
+ command: command || "connect",
109
+ subarg,
110
+ relay: relay.replace(/\/+$/, ""),
111
+ port,
112
+ deviceName: deviceName || "Desktop",
113
+ readonly,
114
+ dlp,
115
+ autoOpen,
116
+ json: jsonOutput,
117
+ dryRun,
118
+ targetClient: targetClient || subarg,
119
+ clientConfigPath,
120
+ serversConfig,
121
+ allowDirs,
122
+ allowTools,
123
+ denyTools
124
+ };
125
+ }
126
+
127
+ const opts = parseArgs(process.argv.slice(2));
128
+ const { trace, debug } = loggingOptions(process.argv.slice(2));
129
+ const configDir = path.join(process.env.APPDATA || path.join(os.homedir(), ".config"), "PrivateDesktopMCP");
130
+ const config = path.join(configDir, "device.json");
131
+ const gatewayLogDir = path.join(configDir, "logs");
132
+ const gatewayLogPath = path.join(gatewayLogDir, "gateway.log");
133
+ const localBaseUrl = `http://127.0.0.1:${opts.port}/mcp`;
134
+ const localGatewayToken = crypto.randomBytes(32).toString("hex");
135
+ const policy = createPolicy({
136
+ readonly: opts.readonly,
137
+ allowTools: opts.allowTools,
138
+ denyTools: opts.denyTools,
139
+ allowDirs: opts.allowDirs,
140
+ protectedDirs: [configDir],
141
+ dlp: opts.dlp
142
+ });
143
+
144
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
145
+ let currentProxy = null;
146
+ let proxyCheckedAt = 0;
147
+ let lastProxyNotice = "";
148
+ const agents = new Map();
149
+
150
+ function remoteTransport() {
151
+ if (!currentProxy || Date.now() - proxyCheckedAt > 10000) {
152
+ currentProxy = resolveProxyForUrl(opts.relay);
153
+ proxyCheckedAt = Date.now();
154
+ if (currentProxy.mode === "unsupported") {
155
+ throw Error(currentProxy.reason + " (use an HTTP/Mixed port via system settings or HTTPS_PROXY)");
156
+ }
157
+ const notice =
158
+ currentProxy.mode === "proxy"
159
+ ? "🌐 Proxy: " + currentProxy.source + " (" + currentProxy.description + ")"
160
+ : currentProxy.mode === "unavailable"
161
+ ? "⚠️ Proxy detection unavailable: " + currentProxy.reason + "; trying direct"
162
+ : "🌐 Direct connection (" + currentProxy.source + ")";
163
+ if (notice !== lastProxyNotice) {
164
+ logLine(currentProxy.mode === "unavailable" ? "warn" : "info", notice);
165
+ lastProxyNotice = notice;
166
+ }
167
+ }
168
+ if (currentProxy.mode !== "proxy") return {};
169
+ let transport = agents.get(currentProxy.url);
170
+ if (!transport) {
171
+ transport = { dispatcher: new ProxyAgent(currentProxy.url), wsAgent: new HttpsProxyAgent(currentProxy.url) };
172
+ agents.set(currentProxy.url, transport);
173
+ }
174
+ return transport;
175
+ }
176
+
177
+ let stopping = false;
178
+ let child = null;
179
+ let gatewayHealthy = false;
180
+ let gatewayRestartCount = 0;
181
+ let gatewayRestartPromise = null;
182
+ let socket = null;
183
+ let activeCreds = null;
184
+ let connectionAttempt = 0;
185
+ let connectedSince = 0;
186
+ let sessionCalls = 0;
187
+ let sessionFails = 0;
188
+ let allCalls = 0;
189
+ let allFails = 0;
190
+ let lastError = "";
191
+ const inflightControllers = new Map();
192
+
193
+ function saved() {
194
+ try {
195
+ return JSON.parse(fs.readFileSync(config, "utf8"));
196
+ } catch {
197
+ return null;
198
+ }
199
+ }
200
+
201
+ function store(x) {
202
+ fs.mkdirSync(path.dirname(config), { recursive: true, mode: 0o700 });
203
+ fs.writeFileSync(config, JSON.stringify(x, null, 2), { mode: 0o600 });
204
+ }
205
+
206
+ function forget() {
207
+ try {
208
+ fs.unlinkSync(config);
209
+ } catch {}
210
+ }
211
+
212
+ function rotateLogIfNeeded(filePath) {
213
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
214
+ try {
215
+ const stat = fs.statSync(filePath);
216
+ if (stat.size >= MAX_GATEWAY_LOG_BYTES) {
217
+ try {
218
+ fs.unlinkSync(filePath + ".1");
219
+ } catch {}
220
+ fs.renameSync(filePath, filePath + ".1");
221
+ }
222
+ } catch {}
223
+ }
224
+
225
+ function tryOpenBrowser(url) {
226
+ if (!opts.autoOpen || !process.stdout.isTTY || process.env.CI) return;
227
+ try {
228
+ let cmd;
229
+ let args;
230
+ if (process.platform === "win32") {
231
+ cmd = "cmd.exe";
232
+ args = ["/c", "start", "", url];
233
+ } else if (process.platform === "darwin") {
234
+ cmd = "open";
235
+ args = [url];
236
+ } else {
237
+ cmd = "xdg-open";
238
+ args = [url];
239
+ }
240
+ const p = spawn(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
241
+ p.on("error", () => {});
242
+ p.unref();
243
+ } catch {}
244
+ }
245
+
246
+ function reportDevice(creds) {
247
+ logLine("info", "━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
248
+ logLine("info", "Computer: " + opts.deviceName + " | User: " + os.userInfo().username + " | Node: " + process.version);
249
+ logLine("info", "Device ID: " + creds.deviceId + " | Gateway PID: " + (child?.pid || "unknown"));
250
+ logLine("info", "Relay: " + opts.relay + " | Local MCP: " + localBaseUrl + " (Bearer+Host protected)");
251
+ logLine(
252
+ "info",
253
+ "Mode: " +
254
+ (trace ? "TRACE" : debug ? "DEBUG" : "LIVE") +
255
+ " | Policy: " +
256
+ (policy.readonly ? "READONLY" : "FULL") +
257
+ " | DLP: " +
258
+ (policy.dlp ? "ON" : "OFF") +
259
+ (policy.allowDirs.length ? " | AllowDirs: " + policy.allowDirs.length : "")
260
+ );
261
+ logLine("info", "Return to your AI client; keep this terminal running. Ctrl+C to disconnect.");
262
+ logLine("info", "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
263
+ }
264
+
265
+ async function post(route, data) {
266
+ const { dispatcher } = remoteTransport();
267
+ const r = await fetch(opts.relay + route, {
268
+ method: "POST",
269
+ headers: { "content-type": "application/json" },
270
+ body: JSON.stringify(data),
271
+ signal: AbortSignal.timeout(12000),
272
+ ...(dispatcher ? { dispatcher } : {})
273
+ });
274
+ const j = await r.json();
275
+ if (!r.ok) throw Error(j.error || "HTTP " + r.status);
276
+ return j;
277
+ }
278
+
279
+ async function pair() {
280
+ const v = await post("/relay/pair/start", { name: opts.deviceName });
281
+ logLine("info", "🔑 New device pairing requested");
282
+ if (opts.json) {
283
+ console.log(
284
+ JSON.stringify({
285
+ event: "pairing_required",
286
+ deviceName: opts.deviceName,
287
+ code: v.code,
288
+ approvalUrl: v.approvalUrl,
289
+ pairId: v.pairId,
290
+ expiresIn: v.expiresIn || 3600
291
+ })
292
+ );
293
+ } else {
294
+ console.log(
295
+ "\nNEW DEVICE: " +
296
+ opts.deviceName +
297
+ "\nPAIRING CODE: " +
298
+ v.code +
299
+ "\nPlease visit " +
300
+ v.approvalUrl +
301
+ " and approve the matching code.\nWaiting for approval (60 minutes)...\n"
302
+ );
303
+ }
304
+ tryOpenBrowser(v.approvalUrl);
305
+ for (let i = 0; i < 720 && !stopping; i++) {
306
+ await sleep(5000);
307
+ let r;
308
+ try {
309
+ r = await post("/relay/pair/poll", { pairId: v.pairId, proof: v.proof });
310
+ } catch (e) {
311
+ if (/expired|invalid/i.test(e.message)) throw e;
312
+ continue;
313
+ }
314
+ if (r.status === "approved") {
315
+ const credentials = { deviceId: r.deviceId, token: r.token };
316
+ store(credentials);
317
+ logLine("info", "✅ Device approved; credentials saved locally.");
318
+ if (opts.json) {
319
+ console.log(JSON.stringify({ event: "pairing_approved", deviceId: r.deviceId, deviceName: opts.deviceName }));
320
+ }
321
+ return credentials;
322
+ }
323
+ }
324
+ throw Error("Pairing timed out. Re-run the command.");
325
+ }
326
+
327
+ async function portOpen(withToken = false) {
328
+ if (withToken) {
329
+ const r = await fetch(`http://127.0.0.1:${opts.port}/healthz`, {
330
+ headers: { authorization: "Bearer " + localGatewayToken },
331
+ signal: AbortSignal.timeout(1500)
332
+ });
333
+ return r.status === 200;
334
+ }
335
+ const r = await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) });
336
+ return r.status > 0;
337
+ }
338
+
339
+ function abortAllInflight(reason) {
340
+ for (const [id, controller] of inflightControllers) {
341
+ inflightControllers.delete(id);
342
+ try {
343
+ controller.abort(new Error(reason));
344
+ } catch {}
345
+ }
346
+ }
347
+
348
+ async function startGateway({ checkOccupied = true } = {}) {
349
+ if (!Number.isInteger(opts.port) || opts.port < 1024 || opts.port > 65535) {
350
+ throw Error("Invalid port: " + opts.port);
351
+ }
352
+ if (checkOccupied) {
353
+ try {
354
+ if (await portOpen(false)) {
355
+ throw Error(`Port ${opts.port} is already occupied. Stop the other MCP gateway or pass --port <port>.`);
356
+ }
357
+ } catch (e) {
358
+ if (/occupied/.test(e.message)) throw e;
359
+ }
360
+ }
361
+
362
+ logLine("info", "🚀 Starting local MCP gateway (Desktop Commander" + (opts.serversConfig ? " + extra servers" : "") + ")...");
363
+ rotateLogIfNeeded(gatewayLogPath);
364
+ const fd = fs.openSync(gatewayLogPath, "a", 0o600);
365
+ const spawned = spawn(process.execPath, [path.join(root, "gateway.mjs")], {
366
+ cwd: root,
367
+ stdio: ["ignore", fd, fd],
368
+ windowsHide: true,
369
+ env: {
370
+ ...process.env,
371
+ MCP_PORT: String(opts.port),
372
+ MCP_LOCAL_TOKEN: localGatewayToken,
373
+ ...(opts.serversConfig ? { PCC_MCP_CONFIG: path.resolve(opts.serversConfig) } : {})
374
+ }
375
+ });
376
+ fs.closeSync(fd);
377
+ child = spawned;
378
+ gatewayHealthy = false;
379
+ logLine("info", "Gateway PID: " + spawned.pid + " | diagnostic log: " + gatewayLogPath);
380
+
381
+ spawned.on("exit", (code, signal) => {
382
+ if (child === spawned) child = null;
383
+ const wasHealthy = gatewayHealthy;
384
+ gatewayHealthy = false;
385
+ abortAllInflight("Local MCP gateway exited unexpectedly");
386
+ if (stopping) return;
387
+ logLine("error", `⚠️ Local MCP gateway exited unexpectedly (code=${code ?? "null"}, signal=${signal ?? "none"})`);
388
+ if (wasHealthy) scheduleGatewayRestart();
389
+ });
390
+
391
+ for (let i = 0; i < 40; i++) {
392
+ if (spawned.exitCode !== null) {
393
+ throw Error("Gateway exited unexpectedly. See " + gatewayLogPath);
394
+ }
395
+ try {
396
+ if (await portOpen(true)) {
397
+ gatewayHealthy = true;
398
+ gatewayRestartCount = 0;
399
+ logLine("info", `🔌 Local MCP gateway ready (127.0.0.1:${opts.port})`);
400
+ return;
401
+ }
402
+ } catch {}
403
+ await sleep(500);
404
+ }
405
+ throw Error(`Gateway failed to listen on port ${opts.port}.`);
406
+ }
407
+
408
+ function scheduleGatewayRestart() {
409
+ if (stopping || gatewayRestartPromise) return;
410
+ gatewayRestartCount++;
411
+ const delayMs = Math.min(30000, 1000 * 2 ** Math.min(4, gatewayRestartCount - 1));
412
+ logLine("warn", `🔄 Restarting local MCP gateway in ${Math.ceil(delayMs / 1000)}s (restart #${gatewayRestartCount})...`);
413
+ gatewayRestartPromise = (async () => {
414
+ await sleep(delayMs);
415
+ if (stopping) return;
416
+ try {
417
+ await startGateway({ checkOccupied: false });
418
+ logLine("info", "✅ Local MCP gateway recovered.");
419
+ } catch (e) {
420
+ logLine("error", "Local MCP gateway restart failed: " + sanitizeText(e.message, 200));
421
+ } finally {
422
+ gatewayRestartPromise = null;
423
+ if (!stopping && !gatewayHealthy && !child) {
424
+ scheduleGatewayRestart();
425
+ }
426
+ }
427
+ })();
428
+ }
429
+
430
+ function stopGateway() {
431
+ gatewayHealthy = false;
432
+ abortAllInflight("Connector shutting down");
433
+ if (child?.pid) {
434
+ if (process.platform === "win32") {
435
+ spawnSync("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, timeout: 8000 });
436
+ } else {
437
+ try {
438
+ child.kill("SIGTERM");
439
+ } catch {}
440
+ }
441
+ child = null;
442
+ }
443
+ }
444
+
445
+ async function respond(ws, msg) {
446
+ const started = Date.now();
447
+ const call = callInfo(msg.body, msg.id);
448
+ const callId = shortCallId(call.requestId);
449
+ const name = call.label;
450
+ const isTool = call.method === "tools/call";
451
+ allCalls++;
452
+ sessionCalls++;
453
+
454
+ logLine("info", "🔧 [" + callId + "] " + (isTool ? "Tool: " : "MCP: ") + name + " | " + requestBrief(call));
455
+ if (debug) logLine("debug", " ↳ Metadata: " + requestDebug(call));
456
+ if (trace) logLine("warn", " ↳ Trace args (locally visible): " + safeTraceRequest(call));
457
+
458
+ let parsedRpc = null;
459
+ try {
460
+ parsedRpc = JSON.parse(String(msg.body || ""));
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));
587
+ if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(response));
588
+ else logLine("warn", " ↳ Response cannot be delivered: relay socket is not open");
589
+ }
590
+
591
+ async function connect(creds, { onHealthy } = {}) {
592
+ return new Promise((resolve) => {
593
+ const { wsAgent } = remoteTransport();
594
+ const attempt = ++connectionAttempt;
595
+ const opening = Date.now();
596
+ logLine("info", "🌐 Connecting to Cloudflare relay (attempt #" + attempt + ")...");
597
+
598
+ const ws = new WebSocket(opts.relay.replace(/^https:/, "wss:").replace(/^http:/, "ws:") + "/relay/ws", {
599
+ headers: {
600
+ Authorization: "Bearer " + creds.token,
601
+ "X-Device-ID": creds.deviceId,
602
+ "X-Device-Platform": process.platform,
603
+ "X-Device-Arch": process.arch,
604
+ "X-Device-Node": process.version,
605
+ "X-Device-Version": PKG_VERSION,
606
+ "X-Device-Mode": policy.readonly ? "READONLY" : "FULL"
607
+ },
608
+ handshakeTimeout: 15000,
609
+ ...(wsAgent ? { agent: wsAgent } : {})
610
+ });
611
+ socket = ws;
612
+
613
+ let status = 0;
614
+ let awaitingPong = false;
615
+ let heartbeatTimer = null;
616
+ let healthyTimer = null;
617
+
618
+ const clearTimers = () => {
619
+ if (heartbeatTimer) {
620
+ clearInterval(heartbeatTimer);
621
+ heartbeatTimer = null;
622
+ }
623
+ if (healthyTimer) {
624
+ clearTimeout(healthyTimer);
625
+ healthyTimer = null;
626
+ }
627
+ };
628
+
629
+ ws.on("open", () => {
630
+ connectedSince = Date.now();
631
+ sessionCalls = 0;
632
+ sessionFails = 0;
633
+ lastError = "";
634
+ awaitingPong = false;
635
+
636
+ // Reset backoff retries once the connection proves stable for 10s
637
+ healthyTimer = setTimeout(() => {
638
+ if (ws.readyState === WebSocket.OPEN) onHealthy?.();
639
+ }, 10000);
640
+ healthyTimer.unref?.();
641
+
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
+ heartbeatTimer = setInterval(() => {
645
+ if (ws.readyState !== WebSocket.OPEN) return;
646
+ if (awaitingPong) {
647
+ logLine("warn", "⚠️ Relay heartbeat timed out (half-open socket detected); forcing reconnect...");
648
+ clearTimers();
649
+ try {
650
+ ws.terminate();
651
+ } catch {}
652
+ return;
653
+ }
654
+ awaitingPong = true;
655
+ try {
656
+ ws.ping();
657
+ } catch {
658
+ try {
659
+ ws.terminate();
660
+ } catch {}
661
+ }
662
+ }, HEARTBEAT_INTERVAL_MS);
663
+ heartbeatTimer.unref?.();
664
+
665
+ logLine("info", "✅ Cloudflare relay connected in " + formatElapsed(Date.now() - opening));
666
+ reportDevice(creds);
667
+ console.log("CONNECTED. Your AI client can now use this device. Ctrl+C to disconnect.");
668
+ });
669
+
670
+ ws.on("pong", () => {
671
+ awaitingPong = false;
672
+ });
673
+
674
+ ws.on("unexpected-response", (_req, res) => {
675
+ status = res.statusCode;
676
+ res.resume();
677
+ lastError = "HTTP " + status;
678
+ logLine("error", "Relay handshake rejected: HTTP " + status);
679
+ });
680
+
681
+ ws.on("message", (data) => {
682
+ awaitingPong = false;
683
+ const text = String(data);
684
+ if (text === "pong") {
685
+ return;
686
+ }
687
+ let m;
688
+ try {
689
+ m = JSON.parse(text);
690
+ } catch {
691
+ if (debug) logLine("debug", "Ignored invalid relay JSON message");
692
+ return;
693
+ }
694
+ if (m.kind === "pong") {
695
+ awaitingPong = false;
696
+ return;
697
+ }
698
+ if (m.kind === "ping") {
699
+ if (ws.readyState === WebSocket.OPEN) {
700
+ ws.send(
701
+ JSON.stringify({
702
+ kind: "pong",
703
+ id: m.id,
704
+ uptimeMs: connectedSince ? Date.now() - connectedSince : 0,
705
+ gatewayReady: gatewayHealthy,
706
+ mode: policy.readonly ? "READONLY" : "FULL",
707
+ version: PKG_VERSION
708
+ })
709
+ );
710
+ }
711
+ return;
712
+ }
713
+ if (m.kind === "cancel" && m.id) {
714
+ const ctrl = inflightControllers.get(m.id);
715
+ if (ctrl) {
716
+ logLine("warn", "🛑 [" + shortCallId(m.id) + "] Aborting in-flight call (client cancelled/timed out)");
717
+ try {
718
+ ctrl.abort(new Error("Cancelled by client"));
719
+ } catch {}
720
+ }
721
+ return;
722
+ }
723
+ if (m.kind === "request") {
724
+ respond(ws, m).catch((e) => logLine("error", "Request handler: " + sanitizeText(e.message, 240)));
725
+ }
726
+ });
727
+
728
+ ws.on("error", (e) => {
729
+ lastError = sanitizeText(e.message, 180);
730
+ logLine("error", "Relay network error: " + lastError);
731
+ });
732
+
733
+ ws.on("close", (code, reason) => {
734
+ clearTimers();
735
+ socket = null;
736
+ const uptime = connectedSince ? formatElapsed(Date.now() - connectedSince) : "not established";
737
+ logLine(
738
+ "warn",
739
+ "🔌 Relay disconnected | code=" + code + " | session uptime=" + uptime + " | calls=" + sessionCalls + " | failures=" + sessionFails
740
+ );
741
+ if (lastError) logLine("warn", " ↳ Last network error: " + lastError);
742
+ if (reason?.length) logLine("warn", " ↳ Close reason: " + sanitizeText(reason.toString(), 100));
743
+ connectedSince = 0;
744
+ resolve({ unauthorized: status === 401 || code === 1008 });
745
+ });
746
+ });
747
+ }
748
+
749
+ async function runDoctor() {
750
+ let healthy = true;
751
+ let proxyInfo = { mode: "unknown", source: "unknown" };
752
+ let transport = {};
753
+ try {
754
+ const p = resolveProxyForUrl(opts.relay);
755
+ proxyInfo = { mode: p.mode, source: p.source, description: p.description || "", reason: p.reason || "" };
756
+ if (p.mode === "unsupported") healthy = false;
757
+ else if (p.mode === "proxy") transport = { dispatcher: new ProxyAgent(p.url) };
758
+ } catch (e) {
759
+ proxyInfo = { mode: "error", source: "system", reason: e.message };
760
+ healthy = false;
761
+ }
762
+
763
+ let relayStatus = { ok: false };
764
+ try {
765
+ const t0 = Date.now();
766
+ const res = await fetch(opts.relay + "/relay/status", {
767
+ signal: AbortSignal.timeout(8000),
768
+ ...transport
769
+ });
770
+ const body = await res.json();
771
+ relayStatus = {
772
+ ok: res.ok && Boolean(body?.ok),
773
+ httpStatus: res.status,
774
+ latencyMs: Date.now() - t0,
775
+ workerVersion: body?.version || "unknown",
776
+ protocol: body?.protocol || 1,
777
+ features: Array.isArray(body?.features) ? body.features : []
778
+ };
779
+ if (!relayStatus.ok) healthy = false;
780
+ } catch (e) {
781
+ relayStatus = { ok: false, error: sanitizeText(e.message, 140) };
782
+ healthy = false;
783
+ }
784
+
785
+ const creds = saved();
786
+ let localPortOccupied = false;
787
+ let localHttpStatus = 0;
788
+ try {
789
+ localHttpStatus = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) })).status;
790
+ localPortOccupied = localHttpStatus > 0;
791
+ } catch {
792
+ localPortOccupied = false;
793
+ }
794
+
795
+ if (opts.json) {
796
+ console.log(
797
+ JSON.stringify(
798
+ {
799
+ ok: healthy,
800
+ version: PKG_VERSION,
801
+ runtime: { node: process.version, platform: process.platform, arch: process.arch },
802
+ relay: opts.relay,
803
+ proxy: proxyInfo,
804
+ relayStatus,
805
+ paired: Boolean(creds?.deviceId),
806
+ deviceId: creds?.deviceId ? String(creds.deviceId).slice(0, 8) + "…" : null,
807
+ localPort: opts.port,
808
+ localPortOccupied,
809
+ policy: {
810
+ readonly: policy.readonly,
811
+ dlp: policy.dlp,
812
+ allowDirsCount: policy.allowDirs.length
813
+ }
814
+ },
815
+ null,
816
+ 2
817
+ )
818
+ );
819
+ if (!healthy) process.exitCode = 1;
820
+ return;
821
+ }
822
+
823
+ console.log(`Private Desktop MCP Doctor (v${PKG_VERSION})`);
824
+ console.log("─".repeat(48));
825
+ console.log("Node.js:", process.version, `(${process.platform}/${process.arch})`);
826
+ console.log("Relay URL:", opts.relay);
827
+ console.log(
828
+ "Proxy:",
829
+ proxyInfo.mode === "proxy"
830
+ ? `${proxyInfo.source} (${proxyInfo.description})`
831
+ : `${proxyInfo.mode} (${proxyInfo.source}${proxyInfo.reason ? ": " + proxyInfo.reason : ""})`
832
+ );
833
+ if (relayStatus.ok) {
834
+ console.log(
835
+ `Relay Status: OK (HTTP ${relayStatus.httpStatus}, ${relayStatus.latencyMs}ms, worker v${relayStatus.workerVersion}, features: ${relayStatus.features.join(",") || "legacy"})`
836
+ );
837
+ } else {
838
+ console.log("Relay Status: UNREACHABLE -", relayStatus.error || `HTTP ${relayStatus.httpStatus || 0}`);
839
+ }
840
+ console.log("Device Pairing:", creds ? `paired (id=${String(creds.deviceId || "").slice(0, 8)}…)` : "not paired");
841
+ console.log(`Local Port ${opts.port}:`, localPortOccupied ? `occupied (HTTP ${localHttpStatus})` : "free");
842
+ console.log("Policy:", policy.readonly ? "READONLY" : "FULL", "| DLP:", policy.dlp ? "ON" : "OFF");
843
+ if (!healthy) process.exitCode = 1;
844
+ }
845
+
846
+ function runReport() {
847
+ const p = resolveProxyForUrl(opts.relay);
848
+ const creds = saved();
849
+ let gatewayLogTail = [];
850
+ try {
851
+ const raw = fs.readFileSync(gatewayLogPath, "utf8");
852
+ gatewayLogTail = raw
853
+ .split(/\r?\n/)
854
+ .slice(-20)
855
+ .filter(Boolean)
856
+ .map((line) => sanitizeText(line, 240));
857
+ } catch {}
858
+
859
+ const report = {
860
+ generatedAt: new Date().toISOString(),
861
+ version: PKG_VERSION,
862
+ runtime: { node: process.version, platform: process.platform, arch: process.arch },
863
+ relay: opts.relay,
864
+ port: opts.port,
865
+ paired: Boolean(creds?.deviceId),
866
+ proxy: {
867
+ mode: p.mode,
868
+ source: p.source,
869
+ description: p.description || "",
870
+ reason: p.reason || ""
871
+ },
872
+ policy: {
873
+ readonly: policy.readonly,
874
+ dlp: policy.dlp,
875
+ allowToolsCount: policy.allowTools.size,
876
+ denyToolsCount: policy.denyTools.size,
877
+ allowDirsCount: policy.allowDirs.length
878
+ },
879
+ recentGatewayLogTail: gatewayLogTail
880
+ };
881
+ console.log(JSON.stringify(report, null, 2));
882
+ }
883
+
884
+ function runSetupClient() {
885
+ const target = String(opts.targetClient || "").toLowerCase().trim();
886
+ if (!target) {
887
+ const msg = `Specify a target client: ${SUPPORTED_CLIENTS.join(", ")} or "all"`;
888
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: msg, supportedClients: SUPPORTED_CLIENTS }, null, 2));
889
+ else console.error(msg);
890
+ process.exitCode = 2;
891
+ return;
892
+ }
893
+
894
+ const clients = target === "all" ? SUPPORTED_CLIENTS : [target];
895
+ const results = [];
896
+ for (const client of clients) {
897
+ try {
898
+ const res = configureMcpClient({
899
+ client,
900
+ relayUrl: opts.relay,
901
+ configPath: clients.length === 1 && opts.clientConfigPath ? opts.clientConfigPath : undefined,
902
+ dryRun: opts.dryRun
903
+ });
904
+ results.push(res);
905
+ } catch (e) {
906
+ results.push({ ok: false, client, error: e.message });
907
+ process.exitCode = 1;
908
+ }
909
+ }
910
+
911
+ if (opts.json) {
912
+ console.log(JSON.stringify(clients.length === 1 ? results[0] : { ok: results.every((r) => r.ok), results }, null, 2));
913
+ return;
914
+ }
915
+
916
+ for (const r of results) {
917
+ if (!r.ok) {
918
+ console.error(`❌ [${r.client}] ${r.error}`);
919
+ continue;
920
+ }
921
+ console.log(`${r.dryRun ? "🔍 [DRY-RUN]" : "✅"} [${r.client}] ${r.action.toUpperCase()} → ${r.path}`);
922
+ if (r.dryRun) {
923
+ console.log(r.preview.trimEnd());
924
+ }
925
+ }
926
+ }
927
+
928
+ function stop() {
929
+ if (stopping) return;
930
+ stopping = true;
931
+ logLine("info", "Disconnecting PCC...");
932
+ try {
933
+ socket?.close(1000, "Manual disconnect");
934
+ } catch {}
935
+ stopGateway();
936
+ setTimeout(() => process.exit(0), 200).unref();
937
+ }
938
+
939
+ process.on("SIGINT", stop);
940
+ process.on("SIGTERM", stop);
941
+
942
+ if (opts.command === "help") {
943
+ console.log(
944
+ `Private Desktop MCP v${PKG_VERSION}: connect | status | doctor | report | setup-client | reset\n` +
945
+ "Subcommands:\n" +
946
+ " connect Pair (if needed), start local gateway, and connect to relay\n" +
947
+ " status [--json] Check local pairing and gateway port state\n" +
948
+ " doctor [--json] End-to-end preflight check (proxy, relay health, pairing, port)\n" +
949
+ " report [--json] Generate sanitized JSON diagnostic bundle\n" +
950
+ ` setup-client <client|all> Configure MCP client (${SUPPORTED_CLIENTS.join(", ")})\n` +
951
+ " reset [--json] Clear local device pairing credentials\n" +
952
+ "Options:\n" +
953
+ " --relay <url> Custom Cloudflare Worker relay URL (env: PCC_RELAY_URL)\n" +
954
+ " --port <port> Local MCP gateway port (default: 8717, env: MCP_PORT)\n" +
955
+ " --name <name> Device display name when pairing (default: hostname)\n" +
956
+ " --readonly Allow read-only tools only and hide mutating tools\n" +
957
+ " --allow-dir <dir> Restrict file tool paths to allowed directories (repeatable)\n" +
958
+ " --allow-tools <csv> Explicit allowlist of MCP tool names\n" +
959
+ " --deny-tools <csv> Explicit denylist of MCP tool names\n" +
960
+ " --servers <file.json> Aggregate additional local stdio MCP servers (env: PCC_MCP_CONFIG)\n" +
961
+ " --no-dlp Disable outbound secret redaction on responses (enabled by default)\n" +
962
+ " --no-open Do not auto-open browser during device pairing\n" +
963
+ " --dry-run Preview client config changes without writing to disk (for setup-client)\n" +
964
+ " --config <path> Custom client config file path override (for setup-client)\n" +
965
+ " --json Emit machine-readable JSON output for agents\n" +
966
+ " --safe | --debug | --trace Terminal logging verbosity (default: TRACE)\n" +
967
+ `Default relay: ${DEFAULT_RELAY}\n` +
968
+ `Approval page: ${opts.relay}/admin/devices\n` +
969
+ "Ctrl+C to disconnect. No automatic startup."
970
+ );
971
+ } else if (opts.command === "status") {
972
+ const creds = saved();
973
+ let localHttpStatus = null;
974
+ try {
975
+ localHttpStatus = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(2000) })).status;
976
+ } catch {
977
+ localHttpStatus = null;
978
+ }
979
+ if (opts.json) {
980
+ console.log(
981
+ JSON.stringify(
982
+ {
983
+ ok: true,
984
+ version: PKG_VERSION,
985
+ paired: Boolean(creds?.deviceId),
986
+ deviceId: creds?.deviceId ? String(creds.deviceId).slice(0, 8) + "…" : null,
987
+ relay: opts.relay,
988
+ localPort: opts.port,
989
+ localGatewayRunning: localHttpStatus !== null,
990
+ localHttpStatus,
991
+ policy: { readonly: policy.readonly, dlp: policy.dlp }
992
+ },
993
+ null,
994
+ 2
995
+ )
996
+ );
997
+ } else {
998
+ console.log("Paired:", !!creds);
999
+ console.log("Relay:", opts.relay);
1000
+ if (localHttpStatus !== null) console.log("Local HTTP:", localHttpStatus);
1001
+ else console.log("Local MCP offline");
1002
+ }
1003
+ } else if (opts.command === "doctor") {
1004
+ await runDoctor();
1005
+ } else if (opts.command === "report") {
1006
+ runReport();
1007
+ } else if (opts.command === "setup-client") {
1008
+ runSetupClient();
1009
+ } else if (opts.command === "reset") {
1010
+ forget();
1011
+ if (opts.json) {
1012
+ console.log(JSON.stringify({ ok: true, cleared: true, configPath: config }, null, 2));
1013
+ } else {
1014
+ console.log("Local credentials cleared. Revoke old credentials in the admin page too.");
1015
+ }
1016
+ } else if (opts.command === "connect") {
1017
+ logLine("info", `╔══════════════ PCC REMOTE v${PKG_VERSION} ══════════════╗`);
1018
+ logLine(
1019
+ "info",
1020
+ "Logging: " +
1021
+ (trace ? "TRACE" : debug ? "DEBUG" : "LIVE") +
1022
+ " | Policy: " +
1023
+ (policy.readonly ? "READONLY" : "FULL") +
1024
+ " | DLP: " +
1025
+ (policy.dlp ? "ON" : "OFF") +
1026
+ " | Gateway: Desktop Commander MCP"
1027
+ );
1028
+ if (trace) logLine("warn", "TRACE mode can display private user content in this terminal; do not share these logs.");
1029
+ logLine("info", "╚═══════════════════════════════════════════════╝");
1030
+ try {
1031
+ const existing = saved();
1032
+ const credentials = existing || (await pair());
1033
+ activeCreds = credentials;
1034
+ if (existing) logLine("info", "💾 Stored device pairing found");
1035
+ await startGateway();
1036
+ let retries = 0;
1037
+ while (!stopping) {
1038
+ const r = await connect(credentials, {
1039
+ onHealthy: () => {
1040
+ retries = 0;
1041
+ }
1042
+ });
1043
+ if (r.unauthorized) {
1044
+ forget();
1045
+ logLine("error", "Credentials revoked; run again to pair.");
1046
+ break;
1047
+ }
1048
+ if (stopping) break;
1049
+ retries++;
1050
+ const baseMs = Math.min(30000, 1500 * 2 ** Math.min(5, retries));
1051
+ const jitterMs = Math.round(baseMs * (0.75 + Math.random() * 0.5));
1052
+ logLine("warn", "Reconnecting in " + (jitterMs / 1000).toFixed(1) + "s");
1053
+ await sleep(jitterMs);
1054
+ }
1055
+ } catch (e) {
1056
+ logLine("error", "ERROR: " + sanitizeText(e.message, 250));
1057
+ process.exitCode = 1;
1058
+ } finally {
1059
+ stopGateway();
1060
+ }
1061
+ } else {
1062
+ console.error("Unknown command. Use help");
1063
+ process.exitCode = 2;
1064
+ }