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,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;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in mapping persistence for the pi extension.
|
|
3
|
+
*
|
|
4
|
+
* pi has no plugin-options channel, so the store is configured with
|
|
5
|
+
* environment variables. The defaults match the OpenCode plugin: off unless
|
|
6
|
+
* enabled, a 7-day session TTL, the default store path, and the same key
|
|
7
|
+
* custody ladder (OS keychain -> explicit keyfile -> memory-only).
|
|
8
|
+
*
|
|
9
|
+
* An invalid value refuses to load the extension instead of silently running
|
|
10
|
+
* without the store the user asked for.
|
|
11
|
+
*/
|
|
12
|
+
import { defaultStorePath } from "../../decision/mapping-key.js";
|
|
13
|
+
import { PERSISTENCE_TTL_DEFAULT_DAYS, PERSISTENCE_TTL_MAX_DAYS } from "../../guard-options.js";
|
|
14
|
+
export const PI_PERSIST_ENV = "LEAKSHIELD_PI_PERSIST";
|
|
15
|
+
export const PI_PERSIST_TTL_ENV = "LEAKSHIELD_PI_PERSIST_TTL_DAYS";
|
|
16
|
+
export const PI_PERSIST_PATH_ENV = "LEAKSHIELD_PI_PERSIST_PATH";
|
|
17
|
+
export const PI_PERSIST_KEYFILE_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE";
|
|
18
|
+
export const PI_PERSIST_KEYFILE_PATH_ENV = "LEAKSHIELD_PI_PERSIST_KEYFILE_PATH";
|
|
19
|
+
export const DEFAULT_PERSIST_TTL_DAYS = PERSISTENCE_TTL_DEFAULT_DAYS;
|
|
20
|
+
export const MAX_PERSIST_TTL_DAYS = PERSISTENCE_TTL_MAX_DAYS;
|
|
21
|
+
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
|
22
|
+
const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
|
|
23
|
+
function invalid(name, expected) {
|
|
24
|
+
throw new Error(`LeakShield: ${name} ${expected}`);
|
|
25
|
+
}
|
|
26
|
+
function parseFlag(raw, name) {
|
|
27
|
+
if (raw === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
const value = raw.trim().toLowerCase();
|
|
30
|
+
if (value.length === 0)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (TRUE_VALUES.has(value))
|
|
33
|
+
return true;
|
|
34
|
+
if (FALSE_VALUES.has(value))
|
|
35
|
+
return false;
|
|
36
|
+
return invalid(name, "must be 1/true/yes or 0/false/no");
|
|
37
|
+
}
|
|
38
|
+
function nonEmpty(raw, name) {
|
|
39
|
+
if (raw === undefined)
|
|
40
|
+
return undefined;
|
|
41
|
+
const value = raw.trim();
|
|
42
|
+
if (value.length === 0)
|
|
43
|
+
return undefined;
|
|
44
|
+
if (value.length > 4096)
|
|
45
|
+
return invalid(name, "is too long");
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
function parseTtl(raw) {
|
|
49
|
+
const value = nonEmpty(raw, PI_PERSIST_TTL_ENV);
|
|
50
|
+
if (value === undefined)
|
|
51
|
+
return DEFAULT_PERSIST_TTL_DAYS;
|
|
52
|
+
if (!/^\d+$/.test(value))
|
|
53
|
+
return invalid(PI_PERSIST_TTL_ENV, "must be a whole number of days");
|
|
54
|
+
const days = Number(value);
|
|
55
|
+
if (!Number.isSafeInteger(days) || days > MAX_PERSIST_TTL_DAYS) {
|
|
56
|
+
return invalid(PI_PERSIST_TTL_ENV, `must be between 0 and ${MAX_PERSIST_TTL_DAYS}`);
|
|
57
|
+
}
|
|
58
|
+
return days;
|
|
59
|
+
}
|
|
60
|
+
export function piPersistenceOptions(env) {
|
|
61
|
+
if (parseFlag(env[PI_PERSIST_ENV], PI_PERSIST_ENV) !== true)
|
|
62
|
+
return undefined;
|
|
63
|
+
return {
|
|
64
|
+
ttlDays: parseTtl(env[PI_PERSIST_TTL_ENV]),
|
|
65
|
+
path: nonEmpty(env[PI_PERSIST_PATH_ENV], PI_PERSIST_PATH_ENV) ?? defaultStorePath(),
|
|
66
|
+
keyFile: parseFlag(env[PI_PERSIST_KEYFILE_ENV], PI_PERSIST_KEYFILE_ENV) === true,
|
|
67
|
+
keyfilePath: nonEmpty(env[PI_PERSIST_KEYFILE_PATH_ENV], PI_PERSIST_KEYFILE_PATH_ENV),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
interface PiModelEntry {
|
|
2
|
+
id?: string;
|
|
3
|
+
api?: string;
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
[key: string]: unknown;
|
|
7
|
+
}
|
|
8
|
+
interface PiProviderEntry {
|
|
9
|
+
baseUrl?: string;
|
|
10
|
+
api?: string;
|
|
11
|
+
apiKey?: string;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
models?: PiModelEntry[];
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
interface PiUserSettings {
|
|
17
|
+
defaultModel?: string;
|
|
18
|
+
defaultProvider?: string;
|
|
19
|
+
sessionDir?: string;
|
|
20
|
+
extensions?: unknown[];
|
|
21
|
+
packages?: unknown[];
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
export interface PiUserAgent {
|
|
25
|
+
agentDir: string;
|
|
26
|
+
settings: PiUserSettings;
|
|
27
|
+
providers: Record<string, PiProviderEntry>;
|
|
28
|
+
}
|
|
29
|
+
export declare const SUPPORTED_PI_APIS: ReadonlySet<string>;
|
|
30
|
+
export type PiApi = "openai-completions" | "openai-responses" | "anthropic-messages";
|
|
31
|
+
export declare function isSupportedPiApi(value: string): value is PiApi;
|
|
32
|
+
/** pi's default agent directory for a home path. */
|
|
33
|
+
export declare function defaultPiAgentDir(home: string): string;
|
|
34
|
+
/** Reads the user's pi agent configuration. Throws on malformed JSON. */
|
|
35
|
+
export declare function loadPiUserAgent(agentDir: string, readFile: (filePath: string) => string | null): PiUserAgent;
|
|
36
|
+
export interface PiSelectedModel {
|
|
37
|
+
provider: string;
|
|
38
|
+
model?: string;
|
|
39
|
+
api?: string;
|
|
40
|
+
baseUrl?: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The provider/model pi would start with. With a configured provider,
|
|
44
|
+
* `defaultModel` is a model id and may itself contain slashes. Without one it
|
|
45
|
+
* may be provider/id; like pi's resolver, the longest declared provider id
|
|
46
|
+
* followed by "/" wins.
|
|
47
|
+
*/
|
|
48
|
+
export declare function resolvePiSelectedModel(agent: PiUserAgent, env: Readonly<Record<string, string | undefined>>): PiSelectedModel | null;
|
|
49
|
+
/** Resolves an extension entry against the working directory, the agent directory and as given. */
|
|
50
|
+
export declare function resolveExtensionEntry(entry: string, cwd: string, agentDir: string): string[];
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi user settings as inputs to the extension and the doctor.
|
|
3
|
+
*
|
|
4
|
+
* The extension protects the process it runs in; it never rewrites pi's agent
|
|
5
|
+
* directory. This module only reads that configuration to answer what the
|
|
6
|
+
* doctor needs: which provider and model are selected, which wire API they
|
|
7
|
+
* use, and where the extension has to be registered.
|
|
8
|
+
*/
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
export const SUPPORTED_PI_APIS = new Set([
|
|
11
|
+
"openai-completions",
|
|
12
|
+
"openai-responses",
|
|
13
|
+
"anthropic-messages",
|
|
14
|
+
]);
|
|
15
|
+
export function isSupportedPiApi(value) {
|
|
16
|
+
return SUPPORTED_PI_APIS.has(value);
|
|
17
|
+
}
|
|
18
|
+
function isRecord(value) {
|
|
19
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
function parseJsonFile(raw, label) {
|
|
22
|
+
if (raw === null)
|
|
23
|
+
return undefined;
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(raw);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new Error(`${label} is not valid JSON`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function stringField(record, key, label) {
|
|
32
|
+
const value = record[key];
|
|
33
|
+
if (value === undefined)
|
|
34
|
+
return undefined;
|
|
35
|
+
if (typeof value !== "string" || value.length === 0)
|
|
36
|
+
throw new Error(`${label}.${key} must be a non-empty string`);
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
/** pi's default agent directory for a home path. */
|
|
40
|
+
export function defaultPiAgentDir(home) {
|
|
41
|
+
return path.join(home, ".pi", "agent");
|
|
42
|
+
}
|
|
43
|
+
/** Reads the user's pi agent configuration. Throws on malformed JSON. */
|
|
44
|
+
export function loadPiUserAgent(agentDir, readFile) {
|
|
45
|
+
const settingsRaw = readFile(path.join(agentDir, "settings.json"));
|
|
46
|
+
const settingsValue = parseJsonFile(settingsRaw, "pi settings.json");
|
|
47
|
+
if (settingsValue !== undefined && !isRecord(settingsValue))
|
|
48
|
+
throw new Error("pi settings.json must be a JSON object");
|
|
49
|
+
const settings = {};
|
|
50
|
+
if (settingsValue !== undefined) {
|
|
51
|
+
const model = stringField(settingsValue, "defaultModel", "pi settings.json");
|
|
52
|
+
const defaultProvider = stringField(settingsValue, "defaultProvider", "pi settings.json");
|
|
53
|
+
const sessionDir = stringField(settingsValue, "sessionDir", "pi settings.json");
|
|
54
|
+
if (model !== undefined)
|
|
55
|
+
settings.defaultModel = model;
|
|
56
|
+
if (defaultProvider !== undefined)
|
|
57
|
+
settings.defaultProvider = defaultProvider;
|
|
58
|
+
if (sessionDir !== undefined)
|
|
59
|
+
settings.sessionDir = sessionDir;
|
|
60
|
+
if (settingsValue.extensions !== undefined) {
|
|
61
|
+
if (!Array.isArray(settingsValue.extensions))
|
|
62
|
+
throw new Error("pi settings.json.extensions must be an array");
|
|
63
|
+
settings.extensions = settingsValue.extensions;
|
|
64
|
+
}
|
|
65
|
+
if (settingsValue.packages !== undefined) {
|
|
66
|
+
if (!Array.isArray(settingsValue.packages))
|
|
67
|
+
throw new Error("pi settings.json.packages must be an array");
|
|
68
|
+
settings.packages = settingsValue.packages;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const modelsRaw = readFile(path.join(agentDir, "models.json"));
|
|
72
|
+
const modelsValue = parseJsonFile(modelsRaw, "pi models.json");
|
|
73
|
+
if (modelsValue !== undefined && !isRecord(modelsValue))
|
|
74
|
+
throw new Error("pi models.json must be a JSON object");
|
|
75
|
+
const providers = {};
|
|
76
|
+
if (modelsValue !== undefined && modelsValue.providers !== undefined) {
|
|
77
|
+
if (!isRecord(modelsValue.providers))
|
|
78
|
+
throw new Error("pi models.json.providers must be an object");
|
|
79
|
+
for (const [id, entry] of Object.entries(modelsValue.providers)) {
|
|
80
|
+
if (!isRecord(entry))
|
|
81
|
+
throw new Error(`pi models.json.providers.${id} must be an object`);
|
|
82
|
+
if (entry.models !== undefined && !Array.isArray(entry.models)) {
|
|
83
|
+
throw new Error(`pi models.json.providers.${id}.models must be an array`);
|
|
84
|
+
}
|
|
85
|
+
if (entry.headers !== undefined) {
|
|
86
|
+
if (!isRecord(entry.headers) || Object.values(entry.headers).some((value) => typeof value !== "string")) {
|
|
87
|
+
throw new Error(`pi models.json.providers.${id}.headers must be a string map`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
providers[id] = entry;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return { agentDir, settings, providers };
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The provider/model pi would start with. With a configured provider,
|
|
97
|
+
* `defaultModel` is a model id and may itself contain slashes. Without one it
|
|
98
|
+
* may be provider/id; like pi's resolver, the longest declared provider id
|
|
99
|
+
* followed by "/" wins.
|
|
100
|
+
*/
|
|
101
|
+
export function resolvePiSelectedModel(agent, env) {
|
|
102
|
+
const configured = env.PI_PROVIDER ?? agent.settings.defaultProvider;
|
|
103
|
+
const providerConfigured = configured !== undefined && configured.length > 0;
|
|
104
|
+
let provider = providerConfigured ? configured : undefined;
|
|
105
|
+
let model = agent.settings.defaultModel;
|
|
106
|
+
if (!providerConfigured && model !== undefined) {
|
|
107
|
+
let best;
|
|
108
|
+
for (const id of Object.keys(agent.providers)) {
|
|
109
|
+
if (id.length === 0 || !model.toLowerCase().startsWith(`${id.toLowerCase()}/`))
|
|
110
|
+
continue;
|
|
111
|
+
if (best === undefined || id.length > best.length)
|
|
112
|
+
best = id;
|
|
113
|
+
}
|
|
114
|
+
if (best !== undefined) {
|
|
115
|
+
provider = best;
|
|
116
|
+
model = model.slice(best.length + 1);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (provider === undefined || provider.length === 0)
|
|
120
|
+
return null;
|
|
121
|
+
const entry = agent.providers[provider];
|
|
122
|
+
if (entry === undefined)
|
|
123
|
+
return { provider, model };
|
|
124
|
+
const declared = entry.models?.find((candidate) => candidate.id === model);
|
|
125
|
+
return {
|
|
126
|
+
provider,
|
|
127
|
+
model,
|
|
128
|
+
api: declared?.api ?? entry.api,
|
|
129
|
+
baseUrl: declared?.baseUrl ?? entry.baseUrl,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** Resolves an extension entry against the working directory, the agent directory and as given. */
|
|
133
|
+
export function resolveExtensionEntry(entry, cwd, agentDir) {
|
|
134
|
+
const candidates = [path.resolve(cwd, entry), path.resolve(agentDir, entry), entry];
|
|
135
|
+
return [...new Set(candidates)];
|
|
136
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { HostToolPolicy } from "../../core/session-guard.js";
|
|
2
|
+
export declare function piUnknownToolError(rawTool: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Unknown and extension tools cannot be classified, so a placeholder must not
|
|
5
|
+
* reach them: their arguments may be forwarded to a remote service that never
|
|
6
|
+
* saw the pseudonymized session. Known pi built-ins go through the core, and
|
|
7
|
+
* `codemode` inherits the core's Code Mode handling.
|
|
8
|
+
* This deliberately overrides ADR-0001 for the pi host; see ADR-0006/ADR-0007.
|
|
9
|
+
*/
|
|
10
|
+
export declare function assertPiToolBoundary(rawTool: string, input: unknown): void;
|
|
11
|
+
export declare const piToolPolicy: HostToolPolicy;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-specific tool classification for the shared guard core.
|
|
3
|
+
*
|
|
4
|
+
* The core restores placeholders only inside the host's local execution
|
|
5
|
+
* boundary; it needs to know which fields are shell command text, which are
|
|
6
|
+
* code, and which tools may keep a literal placeholder when a mapping is
|
|
7
|
+
* missing. pi's built-ins use flat JSON inputs, so the key-based rules from
|
|
8
|
+
* `core/tool-restore-policy.ts` cover them.
|
|
9
|
+
*
|
|
10
|
+
* Unknown and MCP tools never restore and never degrade: a placeholder there
|
|
11
|
+
* could reach a remote service, so the call is refused instead. `codemode` is
|
|
12
|
+
* the exception: its script stays literal and the host re-fires this boundary
|
|
13
|
+
* for every call the sandbox makes, which is where restoration happens.
|
|
14
|
+
*/
|
|
15
|
+
import { types } from "node:util";
|
|
16
|
+
import { containsTokenPrefix } from "../../decision/pseudonymization.js";
|
|
17
|
+
import { isShellTool, isShellKey, isCodeKey, keyPolicy, } from "../../core/tool-restore-policy.js";
|
|
18
|
+
/** pi 1.6.0 built-in tools whose inputs execute a command. */
|
|
19
|
+
const PI_SHELL_TOOLS = new Set(["bash", "powershell"]);
|
|
20
|
+
/** The built-ins whose input shapes this adapter understands. */
|
|
21
|
+
const PI_KNOWN_TOOLS = new Set(["read", "write", "edit", "bash", "powershell", "grep", "find", "ls"]);
|
|
22
|
+
/** pi 1.6.0's built-in extension tool: raw JavaScript source in `{ code }`. */
|
|
23
|
+
const CODE_MODE_TOOL = "codemode";
|
|
24
|
+
export function piUnknownToolError(rawTool) {
|
|
25
|
+
const name = rawTool.length > 0 ? `\`${rawTool}\`` : "this tool";
|
|
26
|
+
return `LeakShield blocked this tool call because ${name} is not a known pi built-in and its arguments contain a placeholder. The tool did not run.`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A codemode script runs in a QuickJS sandbox with no network, file system or
|
|
30
|
+
* timers; its only way out is `tools.<name>()`, and pi re-fires `tool_call` for
|
|
31
|
+
* each of those with evaluated arguments. A placeholder in the source therefore
|
|
32
|
+
* stays literal, exactly like OpenCode's Code Mode (ADR-0003, ADR-0007).
|
|
33
|
+
*/
|
|
34
|
+
function isPiCodeModeCall(rawTool, input) {
|
|
35
|
+
if (rawTool.toLowerCase() !== CODE_MODE_TOOL)
|
|
36
|
+
return false;
|
|
37
|
+
if (input === null || typeof input !== "object" || types.isProxy(input))
|
|
38
|
+
return false;
|
|
39
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, "code");
|
|
40
|
+
return descriptor !== undefined && "value" in descriptor && typeof descriptor.value === "string";
|
|
41
|
+
}
|
|
42
|
+
function carriesPlaceholder(value, depth) {
|
|
43
|
+
if (depth > 32)
|
|
44
|
+
return true;
|
|
45
|
+
if (typeof value === "string")
|
|
46
|
+
return containsTokenPrefix(value);
|
|
47
|
+
if (value === null || typeof value !== "object")
|
|
48
|
+
return false;
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
const stack = [{ value, depth }];
|
|
51
|
+
while (stack.length > 0) {
|
|
52
|
+
const item = stack.pop();
|
|
53
|
+
if (item.depth > 32)
|
|
54
|
+
return true;
|
|
55
|
+
if (typeof item.value === "string") {
|
|
56
|
+
if (containsTokenPrefix(item.value))
|
|
57
|
+
return true;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (item.value === null || typeof item.value !== "object")
|
|
61
|
+
continue;
|
|
62
|
+
if (seen.has(item.value))
|
|
63
|
+
continue;
|
|
64
|
+
seen.add(item.value);
|
|
65
|
+
if (Array.isArray(item.value)) {
|
|
66
|
+
for (const entry of item.value)
|
|
67
|
+
stack.push({ value: entry, depth: item.depth + 1 });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
for (const [key, entry] of Object.entries(item.value)) {
|
|
71
|
+
if (containsTokenPrefix(key))
|
|
72
|
+
return true;
|
|
73
|
+
stack.push({ value: entry, depth: item.depth + 1 });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Unknown and extension tools cannot be classified, so a placeholder must not
|
|
80
|
+
* reach them: their arguments may be forwarded to a remote service that never
|
|
81
|
+
* saw the pseudonymized session. Known pi built-ins go through the core, and
|
|
82
|
+
* `codemode` inherits the core's Code Mode handling.
|
|
83
|
+
* This deliberately overrides ADR-0001 for the pi host; see ADR-0006/ADR-0007.
|
|
84
|
+
*/
|
|
85
|
+
export function assertPiToolBoundary(rawTool, input) {
|
|
86
|
+
if (PI_KNOWN_TOOLS.has(rawTool.toLowerCase()))
|
|
87
|
+
return;
|
|
88
|
+
if (isPiCodeModeCall(rawTool, input))
|
|
89
|
+
return;
|
|
90
|
+
if (carriesPlaceholder(input, 0))
|
|
91
|
+
throw new Error(piUnknownToolError(rawTool));
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* pi 1.6.0 built-ins whose arguments only read or search local state. A
|
|
95
|
+
* literal placeholder there matches nothing; it cannot write, delete, or
|
|
96
|
+
* transmit. Everything else must refuse an incomplete restoration.
|
|
97
|
+
*/
|
|
98
|
+
const PI_READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
|
|
99
|
+
export const piToolPolicy = {
|
|
100
|
+
isCodeModeCall(event) {
|
|
101
|
+
return isPiCodeModeCall(typeof event.tool === "string" ? event.tool : "", event.input);
|
|
102
|
+
},
|
|
103
|
+
isShellTool(rawTool) {
|
|
104
|
+
return PI_SHELL_TOOLS.has(rawTool.toLowerCase()) || isShellTool(rawTool);
|
|
105
|
+
},
|
|
106
|
+
classifyField: keyPolicy,
|
|
107
|
+
allowsDegradedRestore(rawTool, input) {
|
|
108
|
+
if (!PI_READ_ONLY_TOOLS.has(rawTool.toLowerCase()))
|
|
109
|
+
return false;
|
|
110
|
+
return !(input !== null &&
|
|
111
|
+
typeof input === "object" &&
|
|
112
|
+
Object.keys(input).some((key) => isShellKey(key) || isCodeKey(key)));
|
|
113
|
+
},
|
|
114
|
+
};
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* leakshield — entry point
|
|
4
|
+
* CLI 掃描模式:npx tsx src/cli.ts --cli --text "..."
|
|
5
|
+
* Web 模式:npx tsx src/cli.ts --web
|
|
6
|
+
*/
|
|
7
|
+
export type { GuardConfig, Finding, ScanResult, FindingType, Rule } from "./types.js";
|
|
8
|
+
export { BUILTIN_RULES } from "./rules/builtin.js";
|
|
9
|
+
export { buildDynamicRules } from "./rules/dynamic.js";
|
|
10
|
+
export { redact, getLineCol, getIgnoredLines } from "./scanner/utils.js";
|
|
11
|
+
export { scanText } from "./scanner/engine.js";
|
|
12
|
+
export type { GuardDecision, GuardRiskLevel, GuardRecommendedAction, GuardDecisionFinding, GuardDecisionResult, } from "./decision/model.js";
|
|
13
|
+
export { toDecisionResult } from "./decision/model.js";
|
|
14
|
+
export { protectText, protectUnknownStrings } from "./decision/ingress.js";
|
|
15
|
+
export type { IngressMode, ProtectionAction, ProtectedText, ProtectionOptions } from "./decision/ingress.js";
|
|
16
|
+
export { scanTextWithDecoding } from "./scanner/engine.js";
|
|
17
|
+
export type { ScanWithDecodingResult } from "./scanner/encoding.js";
|
|
18
|
+
export { sanitizeForScanning, isLikelyHomographAttack, detectSuspiciousUnicode, } from "./scanner/unicode.js";
|
package/dist/cli.js
CHANGED
|
@@ -23,13 +23,22 @@ initWindowsEncoding();
|
|
|
23
23
|
const args = process.argv;
|
|
24
24
|
const isCliMode = args.includes("--cli");
|
|
25
25
|
const isWebMode = args.includes("--web");
|
|
26
|
-
const isDoctorMode = args.
|
|
26
|
+
const isDoctorMode = args.some((arg) => arg === "--doctor" || arg.startsWith("--doctor="));
|
|
27
27
|
const isForgetMode = args.includes("--forget");
|
|
28
|
+
const piIndex = args.indexOf("--pi");
|
|
29
|
+
const isPiSubcommand = piIndex === -1 && args[2] === "pi";
|
|
30
|
+
const isPiMode = piIndex !== -1 || isPiSubcommand || args.includes("--pi-install");
|
|
28
31
|
const valueOf = (flag) => {
|
|
29
32
|
const index = args.indexOf(flag);
|
|
30
33
|
return index !== -1 && index + 1 < args.length ? args[index + 1] : undefined;
|
|
31
34
|
};
|
|
32
|
-
if (
|
|
35
|
+
if (isPiMode) {
|
|
36
|
+
console.error("leakshield: `leakshield pi` was removed. pi now runs directly with the LeakShield extension loaded in-process.");
|
|
37
|
+
console.error("leakshield: add node_modules/leakshield/dist/adapters/pi/extension.js as the first entry of pi settings.extensions, or start pi with -e <path>.");
|
|
38
|
+
console.error("leakshield: check the setup with `leakshield --doctor pi`.");
|
|
39
|
+
process.exitCode = 2;
|
|
40
|
+
}
|
|
41
|
+
else if (isHelpRequest(args)) {
|
|
33
42
|
console.log(HELP_TEXT);
|
|
34
43
|
}
|
|
35
44
|
else if (isForgetMode) {
|
|
@@ -42,11 +51,13 @@ else if (isForgetMode) {
|
|
|
42
51
|
storePath: valueOf("--path") ?? defaultStorePath(),
|
|
43
52
|
});
|
|
44
53
|
}
|
|
54
|
+
else if (args.includes("--claude-code-proxy")) {
|
|
55
|
+
const { runClaudeCodeProxy } = await import("./adapters/claude-code/cli.js");
|
|
56
|
+
process.exitCode = await runClaudeCodeProxy(args);
|
|
57
|
+
}
|
|
45
58
|
else if (isDoctorMode) {
|
|
46
|
-
const {
|
|
47
|
-
|
|
48
|
-
console.log(formatDoctorReport(report));
|
|
49
|
-
process.exitCode = report.status === "PROTECTED" || report.status === "PARTIAL" ? 0 : 1;
|
|
59
|
+
const { runDoctorCommand } = await import("./doctor-hosts.js");
|
|
60
|
+
process.exitCode = await runDoctorCommand(args);
|
|
50
61
|
}
|
|
51
62
|
else if (isWebMode) {
|
|
52
63
|
const portIdx = args.indexOf("--port");
|