@juexibobi/private-desktop-mcp 0.3.3 → 0.3.5

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/README.md CHANGED
@@ -22,6 +22,12 @@ For more details, use `--debug`:
22
22
  npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --debug
23
23
  ```
24
24
 
25
+ ### Windows system proxy detection (v0.3.4)
26
+
27
+ PCC automatically uses the current Windows user's **effective system proxy** (WinINET), including static HTTP/Mixed proxies, Windows proxy bypass rules, and supported PAC/WPAD configurations. It uses the same detected proxy for the HTTPS device-pairing API and for the secure WebSocket relay. No manual `HTTPS_PROXY` configuration is required for normal Windows system proxy settings.
28
+
29
+ Explicit `HTTPS_PROXY`, `HTTP_PROXY` or `ALL_PROXY` settings take precedence over Windows settings; `NO_PROXY` exclusions are respected for an explicitly configured environment proxy. Supported proxy transport is HTTP/HTTPS CONNECT. SOCKS-only proxy endpoints must be exposed through an HTTP/Mixed port. The detected proxy is re-checked periodically when retrying a lost connection. If system lookup fails or times out, PCC reports a warning and tries a direct connection.
30
+
25
31
  Debug mode prints **redacted parameter metadata and response size/type**, not command contents, file contents or raw tool results. Sensitive fields and inline tokens are masked, but local paths and other non-sensitive metadata may still appear, so avoid sharing debug logs publicly. The child gateway's detailed stderr/stdout is still stored at `%TEMP%\private-desktop-mcp-device.log`. Neither logging mode changes device pairing, OAuth or startup behavior.
26
32
 
27
33
  ## Current independent endpoint
@@ -66,3 +72,24 @@ Never protect the **entire Worker** with Worker-level Access: this would prevent
66
72
  ## Security
67
73
 
68
74
  This tool has Windows filesystem and command-execution capabilities. Restrict Cloudflare Access to your own identity, approve only devices you control and never expose a naked HTTP MCP endpoint. See [SECURITY.md](SECURITY.md).
75
+
76
+
77
+ ## Detailed live console (v0.3.5)
78
+
79
+ PCC now displays an expanded terminal startup banner with computer, device ID, Node version, gateway PID, local MCP URL, Cloudflare relay state and logging mode. Every incoming MCP method/tool call has a short correlation ID, safe parameter summary, MCP/HTTP outcome, duration and structured result summaries (process PID, exit code, line count and output size when available). WebSocket disconnections include close code, connection uptime, total calls and failures. A tool can fail at the MCP layer even when HTTP returns 200; this is reported as an **MCP tool error**.
80
+
81
+ Logging has three levels:
82
+
83
+ | Command option | Terminal contents | Privacy |
84
+ | --- | --- | --- |
85
+ | No option | Rich startup, call and response summaries; no raw files/commands | Default |
86
+ | \`--debug\` | Adds redacted request metadata, result sizes and aggregate counters | Safe diagnostic metadata |
87
+ | \`--trace\` | Also shows sanitized, truncated command and response previews | **Local opt-in; may expose confidential user text** |
88
+
89
+ Example for full local previews (not recommended when screen sharing or saving terminal transcripts):
90
+
91
+ \`\`\`powershell
92
+ npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --trace
93
+ \`\`\`
94
+
95
+ **Important:** \`--trace\` is best-effort redaction, not a guarantee that arbitrary secrets embedded in file contents or command results will be removed. Use normal logging or \`--debug\` for everyday use. All logs print to the local terminal and are not transmitted to third-party logging services by this feature. The underlying gateway's diagnostics remain in \`%TEMP%\private-desktop-mcp-device.log\`.
@@ -0,0 +1,112 @@
1
+ import path from "node:path";
2
+ import { sanitizeText, safeValue } from "./logging.mjs";
3
+
4
+ const OMIT="[hidden; use --trace to inspect local content]";
5
+ const safeId=value=>typeof value==="string"?sanitizeText(value,70):typeof value==="number"?String(value):"unknown";
6
+ const byteSize=value=>Buffer.byteLength(String(value??""),"utf8");
7
+ function compact(value,limit=140){
8
+ return sanitizeText(String(value??""),limit);
9
+ }
10
+ export function parseRpc(body,contentType=""){
11
+ let text=String(body||"");
12
+ if(contentType.toLowerCase().includes("text/event-stream")){
13
+ const candidates=text.split(/\r?\n/).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trim()).filter(s=>s&&s!=="[DONE]");
14
+ for(let i=candidates.length-1;i>=0;i--){try{return JSON.parse(candidates[i])}catch{}}
15
+ }
16
+ try{return JSON.parse(text)}catch{return null}
17
+ }
18
+ export function callInfo(body,requestId=""){
19
+ const r=parseRpc(body)||{},params=r.params&&typeof r.params==="object"?r.params:{};
20
+ const name=typeof params.name==="string"?compact(params.name,80):"";
21
+ const args=params.arguments&&typeof params.arguments==="object"?params.arguments:{};
22
+ return {
23
+ requestId:safeId(requestId),
24
+ method:typeof r.method==="string"?compact(r.method,80):"unknown",
25
+ name,
26
+ jsonRpcId:safeId(r.id),
27
+ args,
28
+ label:name||compact(r.method||"unknown",80)
29
+ };
30
+ }
31
+ export function requestBrief(call){
32
+ const {args,name,method}=call;
33
+ if(method==="tools/list")return "Discover available tools";
34
+ if(method==="initialize")return "MCP session initialization";
35
+ if(method==="notifications/initialized")return "MCP session established";
36
+ if(method!=="tools/call")return method;
37
+ const fields=[];
38
+ if(typeof args.path==="string"){
39
+ const filepath=args.path.replace(/\\/g,"/");
40
+ fields.push("file="+compact(filepath.split("/").at(-1),72));
41
+ }
42
+ if(typeof args.pid==="number")fields.push("pid="+args.pid);
43
+ if(typeof args.timeout_ms==="number")fields.push("timeout="+args.timeout_ms+"ms");
44
+ if(typeof args.length==="number")fields.push("length="+args.length);
45
+ if(typeof args.offset==="number")fields.push("offset="+args.offset);
46
+ if(typeof args.shell==="string")fields.push("shell="+compact(args.shell,48));
47
+ if(typeof args.command==="string")fields.push("command="+OMIT+" ("+args.command.length+" chars)");
48
+ if(typeof args.content==="string")fields.push("content=[hidden] ("+args.content.length+" chars)");
49
+ if(typeof args.name==="string")fields.push("name="+compact(args.name,56));
50
+ return fields.join(" | ")||"parameters="+Object.keys(args).length+" fields";
51
+ }
52
+ export function requestDebug(call){
53
+ return JSON.stringify({method:call.method,id:call.jsonRpcId,tool:call.name,arguments:safeValue(call.args,"arguments")});
54
+ }
55
+ function getTextBlocks(result){
56
+ return Array.isArray(result?.content)?result.content.filter(x=>x?.type==="text"&&typeof x.text==="string").map(x=>x.text):[];
57
+ }
58
+ function safeResultSummary(result,textBlocks){
59
+ if(Array.isArray(result?.tools))return "tools="+result.tools.length;
60
+ if(result?.serverInfo&&typeof result.serverInfo.name==="string")return "server="+compact(result.serverInfo.name,56);
61
+ const joined=textBlocks.join("\n");
62
+ const hints=[];
63
+ const process=joined.match(/Process started with PID\s+(\d+)/i);
64
+ const complete=joined.match(/Process (?:completed|finished)(?: with exit code\s+(-?\d+))?/i);
65
+ const reading=joined.match(/\[Reading\s+(\d+)\s+(?:new\s+)?lines?/i);
66
+ if(process)hints.push("process PID="+process[1]);
67
+ if(complete)hints.push(complete[1]===undefined?"process finished":"exit="+complete[1]);
68
+ if(reading)hints.push("lines="+reading[1]);
69
+ if(textBlocks.length)hints.push("text blocks="+textBlocks.length);
70
+ if(joined)hints.push("output="+byteSize(joined)+" bytes");
71
+ if(!hints.length&&result&&typeof result==="object")hints.push("fields="+Object.keys(result).length);
72
+ return hints.join(" | ")||"no result";
73
+ }
74
+ export function responseBrief(body,contentType="",status=200){
75
+ const rpc=parseRpc(body,contentType);
76
+ const payloadSize=byteSize(body);
77
+ if(!rpc)return {failed:status>=400,kind:"non-JSON response",summary:"response="+payloadSize+" bytes",error:"",bytes:payloadSize,trace:""};
78
+ const error=rpc.error&&typeof rpc.error==="object"?rpc.error:null;
79
+ const result=rpc.result&&typeof rpc.result==="object"?rpc.result:null;
80
+ const blocks=getTextBlocks(result);
81
+ const failed=Boolean(status>=400||error||result?.isError);
82
+ const kind=error?"JSON-RPC error":result?.isError?"MCP tool error":failed?"HTTP error":"MCP response";
83
+ const errorText=error?.message?compact(error.message,155):"";
84
+ return {
85
+ failed,kind,
86
+ summary:result?safeResultSummary(result,blocks):"response="+payloadSize+" bytes",
87
+ error:errorText,
88
+ bytes:payloadSize,
89
+ trace:blocks.join("\n")
90
+ };
91
+ }
92
+ export function safeTraceRequest(call,limit=1200){
93
+ const value=call.args;
94
+ if(!value||typeof value!=="object")return "{}";
95
+ const output={};
96
+ for(const [key,entry] of Object.entries(value).slice(0,20)){
97
+ if(/authorization|token|password|secret|credential|cookie|proof|api.?key/i.test(key))output[key]="[REDACTED]";
98
+ else if(typeof entry==="string")output[key]=compact(entry,500);
99
+ else output[key]=safeValue(entry,key);
100
+ }
101
+ return compact(JSON.stringify(output),limit);
102
+ }
103
+ export function safeTraceOutput(info,limit=1200){
104
+ return info.trace?compact(info.trace,limit):"(no text content)";
105
+ }
106
+ export function shortCallId(id){
107
+ const text=safeId(id);
108
+ return text==="unknown"?"unknown":text.slice(0,8);
109
+ }
110
+ export function formatElapsed(ms){
111
+ return ms>=1000?(ms/1000).toFixed(2)+"s":ms+"ms";
112
+ }
package/bin/cli.mjs CHANGED
@@ -5,20 +5,51 @@ import os from "node:os";
5
5
  import {spawn,spawnSync} from "node:child_process";
6
6
  import {fileURLToPath} from "node:url";
7
7
  import WebSocket from "ws";
8
- import { EnvHttpProxyAgent, setGlobalDispatcher } from "undici";
9
- import { getProxyForUrl } from "proxy-from-env";
8
+ import { ProxyAgent } from "undici";
9
+ import { resolveProxyForUrl } from "./proxy.mjs";
10
10
  import { HttpsProxyAgent } from "https-proxy-agent";
11
- import { logLine, rpcDescription, rpcOutcome, sanitizeText } from "./logging.mjs";
12
- setGlobalDispatcher(new EnvHttpProxyAgent());
11
+ import { logLine, sanitizeText } from "./logging.mjs";
12
+ import { callInfo, requestBrief, requestDebug, responseBrief, safeTraceRequest, safeTraceOutput, shortCallId, formatElapsed } from "./activity.mjs";
13
+
13
14
  const root=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
14
- const command=process.argv.slice(2).find(a=>!a.startsWith("--"))||"connect",debug=process.argv.includes("--debug"),relay="https://private-desktop-device-relay.ljx2043979076.workers.dev";
15
+ const command=process.argv.slice(2).find(a=>!a.startsWith("--"))||"connect",trace=process.argv.includes("--trace"),debug=process.argv.includes("--debug")||trace,relay="https://private-desktop-device-relay.ljx2043979076.workers.dev";
15
16
  const config=path.join(process.env.APPDATA||path.join(os.homedir(),".config"),"PrivateDesktopMCP","device.json");
16
17
  const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
18
+ let currentProxy=null,proxyCheckedAt=0,lastProxyNotice="";
19
+ const agents=new Map();
20
+ function remoteTransport(){
21
+ if(!currentProxy||Date.now()-proxyCheckedAt>10000){
22
+ currentProxy=resolveProxyForUrl(relay);
23
+ proxyCheckedAt=Date.now();
24
+ if(currentProxy.mode==="unsupported")throw Error(currentProxy.reason+" (use an HTTP/Mixed port via system settings or HTTPS_PROXY)");
25
+ const notice=currentProxy.mode==="proxy"?"🌐 Proxy: "+currentProxy.source+" ("+currentProxy.description+")":
26
+ currentProxy.mode==="unavailable"?"⚠️ Proxy detection unavailable: "+currentProxy.reason+"; trying direct":
27
+ "🌐 Direct connection ("+currentProxy.source+")";
28
+ if(notice!==lastProxyNotice){logLine(currentProxy.mode==="unavailable"?"warn":"info",notice);lastProxyNotice=notice}
29
+ }
30
+ if(currentProxy.mode!=="proxy")return {};
31
+ let transport=agents.get(currentProxy.url);
32
+ if(!transport){
33
+ transport={dispatcher:new ProxyAgent(currentProxy.url),wsAgent:new HttpsProxyAgent(currentProxy.url)};
34
+ agents.set(currentProxy.url,transport);
35
+ }
36
+ return transport;
37
+ }
17
38
  let stopping=false,child=null,socket=null;
39
+ let connectionAttempt=0,connectedSince=0,sessionCalls=0,sessionFails=0,allCalls=0,allFails=0,lastError="";
40
+ function reportDevice(creds){
41
+ logLine("info","━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
42
+ logLine("info","Computer: "+os.hostname()+" | User: "+os.userInfo().username+" | Node: "+process.version);
43
+ logLine("info","Device ID: "+creds.deviceId+" | Gateway PID: "+(child?.pid||"unknown"));
44
+ logLine("info","Relay: "+relay+" | Local MCP: http://127.0.0.1:8717/mcp");
45
+ logLine("info","Mode: "+(trace?"TRACE":debug?"DEBUG":"LIVE"));
46
+ logLine("info","Return to ChatGPT; keep this terminal running. Ctrl+C to disconnect.");
47
+ logLine("info","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
48
+ }
18
49
  function saved(){try{return JSON.parse(fs.readFileSync(config,"utf8"))}catch{return null}}
19
50
  function store(x){fs.mkdirSync(path.dirname(config),{recursive:true,mode:0o700});fs.writeFileSync(config,JSON.stringify(x,null,2),{mode:0o600});}
20
51
  function forget(){try{fs.unlinkSync(config)}catch{}}
21
- async function post(route,data){const r=await fetch(relay+route,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(data),signal:AbortSignal.timeout(12000)});const j=await r.json();if(!r.ok)throw Error(j.error||"HTTP "+r.status);return j;}
52
+ 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;}
22
53
  async function pair(){
23
54
  const v=await post("/relay/pair/start",{name:os.hostname()});
24
55
  logLine("info","🔑 New device pairing requested");
@@ -35,15 +66,18 @@ async function startGateway(){
35
66
  logLine("info","🚀 Starting local Desktop Commander gateway...");
36
67
  const fd=fs.openSync(path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"),"a");
37
68
  child=spawn(process.execPath,[path.join(root,"gateway.mjs")],{cwd:root,stdio:["ignore",fd,fd],windowsHide:true});fs.closeSync(fd);
69
+ logLine("info","Gateway PID: "+child.pid+" | diagnostic log: "+path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"));
38
70
  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)}
39
71
  throw Error("Gateway failed to listen on port 8717.");
40
72
  }
41
73
  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;}}
42
74
  async function respond(ws,msg){
43
- const started=Date.now(),request=rpcDescription(msg.body);
44
- const title=request.name?request.method+" "+request.name:request.method;
45
- logLine("info","🔧 Received "+title);
46
- if(debug)logLine("debug","Request parameters: "+JSON.stringify(request.params));
75
+ const started=Date.now(),call=callInfo(msg.body,msg.id),callId=shortCallId(call.requestId);
76
+ const name=call.label,isTool=call.method==="tools/call";
77
+ allCalls++;sessionCalls++;
78
+ logLine("info","🔧 ["+callId+"] "+(isTool?"Tool: ":"MCP: ")+name+" | "+requestBrief(call));
79
+ if(debug)logLine("debug"," ↳ Metadata: "+requestDebug(call));
80
+ if(trace)logLine("warn"," ↳ Trace args (locally visible): "+safeTraceRequest(call));
47
81
  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];
48
82
  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{}
49
83
  let response;
@@ -52,30 +86,57 @@ async function respond(ws,msg){
52
86
  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);
53
87
  response={kind:"response",id:msg.id,status:r.status,headers:forward,body:body.slice(0,8*1024*1024)};
54
88
  }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)})}}
55
- const details=rpcOutcome(response.body,response.headers?.["content-type"]||"");
56
- const failed=response.status>=400||details.failed;
57
- logLine(failed?"error":"info",(failed?"❌ Failed ":"✅ Completed ")+title+" | HTTP "+response.status+" | "+(Date.now()-started)+"ms");
58
- if(debug)logLine("debug","Response metadata: "+JSON.stringify({kind:details.kind,bytes:details.size,resultFields:details.resultFields}));
89
+ const result=responseBrief(response.body,response.headers?.["content-type"]||"",response.status);
90
+ const failed=result.failed;
91
+ if(failed){allFails++;sessionFails++;}
92
+ logLine(failed?"error":"info",(failed?"❌":"✅")+" ["+callId+"] "+name+
93
+ " | "+result.kind+" | HTTP "+response.status+" | "+formatElapsed(Date.now()-started));
94
+ logLine(failed?"warn":"info"," ↳ "+result.summary);
95
+ if(result.error)logLine("error"," ↳ JSON-RPC: "+result.error);
96
+ if(debug)logLine("debug"," ↳ Response size: "+result.bytes+" bytes | Total calls: "+allCalls+" | Errors: "+allFails);
97
+ if(trace)logLine("warn"," ↳ Trace output (may contain private data): "+safeTraceOutput(result));
59
98
  if(ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify(response));
99
+ else logLine("warn"," ↳ Response cannot be delivered: relay socket is not open");
60
100
  }
61
101
  async function connect(creds){return new Promise(resolve=>{
62
- const proxyUrl=getProxyForUrl(relay);
63
- logLine("info","🌐 Connecting to Cloudflare relay...");
64
- const ws=new WebSocket(relay.replace(/^https:/,"wss:")+"/relay/ws",{headers:{"Authorization":"Bearer "+creds.token,"X-Device-ID":creds.deviceId},handshakeTimeout:15000,...(proxyUrl?{agent:new HttpsProxyAgent(proxyUrl)}:{})});socket=ws;
102
+ const {wsAgent}=remoteTransport();
103
+ const attempt=++connectionAttempt,opening=Date.now();
104
+ logLine("info","🌐 Connecting to Cloudflare relay (attempt #"+attempt+")...");
105
+ 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;
65
106
  let status=0;
66
- ws.on("open",()=>{logLine("info","✅ Connected to Cloudflare relay");logLine("info","🟢 Device online: "+os.hostname());console.log("CONNECTED. ChatGPT can now use this device. Ctrl+C to disconnect.");});
67
- ws.on("unexpected-response",(req,res)=>{status=res.statusCode;res.resume();logLine("error","Relay refused: HTTP "+status)});
68
- ws.on("message",data=>{let m;try{m=JSON.parse(String(data))}catch{return}if(m.kind==="request")respond(ws,m).catch(e=>console.error(e.message))});
69
- ws.on("error",e=>logLine("error","Relay: "+sanitizeText(e.message,200)));
70
- ws.on("close",(code)=>{socket=null;logLine("warn","🔌 Relay disconnected (code "+code+")");resolve({unauthorized:status===401})});
107
+ ws.on("open",()=>{
108
+ connectedSince=Date.now();sessionCalls=0;sessionFails=0;lastError="";
109
+ logLine("info","✅ Cloudflare relay connected in "+formatElapsed(Date.now()-opening));
110
+ reportDevice(creds);
111
+ console.log("CONNECTED. ChatGPT can now use this device. Ctrl+C to disconnect.");
112
+ });
113
+ ws.on("unexpected-response",(_req,res)=>{status=res.statusCode;res.resume();lastError="HTTP "+status;logLine("error","Relay handshake rejected: HTTP "+status)});
114
+ ws.on("message",data=>{
115
+ let m;try{m=JSON.parse(String(data))}catch{if(debug)logLine("debug","Ignored invalid relay JSON message");return}
116
+ if(m.kind==="request")respond(ws,m).catch(e=>logLine("error","Request handler: "+sanitizeText(e.message,240)));
117
+ });
118
+ ws.on("error",e=>{lastError=sanitizeText(e.message,180);logLine("error","Relay network error: "+lastError)});
119
+ ws.on("close",(code,reason)=>{
120
+ socket=null;
121
+ const uptime=connectedSince?formatElapsed(Date.now()-connectedSince):"not established";
122
+ logLine("warn","🔌 Relay disconnected | code="+code+" | session uptime="+uptime+
123
+ " | calls="+sessionCalls+" | failures="+sessionFails);
124
+ if(lastError)logLine("warn"," ↳ Last network error: "+lastError);
125
+ if(reason?.length)logLine("warn"," ↳ Close reason: "+sanitizeText(reason.toString(),100));
126
+ connectedSince=0;
127
+ resolve({unauthorized:status===401});
128
+ });
71
129
  })}
72
130
  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();}
73
131
  process.on("SIGINT",stop);process.on("SIGTERM",stop);
74
- if(["help","--help","-h"].includes(command)){console.log("Private Desktop MCP: connect | status | reset [--debug]\nUse --debug for redacted request/response metadata.\nFirst connect requires approval at https://private-desktop-device-relay.ljx2043979076.workers.dev/admin/devices\nCtrl+C to disconnect. No automatic startup.");}
132
+ if(["help","--help","-h"].includes(command)){console.log("Private Desktop MCP: connect | status | reset [--debug | --trace]\nUse --debug for safe metadata; --trace shows redacted/truncated content previews (may contain private data).\nFirst connect requires approval at https://private-desktop-device-relay.ljx2043979076.workers.dev/admin/devices\nCtrl+C to disconnect. No automatic startup.");}
75
133
  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")}}
76
134
  else if(command==="reset"){forget();console.log("Local credentials cleared. Revoke old credentials in the admin page too.");}
77
135
  else if(command==="connect"){
78
- logLine("info","PCC v0.3.3 starting ("+(debug?"debug":"normal")+" logging)");
136
+ logLine("info","╔══════════════ PCC REMOTE v0.3.5 ══════════════╗");
137
+ logLine("info","Logging: "+(trace?"TRACE":debug?"DEBUG":"LIVE")+" | Gateway: Desktop Commander MCP");
138
+ if(trace)logLine("warn","TRACE mode can display private user content in this terminal; do not share these logs.");
139
+ logLine("info","╚═══════════════════════════════════════════════╝");
79
140
  try{const credentials=saved()||await pair();if(saved())logLine("info","💾 Stored device pairing found");await startGateway();let retries=0;
80
141
  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);}
81
142
  }catch(e){logLine("error","ERROR: "+sanitizeText(e.message,250));process.exitCode=1}finally{stopGateway()}
package/bin/logging.mjs CHANGED
@@ -50,6 +50,6 @@ export function rpcOutcome(body,contentType=""){
50
50
  }
51
51
  export function logLine(level,message){
52
52
  const tag={info:"INFO",warn:"WARN",error:"ERROR",debug:"DEBUG"}[level]||"INFO";
53
- const output="["+timestamp()+"] ["+tag+"] "+sanitizeText(message,800);
53
+ const output="["+timestamp()+"] ["+tag+"] "+sanitizeText(message,1550);
54
54
  if(level==="error")console.error(output);else console.log(output);
55
55
  }
package/bin/proxy.mjs ADDED
@@ -0,0 +1,53 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { getProxyForUrl } from "proxy-from-env";
3
+
4
+ const proxyEnvironmentKeys=[
5
+ "https_proxy","http_proxy","all_proxy",
6
+ "npm_config_https_proxy","npm_config_http_proxy","npm_config_proxy"
7
+ ];
8
+ export function hasEnvironmentProxy(env=process.env){
9
+ const names=new Set(Object.keys(env).filter(k=>proxyEnvironmentKeys.includes(k.toLowerCase())));
10
+ return [...names].some(k=>String(env[k]??"").trim().length>0);
11
+ }
12
+ export function normalizeProxy(value,source){
13
+ const raw=String(value||"").trim();
14
+ if(!raw)return {mode:"direct",source};
15
+ const uri=/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)?raw:"http://"+raw;
16
+ let parsed;
17
+ try{parsed=new URL(uri)}catch{return {mode:"unsupported",source,reason:"Invalid proxy address"}}
18
+ if(!["http:","https:"].includes(parsed.protocol)){
19
+ return {mode:"unsupported",source,reason:"Proxy protocol "+parsed.protocol+" is not HTTP CONNECT; use an HTTP/Mixed proxy port"};
20
+ }
21
+ if(!parsed.hostname)return {mode:"unsupported",source,reason:"Missing proxy hostname"};
22
+ return {mode:"proxy",source,url:parsed.href,description:parsed.protocol.slice(0,-1).toUpperCase()+" CONNECT via "+parsed.hostname+":"+(parsed.port||(["https:"].includes(parsed.protocol)?"443":"80"))};
23
+ }
24
+ export function queryWindowsProxy(url,{spawn=spawnSync}={}){
25
+ // Windows WinINET system proxy, including static proxy, exclusions, PAC and WPAD.
26
+ // Use the Windows user's configuration instead of guessing a Clash/v2rayN port.
27
+ const target=String(url).replace(/'/g,"''");
28
+ const script="$ErrorActionPreference='Stop';"
29
+ +"$u=[Uri]'"+target+"';"
30
+ +"$p=[System.Net.WebRequest]::GetSystemWebProxy();"
31
+ +"if($p.IsBypassed($u)){[Console]::Out.Write('DIRECT')}"
32
+ +"else{$v=$p.GetProxy($u);if($v.AbsoluteUri -eq $u.AbsoluteUri){[Console]::Out.Write('DIRECT')}else{[Console]::Out.Write($v.AbsoluteUri)}}";
33
+ const result=spawn("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",script],{
34
+ encoding:"utf8",timeout:6000,windowsHide:true,maxBuffer:4096
35
+ });
36
+ if(result.error||result.status!==0){
37
+ return {mode:"unavailable",source:"windows",reason:result.error?.code==="ETIMEDOUT"?"Windows proxy lookup timed out":"Windows proxy lookup failed"};
38
+ }
39
+ const output=String(result.stdout||"").trim();
40
+ if(output==="DIRECT")return {mode:"direct",source:"windows"};
41
+ if(!output)return {mode:"unavailable",source:"windows",reason:"Windows proxy lookup returned no result"};
42
+ return normalizeProxy(output,"windows");
43
+ }
44
+ export function resolveProxyForUrl(url,{
45
+ platform=process.platform,env=process.env,envLookup=getProxyForUrl,windowsLookup=queryWindowsProxy
46
+ }={}){
47
+ if(hasEnvironmentProxy(env)){
48
+ const chosen=envLookup(url);
49
+ return chosen?normalizeProxy(chosen,"environment"):{mode:"direct",source:"environment-bypass"};
50
+ }
51
+ if(platform==="win32")return windowsLookup(url);
52
+ return {mode:"direct",source:"system"};
53
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juexibobi/private-desktop-mcp",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Private multi-device Desktop Commander MCP connector for Cloudflare Workers with paired WebSocket relays",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,6 +12,8 @@
12
12
  },
13
13
  "files": [
14
14
  "bin/cli.mjs",
15
+ "bin/activity.mjs",
16
+ "bin/proxy.mjs",
15
17
  "bin/logging.mjs",
16
18
  "gateway.mjs",
17
19
  "README.md",