@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/gateway.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import crypto from "node:crypto";
1
2
  import path from "node:path";
2
3
  import fs from "node:fs";
3
4
  import { fileURLToPath } from "node:url";
@@ -7,38 +8,235 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
7
8
  import { Server } from "@modelcontextprotocol/server";
8
9
  import { proxyServer, startHTTPServer } from "mcp-proxy";
9
10
 
10
- const root = path.dirname(fileURLToPath(import.meta.url));
11
- if (process.platform === "win32" && !process.env.PUPPETEER_EXECUTABLE_PATH) {
12
- const edge = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe";
13
- if (fs.existsSync(edge)) process.env.PUPPETEER_EXECUTABLE_PATH = edge;
11
+ const __filename = fileURLToPath(import.meta.url);
12
+
13
+ export function isAllowedLocalHost(hostHeader, port) {
14
+ const host = String(hostHeader || "").trim().toLowerCase();
15
+ if (!host) return false;
16
+ const p = String(port);
17
+ return host === `127.0.0.1:${p}` || host === `localhost:${p}` || host === `[::1]:${p}`;
18
+ }
19
+
20
+ export function constantTimeTokenEqual(actual, expected) {
21
+ const a = Buffer.from(String(actual || ""), "utf8");
22
+ const b = Buffer.from(String(expected || ""), "utf8");
23
+ return a.length === b.length && a.length > 0 && crypto.timingSafeEqual(a, b);
24
+ }
25
+
26
+ /**
27
+ * Local MCP HTTP security guard:
28
+ * - Blocks DNS rebinding via strict Host header validation.
29
+ * - Blocks browser CSRF by rejecting any Origin header.
30
+ * - Enforces ephemeral per-launch Bearer token when MCP_LOCAL_TOKEN is set.
31
+ */
32
+ export function createLocalAuthGuard({ port, localToken = "" }) {
33
+ return async (req) => {
34
+ if (!isAllowedLocalHost(req.headers?.host, port)) {
35
+ throw new Response("Forbidden: invalid Host header", { status: 403 });
36
+ }
37
+ if (req.headers?.origin) {
38
+ throw new Response("Forbidden: browser Origin not allowed on local gateway", { status: 403 });
39
+ }
40
+ if (localToken) {
41
+ const auth = String(req.headers?.authorization || "");
42
+ const prefix = "Bearer ";
43
+ if (!auth.startsWith(prefix) || !constantTimeTokenEqual(auth.slice(prefix.length), localToken)) {
44
+ return { authenticated: false, error: "Unauthorized: invalid local gateway token" };
45
+ }
46
+ }
47
+ return { authenticated: true };
48
+ };
49
+ }
50
+
51
+ export function loadExtraServersConfig(configPath) {
52
+ if (!configPath) return [];
53
+ const resolved = path.resolve(configPath);
54
+ const raw = JSON.parse(fs.readFileSync(resolved, "utf8"));
55
+ const map = raw?.mcpServers || raw?.servers || {};
56
+ const entries = [];
57
+ for (const [rawName, cfg] of Object.entries(map)) {
58
+ const namespace = String(rawName)
59
+ .replace(/[^a-zA-Z0-9_-]/g, "_")
60
+ .slice(0, 32);
61
+ if (!namespace || !cfg || typeof cfg.command !== "string" || !cfg.command.trim()) continue;
62
+ entries.push({
63
+ namespace,
64
+ command: cfg.command.trim(),
65
+ args: Array.isArray(cfg.args) ? cfg.args.map(String) : [],
66
+ env: cfg.env && typeof cfg.env === "object" ? Object.fromEntries(Object.entries(cfg.env).map(([k, v]) => [k, String(v)])) : undefined,
67
+ cwd: typeof cfg.cwd === "string" ? cfg.cwd : undefined
68
+ });
69
+ }
70
+ return entries;
71
+ }
72
+
73
+ export function createAggregatedClient(primary, extras = []) {
74
+ if (!extras.length) return primary;
75
+ const byNamespace = new Map(extras.map((e) => [e.namespace, e.client]));
76
+
77
+ return new Proxy(primary, {
78
+ get(target, prop, receiver) {
79
+ if (prop === "listTools") {
80
+ return async (params, options) => {
81
+ const base = await target.listTools(params, options);
82
+ const merged = [...(base.tools || [])];
83
+ for (const [ns, client] of byNamespace) {
84
+ try {
85
+ const extraRes = await client.listTools(undefined, options);
86
+ for (const tool of extraRes.tools || []) {
87
+ merged.push({
88
+ ...tool,
89
+ name: `${ns}__${tool.name}`,
90
+ description: `[${ns}] ${tool.description || ""}`.trim()
91
+ });
92
+ }
93
+ } catch (e) {
94
+ console.error(`Failed to list tools from extra MCP server "${ns}":`, e?.message || e);
95
+ }
96
+ }
97
+ return { ...base, tools: merged };
98
+ };
99
+ }
100
+ if (prop === "callTool") {
101
+ return async (params, options) => {
102
+ const name = String(params?.name || "");
103
+ const sep = name.indexOf("__");
104
+ if (sep > 0) {
105
+ const ns = name.slice(0, sep);
106
+ const rawTool = name.slice(sep + 2);
107
+ const client = byNamespace.get(ns);
108
+ if (client) {
109
+ return client.callTool({ ...params, name: rawTool }, options);
110
+ }
111
+ }
112
+ return target.callTool(params, options);
113
+ };
114
+ }
115
+ const value = Reflect.get(target, prop, target);
116
+ return typeof value === "function" ? value.bind(target) : value;
117
+ }
118
+ });
14
119
  }
15
- const require = createRequire(import.meta.url);
16
- const pkgFile = require.resolve("@wonderwhy-er/desktop-commander/package.json");
17
- const exe = path.join(path.dirname(pkgFile), "dist", "index.js");
18
- const transport = new StdioClientTransport({ command: process.execPath, args: [exe], stderr: "inherit" });
19
- const upstream = new Client({ name: "private-mcp-gateway", version: "0.1.0" }, { capabilities: {} });
20
- await upstream.connect(transport);
21
- const serverCapabilities = upstream.getServerCapabilities();
22
- const serverInfo = upstream.getServerVersion();
23
- const tools = await upstream.listTools();
24
- const port = Number(process.env.MCP_PORT || 8717);
25
- if (!Number.isInteger(port) || port < 1024 || port > 65535) throw Error("Invalid MCP_PORT");
26
- console.log("MCP upstream ready:", serverInfo?.name, "tools:", tools.tools?.length);
27
- const { close } = await startHTTPServer({
28
- host: "127.0.0.1",
29
- port,
30
- streamEndpoint: "/mcp",
31
- sseEndpoint: null,
32
- cors: false,
33
- maxBodySize: 1048576,
34
- eventStoreMaxEvents: 100,
35
- createServer: async () => {
36
- const downstream = new Server(serverInfo, { capabilities: serverCapabilities });
37
- await proxyServer({ client: upstream, server: downstream, serverCapabilities });
38
- return downstream;
120
+
121
+ async function main() {
122
+ if (process.platform === "win32" && !process.env.PUPPETEER_EXECUTABLE_PATH) {
123
+ const edge = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe";
124
+ if (fs.existsSync(edge)) process.env.PUPPETEER_EXECUTABLE_PATH = edge;
39
125
  }
40
- });
41
- console.log(`Local MCP gateway listening at http://127.0.0.1:${port}/mcp`);
42
- const stop = async () => { await close(); await upstream.close(); process.exit(0); };
43
- process.on("SIGINT", stop);
44
- process.on("SIGTERM", stop);
126
+
127
+ const port = Number(process.env.MCP_PORT || 8717);
128
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw Error("Invalid MCP_PORT");
129
+ const localToken = String(process.env.MCP_LOCAL_TOKEN || "");
130
+
131
+ const require = createRequire(import.meta.url);
132
+ const pkgFile = require.resolve("@wonderwhy-er/desktop-commander/package.json");
133
+ const exe = path.join(path.dirname(pkgFile), "dist", "index.js");
134
+ const transport = new StdioClientTransport({
135
+ command: process.execPath,
136
+ args: [exe, "--no-onboarding"],
137
+ stderr: "inherit"
138
+ });
139
+ const primary = new Client({ name: "private-mcp-gateway", version: "0.4.0" }, { capabilities: {} });
140
+ await primary.connect(transport);
141
+
142
+ const extras = [];
143
+ if (process.env.PCC_MCP_CONFIG) {
144
+ const configs = loadExtraServersConfig(process.env.PCC_MCP_CONFIG);
145
+ for (const cfg of configs) {
146
+ try {
147
+ const extraTransport = new StdioClientTransport({
148
+ command: cfg.command,
149
+ args: cfg.args,
150
+ env: cfg.env ? { ...process.env, ...cfg.env } : undefined,
151
+ cwd: cfg.cwd,
152
+ stderr: "inherit"
153
+ });
154
+ const extraClient = new Client({ name: `private-mcp-gateway-${cfg.namespace}`, version: "0.4.0" }, { capabilities: {} });
155
+ await extraClient.connect(extraTransport);
156
+ extras.push({ namespace: cfg.namespace, client: extraClient });
157
+ console.log("Attached extra MCP server:", cfg.namespace);
158
+ } catch (e) {
159
+ console.error(`Skipping extra MCP server "${cfg.namespace}":`, e?.message || e);
160
+ }
161
+ }
162
+ }
163
+
164
+ const upstream = createAggregatedClient(primary, extras);
165
+ const serverCapabilities = primary.getServerCapabilities();
166
+ const serverInfo = primary.getServerVersion();
167
+ const tools = await upstream.listTools();
168
+
169
+ console.log(
170
+ "MCP upstream ready:",
171
+ serverInfo?.name,
172
+ "tools:",
173
+ tools.tools?.length,
174
+ "extraServers:",
175
+ extras.length,
176
+ "localAuth:",
177
+ localToken ? "bearer+host" : "host-only"
178
+ );
179
+
180
+ const localGuard = createLocalAuthGuard({ port, localToken });
181
+ const { close } = await startHTTPServer({
182
+ host: "127.0.0.1",
183
+ port,
184
+ streamEndpoint: "/mcp",
185
+ sseEndpoint: null,
186
+ cors: false,
187
+ maxBodySize: 1048576,
188
+ eventStoreMaxEvents: 100,
189
+ authenticate: localGuard,
190
+ onUnhandledRequest: async (req, res) => {
191
+ if (req.method === "GET" && req.url === "/healthz") {
192
+ try {
193
+ const verdict = await localGuard(req);
194
+ if (!verdict?.authenticated) {
195
+ res.writeHead(401, { "content-type": "application/json" }).end('{"error":"Unauthorized"}');
196
+ return;
197
+ }
198
+ res
199
+ .writeHead(200, { "content-type": "application/json", "cache-control": "no-store" })
200
+ .end(JSON.stringify({ ok: true, tools: tools.tools?.length || 0, extraServers: extras.length }));
201
+ return;
202
+ } catch (err) {
203
+ const status = err instanceof Response ? err.status : 403;
204
+ res.writeHead(status, { "content-type": "application/json" }).end('{"error":"Forbidden"}');
205
+ return;
206
+ }
207
+ }
208
+ res.writeHead(404).end();
209
+ },
210
+ createServer: async () => {
211
+ const downstream = new Server(serverInfo, { capabilities: serverCapabilities });
212
+ await proxyServer({ client: upstream, server: downstream, serverCapabilities });
213
+ return downstream;
214
+ }
215
+ });
216
+
217
+ console.log(`Local MCP gateway listening at http://127.0.0.1:${port}/mcp`);
218
+
219
+ const stop = async () => {
220
+ try {
221
+ await close();
222
+ } catch {}
223
+ for (const extra of extras) {
224
+ try {
225
+ await extra.client.close();
226
+ } catch {}
227
+ }
228
+ try {
229
+ await primary.close();
230
+ } catch {}
231
+ process.exit(0);
232
+ };
233
+ process.on("SIGINT", stop);
234
+ process.on("SIGTERM", stop);
235
+ }
236
+
237
+ if (process.argv[1] && path.resolve(process.argv[1]) === __filename) {
238
+ main().catch((err) => {
239
+ console.error("Local MCP gateway fatal error:", err?.message || err);
240
+ process.exit(1);
241
+ });
242
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juexibobi/private-desktop-mcp",
3
- "version": "0.3.6",
3
+ "version": "0.4.0",
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",
@@ -15,6 +15,7 @@
15
15
  "bin/activity.mjs",
16
16
  "bin/proxy.mjs",
17
17
  "bin/logging.mjs",
18
+ "bin/policy.mjs",
18
19
  "gateway.mjs",
19
20
  "README.md",
20
21
  "LICENSE"
@@ -25,16 +26,16 @@
25
26
  },
26
27
  "homepage": "https://github.com/KFCheems/private-desktop-mcp",
27
28
  "scripts": {
28
- "test": "node --check bin/cli.mjs && node --check gateway.mjs && node --test tests/*.test.mjs"
29
+ "test": "node --check bin/cli.mjs && node --check bin/policy.mjs && node --check bin/proxy.mjs && node --check gateway.mjs && node --check worker/index.mjs && node --check worker/auth.mjs && node --test tests/*.test.mjs"
29
30
  },
30
31
  "dependencies": {
31
- "@wonderwhy-er/desktop-commander": "0.2.52",
32
- "mcp-proxy": "6.7.19",
33
- "ws": "8.18.3",
34
- "undici": "7.30.0",
32
+ "@modelcontextprotocol/client": "2.3.1",
33
+ "@modelcontextprotocol/server": "2.3.1",
34
+ "@wonderwhy-er/desktop-commander": "0.3.4",
35
35
  "https-proxy-agent": "9.1.0",
36
+ "mcp-proxy": "6.7.19",
36
37
  "proxy-from-env": "2.1.0",
37
- "@modelcontextprotocol/client": "2.3.1",
38
- "@modelcontextprotocol/server": "2.3.1"
38
+ "undici": "7.30.0",
39
+ "ws": "8.18.3"
39
40
  }
40
41
  }