leakshield 0.3.1 → 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.
- package/README.md +144 -546
- package/README.zh-TW.md +143 -520
- package/dist/adapters/claude-code/capabilities.d.ts +14 -0
- package/dist/adapters/claude-code/capabilities.js +47 -0
- package/dist/adapters/claude-code/cli.d.ts +10 -0
- package/dist/adapters/claude-code/cli.js +51 -0
- package/dist/adapters/claude-code/doctor.d.ts +19 -0
- package/dist/adapters/claude-code/doctor.js +177 -0
- package/dist/adapters/claude-code/proxy.d.ts +47 -0
- package/dist/adapters/claude-code/proxy.js +348 -0
- package/dist/adapters/opencode/capabilities.d.ts +10 -0
- package/dist/adapters/opencode/capabilities.js +48 -0
- package/dist/adapters/opencode/doctor.d.ts +67 -0
- package/dist/{doctor.js → adapters/opencode/doctor.js} +26 -44
- package/dist/adapters/opencode/env-queries.d.ts +133 -0
- package/dist/adapters/opencode/env-tools.d.ts +20 -0
- package/dist/adapters/opencode/hooks.d.ts +4 -0
- package/dist/adapters/opencode/plugin.d.ts +12 -0
- package/dist/{opencode.js → adapters/opencode/plugin.js} +43 -14
- package/dist/adapters/opencode/tool-policy.d.ts +2 -0
- package/dist/adapters/opencode/tool-policy.js +23 -0
- package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
- package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
- package/dist/adapters/opencode/transparent.d.ts +70 -0
- package/dist/adapters/opencode/transparent.js +242 -0
- package/dist/adapters/opencode/v2.d.ts +23 -0
- package/dist/{opencode-v2.js → adapters/opencode/v2.js} +13 -8
- package/dist/adapters/pi/capabilities.d.ts +10 -0
- package/dist/adapters/pi/capabilities.js +50 -0
- package/dist/adapters/pi/doctor.d.ts +26 -0
- package/dist/adapters/pi/doctor.js +276 -0
- package/dist/adapters/pi/extension.d.ts +28 -0
- package/dist/adapters/pi/extension.js +109 -0
- package/dist/adapters/pi/guard.d.ts +33 -0
- package/dist/adapters/pi/guard.js +154 -0
- package/dist/adapters/pi/persistence.d.ts +9 -0
- package/dist/adapters/pi/persistence.js +69 -0
- package/dist/adapters/pi/settings.d.ts +51 -0
- package/dist/adapters/pi/settings.js +136 -0
- package/dist/adapters/pi/tool-policy.d.ts +11 -0
- package/dist/adapters/pi/tool-policy.js +114 -0
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +17 -6
- package/dist/config/loader.d.ts +70 -0
- package/dist/config/loader.js +8 -0
- package/dist/config/plain-object.d.ts +2 -0
- package/dist/core/index.d.ts +9 -0
- package/dist/core/index.js +9 -0
- package/dist/core/session-guard.d.ts +62 -0
- package/dist/{opencode-transparent.js → core/session-guard.js} +56 -713
- package/dist/core/sse-recovery.d.ts +6 -0
- package/dist/core/tool-restore-policy.d.ts +153 -0
- package/dist/core/tool-restore-policy.js +453 -0
- package/dist/core/wire.d.ts +213 -0
- package/dist/{opencode-transparent-http.js → core/wire.js} +125 -42
- package/dist/core/ws.d.ts +26 -0
- package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
- package/dist/decision/deidentify.d.ts +63 -0
- package/dist/decision/ingress.d.ts +40 -0
- package/dist/decision/mapping-key.d.ts +91 -0
- package/dist/decision/mapping-store.d.ts +166 -0
- package/dist/decision/model.d.ts +41 -0
- package/dist/decision/pseudonymization.d.ts +176 -0
- package/dist/decision/redaction.d.ts +56 -0
- package/dist/decision/redaction.js +3 -0
- package/dist/decision/schema-strings.d.ts +23 -0
- package/dist/decision/schema-strings.js +2 -2
- package/dist/decision/value-search.d.ts +39 -0
- package/dist/doctor-capabilities.d.ts +21 -0
- package/dist/doctor-capabilities.js +58 -0
- package/dist/doctor-hosts.d.ts +18 -0
- package/dist/doctor-hosts.js +144 -0
- package/dist/doctor-report.d.ts +45 -0
- package/dist/doctor-report.js +111 -0
- package/dist/forget.d.ts +18 -0
- package/dist/guard-options.d.ts +45 -0
- package/dist/{plugin-options.js → guard-options.js} +8 -6
- package/dist/help.d.ts +2 -0
- package/dist/help.js +15 -1
- package/dist/i18n/en.d.ts +65 -0
- package/dist/i18n/index.d.ts +15 -0
- package/dist/i18n/zh-TW.d.ts +65 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +1 -1
- package/dist/rules/builtin.d.ts +4 -0
- package/dist/rules/builtin.js +75 -2
- package/dist/rules/dynamic.d.ts +33 -0
- package/dist/scanner/allowlist.d.ts +22 -0
- package/dist/scanner/cidr.d.ts +39 -0
- package/dist/scanner/encoding.d.ts +87 -0
- package/dist/scanner/engine.d.ts +43 -0
- package/dist/scanner/exact-values.d.ts +11 -0
- package/dist/scanner/redaction-verifier.d.ts +24 -0
- package/dist/scanner/remotes.d.ts +29 -0
- package/dist/scanner/unicode.d.ts +57 -0
- package/dist/scanner/utils.d.ts +22 -0
- package/dist/transports/cli.d.ts +27 -0
- package/dist/transports/web-ui.d.ts +1 -0
- package/dist/transports/web-ui.js +1 -1
- package/dist/transports/web.d.ts +4 -0
- package/dist/types/capabilities.d.ts +67 -0
- package/dist/types/capabilities.js +133 -0
- package/dist/types.d.ts +149 -0
- package/dist/types.js +3 -0
- package/dist/utils/files.d.ts +3 -0
- package/dist/utils/path-security.d.ts +18 -0
- package/dist/utils/win-encoding.d.ts +16 -0
- package/package.json +15 -3
- /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
- /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
- /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
- /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code host adapter (issue #86): a loopback HTTP proxy that Claude Code
|
|
3
|
+
* reaches through `ANTHROPIC_BASE_URL`. Anthropic Messages requests are masked
|
|
4
|
+
* by the host-independent core before they leave the machine, and assistant
|
|
5
|
+
* text in JSON and SSE replies is restored before Claude Code shows it.
|
|
6
|
+
*
|
|
7
|
+
* Fail closed: a request the proxy cannot mask (unknown route with a body,
|
|
8
|
+
* unrecognised body shape, masking error) is answered locally with a 400
|
|
9
|
+
* Anthropic-style error and nothing is forwarded. Bodyless GET/HEAD probes
|
|
10
|
+
* (Claude Code sends `HEAD /api/hello`) are forwarded when their URL carries
|
|
11
|
+
* no finding.
|
|
12
|
+
*
|
|
13
|
+
* Not covered here: tool-execution restoration (tool_use input stays
|
|
14
|
+
* tokenized, so Claude Code's tools receive placeholders), and anything
|
|
15
|
+
* Claude Code sends outside the base URL.
|
|
16
|
+
*/
|
|
17
|
+
import { createServer } from "node:http";
|
|
18
|
+
import { Readable } from "node:stream";
|
|
19
|
+
import { createGuardCore, PROTECT_FAILED_ERROR } from "../../core/session-guard.js";
|
|
20
|
+
import { containsTokenPrefix, createPseudonymizer } from "../../decision/pseudonymization.js";
|
|
21
|
+
export const DEFAULT_PROXY_HOST = "127.0.0.1";
|
|
22
|
+
export const DEFAULT_PROXY_PORT = 8787;
|
|
23
|
+
export const DEFAULT_UPSTREAM = "https://api.anthropic.com";
|
|
24
|
+
export const HEALTH_PATH = "/__leakshield/health";
|
|
25
|
+
export const HEALTH_SERVICE = "leakshield-claude-code-proxy";
|
|
26
|
+
const SESSION_HEADER = "x-claude-code-session-id";
|
|
27
|
+
const SESSION_ID_SHAPE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
28
|
+
// Claude Code always sends its session header today; the shared fallback
|
|
29
|
+
// keeps one stable mapping if a version stops sending it.
|
|
30
|
+
const FALLBACK_SESSION = "claude-code";
|
|
31
|
+
const MESSAGES_PATH = /\/v1\/messages\/?$/;
|
|
32
|
+
const COUNT_TOKENS_PATH = /\/v1\/messages\/count_tokens\/?$/;
|
|
33
|
+
// undici sets its own accept-encoding and decompresses; forwarding the
|
|
34
|
+
// client's value would hand the core compressed bytes it cannot read.
|
|
35
|
+
const DROP_REQUEST_HEADERS = new Set([
|
|
36
|
+
"host", "connection", "keep-alive", "proxy-connection", "proxy-authorization", "te", "trailer",
|
|
37
|
+
"transfer-encoding", "upgrade", "content-length", "accept-encoding",
|
|
38
|
+
]);
|
|
39
|
+
// The body is decompressed by fetch and may change length during restore.
|
|
40
|
+
const DROP_RESPONSE_HEADERS = new Set([
|
|
41
|
+
"connection", "keep-alive", "transfer-encoding", "content-encoding", "content-length", "trailer", "upgrade",
|
|
42
|
+
]);
|
|
43
|
+
const UNSUPPORTED_ROUTE = "LeakShield blocked a request on a route the Claude Code proxy cannot mask. [proxy-route]";
|
|
44
|
+
const UNSAFE_URL = "LeakShield blocked a request whose URL carries sensitive content. [proxy-url]";
|
|
45
|
+
const UNSAFE_HEADER = "LeakShield blocked a request whose headers carry sensitive content. [proxy-header]";
|
|
46
|
+
const UNREADABLE_BODY = "LeakShield blocked the request because its body is unsupported or could not be identified. [proxy-body]";
|
|
47
|
+
const UPSTREAM_REDIRECT = "LeakShield blocked an upstream redirect; following it would resend the request outside the proxy. [proxy-redirect]";
|
|
48
|
+
const UPSTREAM_UNREACHABLE = "LeakShield could not reach the upstream API. [proxy-upstream]";
|
|
49
|
+
// Mirrors the core's request cap so an oversized body is refused before the
|
|
50
|
+
// proxy buffers more of it.
|
|
51
|
+
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
52
|
+
const CREDENTIAL_HEADERS = new Set(["authorization", "x-api-key", "cookie", "proxy-authorization"]);
|
|
53
|
+
function isLoopbackHost(hostname) {
|
|
54
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
|
55
|
+
}
|
|
56
|
+
/** Plain http is accepted only for a loopback upstream (a local stub or gateway). */
|
|
57
|
+
export function parseUpstream(raw) {
|
|
58
|
+
const url = new URL(raw);
|
|
59
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) {
|
|
60
|
+
throw new Error("upstream must be https (plain http is allowed only on loopback)");
|
|
61
|
+
}
|
|
62
|
+
if (url.search !== "" || url.hash !== "")
|
|
63
|
+
throw new Error("upstream must not carry a query or fragment");
|
|
64
|
+
return url;
|
|
65
|
+
}
|
|
66
|
+
function anthropicError(status, message) {
|
|
67
|
+
return new Response(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message } }), {
|
|
68
|
+
status,
|
|
69
|
+
headers: { "content-type": "application/json" },
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function sessionOf(request) {
|
|
73
|
+
const value = request.headers.get(SESSION_HEADER);
|
|
74
|
+
return value !== null && SESSION_ID_SHAPE.test(value) ? value : FALLBACK_SESSION;
|
|
75
|
+
}
|
|
76
|
+
function forwardHeaders(source) {
|
|
77
|
+
const headers = new Headers();
|
|
78
|
+
source.forEach((value, key) => {
|
|
79
|
+
if (!DROP_REQUEST_HEADERS.has(key))
|
|
80
|
+
headers.set(key, value);
|
|
81
|
+
});
|
|
82
|
+
return headers;
|
|
83
|
+
}
|
|
84
|
+
function relay(response, method) {
|
|
85
|
+
const headers = new Headers();
|
|
86
|
+
response.headers.forEach((value, key) => {
|
|
87
|
+
if (!DROP_RESPONSE_HEADERS.has(key) && key !== "set-cookie")
|
|
88
|
+
headers.set(key, value);
|
|
89
|
+
});
|
|
90
|
+
for (const cookie of response.headers.getSetCookie())
|
|
91
|
+
headers.append("set-cookie", cookie);
|
|
92
|
+
return new Response(method === "HEAD" ? null : response.body, {
|
|
93
|
+
status: response.status,
|
|
94
|
+
statusText: response.statusText,
|
|
95
|
+
headers,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
function urlCarriesFinding(url, unsafe) {
|
|
99
|
+
let text = url.pathname + url.search;
|
|
100
|
+
try {
|
|
101
|
+
text = decodeURIComponent(text);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
if (unsafe(text))
|
|
107
|
+
return true;
|
|
108
|
+
// decodeURIComponent leaves `+` as is; form decoding turns it into a space,
|
|
109
|
+
// which a multi-word keyword needs to match.
|
|
110
|
+
for (const [name, value] of url.searchParams) {
|
|
111
|
+
if (unsafe(name) || unsafe(value))
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
/** Credential headers are meant for the upstream and are not content. */
|
|
117
|
+
function headersCarryFinding(headers, unsafe) {
|
|
118
|
+
let found = false;
|
|
119
|
+
headers.forEach((value, key) => {
|
|
120
|
+
if (!found && !CREDENTIAL_HEADERS.has(key) && (unsafe(key) || unsafe(value)))
|
|
121
|
+
found = true;
|
|
122
|
+
});
|
|
123
|
+
return found;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The core also forwards only what it scanned (#93); normalizing here as
|
|
127
|
+
* well keeps that guarantee independent of the core and lets an oversized or
|
|
128
|
+
* non-JSON body be refused before the core reads it.
|
|
129
|
+
*/
|
|
130
|
+
async function canonicalJsonBody(request) {
|
|
131
|
+
if (request.body === null)
|
|
132
|
+
return null;
|
|
133
|
+
const reader = request.body.getReader();
|
|
134
|
+
const chunks = [];
|
|
135
|
+
let total = 0;
|
|
136
|
+
for (;;) {
|
|
137
|
+
const step = await reader.read();
|
|
138
|
+
if (step.done)
|
|
139
|
+
break;
|
|
140
|
+
total += step.value.byteLength;
|
|
141
|
+
if (total > MAX_BODY_BYTES) {
|
|
142
|
+
void reader.cancel().catch(() => { });
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
chunks.push(step.value);
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
return JSON.stringify(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** Static refusal text only: native errors may embed a URL or header value. */
|
|
155
|
+
function refusalMessage(error) {
|
|
156
|
+
return error instanceof Error && error.message.startsWith("LeakShield ") ? error.message : PROTECT_FAILED_ERROR;
|
|
157
|
+
}
|
|
158
|
+
export function createClaudeCodeProxy(options) {
|
|
159
|
+
const upstream = parseUpstream(options.upstream ?? DEFAULT_UPSTREAM);
|
|
160
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
161
|
+
const log = options.log ?? ((line) => console.error(line));
|
|
162
|
+
// The core's model-boundary scan, not a plain scanText: it ignores in-text
|
|
163
|
+
// ignore directives and treats a truncated scan as unsafe, so metadata
|
|
164
|
+
// cannot opt itself out or hide past the scan limit.
|
|
165
|
+
const boundary = createPseudonymizer(options.config);
|
|
166
|
+
const metadataUnsafe = (text) => !boundary.ok || containsTokenPrefix(text) || !boundary.isTextSafe(text);
|
|
167
|
+
const core = createGuardCore(options.config, options.attachments ?? "block", true, undefined, {
|
|
168
|
+
anthropicThinking: "mask",
|
|
169
|
+
});
|
|
170
|
+
const targetOf = (incoming, pathname = incoming.pathname) => {
|
|
171
|
+
const target = new URL(upstream);
|
|
172
|
+
target.pathname = upstream.pathname.replace(/\/+$/, "") + pathname;
|
|
173
|
+
target.search = incoming.search;
|
|
174
|
+
return target;
|
|
175
|
+
};
|
|
176
|
+
// The route label, not the path: a refused path may itself hold the value.
|
|
177
|
+
const refuse = (method, route, message) => {
|
|
178
|
+
log(`[leakshield] blocked ${method} ${route}: ${message}`);
|
|
179
|
+
return anthropicError(400, message);
|
|
180
|
+
};
|
|
181
|
+
// A redirect is neither followed here (it would resend the credentials and
|
|
182
|
+
// masked body to an unconfigured host) nor relayed: a client that follows
|
|
183
|
+
// a 307/308 itself resends its original, unmasked request to the target.
|
|
184
|
+
const send = async (request, signal) => {
|
|
185
|
+
let response;
|
|
186
|
+
try {
|
|
187
|
+
response = await fetchImpl(request, { signal, redirect: "manual" });
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
if (response.status >= 300 && response.status < 400) {
|
|
193
|
+
void response.body?.cancel().catch(() => { });
|
|
194
|
+
log(`[leakshield] blocked ${request.method} upstream redirect: ${UPSTREAM_REDIRECT}`);
|
|
195
|
+
return anthropicError(400, UPSTREAM_REDIRECT);
|
|
196
|
+
}
|
|
197
|
+
return response;
|
|
198
|
+
};
|
|
199
|
+
const handle = async (request, signal) => {
|
|
200
|
+
const incoming = new URL(request.url);
|
|
201
|
+
const method = request.method.toUpperCase();
|
|
202
|
+
const path = incoming.pathname;
|
|
203
|
+
if (path === HEALTH_PATH && (method === "GET" || method === "HEAD")) {
|
|
204
|
+
return new Response(method === "HEAD" ? null : JSON.stringify({ service: HEALTH_SERVICE, upstream: upstream.origin }), {
|
|
205
|
+
status: 200,
|
|
206
|
+
headers: { "content-type": "application/json" },
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
const route = method === "POST" && COUNT_TOKENS_PATH.test(path) ? "count_tokens"
|
|
210
|
+
: method === "POST" && MESSAGES_PATH.test(path) ? "messages"
|
|
211
|
+
: (method === "GET" || method === "HEAD") && request.body === null ? "probe"
|
|
212
|
+
: "other";
|
|
213
|
+
if (core === null)
|
|
214
|
+
return refuse(method, route, PROTECT_FAILED_ERROR);
|
|
215
|
+
if (route === "other")
|
|
216
|
+
return refuse(method, route, UNSUPPORTED_ROUTE);
|
|
217
|
+
if (urlCarriesFinding(incoming, metadataUnsafe))
|
|
218
|
+
return refuse(method, route, UNSAFE_URL);
|
|
219
|
+
const headers = forwardHeaders(request.headers);
|
|
220
|
+
const sessionID = sessionOf(request);
|
|
221
|
+
if (route === "probe") {
|
|
222
|
+
if (headersCarryFinding(headers, metadataUnsafe))
|
|
223
|
+
return refuse(method, route, UNSAFE_HEADER);
|
|
224
|
+
const response = await send(new Request(targetOf(incoming), { method, headers }), signal);
|
|
225
|
+
return response === null ? anthropicError(502, UPSTREAM_UNREACHABLE) : relay(response, method);
|
|
226
|
+
}
|
|
227
|
+
const body = await canonicalJsonBody(request).catch(() => null);
|
|
228
|
+
if (body === null)
|
|
229
|
+
return refuse(method, route, UNREADABLE_BODY);
|
|
230
|
+
if (route === "count_tokens") {
|
|
231
|
+
// count_tokens carries the whole conversation in Messages shape. The
|
|
232
|
+
// core masks only a /messages URL, so it masks under that path and the
|
|
233
|
+
// masked body is then sent to the real count_tokens route.
|
|
234
|
+
const event = {
|
|
235
|
+
sessionID,
|
|
236
|
+
request: new Request(targetOf(incoming, path.replace(/\/count_tokens\/?$/, "")), { method, headers, body }),
|
|
237
|
+
};
|
|
238
|
+
try {
|
|
239
|
+
await core.onHttpRequest(event);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
return refuse(method, route, refusalMessage(error));
|
|
243
|
+
}
|
|
244
|
+
const masked = event.request;
|
|
245
|
+
const response = await send(new Request(targetOf(incoming), {
|
|
246
|
+
method, headers: masked.headers, body: await masked.arrayBuffer(),
|
|
247
|
+
}), signal);
|
|
248
|
+
return response === null ? anthropicError(502, UPSTREAM_UNREACHABLE) : relay(response, method);
|
|
249
|
+
}
|
|
250
|
+
const event = { sessionID, request: new Request(targetOf(incoming), { method, headers, body }) };
|
|
251
|
+
try {
|
|
252
|
+
await core.onHttpRequest(event);
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
return refuse(method, route, refusalMessage(error));
|
|
256
|
+
}
|
|
257
|
+
const sent = event.request;
|
|
258
|
+
const response = await send(sent, signal);
|
|
259
|
+
if (response === null)
|
|
260
|
+
return anthropicError(502, UPSTREAM_UNREACHABLE);
|
|
261
|
+
// Same request object and session as the masking call: the core only
|
|
262
|
+
// restores a reply it can attribute to a request it masked.
|
|
263
|
+
const reply = { sessionID, request: sent, response };
|
|
264
|
+
await core.onHttpResponse(reply);
|
|
265
|
+
return relay(reply.response, method);
|
|
266
|
+
};
|
|
267
|
+
return {
|
|
268
|
+
upstream: upstream.toString(),
|
|
269
|
+
handle,
|
|
270
|
+
dispose: () => core?.dispose(),
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function toHeaders(raw) {
|
|
274
|
+
const headers = new Headers();
|
|
275
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
276
|
+
if (value === undefined)
|
|
277
|
+
continue;
|
|
278
|
+
headers.set(key, Array.isArray(value) ? value.join(", ") : value);
|
|
279
|
+
}
|
|
280
|
+
return headers;
|
|
281
|
+
}
|
|
282
|
+
export async function startClaudeCodeProxy(options) {
|
|
283
|
+
const host = options.host ?? DEFAULT_PROXY_HOST;
|
|
284
|
+
if (!isLoopbackHost(host))
|
|
285
|
+
throw new Error("the proxy listens on loopback only");
|
|
286
|
+
const proxy = createClaudeCodeProxy(options);
|
|
287
|
+
const server = createServer((req, res) => {
|
|
288
|
+
const controller = new AbortController();
|
|
289
|
+
res.on("close", () => {
|
|
290
|
+
if (!res.writableFinished)
|
|
291
|
+
controller.abort();
|
|
292
|
+
});
|
|
293
|
+
void (async () => {
|
|
294
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
295
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
296
|
+
// 400 rather than 5xx for every local failure: Claude Code retries 5xx,
|
|
297
|
+
// and a malformed target must not take the whole proxy down.
|
|
298
|
+
let response;
|
|
299
|
+
try {
|
|
300
|
+
const request = new Request(new URL(req.url ?? "/", `http://${host}`), {
|
|
301
|
+
method,
|
|
302
|
+
headers: toHeaders(req.headers),
|
|
303
|
+
body: hasBody ? Readable.toWeb(req) : null,
|
|
304
|
+
duplex: "half",
|
|
305
|
+
});
|
|
306
|
+
response = await proxy.handle(request, controller.signal);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
response = anthropicError(400, PROTECT_FAILED_ERROR);
|
|
310
|
+
}
|
|
311
|
+
const headers = {};
|
|
312
|
+
response.headers.forEach((value, key) => {
|
|
313
|
+
if (key !== "set-cookie")
|
|
314
|
+
headers[key] = value;
|
|
315
|
+
});
|
|
316
|
+
const cookies = response.headers.getSetCookie();
|
|
317
|
+
if (cookies.length > 0)
|
|
318
|
+
headers["set-cookie"] = cookies;
|
|
319
|
+
res.writeHead(response.status, headers);
|
|
320
|
+
if (response.body === null) {
|
|
321
|
+
res.end();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const body = Readable.fromWeb(response.body);
|
|
325
|
+
// A restore failure mid-stream must cut the connection, not end it
|
|
326
|
+
// cleanly: a clean end would look like a complete reply.
|
|
327
|
+
body.on("error", () => res.destroy());
|
|
328
|
+
body.pipe(res);
|
|
329
|
+
})().catch(() => res.destroy());
|
|
330
|
+
});
|
|
331
|
+
await new Promise((resolve, reject) => {
|
|
332
|
+
server.once("error", reject);
|
|
333
|
+
server.listen(options.port ?? DEFAULT_PROXY_PORT, host, () => {
|
|
334
|
+
server.off("error", reject);
|
|
335
|
+
resolve();
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
const address = server.address();
|
|
339
|
+
return {
|
|
340
|
+
url: `http://${host}:${address.port}`,
|
|
341
|
+
server,
|
|
342
|
+
close: () => new Promise((resolve) => {
|
|
343
|
+
server.close(() => resolve());
|
|
344
|
+
server.closeAllConnections();
|
|
345
|
+
proxy.dispose();
|
|
346
|
+
}),
|
|
347
|
+
};
|
|
348
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode's declared coverage, printed by `leakshield --doctor`.
|
|
3
|
+
*
|
|
4
|
+
* The HTTP and WebSocket rows hold only in transparent mode with wire
|
|
5
|
+
* protection on; hook-first installs register no outbound hooks and report
|
|
6
|
+
* PARTIAL for install-level reasons instead. Non-fetch transports are not
|
|
7
|
+
* audited yet, so the host is capped at PARTIAL until a probe closes that row.
|
|
8
|
+
*/
|
|
9
|
+
import type { HostCapabilities } from "../../types/capabilities.js";
|
|
10
|
+
export declare const OPENCODE_CAPABILITIES: HostCapabilities;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export const OPENCODE_CAPABILITIES = {
|
|
2
|
+
host: "opencode",
|
|
3
|
+
verifiedVersion: "2.2.5",
|
|
4
|
+
interception: "in-process-host-hook",
|
|
5
|
+
transports: {
|
|
6
|
+
http: {
|
|
7
|
+
state: "protected",
|
|
8
|
+
mechanism: "core.onHttpRequest over the host's http.request hook (transparent mode, wire protection on)",
|
|
9
|
+
evidence: "tests/opencode-transparent.test.ts",
|
|
10
|
+
note: "Hook-first (wireProtection: false) registers no outbound hook: later-added content can leave unmasked and the doctor reports PARTIAL.",
|
|
11
|
+
},
|
|
12
|
+
websocket: {
|
|
13
|
+
state: "protected",
|
|
14
|
+
mechanism: "core.onWsHandshake / onWsSend over experimental.ws.* (Responses family, wire protection on)",
|
|
15
|
+
evidence: "tests/opencode-transparent-ws.test.ts",
|
|
16
|
+
note: "Responses-family flat response.create frames only; other dialects are not adapted.",
|
|
17
|
+
},
|
|
18
|
+
nonFetch: {
|
|
19
|
+
state: "unknown",
|
|
20
|
+
mechanism: "no probe yet for Bedrock, Vertex or SDK-internal transports",
|
|
21
|
+
note: "Unaudited (#110). The OpenCode verdict stays PARTIAL until a probe records what these transports carry.",
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
surfaces: {
|
|
25
|
+
toolArgs: {
|
|
26
|
+
state: "protected",
|
|
27
|
+
mechanism: "the tool gate restores known safe arguments and refuses unsafe mappings",
|
|
28
|
+
evidence: "tests/opencode-tool-policy.test.ts",
|
|
29
|
+
note: "A tool holding a placeholder can still send it; `curl` and `http` restore inside an argument by design. Unlike pi, unknown tools restore by field instead of refusing, because they run in the host process (ADR-0001, ADR-0006).",
|
|
30
|
+
},
|
|
31
|
+
replyDisplay: {
|
|
32
|
+
state: "protected",
|
|
33
|
+
mechanism: "core.onHttpResponse / onWsReceive, attributed to the masked request",
|
|
34
|
+
evidence: "tests/opencode-transparent-recovery.test.ts",
|
|
35
|
+
},
|
|
36
|
+
background: {
|
|
37
|
+
state: "protected",
|
|
38
|
+
mechanism: "core.protectRequestKind on the context, compaction, generate and title payload hooks",
|
|
39
|
+
evidence: "tests/opencode-transparent.test.ts",
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
credentials: "in-process",
|
|
43
|
+
persistence: "opt-in",
|
|
44
|
+
residuals: [
|
|
45
|
+
"transports.http: hook-first installs (wireProtection: false) register no outbound HTTP hook; /alpha/generate is untouched there and refused with wire protection on.",
|
|
46
|
+
"surfaces.toolArgs: a tool holding a placeholder can send it; curl and http restore inside an argument by design.",
|
|
47
|
+
],
|
|
48
|
+
};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `leakshield --doctor` — install-level verification for the OpenCode
|
|
3
|
+
* plugin (Phase 1a of the transparent-hardening plan).
|
|
4
|
+
*
|
|
5
|
+
* The doctor answers one question: "is this machine's OpenCode configured so
|
|
6
|
+
* that LeakShield is actually loaded, with valid options and a working
|
|
7
|
+
* scanner?" It runs OUTSIDE the OpenCode host, so it can verify configuration,
|
|
8
|
+
* registration shape, plugin options, and the local scanner — but it cannot
|
|
9
|
+
* see inside a live session. Runtime registration is proven by the boundary
|
|
10
|
+
* harness (scripts/e2e/run-boundary.mjs) and the documented smoke test.
|
|
11
|
+
*
|
|
12
|
+
* Statuses:
|
|
13
|
+
* - PROTECTED registered + dist present + options valid + config loads + smoke passes
|
|
14
|
+
* - PARTIAL transparent hook-only mode (wireProtection=false): no final-body inspection
|
|
15
|
+
* - BROKEN something is registered but would not work (dist missing / invalid options /
|
|
16
|
+
* guard config broken / smoke fails), or the host is OpenCode v1, which is
|
|
17
|
+
* no longer supported (the package only blocks its model requests)
|
|
18
|
+
* - NOT_REGISTERED host found, config found or absent, but LeakShield is not in it
|
|
19
|
+
* - HOST_MISSING no usable `opencode` binary on PATH
|
|
20
|
+
*/
|
|
21
|
+
import { type PluginOptions } from "../../guard-options.js";
|
|
22
|
+
import type { DoctorCheck, DoctorReport } from "../../doctor-report.js";
|
|
23
|
+
import type { GuardConfig } from "../../types.js";
|
|
24
|
+
export interface DoctorDeps {
|
|
25
|
+
opencodeVersion(): string | null;
|
|
26
|
+
readIfExists(filePath: string): string | null;
|
|
27
|
+
existsDir(p: string): boolean;
|
|
28
|
+
existsFile(p: string): boolean;
|
|
29
|
+
/** W2/B5: optional store-health probe (session count only). Defaults to a
|
|
30
|
+
* throwaway-key open — counting needs no decryption. */
|
|
31
|
+
openStoreProbe?(storePath: string, ttlDays: number): {
|
|
32
|
+
sessions: number;
|
|
33
|
+
} | {
|
|
34
|
+
error: string;
|
|
35
|
+
};
|
|
36
|
+
loadGuardConfig(overridePath: string | undefined, workspaceRoot: string): GuardConfig;
|
|
37
|
+
smokeScan(text: string, config: GuardConfig): {
|
|
38
|
+
findings: number;
|
|
39
|
+
};
|
|
40
|
+
/** Severity-agnostic scan for the allowlist diagnostics. Defaults to the real
|
|
41
|
+
* scanner; `smokeScan` is a HIGH-only credential probe and would call a
|
|
42
|
+
* working MEDIUM/LOW allowlist entry dead. `exact` lists the findings whose
|
|
43
|
+
* text is exactly this input, tagged so doctor can ignore diagnostics that an
|
|
44
|
+
* allowlist cannot suppress (the Unicode/homograph warning is one). */
|
|
45
|
+
probeScan?(text: string, config: GuardConfig): {
|
|
46
|
+
findings: number;
|
|
47
|
+
exact: {
|
|
48
|
+
description: string | null;
|
|
49
|
+
unicodeWarning: boolean;
|
|
50
|
+
}[];
|
|
51
|
+
};
|
|
52
|
+
cwd: string;
|
|
53
|
+
home: string;
|
|
54
|
+
xdgConfigHome?: string;
|
|
55
|
+
}
|
|
56
|
+
export declare function createDoctorDeps(): DoctorDeps;
|
|
57
|
+
/** Tolerant JSONC parse: strips line and block comments plus trailing commas,
|
|
58
|
+
* then falls back to plain JSON.parse errors when still invalid. */
|
|
59
|
+
export declare function parseJsonc(text: string): unknown;
|
|
60
|
+
/**
|
|
61
|
+
* W2 (B5) persistence status — a warn/ok/skip check, never a status flip:
|
|
62
|
+
* a degraded store weakens nothing (the plugin degrades to memory-only);
|
|
63
|
+
* the check exists so "enabled but silently not working" is visible here
|
|
64
|
+
* instead of only as a setup-time console WARN (decision §4.6).
|
|
65
|
+
*/
|
|
66
|
+
export declare function persistenceCheck(options: PluginOptions, deps: DoctorDeps): DoctorCheck;
|
|
67
|
+
export declare function runDoctor(deps: DoctorDeps): Promise<DoctorReport>;
|
|
@@ -23,14 +23,14 @@ import fs from "node:fs";
|
|
|
23
23
|
import os from "node:os";
|
|
24
24
|
import path from "node:path";
|
|
25
25
|
import { fileURLToPath } from "node:url";
|
|
26
|
-
import { loadConfig } from "
|
|
27
|
-
import { defaultKeyfilePath, defaultStorePath } from "
|
|
28
|
-
import { InMemoryMappingKeyProvider, openMappingStore } from "
|
|
29
|
-
import { validatePluginOptions } from "
|
|
30
|
-
import { BUILTIN_RULE_IDS } from "
|
|
31
|
-
import { skippedCustomRules, customRuleBoundaries } from "
|
|
32
|
-
import { allowlistSuppressions } from "
|
|
33
|
-
import { scanText } from "
|
|
26
|
+
import { loadConfig } from "../../config/loader.js";
|
|
27
|
+
import { defaultKeyfilePath, defaultStorePath } from "../../decision/mapping-key.js";
|
|
28
|
+
import { InMemoryMappingKeyProvider, openMappingStore } from "../../decision/mapping-store.js";
|
|
29
|
+
import { validatePluginOptions } from "../../guard-options.js";
|
|
30
|
+
import { BUILTIN_RULE_IDS } from "../../rules/builtin.js";
|
|
31
|
+
import { skippedCustomRules, customRuleBoundaries } from "../../rules/dynamic.js";
|
|
32
|
+
import { allowlistSuppressions } from "../../scanner/allowlist.js";
|
|
33
|
+
import { scanText } from "../../scanner/engine.js";
|
|
34
34
|
const SMOKE_CANARY = "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA";
|
|
35
35
|
/**
|
|
36
36
|
* Severity-agnostic probe for the allowlist diagnostics: every finding, plus
|
|
@@ -633,7 +633,7 @@ export async function runDoctor(deps) {
|
|
|
633
633
|
id: "options",
|
|
634
634
|
state: "fail",
|
|
635
635
|
detail: `Plugin options are invalid for "${entry.ref}" (${entry.source}) — every protected request would fail closed at runtime: ${validation.error}`,
|
|
636
|
-
fix:
|
|
636
|
+
fix: 'Correct the options in opencode.json (valid combinations: the "OpenCode Plugin" section of README.md and docs/plugin/env-queries.md).',
|
|
637
637
|
});
|
|
638
638
|
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
|
|
639
639
|
}
|
|
@@ -642,6 +642,9 @@ export async function runDoctor(deps) {
|
|
|
642
642
|
const weakness = (candidate) => candidate.mode === "transparent" ? (candidate.wireProtection === false ? 0 : 1) : 2;
|
|
643
643
|
const weakest = [...validated].sort((a, b) => weakness(a.options) - weakness(b.options))[0];
|
|
644
644
|
const options = weakest.options;
|
|
645
|
+
const wireProtection = options.mode !== "transparent"
|
|
646
|
+
? "not-applicable"
|
|
647
|
+
: options.wireProtection === false ? "disabled" : "enabled";
|
|
645
648
|
// Attachments are reported conservatively too: any transparent entry that
|
|
646
649
|
// lets them through unscanned outranks a stricter tied entry (#67).
|
|
647
650
|
if (options.mode === "transparent" &&
|
|
@@ -652,9 +655,17 @@ export async function runDoctor(deps) {
|
|
|
652
655
|
checks.push({
|
|
653
656
|
id: "options",
|
|
654
657
|
state: "ok",
|
|
655
|
-
detail: `mode=${options.mode}${weakest.entry.options?.mode === undefined ? " (default)" : ""}${options.mode === "transparent" ? ` wireProtection=${options.wireProtection ?? true}` : ""}${options.attachments === "allow" ? " attachments=allow" : ""}${options.deidentify ? " +deidentify" : ""}${options.envQueries ? " +envQueries" : ""}${options.configPath ? ` configPath=${options.configPath}` : ""}${across}`,
|
|
658
|
+
detail: `mode=${options.mode}${weakest.entry.options?.mode === undefined ? " (default)" : ""}${options.mode === "transparent" ? ` wireProtection=${options.wireProtection ?? true}` : ""}${options.attachments === "allow" ? " attachments=allow" : ""}${options.deidentify ? " +deidentify" : ""}${options.envQueries ? (options.mode === "transparent" ? " +envQueries(ignored)" : " +envQueries") : ""}${options.configPath ? ` configPath=${options.configPath}` : ""}${across}`,
|
|
656
659
|
});
|
|
657
660
|
checks.push(persistenceCheck(options, deps));
|
|
661
|
+
if (validated.some((candidate) => candidate.options.mode === "transparent" && candidate.options.envQueries)) {
|
|
662
|
+
checks.push({
|
|
663
|
+
id: "env-queries",
|
|
664
|
+
state: "warn",
|
|
665
|
+
detail: "envQueries is ignored in transparent mode; the guard_env_* tools are not registered.",
|
|
666
|
+
fix: 'Remove envQueries, or set mode to "block" or "redact" to use the env query tools.',
|
|
667
|
+
});
|
|
668
|
+
}
|
|
658
669
|
// Guard config load. Every configured entry's guard config must load: the
|
|
659
670
|
// weakest entry supplies the summary, but a broken configPath in another
|
|
660
671
|
// entry still breaks the install it would run under (#67).
|
|
@@ -675,7 +686,7 @@ export async function runDoctor(deps) {
|
|
|
675
686
|
detail: `Guard config failed to load${guardPath ? ` for ${guardPath}` : ""}: ${error.message}`,
|
|
676
687
|
fix: "Fix the config file, or remove configPath to use defaults.",
|
|
677
688
|
});
|
|
678
|
-
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
|
|
689
|
+
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks, wireProtection };
|
|
679
690
|
}
|
|
680
691
|
}
|
|
681
692
|
if (!guardConfig) {
|
|
@@ -685,7 +696,7 @@ export async function runDoctor(deps) {
|
|
|
685
696
|
detail: "Guard config did not load for the entry that decides the verdict.",
|
|
686
697
|
fix: "Rerun the doctor; if it repeats, report the configuration.",
|
|
687
698
|
});
|
|
688
|
-
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
|
|
699
|
+
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks, wireProtection };
|
|
689
700
|
}
|
|
690
701
|
checks.push({
|
|
691
702
|
id: "guard-config",
|
|
@@ -844,12 +855,12 @@ export async function runDoctor(deps) {
|
|
|
844
855
|
detail: `Synthetic sk- canary NOT detected${smokeFailures[0].path ? ` under ${smokeFailures[0].path}` : ""} — that guard config disables the rules this install relies on.`,
|
|
845
856
|
fix: "Restore credential rules in the guard config, or remove configPath to use defaults.",
|
|
846
857
|
});
|
|
847
|
-
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
|
|
858
|
+
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks, wireProtection };
|
|
848
859
|
}
|
|
849
860
|
// A failed check must not still read as PARTIAL or PROTECTED: an allowlist
|
|
850
861
|
// failure is a "do not trust this install" signal, like a missing canary.
|
|
851
862
|
if (checks.some((check) => check.state === "fail")) {
|
|
852
|
-
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
|
|
863
|
+
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks, wireProtection };
|
|
853
864
|
}
|
|
854
865
|
if (options.mode === "transparent") {
|
|
855
866
|
checks.push({
|
|
@@ -863,34 +874,5 @@ export async function runDoctor(deps) {
|
|
|
863
874
|
state: "warn",
|
|
864
875
|
detail: "Install-level checks pass. Live-session proof: run the README smoke test or scripts/e2e/run-boundary.mjs.",
|
|
865
876
|
});
|
|
866
|
-
return { status: options.mode === "transparent" && options.wireProtection === false ? "PARTIAL" : "PROTECTED", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
|
|
867
|
-
}
|
|
868
|
-
export function formatDoctorReport(report) {
|
|
869
|
-
const icon = { ok: "[OK] ", warn: "[WARN]", fail: "[FAIL]", skip: "[SKIP]" };
|
|
870
|
-
const lines = [];
|
|
871
|
-
lines.push(`leakshield doctor — ${new Date().toISOString()}`);
|
|
872
|
-
for (const check of report.checks) {
|
|
873
|
-
lines.push(`${icon[check.state]} ${check.id}: ${check.detail}`);
|
|
874
|
-
if (check.fix)
|
|
875
|
-
lines.push(` fix: ${check.fix}`);
|
|
876
|
-
}
|
|
877
|
-
if (report.snippet) {
|
|
878
|
-
lines.push("");
|
|
879
|
-
lines.push("Registration snippet for your opencode.json:");
|
|
880
|
-
lines.push(report.snippet);
|
|
881
|
-
}
|
|
882
|
-
lines.push("");
|
|
883
|
-
const verdict = report.status === "PROTECTED"
|
|
884
|
-
? "PROTECTED — install-level checks pass."
|
|
885
|
-
: report.status === "PARTIAL"
|
|
886
|
-
? "PARTIAL — hook-first protection; final outbound HTTP bodies are not inspected."
|
|
887
|
-
: report.status === "BROKEN"
|
|
888
|
-
? "BROKEN — registered but would not protect; fix the [FAIL] items above."
|
|
889
|
-
: report.status === "NOT_REGISTERED"
|
|
890
|
-
? "NOT REGISTERED — LeakShield is not in the OpenCode config; sessions are unprotected."
|
|
891
|
-
: "HOST MISSING — no OpenCode binary found.";
|
|
892
|
-
lines.push(verdict);
|
|
893
|
-
lines.push("");
|
|
894
|
-
lines.push("Scope: model-conversation leak protection. This is NOT a tool-egress firewall: permitted local tools (curl, remote MCP, …) can still transmit originals. See README.");
|
|
895
|
-
return lines.join("\n");
|
|
877
|
+
return { status: options.mode === "transparent" && options.wireProtection === false ? "PARTIAL" : "PROTECTED", hostVersion: host.version, hostGeneration: host.generation, configPath, checks, wireProtection };
|
|
896
878
|
}
|