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.
Files changed (108) hide show
  1. package/README.md +35 -5
  2. package/README.zh-TW.md +34 -5
  3. package/dist/adapters/claude-code/capabilities.d.ts +14 -0
  4. package/dist/adapters/claude-code/capabilities.js +47 -0
  5. package/dist/adapters/claude-code/cli.d.ts +10 -0
  6. package/dist/adapters/claude-code/cli.js +51 -0
  7. package/dist/adapters/claude-code/doctor.d.ts +19 -0
  8. package/dist/adapters/claude-code/doctor.js +177 -0
  9. package/dist/adapters/claude-code/proxy.d.ts +47 -0
  10. package/dist/adapters/claude-code/proxy.js +348 -0
  11. package/dist/adapters/opencode/capabilities.d.ts +10 -0
  12. package/dist/adapters/opencode/capabilities.js +48 -0
  13. package/dist/adapters/opencode/doctor.d.ts +67 -0
  14. package/dist/{doctor.js → adapters/opencode/doctor.js} +16 -42
  15. package/dist/adapters/opencode/env-queries.d.ts +133 -0
  16. package/dist/adapters/opencode/env-tools.d.ts +20 -0
  17. package/dist/adapters/opencode/hooks.d.ts +4 -0
  18. package/dist/adapters/opencode/plugin.d.ts +12 -0
  19. package/dist/{opencode.js → adapters/opencode/plugin.js} +7 -7
  20. package/dist/adapters/opencode/tool-policy.d.ts +2 -0
  21. package/dist/adapters/opencode/tool-policy.js +23 -0
  22. package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
  23. package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
  24. package/dist/adapters/opencode/transparent.d.ts +66 -0
  25. package/dist/adapters/opencode/transparent.js +237 -0
  26. package/dist/adapters/opencode/v2.d.ts +20 -0
  27. package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
  28. package/dist/adapters/pi/capabilities.d.ts +10 -0
  29. package/dist/adapters/pi/capabilities.js +50 -0
  30. package/dist/adapters/pi/doctor.d.ts +26 -0
  31. package/dist/adapters/pi/doctor.js +276 -0
  32. package/dist/adapters/pi/extension.d.ts +28 -0
  33. package/dist/adapters/pi/extension.js +109 -0
  34. package/dist/adapters/pi/guard.d.ts +33 -0
  35. package/dist/adapters/pi/guard.js +154 -0
  36. package/dist/adapters/pi/persistence.d.ts +9 -0
  37. package/dist/adapters/pi/persistence.js +69 -0
  38. package/dist/adapters/pi/settings.d.ts +51 -0
  39. package/dist/adapters/pi/settings.js +136 -0
  40. package/dist/adapters/pi/tool-policy.d.ts +11 -0
  41. package/dist/adapters/pi/tool-policy.js +114 -0
  42. package/dist/cli.d.ts +18 -0
  43. package/dist/cli.js +17 -6
  44. package/dist/config/loader.d.ts +70 -0
  45. package/dist/config/plain-object.d.ts +2 -0
  46. package/dist/core/index.d.ts +9 -0
  47. package/dist/core/index.js +9 -0
  48. package/dist/core/session-guard.d.ts +61 -0
  49. package/dist/{opencode-transparent.js → core/session-guard.js} +55 -713
  50. package/dist/core/sse-recovery.d.ts +6 -0
  51. package/dist/core/tool-restore-policy.d.ts +153 -0
  52. package/dist/core/tool-restore-policy.js +453 -0
  53. package/dist/core/wire.d.ts +213 -0
  54. package/dist/{opencode-transparent-http.js → core/wire.js} +125 -42
  55. package/dist/core/ws.d.ts +26 -0
  56. package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
  57. package/dist/decision/deidentify.d.ts +63 -0
  58. package/dist/decision/ingress.d.ts +40 -0
  59. package/dist/decision/mapping-key.d.ts +91 -0
  60. package/dist/decision/mapping-store.d.ts +166 -0
  61. package/dist/decision/model.d.ts +41 -0
  62. package/dist/decision/pseudonymization.d.ts +176 -0
  63. package/dist/decision/redaction.d.ts +56 -0
  64. package/dist/decision/schema-strings.d.ts +23 -0
  65. package/dist/decision/schema-strings.js +2 -2
  66. package/dist/decision/value-search.d.ts +39 -0
  67. package/dist/doctor-capabilities.d.ts +21 -0
  68. package/dist/doctor-capabilities.js +58 -0
  69. package/dist/doctor-hosts.d.ts +18 -0
  70. package/dist/doctor-hosts.js +144 -0
  71. package/dist/doctor-report.d.ts +45 -0
  72. package/dist/doctor-report.js +111 -0
  73. package/dist/forget.d.ts +18 -0
  74. package/dist/guard-options.d.ts +45 -0
  75. package/dist/{plugin-options.js → guard-options.js} +4 -1
  76. package/dist/help.d.ts +2 -0
  77. package/dist/help.js +15 -1
  78. package/dist/i18n/en.d.ts +65 -0
  79. package/dist/i18n/index.d.ts +15 -0
  80. package/dist/i18n/zh-TW.d.ts +65 -0
  81. package/dist/index.d.ts +13 -0
  82. package/dist/index.js +1 -1
  83. package/dist/rules/builtin.d.ts +4 -0
  84. package/dist/rules/dynamic.d.ts +33 -0
  85. package/dist/scanner/allowlist.d.ts +22 -0
  86. package/dist/scanner/cidr.d.ts +39 -0
  87. package/dist/scanner/encoding.d.ts +87 -0
  88. package/dist/scanner/engine.d.ts +43 -0
  89. package/dist/scanner/exact-values.d.ts +11 -0
  90. package/dist/scanner/redaction-verifier.d.ts +24 -0
  91. package/dist/scanner/remotes.d.ts +29 -0
  92. package/dist/scanner/unicode.d.ts +57 -0
  93. package/dist/scanner/utils.d.ts +22 -0
  94. package/dist/transports/cli.d.ts +27 -0
  95. package/dist/transports/web-ui.d.ts +1 -0
  96. package/dist/transports/web-ui.js +1 -1
  97. package/dist/transports/web.d.ts +4 -0
  98. package/dist/types/capabilities.d.ts +67 -0
  99. package/dist/types/capabilities.js +133 -0
  100. package/dist/types.d.ts +149 -0
  101. package/dist/utils/files.d.ts +3 -0
  102. package/dist/utils/path-security.d.ts +18 -0
  103. package/dist/utils/win-encoding.d.ts +16 -0
  104. package/package.json +11 -3
  105. /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
  106. /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
  107. /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
  108. /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
@@ -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.includes("--doctor");
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 (isHelpRequest(args)) {
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 { runDoctor, createDoctorDeps, formatDoctorReport } = await import("./doctor.js");
47
- const report = await runDoctor(createDoctorDeps());
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");
@@ -0,0 +1,70 @@
1
+ import { z } from "zod";
2
+ import type { GuardConfig } from "../types.js";
3
+ export declare const GuardConfigSchema: z.ZodPipe<z.ZodCustom<unknown, unknown>, z.ZodObject<{
4
+ nda_keywords: z.ZodDefault<z.ZodArray<z.ZodString>>;
5
+ private_domains: z.ZodDefault<z.ZodArray<z.ZodString>>;
6
+ custom_rules: z.ZodPipe<z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
7
+ description: z.ZodString;
8
+ pattern: z.ZodString;
9
+ severity: z.ZodDefault<z.ZodEnum<{
10
+ HIGH: "HIGH";
11
+ MEDIUM: "MEDIUM";
12
+ LOW: "LOW";
13
+ }>>;
14
+ flags: z.ZodOptional<z.ZodString>;
15
+ word_boundary: z.ZodOptional<z.ZodBoolean>;
16
+ allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
17
+ path: z.ZodOptional<z.ZodArray<z.ZodString>>;
18
+ }, z.core.$strip>>>>, z.ZodTransform<{
19
+ description: string;
20
+ pattern: string;
21
+ severity: "HIGH" | "MEDIUM" | "LOW";
22
+ flags?: string | undefined;
23
+ word_boundary?: boolean | undefined;
24
+ allow?: string[] | undefined;
25
+ path?: string[] | undefined;
26
+ }[], {
27
+ description: string;
28
+ pattern: string;
29
+ severity: "HIGH" | "MEDIUM" | "LOW";
30
+ flags?: string | undefined;
31
+ word_boundary?: boolean | undefined;
32
+ allow?: string[] | undefined;
33
+ path?: string[] | undefined;
34
+ }[] | null>>;
35
+ settings: z.ZodPrefault<z.ZodPipe<z.ZodCustom<unknown, unknown>, z.ZodObject<{
36
+ max_chars: z.ZodDefault<z.ZodNumber>;
37
+ show_line_numbers: z.ZodDefault<z.ZodBoolean>;
38
+ preview_length: z.ZodDefault<z.ZodNumber>;
39
+ encoding_detection: z.ZodDefault<z.ZodBoolean>;
40
+ env_files: z.ZodDefault<z.ZodArray<z.ZodString>>;
41
+ rule_overrides: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
42
+ private_cidrs: z.ZodDefault<z.ZodArray<z.ZodString>>;
43
+ allowlist: z.ZodDefault<z.ZodArray<z.ZodString>>;
44
+ }, z.core.$strip>>>;
45
+ }, z.core.$strip>>;
46
+ /**
47
+ * Resolves the guard config path exactly like `loadConfig` does: the override
48
+ * when it exists, otherwise the first default candidate that exists. Returns
49
+ * undefined when no config file is present (defaults apply).
50
+ */
51
+ export declare function findConfigPath(overridePath?: string): string | undefined;
52
+ export interface LoadedGuardConfig {
53
+ config: GuardConfig;
54
+ /**
55
+ * sha256 of the exact bytes `config` was parsed from, or "absent" when no
56
+ * configuration file exists (defaults apply). Consumers that authorize from
57
+ * this config can compare the fingerprint on later reads.
58
+ */
59
+ fingerprint: string;
60
+ configPath: string | undefined;
61
+ }
62
+ /**
63
+ * Loads the guard config and, from the very same read, the fingerprint of the
64
+ * bytes it was parsed from. The allowlist inside `config` and `fingerprint`
65
+ * are therefore guaranteed to describe one configuration state — an edit
66
+ * between a config load and a separate fingerprint read could otherwise
67
+ * authorize against content that never existed at a single point in time.
68
+ */
69
+ export declare function loadConfigWithFingerprint(overridePath?: string, workspaceRoot?: string): LoadedGuardConfig;
70
+ export declare function loadConfig(overridePath?: string, workspaceRoot?: string): GuardConfig;
@@ -0,0 +1,2 @@
1
+ import { z } from "zod";
2
+ export declare function plainObject<T extends z.ZodType>(schema: T): z.ZodPipe<z.ZodCustom<unknown, unknown>, T>;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Experimental host-neutral LeakShield core entrypoint.
3
+ *
4
+ * This subpath is an incremental packaging boundary, not a separate npm
5
+ * package. Tool restoration requires an explicit HostToolPolicy; without one, token-bearing tool calls are refused.
6
+ *
7
+ * Do not import OpenCode or Claude Code adapters from this module.
8
+ */
9
+ export { createGuardCore, requireSessionID, INITIALIZATION_ERROR, PROTECT_FAILED_ERROR, ATTRIBUTION_ERROR, UNSUPPORTED_ROUTE_ERROR, type GuardCore, type GuardPersistenceOptions, type HostToolPolicy, type RecordLike, } from "./session-guard.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Experimental host-neutral LeakShield core entrypoint.
3
+ *
4
+ * This subpath is an incremental packaging boundary, not a separate npm
5
+ * package. Tool restoration requires an explicit HostToolPolicy; without one, token-bearing tool calls are refused.
6
+ *
7
+ * Do not import OpenCode or Claude Code adapters from this module.
8
+ */
9
+ export { createGuardCore, requireSessionID, INITIALIZATION_ERROR, PROTECT_FAILED_ERROR, ATTRIBUTION_ERROR, UNSUPPORTED_ROUTE_ERROR, } from "./session-guard.js";
@@ -0,0 +1,61 @@
1
+ import { type MappingKeyProvider } from "../decision/mapping-store.js";
2
+ import { createResponsesWebSocketAdapter } from "./ws.js";
3
+ import { ToolLeafPolicy } from "./tool-restore-policy.js";
4
+ import type { GuardConfig } from "../types.js";
5
+ export type RecordLike = {
6
+ [key: string]: unknown;
7
+ };
8
+ export declare const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
9
+ export declare const PROTECT_FAILED_ERROR = "LeakShield blocked a model request because it could not be masked safely.";
10
+ export declare const ATTRIBUTION_ERROR = "LeakShield blocked a response because it could not be matched to a request.";
11
+ export declare const UNSUPPORTED_ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
12
+ export declare function requireSessionID(event: RecordLike): string;
13
+ /** Persistence wiring options (W2/B4 + R-round), mapped from
14
+ * PluginOptions.persistence. `keyProvider` is a test/CI injection seam —
15
+ * production callers leave it unset and the OS keychain ladder resolves;
16
+ * an explicit null forces the ladder-bottom memory-only path deterministically. */
17
+ export interface GuardPersistenceOptions {
18
+ ttlDays: number;
19
+ path: string;
20
+ keyFile: boolean;
21
+ keyfilePath?: string;
22
+ keyProvider?: MappingKeyProvider | null;
23
+ }
24
+ /** Host-defined classification. Without this capability, token-bearing tool calls refuse. */
25
+ export interface HostToolPolicy {
26
+ isCodeModeCall(event: RecordLike): boolean;
27
+ isShellTool(rawTool: string): boolean;
28
+ classifyField(key: string, inherited: ToolLeafPolicy): ToolLeafPolicy;
29
+ /** `rawTool` is the tool name as the host sent it, not lowercased. */
30
+ allowsDegradedRestore(rawTool: string, input: unknown): boolean;
31
+ }
32
+ export interface GuardCore {
33
+ readonly hasSession: (sessionID: string) => boolean;
34
+ readonly assertTrackable: (sessionID: string) => void;
35
+ readonly ensureSeeded: (sessionID: string) => void;
36
+ readonly track: (sessionID: string) => void;
37
+ readonly persistIfChanged: (sessionID: string) => void;
38
+ readonly protectRequestKind: (event: RecordLike, kind: "primary" | "title" | "compaction" | "generate") => void;
39
+ readonly onHttpRequest: (event: RecordLike) => Promise<void>;
40
+ readonly onHttpResponse: (event: RecordLike) => Promise<void>;
41
+ readonly onToolBefore: (event: RecordLike) => void;
42
+ readonly releaseSession: (sessionID: string) => void;
43
+ readonly noticeOnce: (message: string) => void;
44
+ readonly webSocket: ReturnType<typeof createResponsesWebSocketAdapter>;
45
+ readonly assertWritableDataProperty: (record: object, key: string | number) => void;
46
+ /** Releases handles without clearing sessions: used when registration fails before any hook ran. */
47
+ readonly closeResources: () => void;
48
+ readonly dispose: () => void;
49
+ }
50
+ /**
51
+ * Creates the host-independent guard core for one plugin setup (= one OpenCode
52
+ * process): a single bounded pseudonymizer, exact-session mapping and private
53
+ * request attribution. The host layer registers hooks that call its handlers.
54
+ * With persistence options the core additionally hydrates sessions from the
55
+ * encrypted store on first touch and writes committed mappings back (decision
56
+ * §4: dispose unloads hooks but never deletes persisted mappings — forget is
57
+ * the only erasure path). Returns null when the pseudonymizer cannot be built.
58
+ */
59
+ export declare function createGuardCore(config: GuardConfig, attachmentsPolicy?: "block" | "allow", wireProtection?: boolean, persistence?: GuardPersistenceOptions, dialect?: {
60
+ anthropicThinking?: "refuse" | "mask";
61
+ }, hostToolPolicy?: HostToolPolicy): GuardCore | null;