leakshield 0.3.0 → 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.
Files changed (110) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +2 -0
  3. package/README.md +39 -9
  4. package/README.zh-TW.md +38 -9
  5. package/dist/adapters/claude-code/capabilities.d.ts +14 -0
  6. package/dist/adapters/claude-code/capabilities.js +47 -0
  7. package/dist/adapters/claude-code/cli.d.ts +10 -0
  8. package/dist/adapters/claude-code/cli.js +51 -0
  9. package/dist/adapters/claude-code/doctor.d.ts +19 -0
  10. package/dist/adapters/claude-code/doctor.js +177 -0
  11. package/dist/adapters/claude-code/proxy.d.ts +47 -0
  12. package/dist/adapters/claude-code/proxy.js +348 -0
  13. package/dist/adapters/opencode/capabilities.d.ts +10 -0
  14. package/dist/adapters/opencode/capabilities.js +48 -0
  15. package/dist/adapters/opencode/doctor.d.ts +67 -0
  16. package/dist/{doctor.js → adapters/opencode/doctor.js} +16 -42
  17. package/dist/adapters/opencode/env-queries.d.ts +133 -0
  18. package/dist/adapters/opencode/env-tools.d.ts +20 -0
  19. package/dist/adapters/opencode/hooks.d.ts +4 -0
  20. package/dist/adapters/opencode/plugin.d.ts +12 -0
  21. package/dist/{opencode.js → adapters/opencode/plugin.js} +7 -7
  22. package/dist/adapters/opencode/tool-policy.d.ts +2 -0
  23. package/dist/adapters/opencode/tool-policy.js +23 -0
  24. package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
  25. package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
  26. package/dist/adapters/opencode/transparent.d.ts +66 -0
  27. package/dist/adapters/opencode/transparent.js +237 -0
  28. package/dist/adapters/opencode/v2.d.ts +20 -0
  29. package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
  30. package/dist/adapters/pi/capabilities.d.ts +10 -0
  31. package/dist/adapters/pi/capabilities.js +50 -0
  32. package/dist/adapters/pi/doctor.d.ts +26 -0
  33. package/dist/adapters/pi/doctor.js +276 -0
  34. package/dist/adapters/pi/extension.d.ts +28 -0
  35. package/dist/adapters/pi/extension.js +109 -0
  36. package/dist/adapters/pi/guard.d.ts +33 -0
  37. package/dist/adapters/pi/guard.js +154 -0
  38. package/dist/adapters/pi/persistence.d.ts +9 -0
  39. package/dist/adapters/pi/persistence.js +69 -0
  40. package/dist/adapters/pi/settings.d.ts +51 -0
  41. package/dist/adapters/pi/settings.js +136 -0
  42. package/dist/adapters/pi/tool-policy.d.ts +11 -0
  43. package/dist/adapters/pi/tool-policy.js +114 -0
  44. package/dist/cli.d.ts +18 -0
  45. package/dist/cli.js +17 -6
  46. package/dist/config/loader.d.ts +70 -0
  47. package/dist/config/plain-object.d.ts +2 -0
  48. package/dist/core/index.d.ts +9 -0
  49. package/dist/core/index.js +9 -0
  50. package/dist/core/session-guard.d.ts +61 -0
  51. package/dist/{opencode-transparent.js → core/session-guard.js} +55 -713
  52. package/dist/core/sse-recovery.d.ts +6 -0
  53. package/dist/core/tool-restore-policy.d.ts +153 -0
  54. package/dist/core/tool-restore-policy.js +453 -0
  55. package/dist/core/wire.d.ts +213 -0
  56. package/dist/{opencode-transparent-http.js → core/wire.js} +170 -50
  57. package/dist/core/ws.d.ts +26 -0
  58. package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
  59. package/dist/decision/deidentify.d.ts +63 -0
  60. package/dist/decision/ingress.d.ts +40 -0
  61. package/dist/decision/mapping-key.d.ts +91 -0
  62. package/dist/decision/mapping-store.d.ts +166 -0
  63. package/dist/decision/model.d.ts +41 -0
  64. package/dist/decision/pseudonymization.d.ts +176 -0
  65. package/dist/decision/redaction.d.ts +56 -0
  66. package/dist/decision/schema-strings.d.ts +23 -0
  67. package/dist/decision/schema-strings.js +2 -2
  68. package/dist/decision/value-search.d.ts +39 -0
  69. package/dist/doctor-capabilities.d.ts +21 -0
  70. package/dist/doctor-capabilities.js +58 -0
  71. package/dist/doctor-hosts.d.ts +18 -0
  72. package/dist/doctor-hosts.js +144 -0
  73. package/dist/doctor-report.d.ts +45 -0
  74. package/dist/doctor-report.js +111 -0
  75. package/dist/forget.d.ts +18 -0
  76. package/dist/guard-options.d.ts +45 -0
  77. package/dist/{plugin-options.js → guard-options.js} +4 -1
  78. package/dist/help.d.ts +2 -0
  79. package/dist/help.js +15 -1
  80. package/dist/i18n/en.d.ts +65 -0
  81. package/dist/i18n/index.d.ts +15 -0
  82. package/dist/i18n/zh-TW.d.ts +65 -0
  83. package/dist/index.d.ts +13 -0
  84. package/dist/index.js +1 -1
  85. package/dist/rules/builtin.d.ts +4 -0
  86. package/dist/rules/dynamic.d.ts +33 -0
  87. package/dist/scanner/allowlist.d.ts +22 -0
  88. package/dist/scanner/cidr.d.ts +39 -0
  89. package/dist/scanner/encoding.d.ts +87 -0
  90. package/dist/scanner/engine.d.ts +43 -0
  91. package/dist/scanner/exact-values.d.ts +11 -0
  92. package/dist/scanner/redaction-verifier.d.ts +24 -0
  93. package/dist/scanner/remotes.d.ts +29 -0
  94. package/dist/scanner/unicode.d.ts +57 -0
  95. package/dist/scanner/utils.d.ts +22 -0
  96. package/dist/transports/cli.d.ts +27 -0
  97. package/dist/transports/web-ui.d.ts +1 -0
  98. package/dist/transports/web-ui.js +1 -1
  99. package/dist/transports/web.d.ts +4 -0
  100. package/dist/types/capabilities.d.ts +67 -0
  101. package/dist/types/capabilities.js +133 -0
  102. package/dist/types.d.ts +149 -0
  103. package/dist/utils/files.d.ts +3 -0
  104. package/dist/utils/path-security.d.ts +18 -0
  105. package/dist/utils/win-encoding.d.ts +16 -0
  106. package/package.json +15 -5
  107. /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
  108. /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
  109. /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
  110. /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
@@ -0,0 +1,177 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { DEFAULT_PROXY_HOST, DEFAULT_PROXY_PORT, HEALTH_PATH, HEALTH_SERVICE } from "./proxy.js";
6
+ const PROXY_URL = `http://${DEFAULT_PROXY_HOST}:${DEFAULT_PROXY_PORT}`;
7
+ const ALTERNATE_PROVIDERS = ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"];
8
+ export function createClaudeCodeDoctorDeps() {
9
+ return {
10
+ claudeVersion() {
11
+ try {
12
+ const r = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 4000 });
13
+ if (r.error || (r.status !== null && r.status !== 0))
14
+ return null;
15
+ return (r.stdout || "").trim() || null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ },
21
+ readIfExists(filePath) {
22
+ try {
23
+ return fs.readFileSync(filePath, "utf8");
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ },
29
+ async probeProxy(baseUrl) {
30
+ try {
31
+ const response = await fetch(new URL(HEALTH_PATH, baseUrl), { signal: AbortSignal.timeout(2000) });
32
+ const body = await response.json().catch(() => null);
33
+ if (response.ok && typeof body === "object" && body !== null && body.service === HEALTH_SERVICE) {
34
+ const upstream = body.upstream;
35
+ return { ok: true, upstream: typeof upstream === "string" ? upstream : null };
36
+ }
37
+ return { ok: false, reason: "not-leakshield" };
38
+ }
39
+ catch {
40
+ return { ok: false, reason: "unreachable" };
41
+ }
42
+ },
43
+ env: process.env,
44
+ cwd: process.cwd(),
45
+ home: os.homedir(),
46
+ };
47
+ }
48
+ /**
49
+ * Claude Code applies settings `env` over the shell, and among settings files
50
+ * the more specific one wins: project local, then project, then user.
51
+ * Returned highest precedence first.
52
+ */
53
+ function envSources(deps) {
54
+ const configDir = deps.env.CLAUDE_CONFIG_DIR || path.join(deps.home, ".claude");
55
+ const files = [
56
+ path.join(deps.cwd, ".claude", "settings.local.json"),
57
+ path.join(deps.cwd, ".claude", "settings.json"),
58
+ path.join(configDir, "settings.json"),
59
+ ];
60
+ const sources = [];
61
+ const broken = [];
62
+ for (const file of files) {
63
+ const raw = deps.readIfExists(file);
64
+ if (raw === null)
65
+ continue;
66
+ try {
67
+ const parsed = JSON.parse(raw);
68
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : undefined;
69
+ if (typeof env === "object" && env !== null && !Array.isArray(env)) {
70
+ sources.push({ label: file, env: env });
71
+ }
72
+ }
73
+ catch {
74
+ broken.push(file);
75
+ }
76
+ }
77
+ sources.push({ label: "shell environment of this doctor run", env: { ...deps.env } });
78
+ return { sources, broken };
79
+ }
80
+ function effective(sources, key) {
81
+ for (const source of sources) {
82
+ const value = source.env[key];
83
+ if (typeof value === "string" && value.length > 0)
84
+ return { value, source: source.label };
85
+ }
86
+ return null;
87
+ }
88
+ function isLoopbackUrl(raw) {
89
+ try {
90
+ const host = new URL(raw).hostname;
91
+ return host === "127.0.0.1" || host === "localhost" || host === "[::1]";
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ }
97
+ /** Claude Code checks, independent of the OpenCode checks and their status. */
98
+ export async function runClaudeCodeDoctor(deps) {
99
+ const checks = [];
100
+ const version = deps.claudeVersion();
101
+ if (version === null) {
102
+ checks.push({ id: "claude-code", state: "skip", detail: "claude binary not found on PATH; Claude Code checks skipped." });
103
+ return checks;
104
+ }
105
+ checks.push({ id: "claude-code", state: "ok", detail: version });
106
+ const { sources, broken } = envSources(deps);
107
+ for (const file of broken) {
108
+ checks.push({
109
+ id: "claude-code-settings",
110
+ state: "warn",
111
+ detail: `${file} is not valid JSON; its env block was not read.`,
112
+ fix: "Fix the syntax, then rerun this doctor.",
113
+ });
114
+ }
115
+ const provider = ALTERNATE_PROVIDERS.map((key) => effective(sources, key)).find((hit) => hit !== null && hit.value !== "0" && hit.value !== "false");
116
+ if (provider) {
117
+ checks.push({
118
+ id: "claude-code-provider",
119
+ state: "warn",
120
+ detail: `A Bedrock/Vertex/Foundry provider is enabled (from ${provider.source}); those requests bypass ANTHROPIC_BASE_URL and the LeakShield proxy.`,
121
+ fix: "Unset it to send Claude Code through the Anthropic API and the proxy.",
122
+ });
123
+ }
124
+ if (deps.env.CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST) {
125
+ checks.push({
126
+ id: "claude-code-host-managed",
127
+ state: "warn",
128
+ detail: "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST is set in this shell; Claude Code then ignores ANTHROPIC_BASE_URL from settings files, and the embedding app decides the endpoint.",
129
+ fix: "Set ANTHROPIC_BASE_URL in the environment that launches Claude Code, or check the embedding app's provider settings.",
130
+ });
131
+ }
132
+ const baseUrl = effective(sources, "ANTHROPIC_BASE_URL");
133
+ if (baseUrl === null) {
134
+ checks.push({
135
+ id: "claude-code-proxy",
136
+ state: "warn",
137
+ detail: "ANTHROPIC_BASE_URL is not set, so Claude Code talks to Anthropic directly and is not protected.",
138
+ fix: `Run \`leakshield --claude-code-proxy\`, then set ANTHROPIC_BASE_URL=${PROXY_URL} in your shell or in the "env" block of ~/.claude/settings.json.`,
139
+ });
140
+ return checks;
141
+ }
142
+ const probe = await deps.probeProxy(baseUrl.value);
143
+ if (probe.ok) {
144
+ checks.push({
145
+ id: "claude-code-proxy",
146
+ state: "ok",
147
+ detail: `ANTHROPIC_BASE_URL=${baseUrl.value} (from ${baseUrl.source}) is the LeakShield proxy${probe.upstream ? `, forwarding to ${probe.upstream}` : ""}.`,
148
+ });
149
+ }
150
+ else if (probe.reason === "unreachable" && isLoopbackUrl(baseUrl.value)) {
151
+ checks.push({
152
+ id: "claude-code-proxy",
153
+ state: "fail",
154
+ detail: `ANTHROPIC_BASE_URL=${baseUrl.value} (from ${baseUrl.source}) points at a local address where nothing answers; Claude Code requests will fail until the proxy runs.`,
155
+ fix: "Start it with `leakshield --claude-code-proxy` (add `--port` if you changed the port).",
156
+ });
157
+ }
158
+ else {
159
+ checks.push({
160
+ id: "claude-code-proxy",
161
+ state: "warn",
162
+ detail: `ANTHROPIC_BASE_URL=${baseUrl.value} (from ${baseUrl.source}) is not the LeakShield proxy, so Claude Code is not protected.`,
163
+ fix: `Run \`leakshield --claude-code-proxy\` and set ANTHROPIC_BASE_URL=${PROXY_URL}.`,
164
+ });
165
+ }
166
+ if (sources.length > 1 && baseUrl.source !== sources[sources.length - 1].label) {
167
+ const shell = sources[sources.length - 1].env.ANTHROPIC_BASE_URL;
168
+ if (typeof shell === "string" && shell.length > 0 && shell !== baseUrl.value) {
169
+ checks.push({
170
+ id: "claude-code-env",
171
+ state: "warn",
172
+ detail: `This shell sets ANTHROPIC_BASE_URL=${shell}, but ${baseUrl.source} overrides it inside Claude Code.`,
173
+ });
174
+ }
175
+ }
176
+ return checks;
177
+ }
@@ -0,0 +1,47 @@
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 { type Server } from "node:http";
18
+ import type { GuardConfig } from "../../types.js";
19
+ export declare const DEFAULT_PROXY_HOST = "127.0.0.1";
20
+ export declare const DEFAULT_PROXY_PORT = 8787;
21
+ export declare const DEFAULT_UPSTREAM = "https://api.anthropic.com";
22
+ export declare const HEALTH_PATH = "/__leakshield/health";
23
+ export declare const HEALTH_SERVICE = "leakshield-claude-code-proxy";
24
+ export interface ClaudeCodeProxyOptions {
25
+ config: GuardConfig;
26
+ upstream?: string;
27
+ attachments?: "block" | "allow";
28
+ fetch?: typeof fetch;
29
+ log?: (line: string) => void;
30
+ }
31
+ export interface ClaudeCodeProxy {
32
+ readonly upstream: string;
33
+ handle(request: Request, signal?: AbortSignal): Promise<Response>;
34
+ dispose(): void;
35
+ }
36
+ /** Plain http is accepted only for a loopback upstream (a local stub or gateway). */
37
+ export declare function parseUpstream(raw: string): URL;
38
+ export declare function createClaudeCodeProxy(options: ClaudeCodeProxyOptions): ClaudeCodeProxy;
39
+ export interface RunningClaudeCodeProxy {
40
+ readonly url: string;
41
+ readonly server: Server;
42
+ close(): Promise<void>;
43
+ }
44
+ export declare function startClaudeCodeProxy(options: ClaudeCodeProxyOptions & {
45
+ port?: number;
46
+ host?: string;
47
+ }): Promise<RunningClaudeCodeProxy>;
@@ -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
+ };