@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.
@@ -0,0 +1,151 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export const SUPPORTED_CLIENTS = [
6
+ "claude-code",
7
+ "claude-desktop",
8
+ "cursor",
9
+ "vscode",
10
+ "codex",
11
+ "gemini",
12
+ "windsurf"
13
+ ];
14
+
15
+ export function resolveClientConfigPath(
16
+ client,
17
+ { platform = process.platform, homedir = os.homedir(), env = process.env, cwd = process.cwd() } = {}
18
+ ) {
19
+ const c = String(client || "").toLowerCase().trim();
20
+ const appData = env.APPDATA || path.join(homedir, "AppData", "Roaming");
21
+
22
+ switch (c) {
23
+ case "claude-code":
24
+ return path.join(cwd, ".mcp.json");
25
+ case "claude-desktop":
26
+ if (platform === "win32") return path.join(appData, "Claude", "claude_desktop_config.json");
27
+ if (platform === "darwin") {
28
+ return path.join(homedir, "Library", "Application Support", "Claude", "claude_desktop_config.json");
29
+ }
30
+ return path.join(env.XDG_CONFIG_HOME || path.join(homedir, ".config"), "Claude", "claude_desktop_config.json");
31
+ case "cursor":
32
+ return path.join(homedir, ".cursor", "mcp.json");
33
+ case "vscode":
34
+ return path.join(cwd, ".vscode", "mcp.json");
35
+ case "codex":
36
+ return path.join(homedir, ".codex", "config.toml");
37
+ case "gemini":
38
+ return path.join(homedir, ".gemini", "settings.json");
39
+ case "windsurf":
40
+ return path.join(homedir, ".codeium", "windsurf", "mcp_config.json");
41
+ default:
42
+ throw new Error(`Unsupported client "${client}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}`);
43
+ }
44
+ }
45
+
46
+ export function normalizeMcpEndpointUrl(relayUrl) {
47
+ const trimmed = String(relayUrl || "").trim().replace(/\/+$/, "");
48
+ if (!trimmed) throw new Error("Empty relay URL");
49
+ return trimmed.endsWith("/mcp") ? trimmed : `${trimmed}/mcp`;
50
+ }
51
+
52
+ function mergeJsonClientConfig(client, existingText, mcpUrl, serverName = "private-desktop") {
53
+ let root = {};
54
+ if (String(existingText || "").trim()) {
55
+ const parsed = JSON.parse(existingText);
56
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
57
+ root = { ...parsed };
58
+ }
59
+ }
60
+
61
+ if (client === "vscode") {
62
+ const servers = root.servers && typeof root.servers === "object" ? { ...root.servers } : {};
63
+ servers[serverName] = { type: "http", url: mcpUrl };
64
+ root.servers = servers;
65
+ } else if (client === "gemini") {
66
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
67
+ mcpServers[serverName] = { httpUrl: mcpUrl, oauth: { enabled: true } };
68
+ root.mcpServers = mcpServers;
69
+ } else if (client === "cursor" || client === "windsurf") {
70
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
71
+ mcpServers[serverName] = { url: mcpUrl };
72
+ root.mcpServers = mcpServers;
73
+ } else {
74
+ // claude-code, claude-desktop, standard mcpServers
75
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
76
+ mcpServers[serverName] = { type: "http", url: mcpUrl };
77
+ root.mcpServers = mcpServers;
78
+ }
79
+
80
+ return JSON.stringify(root, null, 2) + "\n";
81
+ }
82
+
83
+ function mergeCodexTomlConfig(existingText, mcpUrl, serverName = "private_desktop") {
84
+ const sectionHeader = `[mcp_servers.${serverName}]`;
85
+ const block = `${sectionHeader}\nurl = "${mcpUrl}"\n`;
86
+ const raw = String(existingText || "");
87
+ if (!raw.trim()) return block;
88
+
89
+ const escapedHeader = sectionHeader.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
90
+ const sectionRegex = new RegExp(`(^|\\r?\\n)${escapedHeader}\\r?\\n[\\s\\S]*?(?=(\\r?\\n\\[[^\\]]+\\])|$)`);
91
+ if (sectionRegex.test(raw)) {
92
+ return raw.replace(sectionRegex, `$1${block.trimEnd()}`).replace(/\s*$/, "\n");
93
+ }
94
+ return raw.replace(/\s*$/, "\n\n") + block;
95
+ }
96
+
97
+ export function configureMcpClient({
98
+ client,
99
+ relayUrl,
100
+ serverName,
101
+ configPath,
102
+ dryRun = false,
103
+ platform = process.platform,
104
+ homedir = os.homedir(),
105
+ env = process.env,
106
+ cwd = process.cwd()
107
+ } = {}) {
108
+ const normalizedClient = String(client || "").toLowerCase().trim();
109
+ if (!SUPPORTED_CLIENTS.includes(normalizedClient)) {
110
+ throw new Error(`Unsupported client "${client}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}`);
111
+ }
112
+
113
+ const mcpUrl = normalizeMcpEndpointUrl(relayUrl);
114
+ const targetPath = configPath
115
+ ? path.resolve(configPath)
116
+ : resolveClientConfigPath(normalizedClient, { platform, homedir, env, cwd });
117
+
118
+ let existingText = "";
119
+ let existed = false;
120
+ try {
121
+ existingText = fs.readFileSync(targetPath, "utf8");
122
+ existed = true;
123
+ } catch {
124
+ existingText = "";
125
+ existed = false;
126
+ }
127
+
128
+ const nextContent =
129
+ normalizedClient === "codex"
130
+ ? mergeCodexTomlConfig(existingText, mcpUrl, serverName ? serverName.replace(/-/g, "_") : "private_desktop")
131
+ : mergeJsonClientConfig(normalizedClient, existingText, mcpUrl, serverName || "private-desktop");
132
+
133
+ const changed = nextContent !== existingText;
134
+ const action = !existed ? "create" : changed ? "update" : "unchanged";
135
+
136
+ if (!dryRun && changed) {
137
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
138
+ fs.writeFileSync(targetPath, nextContent, "utf8");
139
+ }
140
+
141
+ return {
142
+ ok: true,
143
+ client: normalizedClient,
144
+ path: targetPath,
145
+ mcpUrl,
146
+ action,
147
+ changed,
148
+ dryRun: Boolean(dryRun),
149
+ preview: nextContent
150
+ };
151
+ }
package/bin/policy.mjs ADDED
@@ -0,0 +1,336 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export const READONLY_TOOLS = new Set([
5
+ "read_file",
6
+ "read_multiple_files",
7
+ "list_directory",
8
+ "get_file_info",
9
+ "start_search",
10
+ "get_more_search_results",
11
+ "list_searches",
12
+ "stop_search",
13
+ "list_processes",
14
+ "list_sessions",
15
+ "read_process_output",
16
+ "get_config",
17
+ "get_usage_stats",
18
+ "get_recent_tool_calls",
19
+ "get_prompts"
20
+ ]);
21
+
22
+ const PATH_ARG_KEYS = [
23
+ "path",
24
+ "paths",
25
+ "source",
26
+ "destination",
27
+ "cwd",
28
+ "workingDirectory",
29
+ "working_directory",
30
+ "filePath",
31
+ "file_path",
32
+ "file_paths",
33
+ "directory",
34
+ "dir"
35
+ ];
36
+
37
+ const HIGH_CONFIDENCE_SECRET_PATTERNS = [
38
+ /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
39
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
40
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b/g,
41
+ /\bgithub_pat_[A-Za-z0-9_]{22,}\b/g,
42
+ /\bsk-(?:proj-|ant-api\d+-)?[A-Za-z0-9_-]{24,}\b/g,
43
+ /\bxox[baprs]-[A-Za-z0-9-]{16,}\b/g,
44
+ /\bAIza[0-9A-Za-z_-]{35}\b/g
45
+ ];
46
+
47
+ const DLP_MARKER = "[REDACTED_BY_PCC_DLP]";
48
+
49
+ function normalizeForComparison(p, platform = process.platform) {
50
+ const resolved = path.resolve(String(p));
51
+ return platform === "win32" ? resolved.toLowerCase() : resolved;
52
+ }
53
+
54
+ function resolveWithSymlinks(targetPath) {
55
+ const resolved = path.resolve(String(targetPath));
56
+ try {
57
+ return fs.realpathSync(resolved);
58
+ } catch {
59
+ // Walk up until an existing parent is found to catch symlinked parent directories
60
+ let current = resolved;
61
+ const tail = [];
62
+ while (true) {
63
+ const parent = path.dirname(current);
64
+ if (parent === current) return resolved;
65
+ tail.unshift(path.basename(current));
66
+ current = parent;
67
+ try {
68
+ const realParent = fs.realpathSync(current);
69
+ return path.join(realParent, ...tail);
70
+ } catch {
71
+ continue;
72
+ }
73
+ }
74
+ }
75
+ }
76
+
77
+ export function isPathInside(candidatePath, rootDir, platform = process.platform) {
78
+ const realCandidate = normalizeForComparison(resolveWithSymlinks(candidatePath), platform);
79
+ const realRoot = normalizeForComparison(resolveWithSymlinks(rootDir), platform);
80
+ const rel = path.relative(realRoot, realCandidate);
81
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
82
+ }
83
+
84
+ function extractPathArgs(args) {
85
+ const paths = [];
86
+ if (!args || typeof args !== "object") return paths;
87
+ for (const key of PATH_ARG_KEYS) {
88
+ const val = args[key];
89
+ if (typeof val === "string" && val.trim()) {
90
+ paths.push({ key, value: val.trim() });
91
+ } else if (Array.isArray(val)) {
92
+ for (const item of val) {
93
+ if (typeof item === "string" && item.trim()) {
94
+ paths.push({ key, value: item.trim() });
95
+ }
96
+ }
97
+ }
98
+ }
99
+ return paths;
100
+ }
101
+
102
+ export function createPolicy({
103
+ readonly = false,
104
+ allowTools = [],
105
+ denyTools = [],
106
+ allowDirs = [],
107
+ protectedDirs = [],
108
+ dlp = true
109
+ } = {}) {
110
+ return {
111
+ readonly: Boolean(readonly),
112
+ allowTools: new Set(allowTools.map((s) => String(s).trim()).filter(Boolean)),
113
+ denyTools: new Set(denyTools.map((s) => String(s).trim()).filter(Boolean)),
114
+ allowDirs: allowDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
115
+ protectedDirs: protectedDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
116
+ learnedReadOnlyTools: new Set(),
117
+ toolAnnotations: new Map(),
118
+ dlp: Boolean(dlp)
119
+ };
120
+ }
121
+
122
+ export function isToolAllowedByName(toolName, policy, annotations = null) {
123
+ if (!toolName) return false;
124
+ if (policy.denyTools.has(toolName)) return false;
125
+ if (policy.allowTools.size > 0 && !policy.allowTools.has(toolName)) return false;
126
+ if (policy.readonly) {
127
+ if (READONLY_TOOLS.has(toolName) || policy.learnedReadOnlyTools?.has(toolName)) return true;
128
+ if (annotations && annotations.readOnlyHint === true && annotations.destructiveHint !== true) return true;
129
+ return false;
130
+ }
131
+ return true;
132
+ }
133
+
134
+ export function evaluateToolCall(rpc, policy, { platform = process.platform } = {}) {
135
+ if (!rpc || rpc.method !== "tools/call") return { allowed: true };
136
+ const toolName = typeof rpc.params?.name === "string" ? rpc.params.name : "";
137
+ const args = rpc.params?.arguments && typeof rpc.params.arguments === "object" ? rpc.params.arguments : {};
138
+
139
+ // Only trust annotations learned from the upstream tools/list response. A caller can
140
+ // freely put whatever it likes in params._meta, so those hints are not authoritative.
141
+ const annotations = policy.toolAnnotations?.get(toolName) || null;
142
+ if (!isToolAllowedByName(toolName, policy, annotations)) {
143
+ const modeReason = policy.readonly ? "connector is running in --readonly mode" : "tool is disallowed by local policy";
144
+ return { allowed: false, reason: `Blocked locally: "${toolName}" is not permitted (${modeReason}).` };
145
+ }
146
+
147
+ const candidatePaths = extractPathArgs(args);
148
+
149
+ // Always block access to PCC's own credential/config directory
150
+ for (const dir of policy.protectedDirs) {
151
+ for (const entry of candidatePaths) {
152
+ if (isPathInside(entry.value, dir, platform)) {
153
+ return {
154
+ allowed: false,
155
+ reason: `Blocked locally: access to protected connector directory via "${entry.key}" is forbidden.`
156
+ };
157
+ }
158
+ }
159
+ if (typeof args.command === "string") {
160
+ const cmdLower = args.command.toLowerCase();
161
+ if (cmdLower.includes("privatedesktopmcp") && cmdLower.includes("device.json")) {
162
+ return {
163
+ allowed: false,
164
+ reason: "Blocked locally: reading or modifying connector device credentials via shell is forbidden."
165
+ };
166
+ }
167
+ }
168
+ }
169
+
170
+ // Optional allow-dir jail
171
+ if (policy.allowDirs.length > 0) {
172
+ for (const entry of candidatePaths) {
173
+ const permitted = policy.allowDirs.some((root) => isPathInside(entry.value, root, platform));
174
+ if (!permitted) {
175
+ return {
176
+ allowed: false,
177
+ reason: `Blocked locally: "${entry.key}" is outside allowed directories (--allow-dir).`
178
+ };
179
+ }
180
+ }
181
+ }
182
+
183
+ return { allowed: true };
184
+ }
185
+
186
+ function transformRpcPayload(bodyText, contentType, transformObj) {
187
+ if (String(contentType || "").toLowerCase().includes("text/event-stream")) {
188
+ let changed = false;
189
+ const lines = String(bodyText || "").split(/\r?\n/);
190
+ const out = lines.map((line) => {
191
+ if (!line.startsWith("data:")) return line;
192
+ const raw = line.slice(5).trim();
193
+ if (!raw || raw === "[DONE]") return line;
194
+ try {
195
+ const parsed = JSON.parse(raw);
196
+ const next = transformObj(parsed);
197
+ if (next) {
198
+ changed = true;
199
+ return "data: " + JSON.stringify(next);
200
+ }
201
+ } catch {
202
+ return line;
203
+ }
204
+ return line;
205
+ });
206
+ return changed ? out.join("\n") : bodyText;
207
+ }
208
+ try {
209
+ const parsed = JSON.parse(String(bodyText || ""));
210
+ const next = transformObj(parsed);
211
+ return next ? JSON.stringify(next) : bodyText;
212
+ } catch {
213
+ return bodyText;
214
+ }
215
+ }
216
+
217
+ export function filterToolsListBody(bodyText, contentType, policy) {
218
+ if (!policy.readonly && policy.allowTools.size === 0 && policy.denyTools.size === 0) {
219
+ return bodyText;
220
+ }
221
+ return transformRpcPayload(bodyText, contentType, (obj) => {
222
+ if (!Array.isArray(obj?.result?.tools)) return null;
223
+ const filtered = obj.result.tools.filter((tool) => {
224
+ if (tool?.name && tool?.annotations && typeof tool.annotations === "object") {
225
+ // Remember discovered annotations so a later tools/call can be authorized against
226
+ // the same readOnlyHint/destructiveHint that tools/list advertised, even if the
227
+ // client does not echo annotations back on the call itself.
228
+ policy.toolAnnotations?.set(tool.name, tool.annotations);
229
+ if (tool.annotations.readOnlyHint === true && tool.annotations.destructiveHint !== true) {
230
+ policy.learnedReadOnlyTools?.add(tool.name);
231
+ }
232
+ }
233
+ return isToolAllowedByName(tool?.name, policy, tool?.annotations || null);
234
+ });
235
+ return {
236
+ ...obj,
237
+ result: {
238
+ ...obj.result,
239
+ tools: filtered
240
+ }
241
+ };
242
+ });
243
+ }
244
+
245
+ export function redactSecretsInText(text, extraSecrets = []) {
246
+ let out = String(text ?? "");
247
+ let count = 0;
248
+
249
+ for (const secret of extraSecrets) {
250
+ const s = String(secret || "");
251
+ if (s.length >= 16 && out.includes(s)) {
252
+ const parts = out.split(s);
253
+ count += parts.length - 1;
254
+ out = parts.join(DLP_MARKER);
255
+ }
256
+ }
257
+
258
+ for (const pattern of HIGH_CONFIDENCE_SECRET_PATTERNS) {
259
+ out = out.replace(pattern, () => {
260
+ count++;
261
+ return DLP_MARKER;
262
+ });
263
+ }
264
+
265
+ return { text: out, redactedCount: count };
266
+ }
267
+
268
+ // Recursively redact string values inside arbitrary JSON (handles structuredContent,
269
+ // nested objects/arrays and JSON-encoded strings). Returns a clone + count of hits.
270
+ function redactValueDeep(value, extraSecrets) {
271
+ let redactedCount = 0;
272
+ const walk = (v) => {
273
+ if (typeof v === "string") {
274
+ const res = redactSecretsInText(v, extraSecrets);
275
+ redactedCount += res.redactedCount;
276
+ return res.text;
277
+ }
278
+ if (Array.isArray(v)) return v.map(walk);
279
+ if (v && typeof v === "object") {
280
+ const out = {};
281
+ for (const [k, val] of Object.entries(v)) out[k] = walk(val);
282
+ return out;
283
+ }
284
+ return v;
285
+ };
286
+ return { value: walk(value), redactedCount };
287
+ }
288
+
289
+ export function redactOutboundResponse(bodyText, contentType = "", { enabled = true, extraSecrets = [] } = {}) {
290
+ if (!enabled || !bodyText) return { body: bodyText, redactedCount: 0 };
291
+ let total = 0;
292
+ const body = transformRpcPayload(bodyText, contentType, (obj) => {
293
+ const hasContent = Array.isArray(obj?.result?.content);
294
+ const hasStructured = obj?.result?.structuredContent !== undefined && obj.result.structuredContent !== null;
295
+ if (!hasContent && !hasStructured) return null;
296
+ let modified = false;
297
+ let content = obj.result.content;
298
+ if (hasContent) {
299
+ content = obj.result.content.map((block) => {
300
+ if (block?.type === "text" && typeof block.text === "string") {
301
+ const res = redactSecretsInText(block.text, extraSecrets);
302
+ if (res.redactedCount > 0) {
303
+ total += res.redactedCount;
304
+ modified = true;
305
+ return { ...block, text: res.text };
306
+ }
307
+ }
308
+ return block;
309
+ });
310
+ }
311
+ let result = hasContent ? { ...obj.result, content } : obj.result;
312
+ // Redact secrets embedded in machine-readable structured output too; otherwise a
313
+ // secret returned via result.structuredContent would still reach the relay/LLM.
314
+ if (hasStructured) {
315
+ const deep = redactValueDeep(obj.result.structuredContent, extraSecrets);
316
+ if (deep.redactedCount > 0) {
317
+ total += deep.redactedCount;
318
+ modified = true;
319
+ result = { ...result, structuredContent: deep.value };
320
+ }
321
+ }
322
+ return modified ? { ...obj, result } : null;
323
+ });
324
+ return { body, redactedCount: total };
325
+ }
326
+
327
+ export function buildPolicyBlockedResponse(rpcId, reason) {
328
+ return JSON.stringify({
329
+ jsonrpc: "2.0",
330
+ id: rpcId ?? null,
331
+ result: {
332
+ isError: true,
333
+ content: [{ type: "text", text: reason }]
334
+ }
335
+ });
336
+ }