@juexibobi/private-desktop-mcp 0.3.5 → 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/bin/policy.mjs ADDED
@@ -0,0 +1,286 @@
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
+ "filePath",
30
+ "directory",
31
+ "dir"
32
+ ];
33
+
34
+ const HIGH_CONFIDENCE_SECRET_PATTERNS = [
35
+ /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
36
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
37
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b/g,
38
+ /\bgithub_pat_[A-Za-z0-9_]{22,}\b/g,
39
+ /\bsk-(?:proj-|ant-api\d+-)?[A-Za-z0-9_-]{24,}\b/g,
40
+ /\bxox[baprs]-[A-Za-z0-9-]{16,}\b/g,
41
+ /\bAIza[0-9A-Za-z_-]{35}\b/g
42
+ ];
43
+
44
+ const DLP_MARKER = "[REDACTED_BY_PCC_DLP]";
45
+
46
+ function normalizeForComparison(p, platform = process.platform) {
47
+ const resolved = path.resolve(String(p));
48
+ return platform === "win32" ? resolved.toLowerCase() : resolved;
49
+ }
50
+
51
+ function resolveWithSymlinks(targetPath) {
52
+ const resolved = path.resolve(String(targetPath));
53
+ try {
54
+ return fs.realpathSync(resolved);
55
+ } catch {
56
+ // Walk up until an existing parent is found to catch symlinked parent directories
57
+ let current = resolved;
58
+ const tail = [];
59
+ while (true) {
60
+ const parent = path.dirname(current);
61
+ if (parent === current) return resolved;
62
+ tail.unshift(path.basename(current));
63
+ current = parent;
64
+ try {
65
+ const realParent = fs.realpathSync(current);
66
+ return path.join(realParent, ...tail);
67
+ } catch {
68
+ continue;
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ export function isPathInside(candidatePath, rootDir, platform = process.platform) {
75
+ const realCandidate = normalizeForComparison(resolveWithSymlinks(candidatePath), platform);
76
+ const realRoot = normalizeForComparison(resolveWithSymlinks(rootDir), platform);
77
+ const rel = path.relative(realRoot, realCandidate);
78
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
79
+ }
80
+
81
+ function extractPathArgs(args) {
82
+ const paths = [];
83
+ if (!args || typeof args !== "object") return paths;
84
+ for (const key of PATH_ARG_KEYS) {
85
+ const val = args[key];
86
+ if (typeof val === "string" && val.trim()) {
87
+ paths.push({ key, value: val.trim() });
88
+ } else if (Array.isArray(val)) {
89
+ for (const item of val) {
90
+ if (typeof item === "string" && item.trim()) {
91
+ paths.push({ key, value: item.trim() });
92
+ }
93
+ }
94
+ }
95
+ }
96
+ return paths;
97
+ }
98
+
99
+ export function createPolicy({
100
+ readonly = false,
101
+ allowTools = [],
102
+ denyTools = [],
103
+ allowDirs = [],
104
+ protectedDirs = [],
105
+ dlp = true
106
+ } = {}) {
107
+ return {
108
+ readonly: Boolean(readonly),
109
+ allowTools: new Set(allowTools.map((s) => String(s).trim()).filter(Boolean)),
110
+ denyTools: new Set(denyTools.map((s) => String(s).trim()).filter(Boolean)),
111
+ allowDirs: allowDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
112
+ protectedDirs: protectedDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
113
+ learnedReadOnlyTools: new Set(),
114
+ dlp: Boolean(dlp)
115
+ };
116
+ }
117
+
118
+ export function isToolAllowedByName(toolName, policy, annotations = null) {
119
+ if (!toolName) return false;
120
+ if (policy.denyTools.has(toolName)) return false;
121
+ if (policy.allowTools.size > 0 && !policy.allowTools.has(toolName)) return false;
122
+ if (policy.readonly) {
123
+ if (READONLY_TOOLS.has(toolName) || policy.learnedReadOnlyTools?.has(toolName)) return true;
124
+ if (annotations && annotations.readOnlyHint === true && annotations.destructiveHint !== true) return true;
125
+ return false;
126
+ }
127
+ return true;
128
+ }
129
+
130
+ export function evaluateToolCall(rpc, policy, { platform = process.platform } = {}) {
131
+ if (!rpc || rpc.method !== "tools/call") return { allowed: true };
132
+ const toolName = typeof rpc.params?.name === "string" ? rpc.params.name : "";
133
+ const args = rpc.params?.arguments && typeof rpc.params.arguments === "object" ? rpc.params.arguments : {};
134
+
135
+ if (!isToolAllowedByName(toolName, policy)) {
136
+ const modeReason = policy.readonly ? "connector is running in --readonly mode" : "tool is disallowed by local policy";
137
+ return { allowed: false, reason: `Blocked locally: "${toolName}" is not permitted (${modeReason}).` };
138
+ }
139
+
140
+ const candidatePaths = extractPathArgs(args);
141
+
142
+ // Always block access to PCC's own credential/config directory
143
+ for (const dir of policy.protectedDirs) {
144
+ for (const entry of candidatePaths) {
145
+ if (isPathInside(entry.value, dir, platform)) {
146
+ return {
147
+ allowed: false,
148
+ reason: `Blocked locally: access to protected connector directory via "${entry.key}" is forbidden.`
149
+ };
150
+ }
151
+ }
152
+ if (typeof args.command === "string") {
153
+ const cmdLower = args.command.toLowerCase();
154
+ if (cmdLower.includes("privatedesktopmcp") && cmdLower.includes("device.json")) {
155
+ return {
156
+ allowed: false,
157
+ reason: "Blocked locally: reading or modifying connector device credentials via shell is forbidden."
158
+ };
159
+ }
160
+ }
161
+ }
162
+
163
+ // Optional allow-dir jail
164
+ if (policy.allowDirs.length > 0) {
165
+ for (const entry of candidatePaths) {
166
+ const permitted = policy.allowDirs.some((root) => isPathInside(entry.value, root, platform));
167
+ if (!permitted) {
168
+ return {
169
+ allowed: false,
170
+ reason: `Blocked locally: "${entry.key}" is outside allowed directories (--allow-dir).`
171
+ };
172
+ }
173
+ }
174
+ }
175
+
176
+ return { allowed: true };
177
+ }
178
+
179
+ function transformRpcPayload(bodyText, contentType, transformObj) {
180
+ if (String(contentType || "").toLowerCase().includes("text/event-stream")) {
181
+ let changed = false;
182
+ const lines = String(bodyText || "").split(/\r?\n/);
183
+ const out = lines.map((line) => {
184
+ if (!line.startsWith("data:")) return line;
185
+ const raw = line.slice(5).trim();
186
+ if (!raw || raw === "[DONE]") return line;
187
+ try {
188
+ const parsed = JSON.parse(raw);
189
+ const next = transformObj(parsed);
190
+ if (next) {
191
+ changed = true;
192
+ return "data: " + JSON.stringify(next);
193
+ }
194
+ } catch {
195
+ return line;
196
+ }
197
+ return line;
198
+ });
199
+ return changed ? out.join("\n") : bodyText;
200
+ }
201
+ try {
202
+ const parsed = JSON.parse(String(bodyText || ""));
203
+ const next = transformObj(parsed);
204
+ return next ? JSON.stringify(next) : bodyText;
205
+ } catch {
206
+ return bodyText;
207
+ }
208
+ }
209
+
210
+ export function filterToolsListBody(bodyText, contentType, policy) {
211
+ if (!policy.readonly && policy.allowTools.size === 0 && policy.denyTools.size === 0) {
212
+ return bodyText;
213
+ }
214
+ return transformRpcPayload(bodyText, contentType, (obj) => {
215
+ if (!Array.isArray(obj?.result?.tools)) return null;
216
+ const filtered = obj.result.tools.filter((tool) => {
217
+ if (tool?.name && tool?.annotations?.readOnlyHint === true && tool?.annotations?.destructiveHint !== true) {
218
+ policy.learnedReadOnlyTools?.add(tool.name);
219
+ }
220
+ return isToolAllowedByName(tool?.name, policy, tool?.annotations || null);
221
+ });
222
+ return {
223
+ ...obj,
224
+ result: {
225
+ ...obj.result,
226
+ tools: filtered
227
+ }
228
+ };
229
+ });
230
+ }
231
+
232
+ export function redactSecretsInText(text, extraSecrets = []) {
233
+ let out = String(text ?? "");
234
+ let count = 0;
235
+
236
+ for (const secret of extraSecrets) {
237
+ const s = String(secret || "");
238
+ if (s.length >= 16 && out.includes(s)) {
239
+ const parts = out.split(s);
240
+ count += parts.length - 1;
241
+ out = parts.join(DLP_MARKER);
242
+ }
243
+ }
244
+
245
+ for (const pattern of HIGH_CONFIDENCE_SECRET_PATTERNS) {
246
+ out = out.replace(pattern, () => {
247
+ count++;
248
+ return DLP_MARKER;
249
+ });
250
+ }
251
+
252
+ return { text: out, redactedCount: count };
253
+ }
254
+
255
+ export function redactOutboundResponse(bodyText, contentType = "", { enabled = true, extraSecrets = [] } = {}) {
256
+ if (!enabled || !bodyText) return { body: bodyText, redactedCount: 0 };
257
+ let total = 0;
258
+ const body = transformRpcPayload(bodyText, contentType, (obj) => {
259
+ if (!Array.isArray(obj?.result?.content)) return null;
260
+ let modified = false;
261
+ const content = obj.result.content.map((block) => {
262
+ if (block?.type === "text" && typeof block.text === "string") {
263
+ const res = redactSecretsInText(block.text, extraSecrets);
264
+ if (res.redactedCount > 0) {
265
+ total += res.redactedCount;
266
+ modified = true;
267
+ return { ...block, text: res.text };
268
+ }
269
+ }
270
+ return block;
271
+ });
272
+ return modified ? { ...obj, result: { ...obj.result, content } } : null;
273
+ });
274
+ return { body, redactedCount: total };
275
+ }
276
+
277
+ export function buildPolicyBlockedResponse(rpcId, reason) {
278
+ return JSON.stringify({
279
+ jsonrpc: "2.0",
280
+ id: rpcId ?? null,
281
+ result: {
282
+ isError: true,
283
+ content: [{ type: "text", text: reason }]
284
+ }
285
+ });
286
+ }
package/bin/proxy.mjs CHANGED
@@ -1,53 +1,181 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { getProxyForUrl } from "proxy-from-env";
3
3
 
4
- const proxyEnvironmentKeys=[
5
- "https_proxy","http_proxy","all_proxy",
6
- "npm_config_https_proxy","npm_config_http_proxy","npm_config_proxy"
4
+ const proxyEnvironmentKeys = [
5
+ "https_proxy",
6
+ "http_proxy",
7
+ "all_proxy",
8
+ "npm_config_https_proxy",
9
+ "npm_config_http_proxy",
10
+ "npm_config_proxy"
7
11
  ];
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);
12
+
13
+ export function hasEnvironmentProxy(env = process.env) {
14
+ const names = new Set(Object.keys(env).filter((k) => proxyEnvironmentKeys.includes(k.toLowerCase())));
15
+ return [...names].some((k) => String(env[k] ?? "").trim().length > 0);
16
+ }
17
+
18
+ export function normalizeProxy(value, source) {
19
+ const raw = String(value || "").trim();
20
+ if (!raw) return { mode: "direct", source };
21
+ const uri = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : "http://" + raw;
22
+ let parsed;
23
+ try {
24
+ parsed = new URL(uri);
25
+ } catch {
26
+ return { mode: "unsupported", source, reason: "Invalid proxy address" };
27
+ }
28
+ if (!["http:", "https:"].includes(parsed.protocol)) {
29
+ return {
30
+ mode: "unsupported",
31
+ source,
32
+ reason: "Proxy protocol " + parsed.protocol + " is not HTTP CONNECT; use an HTTP/Mixed proxy port"
33
+ };
34
+ }
35
+ if (!parsed.hostname) return { mode: "unsupported", source, reason: "Missing proxy hostname" };
36
+ return {
37
+ mode: "proxy",
38
+ source,
39
+ url: parsed.href,
40
+ description:
41
+ parsed.protocol.slice(0, -1).toUpperCase() +
42
+ " CONNECT via " +
43
+ parsed.hostname +
44
+ ":" +
45
+ (parsed.port || (["https:"].includes(parsed.protocol) ? "443" : "80"))
46
+ };
47
+ }
48
+
49
+ export function queryWindowsProxy(url, { spawn = spawnSync } = {}) {
50
+ // Windows WinINET system proxy, including static proxy, exclusions, PAC and WPAD.
51
+ // Use the Windows user's configuration instead of guessing a Clash/v2rayN port.
52
+ const target = String(url).replace(/'/g, "''");
53
+ const script =
54
+ "$ErrorActionPreference='Stop';" +
55
+ "$u=[Uri]'" +
56
+ target +
57
+ "';" +
58
+ "$p=[System.Net.WebRequest]::GetSystemWebProxy();" +
59
+ "if($p.IsBypassed($u)){[Console]::Out.Write('DIRECT')}" +
60
+ "else{$v=$p.GetProxy($u);if($v.AbsoluteUri -eq $u.AbsoluteUri){[Console]::Out.Write('DIRECT')}else{[Console]::Out.Write($v.AbsoluteUri)}}";
61
+ const result = spawn("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
62
+ encoding: "utf8",
63
+ timeout: 6000,
64
+ windowsHide: true,
65
+ maxBuffer: 4096
66
+ });
67
+ if (result.error || result.status !== 0) {
68
+ return {
69
+ mode: "unavailable",
70
+ source: "windows",
71
+ reason: result.error?.code === "ETIMEDOUT" ? "Windows proxy lookup timed out" : "Windows proxy lookup failed"
72
+ };
73
+ }
74
+ const output = String(result.stdout || "").trim();
75
+ if (output === "DIRECT") return { mode: "direct", source: "windows" };
76
+ if (!output) return { mode: "unavailable", source: "windows", reason: "Windows proxy lookup returned no result" };
77
+ return normalizeProxy(output, "windows");
78
+ }
79
+
80
+ function hostMatchesException(hostname, pattern) {
81
+ const host = String(hostname || "").toLowerCase();
82
+ const pat = String(pattern || "").trim().toLowerCase();
83
+ if (!host || !pat) return false;
84
+ if (pat === "*") return true;
85
+ if (pat.startsWith("*.")) {
86
+ const suffix = pat.slice(1); // ".local"
87
+ return host.endsWith(suffix) && host.length > suffix.length;
88
+ }
89
+ if (pat.startsWith(".")) {
90
+ return host === pat.slice(1) || host.endsWith(pat);
91
+ }
92
+ return host === pat;
11
93
  }
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"))};
94
+
95
+ export function parseMacOsScutilProxy(output, url) {
96
+ const text = String(output || "");
97
+ if (!text.trim()) return { mode: "direct", source: "macos" };
98
+
99
+ const fields = new Map();
100
+ const exceptions = [];
101
+ let inExceptions = false;
102
+
103
+ for (const rawLine of text.split(/\r?\n/)) {
104
+ const line = rawLine.trim();
105
+ if (/^ExceptionsList\s*:\s*<array>/.test(line)) {
106
+ inExceptions = true;
107
+ continue;
108
+ }
109
+ if (inExceptions) {
110
+ if (line === "}") {
111
+ inExceptions = false;
112
+ continue;
113
+ }
114
+ const m = line.match(/^\d+\s*:\s*(.+)$/);
115
+ if (m) exceptions.push(m[1].trim());
116
+ continue;
117
+ }
118
+ const kv = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.+)$/);
119
+ if (kv) fields.set(kv[1], kv[2].trim());
120
+ }
121
+
122
+ let parsedTarget;
123
+ try {
124
+ parsedTarget = new URL(url);
125
+ } catch {
126
+ parsedTarget = null;
127
+ }
128
+ if (parsedTarget && exceptions.some((pat) => hostMatchesException(parsedTarget.hostname, pat))) {
129
+ return { mode: "direct", source: "macos" };
130
+ }
131
+
132
+ const wantHttps = parsedTarget ? ["https:", "wss:"].includes(parsedTarget.protocol) : true;
133
+ if (wantHttps && fields.get("HTTPSEnable") === "1" && fields.get("HTTPSProxy")) {
134
+ const port = fields.get("HTTPSPort") ? `:${fields.get("HTTPSPort")}` : "";
135
+ return normalizeProxy(`http://${fields.get("HTTPSProxy")}${port}`, "macos");
136
+ }
137
+ if (fields.get("HTTPEnable") === "1" && fields.get("HTTPProxy")) {
138
+ const port = fields.get("HTTPPort") ? `:${fields.get("HTTPPort")}` : "";
139
+ return normalizeProxy(`http://${fields.get("HTTPProxy")}${port}`, "macos");
140
+ }
141
+ if (fields.get("SOCKSEnable") === "1" && fields.get("SOCKSProxy")) {
142
+ const port = fields.get("SOCKSPort") ? `:${fields.get("SOCKSPort")}` : "";
143
+ return normalizeProxy(`socks5://${fields.get("SOCKSProxy")}${port}`, "macos");
144
+ }
145
+ return { mode: "direct", source: "macos" };
23
146
  }
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");
147
+
148
+ export function queryMacOsProxy(url, { spawn = spawnSync } = {}) {
149
+ const result = spawn("scutil", ["--proxy"], {
150
+ encoding: "utf8",
151
+ timeout: 4000,
152
+ maxBuffer: 16384
153
+ });
154
+ if (result.error || result.status !== 0) {
155
+ return {
156
+ mode: "unavailable",
157
+ source: "macos",
158
+ reason: result.error?.code === "ETIMEDOUT" ? "macOS proxy lookup timed out" : "macOS proxy lookup failed"
159
+ };
160
+ }
161
+ return parseMacOsScutilProxy(result.stdout, url);
43
162
  }
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"};
163
+
164
+ export function resolveProxyForUrl(
165
+ url,
166
+ {
167
+ platform = process.platform,
168
+ env = process.env,
169
+ envLookup = getProxyForUrl,
170
+ windowsLookup = queryWindowsProxy,
171
+ macosLookup = queryMacOsProxy
172
+ } = {}
173
+ ) {
174
+ if (hasEnvironmentProxy(env)) {
175
+ const chosen = envLookup(url);
176
+ return chosen ? normalizeProxy(chosen, "environment") : { mode: "direct", source: "environment-bypass" };
177
+ }
178
+ if (platform === "win32") return windowsLookup(url);
179
+ if (platform === "darwin") return macosLookup(url);
180
+ return { mode: "direct", source: "system" };
53
181
  }