@juexibobi/private-desktop-mcp 0.3.6 → 0.4.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/README.md +79 -33
- package/bin/cli.mjs +888 -136
- package/bin/policy.mjs +286 -0
- package/bin/proxy.mjs +173 -45
- package/gateway.mjs +231 -33
- package/package.json +9 -8
package/bin/cli.mjs
CHANGED
|
@@ -1,144 +1,896 @@
|
|
|
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 {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if(
|
|
81
|
-
if(
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
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
|
+
|
|
32
|
+
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
33
|
+
const PKG_VERSION = (() => {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.4.0";
|
|
36
|
+
} catch {
|
|
37
|
+
return "0.4.0";
|
|
38
|
+
}
|
|
39
|
+
})();
|
|
40
|
+
|
|
41
|
+
const DEFAULT_RELAY = "https://private-desktop-device-relay.ljx2043979076.workers.dev";
|
|
42
|
+
const HEARTBEAT_INTERVAL_MS = 25000;
|
|
43
|
+
const MAX_GATEWAY_LOG_BYTES = 5 * 1024 * 1024;
|
|
44
|
+
|
|
45
|
+
function parseArgs(argv) {
|
|
46
|
+
let command = "";
|
|
47
|
+
let relay = process.env.PCC_RELAY_URL || DEFAULT_RELAY;
|
|
48
|
+
let port = Number(process.env.MCP_PORT || 8717);
|
|
49
|
+
let deviceName = os.hostname();
|
|
50
|
+
let readonly = /^(1|true|yes)$/i.test(String(process.env.PCC_READONLY || ""));
|
|
51
|
+
let dlp = !/^(0|false|no)$/i.test(String(process.env.PCC_DLP || "true"));
|
|
52
|
+
let autoOpen = true;
|
|
53
|
+
let serversConfig = process.env.PCC_MCP_CONFIG || "";
|
|
54
|
+
const allowDirs = String(process.env.PCC_ALLOW_DIRS || "")
|
|
55
|
+
.split(path.delimiter)
|
|
56
|
+
.map((s) => s.trim())
|
|
57
|
+
.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);
|
|
66
|
+
|
|
67
|
+
for (let i = 0; i < argv.length; i++) {
|
|
68
|
+
const arg = argv[i];
|
|
69
|
+
if (!arg.startsWith("-")) {
|
|
70
|
+
if (!command) command = arg;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const eq = arg.indexOf("=");
|
|
74
|
+
const flag = eq > 0 ? arg.slice(0, eq) : arg;
|
|
75
|
+
const inlineVal = eq > 0 ? arg.slice(eq + 1) : null;
|
|
76
|
+
const nextVal = () => (inlineVal !== null ? inlineVal : argv[++i] || "");
|
|
77
|
+
|
|
78
|
+
if (flag === "--help" || flag === "-h") command = "help";
|
|
79
|
+
else if (flag === "--relay") relay = nextVal().replace(/\/+$/, "");
|
|
80
|
+
else if (flag === "--port") port = Number(nextVal());
|
|
81
|
+
else if (flag === "--name") deviceName = nextVal();
|
|
82
|
+
else if (flag === "--readonly") readonly = true;
|
|
83
|
+
else if (flag === "--no-dlp") dlp = false;
|
|
84
|
+
else if (flag === "--no-open") autoOpen = false;
|
|
85
|
+
else if (flag === "--servers") serversConfig = nextVal();
|
|
86
|
+
else if (flag === "--allow-dir") {
|
|
87
|
+
const v = nextVal().trim();
|
|
88
|
+
if (v) allowDirs.push(v);
|
|
89
|
+
} else if (flag === "--allow-tools") {
|
|
90
|
+
for (const item of nextVal().split(",")) if (item.trim()) allowTools.push(item.trim());
|
|
91
|
+
} else if (flag === "--deny-tools") {
|
|
92
|
+
for (const item of nextVal().split(",")) if (item.trim()) denyTools.push(item.trim());
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
command: command || "connect",
|
|
98
|
+
relay: relay.replace(/\/+$/, ""),
|
|
99
|
+
port,
|
|
100
|
+
deviceName: deviceName || "Desktop",
|
|
101
|
+
readonly,
|
|
102
|
+
dlp,
|
|
103
|
+
autoOpen,
|
|
104
|
+
serversConfig,
|
|
105
|
+
allowDirs,
|
|
106
|
+
allowTools,
|
|
107
|
+
denyTools
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const opts = parseArgs(process.argv.slice(2));
|
|
112
|
+
const { trace, debug } = loggingOptions(process.argv.slice(2));
|
|
113
|
+
const configDir = path.join(process.env.APPDATA || path.join(os.homedir(), ".config"), "PrivateDesktopMCP");
|
|
114
|
+
const config = path.join(configDir, "device.json");
|
|
115
|
+
const gatewayLogDir = path.join(configDir, "logs");
|
|
116
|
+
const gatewayLogPath = path.join(gatewayLogDir, "gateway.log");
|
|
117
|
+
const localBaseUrl = `http://127.0.0.1:${opts.port}/mcp`;
|
|
118
|
+
const localGatewayToken = crypto.randomBytes(32).toString("hex");
|
|
119
|
+
const policy = createPolicy({
|
|
120
|
+
readonly: opts.readonly,
|
|
121
|
+
allowTools: opts.allowTools,
|
|
122
|
+
denyTools: opts.denyTools,
|
|
123
|
+
allowDirs: opts.allowDirs,
|
|
124
|
+
protectedDirs: [configDir],
|
|
125
|
+
dlp: opts.dlp
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
129
|
+
let currentProxy = null;
|
|
130
|
+
let proxyCheckedAt = 0;
|
|
131
|
+
let lastProxyNotice = "";
|
|
132
|
+
const agents = new Map();
|
|
133
|
+
|
|
134
|
+
function remoteTransport() {
|
|
135
|
+
if (!currentProxy || Date.now() - proxyCheckedAt > 10000) {
|
|
136
|
+
currentProxy = resolveProxyForUrl(opts.relay);
|
|
137
|
+
proxyCheckedAt = Date.now();
|
|
138
|
+
if (currentProxy.mode === "unsupported") {
|
|
139
|
+
throw Error(currentProxy.reason + " (use an HTTP/Mixed port via system settings or HTTPS_PROXY)");
|
|
140
|
+
}
|
|
141
|
+
const notice =
|
|
142
|
+
currentProxy.mode === "proxy"
|
|
143
|
+
? "🌐 Proxy: " + currentProxy.source + " (" + currentProxy.description + ")"
|
|
144
|
+
: currentProxy.mode === "unavailable"
|
|
145
|
+
? "⚠️ Proxy detection unavailable: " + currentProxy.reason + "; trying direct"
|
|
146
|
+
: "🌐 Direct connection (" + currentProxy.source + ")";
|
|
147
|
+
if (notice !== lastProxyNotice) {
|
|
148
|
+
logLine(currentProxy.mode === "unavailable" ? "warn" : "info", notice);
|
|
149
|
+
lastProxyNotice = notice;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (currentProxy.mode !== "proxy") return {};
|
|
153
|
+
let transport = agents.get(currentProxy.url);
|
|
154
|
+
if (!transport) {
|
|
155
|
+
transport = { dispatcher: new ProxyAgent(currentProxy.url), wsAgent: new HttpsProxyAgent(currentProxy.url) };
|
|
156
|
+
agents.set(currentProxy.url, transport);
|
|
157
|
+
}
|
|
158
|
+
return transport;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let stopping = false;
|
|
162
|
+
let child = null;
|
|
163
|
+
let gatewayHealthy = false;
|
|
164
|
+
let gatewayRestartCount = 0;
|
|
165
|
+
let gatewayRestartPromise = null;
|
|
166
|
+
let socket = null;
|
|
167
|
+
let activeCreds = null;
|
|
168
|
+
let connectionAttempt = 0;
|
|
169
|
+
let connectedSince = 0;
|
|
170
|
+
let sessionCalls = 0;
|
|
171
|
+
let sessionFails = 0;
|
|
172
|
+
let allCalls = 0;
|
|
173
|
+
let allFails = 0;
|
|
174
|
+
let lastError = "";
|
|
175
|
+
const inflightControllers = new Map();
|
|
176
|
+
|
|
177
|
+
function saved() {
|
|
178
|
+
try {
|
|
179
|
+
return JSON.parse(fs.readFileSync(config, "utf8"));
|
|
180
|
+
} catch {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function store(x) {
|
|
186
|
+
fs.mkdirSync(path.dirname(config), { recursive: true, mode: 0o700 });
|
|
187
|
+
fs.writeFileSync(config, JSON.stringify(x, null, 2), { mode: 0o600 });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function forget() {
|
|
191
|
+
try {
|
|
192
|
+
fs.unlinkSync(config);
|
|
193
|
+
} catch {}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function rotateLogIfNeeded(filePath) {
|
|
197
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
198
|
+
try {
|
|
199
|
+
const stat = fs.statSync(filePath);
|
|
200
|
+
if (stat.size >= MAX_GATEWAY_LOG_BYTES) {
|
|
201
|
+
try {
|
|
202
|
+
fs.unlinkSync(filePath + ".1");
|
|
203
|
+
} catch {}
|
|
204
|
+
fs.renameSync(filePath, filePath + ".1");
|
|
205
|
+
}
|
|
206
|
+
} catch {}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function tryOpenBrowser(url) {
|
|
210
|
+
if (!opts.autoOpen || !process.stdout.isTTY || process.env.CI) return;
|
|
211
|
+
try {
|
|
212
|
+
let cmd;
|
|
213
|
+
let args;
|
|
214
|
+
if (process.platform === "win32") {
|
|
215
|
+
cmd = "cmd.exe";
|
|
216
|
+
args = ["/c", "start", "", url];
|
|
217
|
+
} else if (process.platform === "darwin") {
|
|
218
|
+
cmd = "open";
|
|
219
|
+
args = [url];
|
|
220
|
+
} else {
|
|
221
|
+
cmd = "xdg-open";
|
|
222
|
+
args = [url];
|
|
223
|
+
}
|
|
224
|
+
const p = spawn(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
225
|
+
p.on("error", () => {});
|
|
226
|
+
p.unref();
|
|
227
|
+
} catch {}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function reportDevice(creds) {
|
|
231
|
+
logLine("info", "━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
|
|
232
|
+
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)");
|
|
235
|
+
logLine(
|
|
236
|
+
"info",
|
|
237
|
+
"Mode: " +
|
|
238
|
+
(trace ? "TRACE" : debug ? "DEBUG" : "LIVE") +
|
|
239
|
+
" | Policy: " +
|
|
240
|
+
(policy.readonly ? "READONLY" : "FULL") +
|
|
241
|
+
" | DLP: " +
|
|
242
|
+
(policy.dlp ? "ON" : "OFF") +
|
|
243
|
+
(policy.allowDirs.length ? " | AllowDirs: " + policy.allowDirs.length : "")
|
|
244
|
+
);
|
|
245
|
+
logLine("info", "Return to your AI client; keep this terminal running. Ctrl+C to disconnect.");
|
|
246
|
+
logLine("info", "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function post(route, data) {
|
|
250
|
+
const { dispatcher } = remoteTransport();
|
|
251
|
+
const r = await fetch(opts.relay + route, {
|
|
252
|
+
method: "POST",
|
|
253
|
+
headers: { "content-type": "application/json" },
|
|
254
|
+
body: JSON.stringify(data),
|
|
255
|
+
signal: AbortSignal.timeout(12000),
|
|
256
|
+
...(dispatcher ? { dispatcher } : {})
|
|
257
|
+
});
|
|
258
|
+
const j = await r.json();
|
|
259
|
+
if (!r.ok) throw Error(j.error || "HTTP " + r.status);
|
|
260
|
+
return j;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async function pair() {
|
|
264
|
+
const v = await post("/relay/pair/start", { name: opts.deviceName });
|
|
265
|
+
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
|
+
);
|
|
275
|
+
tryOpenBrowser(v.approvalUrl);
|
|
276
|
+
for (let i = 0; i < 720 && !stopping; i++) {
|
|
277
|
+
await sleep(5000);
|
|
278
|
+
let r;
|
|
279
|
+
try {
|
|
280
|
+
r = await post("/relay/pair/poll", { pairId: v.pairId, proof: v.proof });
|
|
281
|
+
} catch (e) {
|
|
282
|
+
if (/expired|invalid/i.test(e.message)) throw e;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (r.status === "approved") {
|
|
286
|
+
const credentials = { deviceId: r.deviceId, token: r.token };
|
|
287
|
+
store(credentials);
|
|
288
|
+
logLine("info", "✅ Device approved; credentials saved locally.");
|
|
289
|
+
return credentials;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
throw Error("Pairing timed out. Re-run the command.");
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function portOpen(withToken = false) {
|
|
296
|
+
if (withToken) {
|
|
297
|
+
const r = await fetch(`http://127.0.0.1:${opts.port}/healthz`, {
|
|
298
|
+
headers: { authorization: "Bearer " + localGatewayToken },
|
|
299
|
+
signal: AbortSignal.timeout(1500)
|
|
300
|
+
});
|
|
301
|
+
return r.status === 200;
|
|
302
|
+
}
|
|
303
|
+
const r = await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) });
|
|
304
|
+
return r.status > 0;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function abortAllInflight(reason) {
|
|
308
|
+
for (const [id, controller] of inflightControllers) {
|
|
309
|
+
inflightControllers.delete(id);
|
|
310
|
+
try {
|
|
311
|
+
controller.abort(new Error(reason));
|
|
312
|
+
} catch {}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function startGateway({ checkOccupied = true } = {}) {
|
|
317
|
+
if (!Number.isInteger(opts.port) || opts.port < 1024 || opts.port > 65535) {
|
|
318
|
+
throw Error("Invalid port: " + opts.port);
|
|
319
|
+
}
|
|
320
|
+
if (checkOccupied) {
|
|
321
|
+
try {
|
|
322
|
+
if (await portOpen(false)) {
|
|
323
|
+
throw Error(`Port ${opts.port} is already occupied. Stop the other MCP gateway or pass --port <port>.`);
|
|
324
|
+
}
|
|
325
|
+
} catch (e) {
|
|
326
|
+
if (/occupied/.test(e.message)) throw e;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
logLine("info", "🚀 Starting local MCP gateway (Desktop Commander" + (opts.serversConfig ? " + extra servers" : "") + ")...");
|
|
331
|
+
rotateLogIfNeeded(gatewayLogPath);
|
|
332
|
+
const fd = fs.openSync(gatewayLogPath, "a", 0o600);
|
|
333
|
+
const spawned = spawn(process.execPath, [path.join(root, "gateway.mjs")], {
|
|
334
|
+
cwd: root,
|
|
335
|
+
stdio: ["ignore", fd, fd],
|
|
336
|
+
windowsHide: true,
|
|
337
|
+
env: {
|
|
338
|
+
...process.env,
|
|
339
|
+
MCP_PORT: String(opts.port),
|
|
340
|
+
MCP_LOCAL_TOKEN: localGatewayToken,
|
|
341
|
+
...(opts.serversConfig ? { PCC_MCP_CONFIG: path.resolve(opts.serversConfig) } : {})
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
fs.closeSync(fd);
|
|
345
|
+
child = spawned;
|
|
346
|
+
gatewayHealthy = false;
|
|
347
|
+
logLine("info", "Gateway PID: " + spawned.pid + " | diagnostic log: " + gatewayLogPath);
|
|
348
|
+
|
|
349
|
+
spawned.on("exit", (code, signal) => {
|
|
350
|
+
if (child === spawned) child = null;
|
|
351
|
+
const wasHealthy = gatewayHealthy;
|
|
352
|
+
gatewayHealthy = false;
|
|
353
|
+
abortAllInflight("Local MCP gateway exited unexpectedly");
|
|
354
|
+
if (stopping) return;
|
|
355
|
+
logLine("error", `⚠️ Local MCP gateway exited unexpectedly (code=${code ?? "null"}, signal=${signal ?? "none"})`);
|
|
356
|
+
if (wasHealthy) scheduleGatewayRestart();
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
for (let i = 0; i < 40; i++) {
|
|
360
|
+
if (spawned.exitCode !== null) {
|
|
361
|
+
throw Error("Gateway exited unexpectedly. See " + gatewayLogPath);
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
if (await portOpen(true)) {
|
|
365
|
+
gatewayHealthy = true;
|
|
366
|
+
gatewayRestartCount = 0;
|
|
367
|
+
logLine("info", `🔌 Local MCP gateway ready (127.0.0.1:${opts.port})`);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
} catch {}
|
|
371
|
+
await sleep(500);
|
|
372
|
+
}
|
|
373
|
+
throw Error(`Gateway failed to listen on port ${opts.port}.`);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function scheduleGatewayRestart() {
|
|
377
|
+
if (stopping || gatewayRestartPromise) return;
|
|
378
|
+
gatewayRestartCount++;
|
|
379
|
+
const delayMs = Math.min(30000, 1000 * 2 ** Math.min(4, gatewayRestartCount - 1));
|
|
380
|
+
logLine("warn", `🔄 Restarting local MCP gateway in ${Math.ceil(delayMs / 1000)}s (restart #${gatewayRestartCount})...`);
|
|
381
|
+
gatewayRestartPromise = (async () => {
|
|
382
|
+
await sleep(delayMs);
|
|
383
|
+
if (stopping) return;
|
|
384
|
+
try {
|
|
385
|
+
await startGateway({ checkOccupied: false });
|
|
386
|
+
logLine("info", "✅ Local MCP gateway recovered.");
|
|
387
|
+
} catch (e) {
|
|
388
|
+
logLine("error", "Local MCP gateway restart failed: " + sanitizeText(e.message, 200));
|
|
389
|
+
} finally {
|
|
390
|
+
gatewayRestartPromise = null;
|
|
391
|
+
if (!stopping && !gatewayHealthy && !child) {
|
|
392
|
+
scheduleGatewayRestart();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
})();
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function stopGateway() {
|
|
399
|
+
gatewayHealthy = false;
|
|
400
|
+
abortAllInflight("Connector shutting down");
|
|
401
|
+
if (child?.pid) {
|
|
402
|
+
if (process.platform === "win32") {
|
|
403
|
+
spawnSync("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, timeout: 8000 });
|
|
404
|
+
} else {
|
|
405
|
+
try {
|
|
406
|
+
child.kill("SIGTERM");
|
|
407
|
+
} catch {}
|
|
408
|
+
}
|
|
409
|
+
child = null;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
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));
|
|
555
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(response));
|
|
556
|
+
else logLine("warn", " ↳ Response cannot be delivered: relay socket is not open");
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
async function connect(creds, { onHealthy } = {}) {
|
|
560
|
+
return new Promise((resolve) => {
|
|
561
|
+
const { wsAgent } = remoteTransport();
|
|
562
|
+
const attempt = ++connectionAttempt;
|
|
563
|
+
const opening = Date.now();
|
|
564
|
+
logLine("info", "🌐 Connecting to Cloudflare relay (attempt #" + attempt + ")...");
|
|
565
|
+
|
|
566
|
+
const ws = new WebSocket(opts.relay.replace(/^https:/, "wss:").replace(/^http:/, "ws:") + "/relay/ws", {
|
|
567
|
+
headers: {
|
|
568
|
+
Authorization: "Bearer " + creds.token,
|
|
569
|
+
"X-Device-ID": creds.deviceId,
|
|
570
|
+
"X-Device-Platform": process.platform,
|
|
571
|
+
"X-Device-Arch": process.arch,
|
|
572
|
+
"X-Device-Node": process.version,
|
|
573
|
+
"X-Device-Version": PKG_VERSION,
|
|
574
|
+
"X-Device-Mode": policy.readonly ? "READONLY" : "FULL"
|
|
575
|
+
},
|
|
576
|
+
handshakeTimeout: 15000,
|
|
577
|
+
...(wsAgent ? { agent: wsAgent } : {})
|
|
578
|
+
});
|
|
579
|
+
socket = ws;
|
|
580
|
+
|
|
581
|
+
let status = 0;
|
|
582
|
+
let awaitingPong = false;
|
|
583
|
+
let heartbeatTimer = null;
|
|
584
|
+
let healthyTimer = null;
|
|
585
|
+
|
|
586
|
+
const clearTimers = () => {
|
|
587
|
+
if (heartbeatTimer) {
|
|
588
|
+
clearInterval(heartbeatTimer);
|
|
589
|
+
heartbeatTimer = null;
|
|
590
|
+
}
|
|
591
|
+
if (healthyTimer) {
|
|
592
|
+
clearTimeout(healthyTimer);
|
|
593
|
+
healthyTimer = null;
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
|
|
597
|
+
ws.on("open", () => {
|
|
598
|
+
connectedSince = Date.now();
|
|
599
|
+
sessionCalls = 0;
|
|
600
|
+
sessionFails = 0;
|
|
601
|
+
lastError = "";
|
|
602
|
+
awaitingPong = false;
|
|
603
|
+
|
|
604
|
+
// Reset backoff retries once the connection proves stable for 10s
|
|
605
|
+
healthyTimer = setTimeout(() => {
|
|
606
|
+
if (ws.readyState === WebSocket.OPEN) onHealthy?.();
|
|
607
|
+
}, 10000);
|
|
608
|
+
healthyTimer.unref?.();
|
|
609
|
+
|
|
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
|
+
heartbeatTimer = setInterval(() => {
|
|
613
|
+
if (ws.readyState !== WebSocket.OPEN) return;
|
|
614
|
+
if (awaitingPong) {
|
|
615
|
+
logLine("warn", "⚠️ Relay heartbeat timed out (half-open socket detected); forcing reconnect...");
|
|
616
|
+
clearTimers();
|
|
617
|
+
try {
|
|
618
|
+
ws.terminate();
|
|
619
|
+
} catch {}
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
awaitingPong = true;
|
|
623
|
+
try {
|
|
624
|
+
ws.ping();
|
|
625
|
+
} catch {
|
|
626
|
+
try {
|
|
627
|
+
ws.terminate();
|
|
628
|
+
} catch {}
|
|
629
|
+
}
|
|
630
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
631
|
+
heartbeatTimer.unref?.();
|
|
632
|
+
|
|
633
|
+
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.");
|
|
636
|
+
});
|
|
637
|
+
|
|
638
|
+
ws.on("pong", () => {
|
|
639
|
+
awaitingPong = false;
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
ws.on("unexpected-response", (_req, res) => {
|
|
643
|
+
status = res.statusCode;
|
|
644
|
+
res.resume();
|
|
645
|
+
lastError = "HTTP " + status;
|
|
646
|
+
logLine("error", "Relay handshake rejected: HTTP " + status);
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
ws.on("message", (data) => {
|
|
650
|
+
awaitingPong = false;
|
|
651
|
+
const text = String(data);
|
|
652
|
+
if (text === "pong") {
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
let m;
|
|
656
|
+
try {
|
|
657
|
+
m = JSON.parse(text);
|
|
658
|
+
} catch {
|
|
659
|
+
if (debug) logLine("debug", "Ignored invalid relay JSON message");
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (m.kind === "pong") {
|
|
663
|
+
awaitingPong = false;
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (m.kind === "ping") {
|
|
667
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
668
|
+
ws.send(
|
|
669
|
+
JSON.stringify({
|
|
670
|
+
kind: "pong",
|
|
671
|
+
id: m.id,
|
|
672
|
+
uptimeMs: connectedSince ? Date.now() - connectedSince : 0,
|
|
673
|
+
gatewayReady: gatewayHealthy,
|
|
674
|
+
mode: policy.readonly ? "READONLY" : "FULL",
|
|
675
|
+
version: PKG_VERSION
|
|
676
|
+
})
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
if (m.kind === "cancel" && m.id) {
|
|
682
|
+
const ctrl = inflightControllers.get(m.id);
|
|
683
|
+
if (ctrl) {
|
|
684
|
+
logLine("warn", "🛑 [" + shortCallId(m.id) + "] Aborting in-flight call (client cancelled/timed out)");
|
|
685
|
+
try {
|
|
686
|
+
ctrl.abort(new Error("Cancelled by client"));
|
|
687
|
+
} catch {}
|
|
688
|
+
}
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
if (m.kind === "request") {
|
|
692
|
+
respond(ws, m).catch((e) => logLine("error", "Request handler: " + sanitizeText(e.message, 240)));
|
|
693
|
+
}
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
ws.on("error", (e) => {
|
|
697
|
+
lastError = sanitizeText(e.message, 180);
|
|
698
|
+
logLine("error", "Relay network error: " + lastError);
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
ws.on("close", (code, reason) => {
|
|
702
|
+
clearTimers();
|
|
703
|
+
socket = null;
|
|
704
|
+
const uptime = connectedSince ? formatElapsed(Date.now() - connectedSince) : "not established";
|
|
705
|
+
logLine(
|
|
706
|
+
"warn",
|
|
707
|
+
"🔌 Relay disconnected | code=" + code + " | session uptime=" + uptime + " | calls=" + sessionCalls + " | failures=" + sessionFails
|
|
708
|
+
);
|
|
709
|
+
if (lastError) logLine("warn", " ↳ Last network error: " + lastError);
|
|
710
|
+
if (reason?.length) logLine("warn", " ↳ Close reason: " + sanitizeText(reason.toString(), 100));
|
|
711
|
+
connectedSince = 0;
|
|
712
|
+
resolve({ unauthorized: status === 401 || code === 1008 });
|
|
713
|
+
});
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
async function runDoctor() {
|
|
718
|
+
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
|
+
|
|
724
|
+
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;
|
|
733
|
+
}
|
|
734
|
+
|
|
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;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
const creds = saved();
|
|
751
|
+
console.log("Device Pairing:", creds ? `paired (id=${String(creds.deviceId || "").slice(0, 8)}…)` : "not paired");
|
|
752
|
+
try {
|
|
753
|
+
const st = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) })).status;
|
|
754
|
+
console.log(`Local Port ${opts.port}: occupied (HTTP ${st})`);
|
|
755
|
+
} catch {
|
|
756
|
+
console.log(`Local Port ${opts.port}: free`);
|
|
757
|
+
}
|
|
758
|
+
console.log("Policy:", policy.readonly ? "READONLY" : "FULL", "| DLP:", policy.dlp ? "ON" : "OFF");
|
|
759
|
+
if (!healthy) process.exitCode = 1;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function runReport() {
|
|
763
|
+
const p = resolveProxyForUrl(opts.relay);
|
|
764
|
+
const creds = saved();
|
|
765
|
+
let gatewayLogTail = [];
|
|
766
|
+
try {
|
|
767
|
+
const raw = fs.readFileSync(gatewayLogPath, "utf8");
|
|
768
|
+
gatewayLogTail = raw
|
|
769
|
+
.split(/\r?\n/)
|
|
770
|
+
.slice(-20)
|
|
771
|
+
.filter(Boolean)
|
|
772
|
+
.map((line) => sanitizeText(line, 240));
|
|
773
|
+
} catch {}
|
|
774
|
+
|
|
775
|
+
const report = {
|
|
776
|
+
generatedAt: new Date().toISOString(),
|
|
777
|
+
version: PKG_VERSION,
|
|
778
|
+
runtime: { node: process.version, platform: process.platform, arch: process.arch },
|
|
779
|
+
relay: opts.relay,
|
|
780
|
+
port: opts.port,
|
|
781
|
+
paired: Boolean(creds?.deviceId),
|
|
782
|
+
proxy: {
|
|
783
|
+
mode: p.mode,
|
|
784
|
+
source: p.source,
|
|
785
|
+
description: p.description || "",
|
|
786
|
+
reason: p.reason || ""
|
|
787
|
+
},
|
|
788
|
+
policy: {
|
|
789
|
+
readonly: policy.readonly,
|
|
790
|
+
dlp: policy.dlp,
|
|
791
|
+
allowToolsCount: policy.allowTools.size,
|
|
792
|
+
denyToolsCount: policy.denyTools.size,
|
|
793
|
+
allowDirsCount: policy.allowDirs.length
|
|
794
|
+
},
|
|
795
|
+
recentGatewayLogTail: gatewayLogTail
|
|
796
|
+
};
|
|
797
|
+
console.log(JSON.stringify(report, null, 2));
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function stop() {
|
|
801
|
+
if (stopping) return;
|
|
802
|
+
stopping = true;
|
|
803
|
+
logLine("info", "Disconnecting PCC...");
|
|
804
|
+
try {
|
|
805
|
+
socket?.close(1000, "Manual disconnect");
|
|
806
|
+
} catch {}
|
|
807
|
+
stopGateway();
|
|
808
|
+
setTimeout(() => process.exit(0), 200).unref();
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
process.on("SIGINT", stop);
|
|
812
|
+
process.on("SIGTERM", stop);
|
|
813
|
+
|
|
814
|
+
if (opts.command === "help") {
|
|
815
|
+
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" +
|
|
829
|
+
`Default relay: ${DEFAULT_RELAY}\n` +
|
|
830
|
+
`Approval page: ${opts.relay}/admin/devices\n` +
|
|
831
|
+
"Ctrl+C to disconnect. No automatic startup."
|
|
832
|
+
);
|
|
833
|
+
} else if (opts.command === "status") {
|
|
834
|
+
console.log("Paired:", !!saved());
|
|
835
|
+
console.log("Relay:", opts.relay);
|
|
836
|
+
try {
|
|
837
|
+
console.log("Local HTTP:", (await fetch(localBaseUrl, { signal: AbortSignal.timeout(2000) })).status);
|
|
838
|
+
} catch {
|
|
839
|
+
console.log("Local MCP offline");
|
|
840
|
+
}
|
|
841
|
+
} else if (opts.command === "doctor") {
|
|
842
|
+
await runDoctor();
|
|
843
|
+
} else if (opts.command === "report") {
|
|
844
|
+
runReport();
|
|
845
|
+
} else if (opts.command === "reset") {
|
|
846
|
+
forget();
|
|
847
|
+
console.log("Local credentials cleared. Revoke old credentials in the admin page too.");
|
|
848
|
+
} 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;
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
if (r.unauthorized) {
|
|
876
|
+
forget();
|
|
877
|
+
logLine("error", "Credentials revoked; run again to pair.");
|
|
878
|
+
break;
|
|
879
|
+
}
|
|
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);
|
|
886
|
+
}
|
|
887
|
+
} catch (e) {
|
|
888
|
+
logLine("error", "ERROR: " + sanitizeText(e.message, 250));
|
|
889
|
+
process.exitCode = 1;
|
|
890
|
+
} finally {
|
|
891
|
+
stopGateway();
|
|
892
|
+
}
|
|
893
|
+
} else {
|
|
894
|
+
console.error("Unknown command. Use help");
|
|
895
|
+
process.exitCode = 2;
|
|
896
|
+
}
|