@juexibobi/private-desktop-mcp 0.4.0 → 0.6.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,181 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { isTailscaleTarget, normalizeIpHost } from "./proxy.mjs";
5
+
6
+ export const SUPPORTED_CLIENTS = [
7
+ "claude-code",
8
+ "claude-desktop",
9
+ "cursor",
10
+ "vscode",
11
+ "codex",
12
+ "gemini",
13
+ "windsurf"
14
+ ];
15
+
16
+ export function isPrivateOrTailscaleUrl(urlStr) {
17
+ try {
18
+ const u = new URL(urlStr);
19
+ const h = normalizeIpHost(u.hostname);
20
+ if (h === "127.0.0.1" || h === "localhost" || h === "::1") return true;
21
+ return isTailscaleTarget(u.hostname);
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+
27
+ export function resolveClientConfigPath(
28
+ client,
29
+ { platform = process.platform, homedir = os.homedir(), env = process.env, cwd = process.cwd() } = {}
30
+ ) {
31
+ const c = String(client || "").toLowerCase().trim();
32
+ const appData = env.APPDATA || path.join(homedir, "AppData", "Roaming");
33
+
34
+ switch (c) {
35
+ case "claude-code":
36
+ return path.join(cwd, ".mcp.json");
37
+ case "claude-desktop":
38
+ if (platform === "win32") return path.join(appData, "Claude", "claude_desktop_config.json");
39
+ if (platform === "darwin") {
40
+ return path.join(homedir, "Library", "Application Support", "Claude", "claude_desktop_config.json");
41
+ }
42
+ return path.join(env.XDG_CONFIG_HOME || path.join(homedir, ".config"), "Claude", "claude_desktop_config.json");
43
+ case "cursor":
44
+ return path.join(homedir, ".cursor", "mcp.json");
45
+ case "vscode":
46
+ return path.join(cwd, ".vscode", "mcp.json");
47
+ case "codex":
48
+ return path.join(homedir, ".codex", "config.toml");
49
+ case "gemini":
50
+ return path.join(homedir, ".gemini", "settings.json");
51
+ case "windsurf":
52
+ return path.join(homedir, ".codeium", "windsurf", "mcp_config.json");
53
+ default:
54
+ throw new Error(`Unsupported client "${client}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}`);
55
+ }
56
+ }
57
+
58
+ export function normalizeMcpEndpointUrl(relayUrl) {
59
+ const trimmed = String(relayUrl || "").trim().replace(/\/+$/, "");
60
+ if (!trimmed) throw new Error("Empty relay URL");
61
+ return trimmed.endsWith("/mcp") ? trimmed : `${trimmed}/mcp`;
62
+ }
63
+
64
+ function mergeJsonClientConfig(client, existingText, mcpUrl, serverName = "private-desktop", { bearerToken = "" } = {}) {
65
+ let root = {};
66
+ if (String(existingText || "").trim()) {
67
+ const parsed = JSON.parse(existingText);
68
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
69
+ root = { ...parsed };
70
+ }
71
+ }
72
+
73
+ const authHeaders = bearerToken ? { headers: { Authorization: `Bearer ${bearerToken}` } } : {};
74
+ const privateEndpoint = isPrivateOrTailscaleUrl(mcpUrl);
75
+
76
+ if (client === "vscode") {
77
+ const servers = root.servers && typeof root.servers === "object" ? { ...root.servers } : {};
78
+ servers[serverName] = { type: "http", url: mcpUrl, ...authHeaders };
79
+ root.servers = servers;
80
+ } else if (client === "gemini") {
81
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
82
+ mcpServers[serverName] = privateEndpoint
83
+ ? { httpUrl: mcpUrl, ...authHeaders }
84
+ : { httpUrl: mcpUrl, oauth: { enabled: true }, ...authHeaders };
85
+ root.mcpServers = mcpServers;
86
+ } else if (client === "cursor" || client === "windsurf") {
87
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
88
+ mcpServers[serverName] = { url: mcpUrl, ...authHeaders };
89
+ root.mcpServers = mcpServers;
90
+ } else {
91
+ // claude-code, claude-desktop, standard mcpServers
92
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
93
+ mcpServers[serverName] = { type: "http", url: mcpUrl, ...authHeaders };
94
+ root.mcpServers = mcpServers;
95
+ }
96
+
97
+ return JSON.stringify(root, null, 2) + "\n";
98
+ }
99
+
100
+ function mergeCodexTomlConfig(existingText, mcpUrl, serverName = "private_desktop", { bearerToken = "" } = {}) {
101
+ const sectionHeader = `[mcp_servers.${serverName}]`;
102
+ const headersLine = bearerToken
103
+ ? `http_headers = { Authorization = ${JSON.stringify(`Bearer ${bearerToken}`)} }\n`
104
+ : "";
105
+ const block = `${sectionHeader}\nurl = ${JSON.stringify(mcpUrl)}\n${headersLine}`;
106
+ const raw = String(existingText || "");
107
+ if (!raw.trim()) return block;
108
+
109
+ const escapedHeader = sectionHeader.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
110
+ const sectionRegex = new RegExp(`(^|\\r?\\n)${escapedHeader}\\r?\\n[\\s\\S]*?(?=(\\r?\\n\\[[^\\]]+\\])|$)`);
111
+ if (sectionRegex.test(raw)) {
112
+ return raw.replace(sectionRegex, `$1${block.trimEnd()}`).replace(/\s*$/, "\n");
113
+ }
114
+ return raw.replace(/\s*$/, "\n\n") + block;
115
+ }
116
+
117
+ export function configureMcpClient({
118
+ client,
119
+ relayUrl,
120
+ serverName,
121
+ configPath,
122
+ bearerToken = "",
123
+ dryRun = false,
124
+ platform = process.platform,
125
+ homedir = os.homedir(),
126
+ env = process.env,
127
+ cwd = process.cwd()
128
+ } = {}) {
129
+ const normalizedClient = String(client || "").toLowerCase().trim();
130
+ if (!SUPPORTED_CLIENTS.includes(normalizedClient)) {
131
+ throw new Error(`Unsupported client "${client}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}`);
132
+ }
133
+
134
+ const mcpUrl = normalizeMcpEndpointUrl(relayUrl);
135
+ const targetPath = configPath
136
+ ? path.resolve(configPath)
137
+ : resolveClientConfigPath(normalizedClient, { platform, homedir, env, cwd });
138
+
139
+ let existingText = "";
140
+ let existed = false;
141
+ try {
142
+ existingText = fs.readFileSync(targetPath, "utf8");
143
+ existed = true;
144
+ } catch (err) {
145
+ // Only a genuinely absent file is safe to treat as "create". Any other
146
+ // failure (EACCES, EISDIR, EIO, ...) must not be mistaken for absence, or
147
+ // the caller would overwrite a config it never read.
148
+ if (err?.code !== "ENOENT") {
149
+ throw new Error(
150
+ `Cannot read existing config at ${targetPath} (${err?.code || "UNKNOWN"}): ${err?.message || err}`,
151
+ { cause: err }
152
+ );
153
+ }
154
+ existingText = "";
155
+ existed = false;
156
+ }
157
+
158
+ const nextContent =
159
+ normalizedClient === "codex"
160
+ ? mergeCodexTomlConfig(existingText, mcpUrl, serverName ? serverName.replace(/-/g, "_") : "private_desktop", { bearerToken })
161
+ : mergeJsonClientConfig(normalizedClient, existingText, mcpUrl, serverName || "private-desktop", { bearerToken });
162
+
163
+ const changed = nextContent !== existingText;
164
+ const action = !existed ? "create" : changed ? "update" : "unchanged";
165
+
166
+ if (!dryRun && changed) {
167
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
168
+ fs.writeFileSync(targetPath, nextContent, "utf8");
169
+ }
170
+
171
+ return {
172
+ ok: true,
173
+ client: normalizedClient,
174
+ path: targetPath,
175
+ mcpUrl,
176
+ action,
177
+ changed,
178
+ dryRun: Boolean(dryRun),
179
+ preview: nextContent
180
+ };
181
+ }
@@ -0,0 +1,251 @@
1
+ import {
2
+ callInfo,
3
+ requestBrief,
4
+ requestDebug,
5
+ responseBrief,
6
+ safeTraceRequest,
7
+ safeTraceOutput,
8
+ shortCallId,
9
+ formatElapsed
10
+ } from "./activity.mjs";
11
+ import { logLine } from "./logging.mjs";
12
+ import {
13
+ evaluateToolCall,
14
+ filterToolsListBody,
15
+ redactOutboundResponse,
16
+ buildPolicyBlockedResponse
17
+ } from "./policy.mjs";
18
+
19
+ const FORWARDED_REQ_HEADERS = [
20
+ "accept",
21
+ "content-type",
22
+ "mcp-session-id",
23
+ "mcp-protocol-version",
24
+ "last-event-id",
25
+ "mcp-method",
26
+ "mcp-name"
27
+ ];
28
+
29
+ const FORWARDED_RES_HEADERS = ["content-type", "mcp-session-id", "mcp-protocol-version"];
30
+
31
+ /**
32
+ * Shared local MCP execution & guardrail pipeline.
33
+ * Ensures Cloudflare WebSocket relay, Tailscale direct/serve node ingress, and local hub
34
+ * forwarding all enforce the exact same local policy (--readonly, --allow-dir, allow/deny tools,
35
+ * self-credential protection), outbound DLP secret redaction, and activity logging.
36
+ */
37
+ export function createLocalBridge({
38
+ localBaseUrl,
39
+ localGatewayToken,
40
+ policy,
41
+ isGatewayHealthy,
42
+ getExtraSecrets = () => [],
43
+ defaultTimeoutMs = 70000,
44
+ maxResponseBytes = 8 * 1024 * 1024,
45
+ debug = false,
46
+ trace = false,
47
+ log = logLine,
48
+ fetcher = fetch,
49
+ inflightControllers = new Map(),
50
+ onStats = null
51
+ } = {}) {
52
+ if (!localBaseUrl) throw new Error("createLocalBridge requires localBaseUrl");
53
+ if (!policy) throw new Error("createLocalBridge requires policy");
54
+
55
+ async function forwardRequest({
56
+ id,
57
+ method = "POST",
58
+ headers: incomingHeaders = {},
59
+ body = "",
60
+ signal = null,
61
+ timeoutMs = defaultTimeoutMs,
62
+ maxBytes = maxResponseBytes,
63
+ sourceLabel = ""
64
+ } = {}) {
65
+ const reqId = id || `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
66
+ const started = Date.now();
67
+ const bodyStr = typeof body === "string" ? body : String(body || "");
68
+ const call = callInfo(bodyStr, reqId);
69
+ const callId = shortCallId(call.requestId);
70
+ const name = call.label;
71
+ const isTool = call.method === "tools/call";
72
+ const prefix = sourceLabel ? `[${sourceLabel}] ` : "";
73
+
74
+ log("info", "🔧 " + prefix + "[" + callId + "] " + (isTool ? "Tool: " : "MCP: ") + name + " | " + requestBrief(call));
75
+ if (debug) log("debug", " ↳ Metadata: " + requestDebug(call));
76
+ if (trace) log("warn", " ↳ Trace args (locally visible): " + safeTraceRequest(call));
77
+
78
+ let parsedRpc = null;
79
+ try {
80
+ parsedRpc = JSON.parse(bodyStr);
81
+ } catch {
82
+ parsedRpc = null;
83
+ }
84
+
85
+ // 1. Enforce local tool policy before forwarding to gateway
86
+ if (parsedRpc) {
87
+ const verdict = evaluateToolCall(parsedRpc, policy);
88
+ if (!verdict.allowed) {
89
+ log("warn", "🛡️ " + prefix + "[" + callId + "] Policy blocked " + name + ": " + verdict.reason);
90
+ const resp = {
91
+ status: 200,
92
+ headers: { "content-type": "application/json" },
93
+ body: buildPolicyBlockedResponse(parsedRpc.id, verdict.reason),
94
+ failed: true,
95
+ blocked: true,
96
+ redactedCount: 0,
97
+ elapsedMs: Date.now() - started
98
+ };
99
+ onStats?.({ failed: true, blocked: true, elapsedMs: resp.elapsedMs, redactedCount: 0 });
100
+ return resp;
101
+ }
102
+ }
103
+
104
+ // 2. Ensure local gateway is healthy
105
+ if (!isGatewayHealthy()) {
106
+ log("error", "❌ " + prefix + "[" + callId + "] " + name + " | Local gateway unavailable");
107
+ const resp = {
108
+ status: 503,
109
+ headers: { "content-type": "application/json" },
110
+ body: JSON.stringify({ error: "Local MCP gateway is currently restarting; retry shortly." }),
111
+ failed: true,
112
+ blocked: false,
113
+ redactedCount: 0,
114
+ elapsedMs: Date.now() - started
115
+ };
116
+ onStats?.({ failed: true, blocked: false, elapsedMs: resp.elapsedMs, redactedCount: 0 });
117
+ return resp;
118
+ }
119
+
120
+ // 3. Build sanitized loopback headers
121
+ const headers = {};
122
+ if (localGatewayToken) headers.authorization = "Bearer " + localGatewayToken;
123
+ for (const k of FORWARDED_REQ_HEADERS) {
124
+ const v = incomingHeaders?.[k];
125
+ if (v) headers[k] = String(v);
126
+ }
127
+ if (parsedRpc && typeof parsedRpc.method === "string") {
128
+ headers["mcp-method"] = parsedRpc.method;
129
+ if (parsedRpc.method === "tools/call" && typeof parsedRpc.params?.name === "string") {
130
+ headers["mcp-name"] = parsedRpc.params.name;
131
+ }
132
+ }
133
+
134
+ const controller = new AbortController();
135
+ const timeout = setTimeout(
136
+ () => controller.abort(new Error(`Local gateway timeout (${Math.round(timeoutMs / 1000)}s)`)),
137
+ timeoutMs
138
+ );
139
+ const onExternalAbort = () => {
140
+ try {
141
+ controller.abort(signal?.reason || new Error("Cancelled by client"));
142
+ } catch {}
143
+ };
144
+ if (signal) {
145
+ if (signal.aborted) {
146
+ clearTimeout(timeout);
147
+ onExternalAbort();
148
+ } else {
149
+ signal.addEventListener("abort", onExternalAbort, { once: true });
150
+ }
151
+ }
152
+ inflightControllers.set(reqId, controller);
153
+
154
+ let status = 502;
155
+ let forwardHeaders = { "content-type": "application/json" };
156
+ let respBody = "";
157
+ let redactedCount = 0;
158
+
159
+ try {
160
+ const fetchOpts = {
161
+ method: method || "POST",
162
+ headers,
163
+ signal: controller.signal
164
+ };
165
+ if (fetchOpts.method !== "DELETE" && fetchOpts.method !== "GET" && fetchOpts.method !== "HEAD") {
166
+ fetchOpts.body = bodyStr;
167
+ }
168
+ const r = await fetcher(localBaseUrl, fetchOpts);
169
+ respBody = await r.text();
170
+ forwardHeaders = {};
171
+ for (const k of FORWARDED_RES_HEADERS) {
172
+ if (r.headers.has(k)) forwardHeaders[k] = r.headers.get(k);
173
+ }
174
+ const ct = forwardHeaders["content-type"] || "";
175
+
176
+ // 4. Filter disallowed tools from tools/list responses
177
+ if (call.method === "tools/list" && r.ok) {
178
+ respBody = filterToolsListBody(respBody, ct, policy);
179
+ }
180
+
181
+ // 5. Outbound DLP secret redaction
182
+ const extraSecrets = [localGatewayToken || "", ...(getExtraSecrets() || [])].filter(Boolean);
183
+ const dlpResult = redactOutboundResponse(respBody, ct, {
184
+ enabled: policy.dlp,
185
+ extraSecrets
186
+ });
187
+ redactedCount = dlpResult.redactedCount;
188
+ if (redactedCount > 0) {
189
+ log("warn", `🛡️ ${prefix}[${callId}] DLP redacted ${redactedCount} secret(s) before returning response`);
190
+ respBody = dlpResult.body;
191
+ }
192
+
193
+ status = r.status;
194
+ if (typeof maxBytes === "number" && maxBytes > 0 && respBody.length > maxBytes) {
195
+ respBody = respBody.slice(0, maxBytes);
196
+ }
197
+ } catch (e) {
198
+ const aborted = controller.signal.aborted;
199
+ const reason = controller.signal.reason?.message || e?.message || "Local gateway error";
200
+ status = aborted && /client|cancel/i.test(reason) ? 499 : 502;
201
+ forwardHeaders = { "content-type": "application/json" };
202
+ respBody = JSON.stringify({ error: "Local gateway error", message: String(reason).slice(0, 180) });
203
+ } finally {
204
+ clearTimeout(timeout);
205
+ if (signal) {
206
+ try {
207
+ signal.removeEventListener("abort", onExternalAbort);
208
+ } catch {}
209
+ }
210
+ inflightControllers.delete(reqId);
211
+ }
212
+
213
+ const elapsedMs = Date.now() - started;
214
+ const result = responseBrief(respBody, forwardHeaders["content-type"] || "", status);
215
+ const failed = result.failed;
216
+ onStats?.({ failed, blocked: false, elapsedMs, redactedCount });
217
+
218
+ log(
219
+ failed ? "error" : "info",
220
+ (failed ? "❌" : "✅") +
221
+ " " +
222
+ prefix +
223
+ "[" +
224
+ callId +
225
+ "] " +
226
+ name +
227
+ " | " +
228
+ result.kind +
229
+ " | HTTP " +
230
+ status +
231
+ " | " +
232
+ formatElapsed(elapsedMs)
233
+ );
234
+ log(failed ? "warn" : "info", " ↳ " + result.summary);
235
+ if (result.error) log("error", " ↳ JSON-RPC: " + result.error);
236
+ if (debug) log("debug", " ↳ Response size: " + result.bytes + " bytes");
237
+ if (trace) log("warn", " ↳ Trace output (may contain private data): " + safeTraceOutput(result));
238
+
239
+ return {
240
+ status,
241
+ headers: forwardHeaders,
242
+ body: respBody,
243
+ failed,
244
+ blocked: false,
245
+ redactedCount,
246
+ elapsedMs
247
+ };
248
+ }
249
+
250
+ return { forwardRequest };
251
+ }
package/bin/logging.mjs CHANGED
@@ -48,8 +48,12 @@ export function rpcOutcome(body,contentType=""){
48
48
  return {failed:false,size:Buffer.byteLength(String(body||""),"utf8"),kind:"non-json",resultFields:[]};
49
49
  }
50
50
  }
51
+ let stdoutMode="text";
52
+ export function setStdoutMode(mode){
53
+ stdoutMode=mode==="json"?"json":"text";
54
+ }
51
55
  export function logLine(level,message){
52
56
  const tag={info:"INFO",warn:"WARN",error:"ERROR",debug:"DEBUG"}[level]||"INFO";
53
57
  const output="["+timestamp()+"] ["+tag+"] "+sanitizeText(message,1550);
54
- if(level==="error")console.error(output);else console.log(output);
58
+ if(level==="error"||stdoutMode==="json")console.error(output);else console.log(output);
55
59
  }
package/bin/policy.mjs CHANGED
@@ -26,7 +26,10 @@ const PATH_ARG_KEYS = [
26
26
  "destination",
27
27
  "cwd",
28
28
  "workingDirectory",
29
+ "working_directory",
29
30
  "filePath",
31
+ "file_path",
32
+ "file_paths",
30
33
  "directory",
31
34
  "dir"
32
35
  ];
@@ -111,6 +114,7 @@ export function createPolicy({
111
114
  allowDirs: allowDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
112
115
  protectedDirs: protectedDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
113
116
  learnedReadOnlyTools: new Set(),
117
+ toolAnnotations: new Map(),
114
118
  dlp: Boolean(dlp)
115
119
  };
116
120
  }
@@ -132,7 +136,10 @@ export function evaluateToolCall(rpc, policy, { platform = process.platform } =
132
136
  const toolName = typeof rpc.params?.name === "string" ? rpc.params.name : "";
133
137
  const args = rpc.params?.arguments && typeof rpc.params.arguments === "object" ? rpc.params.arguments : {};
134
138
 
135
- if (!isToolAllowedByName(toolName, policy)) {
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)) {
136
143
  const modeReason = policy.readonly ? "connector is running in --readonly mode" : "tool is disallowed by local policy";
137
144
  return { allowed: false, reason: `Blocked locally: "${toolName}" is not permitted (${modeReason}).` };
138
145
  }
@@ -151,7 +158,7 @@ export function evaluateToolCall(rpc, policy, { platform = process.platform } =
151
158
  }
152
159
  if (typeof args.command === "string") {
153
160
  const cmdLower = args.command.toLowerCase();
154
- if (cmdLower.includes("privatedesktopmcp") && cmdLower.includes("device.json")) {
161
+ if (cmdLower.includes("privatedesktopmcp") && /(device|hub-state)\.json/.test(cmdLower)) {
155
162
  return {
156
163
  allowed: false,
157
164
  reason: "Blocked locally: reading or modifying connector device credentials via shell is forbidden."
@@ -214,8 +221,14 @@ export function filterToolsListBody(bodyText, contentType, policy) {
214
221
  return transformRpcPayload(bodyText, contentType, (obj) => {
215
222
  if (!Array.isArray(obj?.result?.tools)) return null;
216
223
  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);
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
+ }
219
232
  }
220
233
  return isToolAllowedByName(tool?.name, policy, tool?.annotations || null);
221
234
  });
@@ -252,24 +265,61 @@ export function redactSecretsInText(text, extraSecrets = []) {
252
265
  return { text: out, redactedCount: count };
253
266
  }
254
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
+
255
289
  export function redactOutboundResponse(bodyText, contentType = "", { enabled = true, extraSecrets = [] } = {}) {
256
290
  if (!enabled || !bodyText) return { body: bodyText, redactedCount: 0 };
257
291
  let total = 0;
258
292
  const body = transformRpcPayload(bodyText, contentType, (obj) => {
259
- if (!Array.isArray(obj?.result?.content)) return null;
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;
260
296
  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 };
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
+ }
268
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 };
269
320
  }
270
- return block;
271
- });
272
- return modified ? { ...obj, result: { ...obj.result, content } } : null;
321
+ }
322
+ return modified ? { ...obj, result } : null;
273
323
  });
274
324
  return { body, redactedCount: total };
275
325
  }
package/bin/proxy.mjs CHANGED
@@ -1,6 +1,47 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { getProxyForUrl } from "proxy-from-env";
3
3
 
4
+ export function normalizeIpHost(rawHost) {
5
+ let host = String(rawHost || "").trim().toLowerCase();
6
+ if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
7
+ if (host.startsWith("::ffff:")) host = host.slice(7);
8
+ return host;
9
+ }
10
+
11
+ export function isTailscaleIp(rawHost) {
12
+ const host = normalizeIpHost(rawHost);
13
+ if (!host) return false;
14
+ // IPv4 CGNAT range 100.64.0.0/10 (100.64.0.0 - 100.127.255.255)
15
+ const ipv4Match = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
16
+ if (ipv4Match) {
17
+ const [a, b, c, d] = ipv4Match.slice(1).map(Number);
18
+ if (a > 255 || b > 255 || c > 255 || d > 255) return false;
19
+ return a === 100 && b >= 64 && b <= 127;
20
+ }
21
+ // Tailscale IPv6 ULA prefix fd7a:115c:a1e0::/48
22
+ if (host.startsWith("fd7a:115c:a1e0:") && /^[0-9a-f:]+$/.test(host)) {
23
+ return true;
24
+ }
25
+ return false;
26
+ }
27
+
28
+ export function isTailscaleTarget(urlOrHost) {
29
+ const raw = String(urlOrHost || "").trim();
30
+ if (!raw) return false;
31
+ let host = raw;
32
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
33
+ try {
34
+ host = new URL(raw).hostname;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+ const normalized = normalizeIpHost(host).replace(/\.$/, "");
40
+ if (!normalized) return false;
41
+ if (normalized === "ts.net" || normalized.endsWith(".ts.net")) return true;
42
+ return isTailscaleIp(normalized);
43
+ }
44
+
4
45
  const proxyEnvironmentKeys = [
5
46
  "https_proxy",
6
47
  "http_proxy",
@@ -171,6 +212,9 @@ export function resolveProxyForUrl(
171
212
  macosLookup = queryMacOsProxy
172
213
  } = {}
173
214
  ) {
215
+ if (isTailscaleTarget(url)) {
216
+ return { mode: "direct", source: "tailscale-bypass" };
217
+ }
174
218
  if (hasEnvironmentProxy(env)) {
175
219
  const chosen = envLookup(url);
176
220
  return chosen ? normalizeProxy(chosen, "environment") : { mode: "direct", source: "environment-bypass" };