leakshield 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -5
- package/README.zh-TW.md +34 -5
- 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} +16 -42
- 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} +7 -7
- 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 +66 -0
- package/dist/adapters/opencode/transparent.js +237 -0
- package/dist/adapters/opencode/v2.d.ts +20 -0
- package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
- 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/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 +61 -0
- package/dist/{opencode-transparent.js → core/session-guard.js} +55 -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/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} +4 -1
- 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/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/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 +11 -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,26 @@
|
|
|
1
|
+
import type { DoctorCheck } from "../../doctor-report.js";
|
|
2
|
+
export declare const MINIMUM_PI_MINOR = 6;
|
|
3
|
+
export interface PiDoctorDeps {
|
|
4
|
+
piVersion(): string | null;
|
|
5
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
6
|
+
readFile(filePath: string): string | null;
|
|
7
|
+
fileExists(filePath: string): boolean;
|
|
8
|
+
home: string;
|
|
9
|
+
cwd: string;
|
|
10
|
+
extensionPath(): string;
|
|
11
|
+
/** Loads the guard config the extension would use. */
|
|
12
|
+
checkConfig(): string | null;
|
|
13
|
+
}
|
|
14
|
+
export declare function parsePiVersion(raw: string): {
|
|
15
|
+
major: number;
|
|
16
|
+
minor: number;
|
|
17
|
+
} | null;
|
|
18
|
+
/** Index of the LeakShield entry in `settings.extensions`, or -1. */
|
|
19
|
+
export declare function extensionIndex(entries: readonly string[], extensionPath: string, cwd: string, agentDir: string): number;
|
|
20
|
+
export declare function runPiDoctor(deps: PiDoctorDeps): Promise<DoctorCheck[]>;
|
|
21
|
+
/**
|
|
22
|
+
* The extension ships next to this module in dist/adapters/pi/. A source checkout run
|
|
23
|
+
* through tsx uses the TypeScript file, which pi can load directly.
|
|
24
|
+
*/
|
|
25
|
+
export declare function defaultPiExtensionPath(): string;
|
|
26
|
+
export declare function createPiDoctorDeps(extensionPath?: string): PiDoctorDeps;
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi adapter checks for `leakshield --doctor`.
|
|
3
|
+
*
|
|
4
|
+
* In-process protection has no launcher to inspect, so the checks answer the
|
|
5
|
+
* questions that decide whether pi will actually run behind the guard: is the
|
|
6
|
+
* extension built, is it registered ahead of every other extension, does the
|
|
7
|
+
* guard config load, and does the selected model use a wire API that goes
|
|
8
|
+
* through fetch. Like the Claude Code checks, they never read or print a
|
|
9
|
+
* credential value.
|
|
10
|
+
*/
|
|
11
|
+
import { spawnSync } from "node:child_process";
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import os from "node:os";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { loadConfig } from "../../config/loader.js";
|
|
17
|
+
import { piPersistenceOptions } from "./persistence.js";
|
|
18
|
+
import { defaultPiAgentDir, isSupportedPiApi, loadPiUserAgent, resolveExtensionEntry, resolvePiSelectedModel, } from "./settings.js";
|
|
19
|
+
export const MINIMUM_PI_MINOR = 6;
|
|
20
|
+
const PI_API_LIST = "openai-completions, openai-responses or anthropic-messages";
|
|
21
|
+
export function parsePiVersion(raw) {
|
|
22
|
+
const match = /^(\d+)\.(\d+)/.exec(raw.trim());
|
|
23
|
+
if (match === null)
|
|
24
|
+
return null;
|
|
25
|
+
return { major: Number(match[1]), minor: Number(match[2]) };
|
|
26
|
+
}
|
|
27
|
+
function agentDirOf(deps) {
|
|
28
|
+
return deps.env.PI_CODING_AGENT_DIR ?? defaultPiAgentDir(deps.home);
|
|
29
|
+
}
|
|
30
|
+
function samePath(left, right) {
|
|
31
|
+
try {
|
|
32
|
+
return fs.realpathSync(left) === fs.realpathSync(right);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return path.resolve(left) === path.resolve(right);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Index of the LeakShield entry in `settings.extensions`, or -1. */
|
|
39
|
+
export function extensionIndex(entries, extensionPath, cwd, agentDir) {
|
|
40
|
+
return entries.findIndex((entry) => resolveExtensionEntry(entry, cwd, agentDir).some((candidate) => samePath(candidate, extensionPath)));
|
|
41
|
+
}
|
|
42
|
+
/** Inspect the standard user npm install or a local package, without loading it.
|
|
43
|
+
* Resource filters and actual extension ordering need host/runtime inspection.
|
|
44
|
+
* A valid registration anywhere in the list wins; otherwise the first broken
|
|
45
|
+
* or unverifiable LeakShield entry is reported. */
|
|
46
|
+
function packageRegistrationCheck(agent, deps) {
|
|
47
|
+
const check = (state, detail) => ({
|
|
48
|
+
id: "pi-extension-registered", state, detail,
|
|
49
|
+
});
|
|
50
|
+
let fallback = null;
|
|
51
|
+
for (const entry of agent.settings.packages ?? []) {
|
|
52
|
+
const options = entry !== null && typeof entry === "object" && !Array.isArray(entry)
|
|
53
|
+
? entry : undefined;
|
|
54
|
+
const source = typeof entry === "string" ? entry : options?.source;
|
|
55
|
+
if (typeof source !== "string")
|
|
56
|
+
continue;
|
|
57
|
+
const npm = /^npm:leakshield(?:@[^\s]+)?$/.test(source);
|
|
58
|
+
const local = path.isAbsolute(source) || /^(?:\.{1,2}|~)[\\/]/.test(source);
|
|
59
|
+
if (!npm && !local)
|
|
60
|
+
continue;
|
|
61
|
+
const root = npm ? path.join(agent.agentDir, "npm", "node_modules", "leakshield")
|
|
62
|
+
: /^~[\\/]/.test(source) ? path.join(deps.home, source.slice(2)) : path.resolve(agent.agentDir, source);
|
|
63
|
+
let manifest = null;
|
|
64
|
+
try {
|
|
65
|
+
const raw = deps.readFile(path.join(root, "package.json"));
|
|
66
|
+
if (raw !== null)
|
|
67
|
+
manifest = JSON.parse(raw);
|
|
68
|
+
}
|
|
69
|
+
catch { /* An unreadable manifest cannot verify registration. */ }
|
|
70
|
+
if (!npm && manifest?.name !== "leakshield")
|
|
71
|
+
continue;
|
|
72
|
+
if (manifest?.name !== "leakshield") {
|
|
73
|
+
fallback ??= check("fail", `LeakShield is configured in settings.packages but its installed manifest is missing or invalid at ${root}. Reinstall the package.`);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (options?.extensions !== undefined) {
|
|
77
|
+
fallback ??= Array.isArray(options.extensions) && options.extensions.length === 0
|
|
78
|
+
? check("fail", "LeakShield's settings.packages entry disables all extensions.")
|
|
79
|
+
: check("skip", "LeakShield has package extension filters; this check cannot verify that they enable the guard. Inspect pi config or register the extension path explicitly.");
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const extension = path.join(root, "dist", "adapters", "pi", "extension.js");
|
|
83
|
+
if (!Array.isArray(manifest.pi?.extensions) || !manifest.pi.extensions.some((entry) => typeof entry === "string" && path.resolve(root, entry) === extension) || !deps.fileExists(extension)) {
|
|
84
|
+
fallback ??= check("fail", `LeakShield's package at ${root} does not provide its declared pi extension. Install a version that includes pi support.`);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
return check("warn", `LeakShield is registered in settings.packages (${source}); its manifest and extension exist. Package/CLI/project load order is not verified; earlier extensions can retain the raw fetch.`);
|
|
88
|
+
}
|
|
89
|
+
return fallback;
|
|
90
|
+
}
|
|
91
|
+
/** Adds a hint, without changing the state, when settings.packages also names LeakShield. */
|
|
92
|
+
function withDuplicateNote(agent, deps, registered) {
|
|
93
|
+
if (packageRegistrationCheck(agent, deps) === null)
|
|
94
|
+
return registered;
|
|
95
|
+
return {
|
|
96
|
+
...registered,
|
|
97
|
+
detail: `${registered.detail}. LeakShield is also listed in settings.packages, so pi may load it twice; keep only one registration.`,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export async function runPiDoctor(deps) {
|
|
101
|
+
const checks = [];
|
|
102
|
+
const version = deps.piVersion();
|
|
103
|
+
if (version === null) {
|
|
104
|
+
checks.push({ id: "pi", state: "skip", detail: "pi binary not found on PATH; pi checks skipped." });
|
|
105
|
+
return checks;
|
|
106
|
+
}
|
|
107
|
+
const parsed = parsePiVersion(version);
|
|
108
|
+
if (parsed === null || parsed.major !== 1 || parsed.minor < MINIMUM_PI_MINOR) {
|
|
109
|
+
checks.push({
|
|
110
|
+
id: "pi",
|
|
111
|
+
state: "fail",
|
|
112
|
+
detail: `pi ${version} is not supported; this adapter needs >= 1.${MINIMUM_PI_MINOR} < 2.`,
|
|
113
|
+
fix: "Upgrade pi before relying on the LeakShield extension.",
|
|
114
|
+
});
|
|
115
|
+
return checks;
|
|
116
|
+
}
|
|
117
|
+
checks.push({ id: "pi", state: "ok", detail: `pi ${version}` });
|
|
118
|
+
const extensionPath = deps.extensionPath();
|
|
119
|
+
checks.push(deps.fileExists(extensionPath)
|
|
120
|
+
? { id: "pi-extension", state: "ok", detail: `extension ${extensionPath}` }
|
|
121
|
+
: {
|
|
122
|
+
id: "pi-extension",
|
|
123
|
+
state: "fail",
|
|
124
|
+
detail: `the extension is missing at ${extensionPath}; this build is incomplete.`,
|
|
125
|
+
fix: "Reinstall leakshield (the package must ship dist/adapters/pi/extension.js).",
|
|
126
|
+
});
|
|
127
|
+
const configError = deps.checkConfig();
|
|
128
|
+
checks.push(configError === null
|
|
129
|
+
? { id: "pi-config", state: "ok", detail: "guard configuration loads (checked from this shell's directory)" }
|
|
130
|
+
: {
|
|
131
|
+
id: "pi-config",
|
|
132
|
+
state: "fail",
|
|
133
|
+
detail: `guard configuration could not be loaded: ${configError}`,
|
|
134
|
+
fix: "Fix the guard config, or point LEAKSHIELD_CONFIG at the intended file. pi exits instead of running unprotected.",
|
|
135
|
+
});
|
|
136
|
+
try {
|
|
137
|
+
const persistence = piPersistenceOptions(deps.env);
|
|
138
|
+
checks.push(persistence === undefined
|
|
139
|
+
? { id: "pi-persistence", state: "ok", detail: "mapping persistence is off; mappings last for the process" }
|
|
140
|
+
: {
|
|
141
|
+
id: "pi-persistence",
|
|
142
|
+
state: "ok",
|
|
143
|
+
detail: `mapping persistence is on (ttl ${persistence.ttlDays}d, ${persistence.path})`,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
checks.push({
|
|
148
|
+
id: "pi-persistence",
|
|
149
|
+
state: "fail",
|
|
150
|
+
detail: `persistence configuration is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
151
|
+
fix: "Fix the LEAKSHIELD_PI_PERSIST* values, or unset them; pi refuses to load the extension with an invalid value.",
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
let agent = null;
|
|
155
|
+
try {
|
|
156
|
+
agent = loadPiUserAgent(agentDirOf(deps), deps.readFile);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
checks.push({
|
|
160
|
+
id: "pi-settings",
|
|
161
|
+
state: "fail",
|
|
162
|
+
detail: `pi configuration could not be read: ${error instanceof Error ? error.message : String(error)}`,
|
|
163
|
+
fix: "Fix the JSON, or rerun with PI_CODING_AGENT_DIR pointing at the intended agent directory.",
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
if (agent !== null) {
|
|
167
|
+
const entries = (agent.settings.extensions ?? []).filter((entry) => typeof entry === "string");
|
|
168
|
+
const index = extensionIndex(entries, extensionPath, deps.cwd, agent.agentDir);
|
|
169
|
+
if (index === -1) {
|
|
170
|
+
checks.push(packageRegistrationCheck(agent, deps) ?? {
|
|
171
|
+
id: "pi-extension-registered",
|
|
172
|
+
state: "skip",
|
|
173
|
+
detail: "LeakShield was not verified in user settings.extensions or supported settings.packages entries; CLI -e and project/git packages are not verified here.",
|
|
174
|
+
fix: `Add "${extensionPath}" first in settings.extensions to make this check meaningful, or keep using -e (which always loads before settings extensions).`,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
else if (index > 0) {
|
|
178
|
+
const earlier = entries.slice(0, index).join(", ");
|
|
179
|
+
checks.push(withDuplicateNote(agent, deps, {
|
|
180
|
+
id: "pi-extension-registered",
|
|
181
|
+
state: "warn",
|
|
182
|
+
detail: `LeakShield is extension #${index + 1}; ${earlier} loads first and can keep the raw fetch. pi's own requests are still guarded.`,
|
|
183
|
+
fix: "Move the LeakShield entry to the top of settings.extensions so no earlier extension can hold the raw fetch.",
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
checks.push(withDuplicateNote(agent, deps, {
|
|
188
|
+
id: "pi-extension-registered",
|
|
189
|
+
state: "ok",
|
|
190
|
+
detail: "LeakShield is the first entry of settings.extensions (CLI -e and package entries are not visible to this check)",
|
|
191
|
+
}));
|
|
192
|
+
}
|
|
193
|
+
const selected = resolvePiSelectedModel(agent, deps.env);
|
|
194
|
+
if (selected === null) {
|
|
195
|
+
checks.push({
|
|
196
|
+
id: "pi-provider",
|
|
197
|
+
state: "skip",
|
|
198
|
+
detail: "no provider selected in settings; the guard checks the model at session start.",
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
else if (selected.api === undefined) {
|
|
202
|
+
checks.push({
|
|
203
|
+
id: "pi-provider",
|
|
204
|
+
state: "warn",
|
|
205
|
+
detail: `${selected.provider}${selected.model !== undefined ? ` / ${selected.model}` : ""} declares no api; a built-in provider default applies.`,
|
|
206
|
+
fix: `Declare "api" in pi's models.json (${PI_API_LIST}), or confirm the model at runtime.`,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
else if (!isSupportedPiApi(selected.api)) {
|
|
210
|
+
checks.push({
|
|
211
|
+
id: "pi-provider",
|
|
212
|
+
state: "fail",
|
|
213
|
+
detail: `${selected.provider}${selected.model !== undefined ? ` / ${selected.model}` : ""} uses api ${selected.api}, which does not go through fetch; the extension refuses the run.`,
|
|
214
|
+
fix: `Select a model with ${PI_API_LIST}, or keep this provider for a host that can guard it.`,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
checks.push({
|
|
219
|
+
id: "pi-provider",
|
|
220
|
+
state: "ok",
|
|
221
|
+
detail: `${selected.provider}${selected.model !== undefined ? ` / ${selected.model}` : ""} (${selected.api})`,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return checks;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The extension ships next to this module in dist/adapters/pi/. A source checkout run
|
|
229
|
+
* through tsx uses the TypeScript file, which pi can load directly.
|
|
230
|
+
*/
|
|
231
|
+
export function defaultPiExtensionPath() {
|
|
232
|
+
const built = fileURLToPath(new URL("./extension.js", import.meta.url));
|
|
233
|
+
if (fs.existsSync(built))
|
|
234
|
+
return built;
|
|
235
|
+
const source = fileURLToPath(new URL("./extension.ts", import.meta.url));
|
|
236
|
+
return fs.existsSync(source) ? source : built;
|
|
237
|
+
}
|
|
238
|
+
export function createPiDoctorDeps(extensionPath = defaultPiExtensionPath()) {
|
|
239
|
+
return {
|
|
240
|
+
piVersion() {
|
|
241
|
+
const result = spawnSync("pi", ["--version"], { encoding: "utf8", timeout: 4000 });
|
|
242
|
+
if (result.error || (result.status !== null && result.status !== 0))
|
|
243
|
+
return null;
|
|
244
|
+
return (result.stdout || "").trim() || null;
|
|
245
|
+
},
|
|
246
|
+
env: process.env,
|
|
247
|
+
readFile(filePath) {
|
|
248
|
+
try {
|
|
249
|
+
return fs.readFileSync(filePath, "utf8");
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
fileExists(filePath) {
|
|
256
|
+
try {
|
|
257
|
+
return fs.existsSync(filePath);
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
home: os.homedir(),
|
|
264
|
+
cwd: process.cwd(),
|
|
265
|
+
extensionPath: () => extensionPath,
|
|
266
|
+
checkConfig() {
|
|
267
|
+
try {
|
|
268
|
+
loadConfig(process.env.LEAKSHIELD_CONFIG, process.cwd());
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
return error instanceof Error ? error.message : String(error);
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type PiGuardModel } from "./guard.js";
|
|
2
|
+
export declare const PI_EXTENSION_ID = "leakshield-pi";
|
|
3
|
+
export declare const UNPROTECTED_NOTICE = "LeakShield blocked this run: provider requests for the selected model cannot be protected in-process.";
|
|
4
|
+
export interface PiSessionManager {
|
|
5
|
+
getSessionId(): string;
|
|
6
|
+
}
|
|
7
|
+
export interface PiContext {
|
|
8
|
+
sessionManager: PiSessionManager;
|
|
9
|
+
model?: PiGuardModel;
|
|
10
|
+
ui?: {
|
|
11
|
+
notify(message: string, level?: string): void;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export interface PiToolCallEvent {
|
|
15
|
+
toolName: string;
|
|
16
|
+
toolCallId?: string;
|
|
17
|
+
input: unknown;
|
|
18
|
+
}
|
|
19
|
+
export interface PiModelSelectEvent {
|
|
20
|
+
model: PiGuardModel;
|
|
21
|
+
}
|
|
22
|
+
type Handler = (event: never, ctx: PiContext) => unknown;
|
|
23
|
+
/** The subset of pi's ExtensionAPI this adapter registers. */
|
|
24
|
+
export interface PiExtensionApi {
|
|
25
|
+
on(event: string, handler: Handler): void;
|
|
26
|
+
}
|
|
27
|
+
export default function leakshieldPiExtension(pi: PiExtensionApi): void;
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi extension: the in-process LeakShield boundary.
|
|
3
|
+
*
|
|
4
|
+
* Loaded by pi from an extension path (`-e <path>` or `settings.extensions`),
|
|
5
|
+
* it wraps `globalThis.fetch` before any provider client is built, so every
|
|
6
|
+
* model request on the three supported wire APIs is masked by the shared core
|
|
7
|
+
* and assistant text is restored in the reply. Tool arguments are restored at
|
|
8
|
+
* `tool_call`, and unknown tools are refused instead of receiving placeholders.
|
|
9
|
+
*
|
|
10
|
+
* There is no launcher: pi keeps its own provider configuration and credential.
|
|
11
|
+
* Load order matters, because an extension loaded earlier can hold the raw
|
|
12
|
+
* fetch; the doctor reports when LeakShield is not first.
|
|
13
|
+
*/
|
|
14
|
+
import { loadConfig } from "../../config/loader.js";
|
|
15
|
+
import { createPiGuard, PROTECT_FAILED } from "./guard.js";
|
|
16
|
+
import { piPersistenceOptions } from "./persistence.js";
|
|
17
|
+
const GUARD_KEY = Symbol.for("leakshield.pi.guard");
|
|
18
|
+
export const PI_EXTENSION_ID = "leakshield-pi";
|
|
19
|
+
export const UNPROTECTED_NOTICE = "LeakShield blocked this run: provider requests for the selected model cannot be protected in-process.";
|
|
20
|
+
function guardConfig() {
|
|
21
|
+
const config = loadConfig(process.env.LEAKSHIELD_CONFIG, process.cwd());
|
|
22
|
+
return { ...config, settings: { ...config.settings, encoding_detection: true } };
|
|
23
|
+
}
|
|
24
|
+
function notice(ctx, message) {
|
|
25
|
+
if (ctx?.ui)
|
|
26
|
+
ctx.ui.notify(message, "error");
|
|
27
|
+
else
|
|
28
|
+
console.error(`[${PI_EXTENSION_ID}] ${message}`);
|
|
29
|
+
}
|
|
30
|
+
function refusalText(error) {
|
|
31
|
+
if (error instanceof Error && error.message.startsWith("LeakShield "))
|
|
32
|
+
return error.message;
|
|
33
|
+
return PROTECT_FAILED;
|
|
34
|
+
}
|
|
35
|
+
function installGuard() {
|
|
36
|
+
const existing = globalThis[GUARD_KEY];
|
|
37
|
+
if (existing !== undefined)
|
|
38
|
+
return existing;
|
|
39
|
+
const guard = createPiGuard({ config: guardConfig(), persistence: piPersistenceOptions(process.env) });
|
|
40
|
+
guard.install();
|
|
41
|
+
Object.defineProperty(globalThis, GUARD_KEY, { value: guard, configurable: true });
|
|
42
|
+
return guard;
|
|
43
|
+
}
|
|
44
|
+
export default function leakshieldPiExtension(pi) {
|
|
45
|
+
const guard = installGuard();
|
|
46
|
+
let refusal = guard.refusal;
|
|
47
|
+
let announced = null;
|
|
48
|
+
const announce = (ctx, reason) => {
|
|
49
|
+
if (announced === reason)
|
|
50
|
+
return;
|
|
51
|
+
announced = reason;
|
|
52
|
+
notice(ctx, reason);
|
|
53
|
+
};
|
|
54
|
+
const applyModel = (model, ctx) => {
|
|
55
|
+
guard.setModel(model ?? null);
|
|
56
|
+
refusal = guard.refusal;
|
|
57
|
+
if (refusal === null)
|
|
58
|
+
announced = null;
|
|
59
|
+
else
|
|
60
|
+
announce(ctx, refusal);
|
|
61
|
+
};
|
|
62
|
+
pi.on("session_start", (_event, ctx) => {
|
|
63
|
+
guard.setSession(ctx.sessionManager.getSessionId());
|
|
64
|
+
applyModel(ctx.model, ctx);
|
|
65
|
+
});
|
|
66
|
+
pi.on("model_select", (event, ctx) => {
|
|
67
|
+
applyModel(event.model, ctx);
|
|
68
|
+
});
|
|
69
|
+
// The model is re-read at each run so a switch that skipped `model_select`
|
|
70
|
+
// cannot leave the guard bound to a previous provider.
|
|
71
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
72
|
+
applyModel(ctx.model, ctx);
|
|
73
|
+
});
|
|
74
|
+
const cancelIfRefused = (ctx) => {
|
|
75
|
+
if (refusal === null)
|
|
76
|
+
return undefined;
|
|
77
|
+
announce(ctx, refusal);
|
|
78
|
+
return { cancel: true };
|
|
79
|
+
};
|
|
80
|
+
pi.on("input", (_event, ctx) => {
|
|
81
|
+
// Re-read the model here too: this is the last hook before a run starts,
|
|
82
|
+
// and `before_agent_start` cannot cancel one. Extension-authored input is
|
|
83
|
+
// refused as well, because it can start a request on an API the guard
|
|
84
|
+
// cannot see.
|
|
85
|
+
applyModel(ctx.model, ctx);
|
|
86
|
+
if (refusal === null)
|
|
87
|
+
return { action: "continue" };
|
|
88
|
+
announce(ctx, refusal);
|
|
89
|
+
return { action: "handled" };
|
|
90
|
+
});
|
|
91
|
+
// Manual compaction and /tree summarization invoke the model without an
|
|
92
|
+
// input or before_agent_start event, so they need their own refusal gate.
|
|
93
|
+
pi.on("session_before_compact", (_event, ctx) => cancelIfRefused(ctx));
|
|
94
|
+
pi.on("session_before_tree", (_event, ctx) => cancelIfRefused(ctx));
|
|
95
|
+
pi.on("tool_call", (event, _ctx) => {
|
|
96
|
+
const toolEvent = event;
|
|
97
|
+
if (refusal !== null)
|
|
98
|
+
return { block: true, reason: refusal, terminate: true };
|
|
99
|
+
try {
|
|
100
|
+
const restored = guard.restoreTool(toolEvent.toolName, toolEvent.input);
|
|
101
|
+
if (restored !== toolEvent.input)
|
|
102
|
+
toolEvent.input = restored;
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
return { block: true, reason: refusalText(error), terminate: true };
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createGuardCore, type GuardPersistenceOptions } from "../../core/session-guard.js";
|
|
2
|
+
import type { GuardConfig } from "../../types.js";
|
|
3
|
+
export { SUPPORTED_PI_APIS } from "./settings.js";
|
|
4
|
+
export declare const PROTECT_FAILED = "LeakShield could not protect this provider request. [protect]";
|
|
5
|
+
export declare const UNSUPPORTED_ROUTE = "LeakShield refused a provider request on a route it cannot mask. [route]";
|
|
6
|
+
export declare const UNSUPPORTED_MODEL = "LeakShield cannot protect the selected model: pi's transport for this API does not go through fetch. Use an openai-completions, openai-responses or anthropic-messages model.";
|
|
7
|
+
export declare const MISSING_SESSION = "LeakShield refused a provider request before a session was active. [session]";
|
|
8
|
+
export interface PiGuardModel {
|
|
9
|
+
api: string;
|
|
10
|
+
provider: string;
|
|
11
|
+
id: string;
|
|
12
|
+
baseUrl: string;
|
|
13
|
+
}
|
|
14
|
+
export interface PiGuard {
|
|
15
|
+
/** The reason the current model cannot be protected, or null. */
|
|
16
|
+
readonly refusal: string | null;
|
|
17
|
+
setSession(sessionID: string | null): void;
|
|
18
|
+
setModel(model: PiGuardModel | null): void;
|
|
19
|
+
/** Handles one fetch call: provider traffic is guarded, everything else passes through. */
|
|
20
|
+
handle(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
|
|
21
|
+
/** Restores placeholders in a pi tool call, refusing unknown tools. */
|
|
22
|
+
restoreTool(tool: string, input: unknown): unknown;
|
|
23
|
+
/** Points globalThis.fetch at this guard. */
|
|
24
|
+
install(): void;
|
|
25
|
+
}
|
|
26
|
+
export interface PiGuardOptions {
|
|
27
|
+
config: GuardConfig;
|
|
28
|
+
/** Encrypted mapping store; omitted means process-lifetime mappings. */
|
|
29
|
+
persistence?: GuardPersistenceOptions;
|
|
30
|
+
fetchImpl?: typeof fetch;
|
|
31
|
+
createCore?: typeof createGuardCore;
|
|
32
|
+
}
|
|
33
|
+
export declare function createPiGuard(options: PiGuardOptions): PiGuard;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process provider boundary for pi.
|
|
3
|
+
*
|
|
4
|
+
* pi's provider SDKs resolve `fetch` when they issue a request, so an
|
|
5
|
+
* extension that replaces `globalThis.fetch` sees every model request on the
|
|
6
|
+
* three supported wire APIs. The wrapper sends those requests through the
|
|
7
|
+
* shared guard core, which masks them and restores the assistant text of the
|
|
8
|
+
* reply. Anything that is not provider traffic passes through untouched.
|
|
9
|
+
*
|
|
10
|
+
* The boundary is only as wide as this process: transports that do not use
|
|
11
|
+
* `fetch` (OpenAI Codex over WebSocket, Bedrock, Google service-account auth)
|
|
12
|
+
* are refused by model/API check rather than guarded here.
|
|
13
|
+
*/
|
|
14
|
+
import { classifyModelRoute } from "../../core/wire.js";
|
|
15
|
+
import { createGuardCore } from "../../core/session-guard.js";
|
|
16
|
+
import { isSupportedPiApi } from "./settings.js";
|
|
17
|
+
import { assertPiToolBoundary, piToolPolicy } from "./tool-policy.js";
|
|
18
|
+
export { SUPPORTED_PI_APIS } from "./settings.js";
|
|
19
|
+
export const PROTECT_FAILED = "LeakShield could not protect this provider request. [protect]";
|
|
20
|
+
export const UNSUPPORTED_ROUTE = "LeakShield refused a provider request on a route it cannot mask. [route]";
|
|
21
|
+
export const UNSUPPORTED_MODEL = "LeakShield cannot protect the selected model: pi's transport for this API does not go through fetch. Use an openai-completions, openai-responses or anthropic-messages model.";
|
|
22
|
+
export const MISSING_SESSION = "LeakShield refused a provider request before a session was active. [session]";
|
|
23
|
+
function urlOf(input) {
|
|
24
|
+
if (typeof input === "string")
|
|
25
|
+
return input;
|
|
26
|
+
if (input instanceof URL)
|
|
27
|
+
return input.href;
|
|
28
|
+
return input.url;
|
|
29
|
+
}
|
|
30
|
+
function methodOf(input, init) {
|
|
31
|
+
if (typeof init?.method === "string")
|
|
32
|
+
return init.method.toUpperCase();
|
|
33
|
+
if (input instanceof Request)
|
|
34
|
+
return input.method.toUpperCase();
|
|
35
|
+
return "GET";
|
|
36
|
+
}
|
|
37
|
+
function originOf(baseUrl) {
|
|
38
|
+
try {
|
|
39
|
+
const url = new URL(baseUrl);
|
|
40
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
41
|
+
return null;
|
|
42
|
+
return url.hostname.length > 0 ? url.origin : null;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function refusalText(error) {
|
|
49
|
+
if (error instanceof Error && error.message.startsWith("LeakShield "))
|
|
50
|
+
return error.message;
|
|
51
|
+
return PROTECT_FAILED;
|
|
52
|
+
}
|
|
53
|
+
function refusalResponse(message) {
|
|
54
|
+
return new Response(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message } }), {
|
|
55
|
+
status: 400,
|
|
56
|
+
headers: { "content-type": "application/json" },
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
export function createPiGuard(options) {
|
|
60
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
61
|
+
const core = (options.createCore ?? createGuardCore)(options.config, "block", true, options.persistence, { anthropicThinking: "mask" }, piToolPolicy);
|
|
62
|
+
let sessionID = null;
|
|
63
|
+
let model = null;
|
|
64
|
+
let origin = null;
|
|
65
|
+
let invalidBase = false;
|
|
66
|
+
const refusal = () => {
|
|
67
|
+
if (core === null)
|
|
68
|
+
return PROTECT_FAILED;
|
|
69
|
+
if (model === null)
|
|
70
|
+
return UNSUPPORTED_MODEL;
|
|
71
|
+
if (invalidBase || !isSupportedPiApi(model.api))
|
|
72
|
+
return UNSUPPORTED_MODEL;
|
|
73
|
+
return null;
|
|
74
|
+
};
|
|
75
|
+
const guard = {
|
|
76
|
+
get refusal() {
|
|
77
|
+
return refusal();
|
|
78
|
+
},
|
|
79
|
+
setSession(next) {
|
|
80
|
+
sessionID = next !== null && next.length > 0 ? next : null;
|
|
81
|
+
},
|
|
82
|
+
setModel(next) {
|
|
83
|
+
model = next;
|
|
84
|
+
origin = next === null ? null : originOf(next.baseUrl);
|
|
85
|
+
invalidBase = next !== null && origin === null;
|
|
86
|
+
},
|
|
87
|
+
async handle(input, init) {
|
|
88
|
+
const url = urlOf(input);
|
|
89
|
+
const route = classifyModelRoute(url);
|
|
90
|
+
// A model-shaped POST is guarded wherever it goes: a missed or skipped
|
|
91
|
+
// model switch must not fail open just because the origin changed.
|
|
92
|
+
// Other provider-origin routes are classified below (GET passes, an
|
|
93
|
+
// unknown POST is refused).
|
|
94
|
+
let isProvider = route !== null;
|
|
95
|
+
if (!isProvider && origin !== null) {
|
|
96
|
+
try {
|
|
97
|
+
isProvider = new URL(url).origin === origin;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// An unparsable URL cannot be sent by fetch either; let it surface
|
|
101
|
+
// the native error instead of masking it as a guard refusal.
|
|
102
|
+
return fetchImpl(input, init);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (!isProvider)
|
|
106
|
+
return fetchImpl(input, init);
|
|
107
|
+
// Model catalogs and response lookups are read-only and carry no
|
|
108
|
+
// conversation. They also keep features like OpenRouter's key catalog.
|
|
109
|
+
const method = methodOf(input, init);
|
|
110
|
+
if (method === "GET" || method === "HEAD")
|
|
111
|
+
return fetchImpl(input, init);
|
|
112
|
+
const reason = refusal() ?? (sessionID === null ? MISSING_SESSION : null);
|
|
113
|
+
if (reason !== null)
|
|
114
|
+
return refusalResponse(reason);
|
|
115
|
+
if (route === null)
|
|
116
|
+
return refusalResponse(UNSUPPORTED_ROUTE);
|
|
117
|
+
let request;
|
|
118
|
+
try {
|
|
119
|
+
request = input instanceof Request && init === undefined ? input : new Request(input, init);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return refusalResponse(PROTECT_FAILED);
|
|
123
|
+
}
|
|
124
|
+
const masked = { sessionID, request };
|
|
125
|
+
try {
|
|
126
|
+
await core.onHttpRequest(masked);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
return refusalResponse(refusalText(error));
|
|
130
|
+
}
|
|
131
|
+
const sent = masked.request;
|
|
132
|
+
// Network errors and aborts are not masking failures: propagate them so
|
|
133
|
+
// the SDK keeps its retry/cancel semantics. The request is already masked.
|
|
134
|
+
const response = await fetchImpl(sent);
|
|
135
|
+
const reply = { sessionID, request: sent, response };
|
|
136
|
+
await core.onHttpResponse(reply);
|
|
137
|
+
return reply.response;
|
|
138
|
+
},
|
|
139
|
+
restoreTool(tool, input) {
|
|
140
|
+
if (core === null)
|
|
141
|
+
throw new Error(PROTECT_FAILED);
|
|
142
|
+
if (sessionID === null)
|
|
143
|
+
throw new Error(MISSING_SESSION);
|
|
144
|
+
assertPiToolBoundary(tool, input);
|
|
145
|
+
const event = { sessionID, tool, input };
|
|
146
|
+
core.onToolBefore(event);
|
|
147
|
+
return event.input;
|
|
148
|
+
},
|
|
149
|
+
install() {
|
|
150
|
+
globalThis.fetch = (input, init) => guard.handle(input, init);
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
return guard;
|
|
154
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { GuardPersistenceOptions } from "../../core/session-guard.js";
|
|
2
|
+
export declare const PI_PERSIST_ENV = "LEAKSHIELD_PI_PERSIST";
|
|
3
|
+
export declare const PI_PERSIST_TTL_ENV = "LEAKSHIELD_PI_PERSIST_TTL_DAYS";
|
|
4
|
+
export declare const PI_PERSIST_PATH_ENV = "LEAKSHIELD_PI_PERSIST_PATH";
|
|
5
|
+
export declare const PI_PERSIST_KEYFILE_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE";
|
|
6
|
+
export declare const PI_PERSIST_KEYFILE_PATH_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE_PATH";
|
|
7
|
+
export declare const DEFAULT_PERSIST_TTL_DAYS = 7;
|
|
8
|
+
export declare const MAX_PERSIST_TTL_DAYS = 3650;
|
|
9
|
+
export declare function piPersistenceOptions(env: Readonly<Record<string, string | undefined>>): GuardPersistenceOptions | undefined;
|