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,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Readonly env query service (opt-in `envQueries` plugin option).
|
|
3
|
+
*
|
|
4
|
+
* Lets an agent ask coarse questions about the files listed in
|
|
5
|
+
* `settings.env_files` — which keys exist, whether a key is missing/empty/
|
|
6
|
+
* nonempty, a coarse lexical shape, and whether two keys hold the same value —
|
|
7
|
+
* without ever exposing raw values, lengths, previews, or fingerprints.
|
|
8
|
+
*
|
|
9
|
+
* Security contract:
|
|
10
|
+
* - Only files in the setup-time `env_files` allowlist, resolved inside the
|
|
11
|
+
* workspace root frozen at construction (canonical path plus device/inode
|
|
12
|
+
* identity). No symlinks on any path component, regular files only, at
|
|
13
|
+
* most 16 files of 1 MiB.
|
|
14
|
+
* - File access is best-effort pathname identity validation, not a sandbox.
|
|
15
|
+
* The root and every ancestor directory are lstat'd before the open and
|
|
16
|
+
* again after the read; the opened descriptor must be the exact inode the
|
|
17
|
+
* pre-open lstat authorized (dev/ino binding); the final component is
|
|
18
|
+
* never followed (O_NOFOLLOW); FIFOs cannot hang the event loop
|
|
19
|
+
* (O_NONBLOCK); and post-read size/mtime, ancestor-identity, and
|
|
20
|
+
* canonical-path checks reject observed changes. Stable symlink
|
|
21
|
+
* substitutions — final component or ancestor, resolving inside or
|
|
22
|
+
* outside the workspace — are rejected.
|
|
23
|
+
* - What pathname checks cannot do, stated honestly: a concurrent
|
|
24
|
+
* same-owner mutation that substitutes a component (root, ancestor, or
|
|
25
|
+
* file) and restores it between the checks — an unobserved ABA race — is
|
|
26
|
+
* not detectable; hardlink provenance is not checked (a hardlink to an
|
|
27
|
+
* outside file is indistinguishable from the original); an in-place
|
|
28
|
+
* rewrite that preserves size and mtime is not distinguishable. This is
|
|
29
|
+
* not a claim of race-proofing against malicious concurrent mutation.
|
|
30
|
+
* - Values are read fresh on every invocation and retained only for the
|
|
31
|
+
* duration of the call; nothing parsed is cached or persisted.
|
|
32
|
+
* - File ids are opaque and session-local (HMAC of a per-setup key); they
|
|
33
|
+
* reveal no path or index and are invalid in other sessions.
|
|
34
|
+
* - The allowlist and its authorization fingerprint come from one
|
|
35
|
+
* configuration read (see `loadConfigWithFingerprint`). If the
|
|
36
|
+
* configuration later changes, queries are disabled with a fixed sanitized
|
|
37
|
+
* error until OpenCode restarts — sticky even if the change is reverted,
|
|
38
|
+
* and never a silent fallback to the old or new authorization.
|
|
39
|
+
* - This is not hostile-agent isolation and not a trusted baseline: the
|
|
40
|
+
* agent can modify the queried files through other tools, so results
|
|
41
|
+
* describe the current file state at query time, never a frozen snapshot
|
|
42
|
+
* that someone vouched for.
|
|
43
|
+
*/
|
|
44
|
+
export declare const MAX_ENV_QUERY_FILES = 16;
|
|
45
|
+
export declare const MAX_FILE_ID_LENGTH = 64;
|
|
46
|
+
export declare const MAX_KEY_NAME_LENGTH = 512;
|
|
47
|
+
export type EnvFileUnavailability = "outside_workspace" | "symlink" | "not_regular_file" | "oversize" | "unreadable" | "malformed";
|
|
48
|
+
export type EnvQueryShape = "boolean_like" | "number_like" | "multiline_text" | "text";
|
|
49
|
+
export interface EnvListEntry {
|
|
50
|
+
/** Opaque session-local id; only valid in the session it was issued for. */
|
|
51
|
+
file_id: string;
|
|
52
|
+
available: boolean;
|
|
53
|
+
/** Key names only, when available. Never values. */
|
|
54
|
+
keys?: string[];
|
|
55
|
+
/** Fixed sanitized reason code, when unavailable. */
|
|
56
|
+
reason?: EnvFileUnavailability;
|
|
57
|
+
}
|
|
58
|
+
export type EnvInspectOutcome = {
|
|
59
|
+
ok: true;
|
|
60
|
+
status: "unavailable";
|
|
61
|
+
reason: EnvFileUnavailability;
|
|
62
|
+
} | {
|
|
63
|
+
ok: true;
|
|
64
|
+
status: "missing";
|
|
65
|
+
} | {
|
|
66
|
+
ok: true;
|
|
67
|
+
status: "empty";
|
|
68
|
+
} | {
|
|
69
|
+
ok: true;
|
|
70
|
+
status: "nonempty";
|
|
71
|
+
shape: EnvQueryShape;
|
|
72
|
+
};
|
|
73
|
+
export type EnvCompareOutcome = {
|
|
74
|
+
ok: true;
|
|
75
|
+
result: "equal";
|
|
76
|
+
} | {
|
|
77
|
+
ok: true;
|
|
78
|
+
result: "different";
|
|
79
|
+
} | {
|
|
80
|
+
ok: true;
|
|
81
|
+
result: "unavailable";
|
|
82
|
+
reason?: EnvFileUnavailability;
|
|
83
|
+
};
|
|
84
|
+
export type EnvQueryFailureCode = "invalid_arguments" | "unknown_file_id" | "disabled";
|
|
85
|
+
export type EnvQueryFailure = {
|
|
86
|
+
ok: false;
|
|
87
|
+
code: EnvQueryFailureCode;
|
|
88
|
+
};
|
|
89
|
+
export interface EnvQueryServiceOptions {
|
|
90
|
+
/** Allowlist from `settings.env_files`; frozen at setup. */
|
|
91
|
+
envFiles: readonly string[];
|
|
92
|
+
/** Workspace root; frozen (realpath'd) at setup. */
|
|
93
|
+
workspaceRoot: string;
|
|
94
|
+
/**
|
|
95
|
+
* Resolves the guard configuration path used at setup; re-invoked per call
|
|
96
|
+
* to detect authorization drift. Should share the loader's search logic.
|
|
97
|
+
*/
|
|
98
|
+
resolveConfigPath: () => string | undefined;
|
|
99
|
+
/**
|
|
100
|
+
* sha256 fingerprint of the exact configuration bytes the allowlist was
|
|
101
|
+
* parsed from (see `loadConfigWithFingerprint`). The allowlist and the
|
|
102
|
+
* fingerprint are provably one read: an edit between reading the allowlist
|
|
103
|
+
* and fingerprinting could otherwise authorize against content that never
|
|
104
|
+
* existed at a single point in time.
|
|
105
|
+
*/
|
|
106
|
+
configFingerprint: string;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Strict dotenv parser for the query service. Returns undefined when the file
|
|
110
|
+
* is malformed — the entire file is rejected rather than returning partial,
|
|
111
|
+
* non-authoritative results. Divergences from the exact-value scanner are
|
|
112
|
+
* intentional: all value lengths (including <8) are preserved, and files with
|
|
113
|
+
* stray non-assignment lines or unterminated quotes are rejected wholesale.
|
|
114
|
+
*/
|
|
115
|
+
export declare function parseEnvFileContent(content: string): Map<string, string> | undefined;
|
|
116
|
+
/** Coarse lexical shape of a nonempty value. A shape is a hint, never a claim that the value is a valid boolean or number. */
|
|
117
|
+
export declare function classifyEnvValueShape(value: string): EnvQueryShape;
|
|
118
|
+
export declare class EnvQueryService {
|
|
119
|
+
#private;
|
|
120
|
+
constructor(options: EnvQueryServiceOptions);
|
|
121
|
+
listFiles(sessionID: string): {
|
|
122
|
+
ok: true;
|
|
123
|
+
files: EnvListEntry[];
|
|
124
|
+
} | EnvQueryFailure;
|
|
125
|
+
inspectKey(sessionID: string, fileId: string, key: string): EnvInspectOutcome | EnvQueryFailure;
|
|
126
|
+
compareKeys(sessionID: string, left: {
|
|
127
|
+
fileId: string;
|
|
128
|
+
key: string;
|
|
129
|
+
}, right: {
|
|
130
|
+
fileId: string;
|
|
131
|
+
key: string;
|
|
132
|
+
}): EnvCompareOutcome | EnvQueryFailure;
|
|
133
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Plugin as PluginNamespace } from "@opencode/plugin";
|
|
2
|
+
import type { EnvQueryService } from "./env-queries.js";
|
|
3
|
+
/**
|
|
4
|
+
* Agent tool surface for the opt-in readonly env queries (plugin option
|
|
5
|
+
* `envQueries`, default false). Tools are registered on OpenCode v2 through
|
|
6
|
+
* `ctx.tool.transform(editor => editor.add(...))` with literal JSON Schemas
|
|
7
|
+
* and runtime validation in `execute` (v2 passes raw unknown input).
|
|
8
|
+
*
|
|
9
|
+
* Every payload is fixed and sanitized: statuses, coarse shapes, equality,
|
|
10
|
+
* opaque file ids, and key names only. Values, lengths, previews, paths, and
|
|
11
|
+
* exception text never appear; failures map to fixed messages below.
|
|
12
|
+
*/
|
|
13
|
+
type V2PluginContext = PluginNamespace.Context;
|
|
14
|
+
/**
|
|
15
|
+
* Registers the env query tools on an OpenCode v2 plugin context via
|
|
16
|
+
* `ctx.tool.transform(editor => editor.add(...))`. Tool inputs are literal
|
|
17
|
+
* JSON Schemas; `execute` validates the raw input at runtime.
|
|
18
|
+
*/
|
|
19
|
+
export declare function registerV2EnvTools(ctx: V2PluginContext, service: EnvQueryService): Promise<void>;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Plugin as PluginNamespace } from "@opencode/plugin";
|
|
2
|
+
type V2PluginContext = PluginNamespace.Context;
|
|
3
|
+
/**
|
|
4
|
+
* OpenCode plugin entry. OpenCode v2 reads `id` and `setup(ctx)`. `server` is
|
|
5
|
+
* the fail-closed stub for v1 hosts (1.18.29+), which call `server(input, options)`.
|
|
6
|
+
*/
|
|
7
|
+
declare const leakshieldPlugin: {
|
|
8
|
+
id: string;
|
|
9
|
+
setup: (ctx: V2PluginContext) => Promise<PluginNamespace.Cleanup | void>;
|
|
10
|
+
server: () => Promise<import("@opencode-ai/plugin").Hooks>;
|
|
11
|
+
};
|
|
12
|
+
export default leakshieldPlugin;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { findConfigPath, loadConfigWithFingerprint } from "
|
|
2
|
-
import { createSessionKey } from "
|
|
3
|
-
import { defaultStorePath } from "
|
|
1
|
+
import { findConfigPath, loadConfigWithFingerprint } from "../../config/loader.js";
|
|
2
|
+
import { createSessionKey } from "../../decision/deidentify.js";
|
|
3
|
+
import { defaultStorePath } from "../../decision/mapping-key.js";
|
|
4
4
|
import { EnvQueryService } from "./env-queries.js";
|
|
5
|
-
import { createFailClosedHooks } from "./
|
|
6
|
-
import { createFailClosedV2Setup, createV2Setup } from "./
|
|
7
|
-
import { createFailClosedTransparentGuard, createTransparentSessionGuard } from "./
|
|
8
|
-
import {
|
|
5
|
+
import { createFailClosedHooks } from "./hooks.js";
|
|
6
|
+
import { createFailClosedV2Setup, createV2Setup } from "./v2.js";
|
|
7
|
+
import { createFailClosedTransparentGuard, createTransparentSessionGuard } from "./transparent.js";
|
|
8
|
+
import { validatePluginOptions, withDefaultMode } from "../../guard-options.js";
|
|
9
9
|
function withEncodingDetection(config) {
|
|
10
10
|
return {
|
|
11
11
|
...config,
|
|
@@ -41,16 +41,42 @@ function rawModeIsTransparent(options) {
|
|
|
41
41
|
resolved !== null &&
|
|
42
42
|
resolved.mode === "transparent");
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* The refusal text appended when setup fails, so a user who never runs the
|
|
46
|
+
* doctor still sees why every request is blocked. Option validation messages
|
|
47
|
+
* name option keys and fixed rules, never the rejected values (see
|
|
48
|
+
* `validatePluginOptions`). A guard config failure is described generically:
|
|
49
|
+
* its error can carry file paths or custom rule descriptions.
|
|
50
|
+
*/
|
|
51
|
+
function invalidOptionsReason(error) {
|
|
52
|
+
const detail = error.replace(/\(root\): /g, "").replace(/[.\s]+$/, "");
|
|
53
|
+
return `Invalid LeakShield options in opencode.json: ${detail}. Fix them and restart OpenCode; \`leakshield --doctor\` shows the details.`;
|
|
54
|
+
}
|
|
55
|
+
const CONFIG_LOAD_REASON = "The LeakShield guard config file could not be loaded. Run `leakshield --doctor` to see why, fix it and restart OpenCode.";
|
|
44
56
|
const v2Setup = async (ctx) => {
|
|
57
|
+
let failureReason;
|
|
45
58
|
try {
|
|
46
|
-
const
|
|
47
|
-
|
|
59
|
+
const validation = validatePluginOptions(ctx.options);
|
|
60
|
+
if (!validation.ok) {
|
|
61
|
+
failureReason = invalidOptionsReason(validation.error);
|
|
62
|
+
throw new Error("invalid plugin options");
|
|
63
|
+
}
|
|
64
|
+
const options = validation.options;
|
|
65
|
+
let loaded;
|
|
66
|
+
try {
|
|
67
|
+
loaded = loadConfigWithFingerprint(options.configPath, ctx.location.directory);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
failureReason = CONFIG_LOAD_REASON;
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
48
73
|
const config = withEncodingDetection(loaded.config);
|
|
49
74
|
if (options.mode === "transparent") {
|
|
50
75
|
// Transparent pseudonymization arms its own bounded session service,
|
|
51
|
-
// transport hooks, and disposal
|
|
52
|
-
//
|
|
53
|
-
//
|
|
76
|
+
// transport hooks, and disposal. deidentify is still rejected at the
|
|
77
|
+
// option schema; envQueries is accepted but ignored (warned below) since
|
|
78
|
+
// the guard_env_* tools are not registered here. W2: persistence options
|
|
79
|
+
// flow into the guard only when explicitly enabled (default memory-only,
|
|
54
80
|
// zero behavior change).
|
|
55
81
|
const persistence = options.persistence.enabled
|
|
56
82
|
? {
|
|
@@ -62,6 +88,9 @@ const v2Setup = async (ctx) => {
|
|
|
62
88
|
: undefined;
|
|
63
89
|
const guard = createTransparentSessionGuard(config, options.attachments, options.wireProtection ?? true, persistence);
|
|
64
90
|
await guard.setup(ctx);
|
|
91
|
+
if (options.envQueries) {
|
|
92
|
+
console.warn("[leakshield] envQueries is ignored in transparent mode: the guard_env_* tools are not registered, and env files the agent reads are only partly masked (values shorter than 8 characters stay visible). Set mode to \"block\" or \"redact\" to use envQueries.");
|
|
93
|
+
}
|
|
65
94
|
// Hook-only must leave provider routing/transport preferences untouched.
|
|
66
95
|
if (options.wireProtection === false)
|
|
67
96
|
return () => guard.dispose();
|
|
@@ -107,11 +136,11 @@ const v2Setup = async (ctx) => {
|
|
|
107
136
|
// option is inspected because a schema/refine failure leaves `options`
|
|
108
137
|
// unset. The fallback's dispose is returned for host-triggered cleanup.
|
|
109
138
|
if (rawModeIsTransparent(ctx.options)) {
|
|
110
|
-
const guard = createFailClosedTransparentGuard(ctx.options?.wireProtection !== false);
|
|
139
|
+
const guard = createFailClosedTransparentGuard(ctx.options?.wireProtection !== false, failureReason);
|
|
111
140
|
await guard.setup(ctx);
|
|
112
141
|
return guard.dispose;
|
|
113
142
|
}
|
|
114
|
-
await createFailClosedV2Setup()(ctx);
|
|
143
|
+
await createFailClosedV2Setup(failureReason)(ctx);
|
|
115
144
|
}
|
|
116
145
|
};
|
|
117
146
|
const V1_UNSUPPORTED = "LeakShield no longer supports OpenCode v1, so the request was blocked before anything was sent. Upgrade to OpenCode v2.";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** OpenCode-specific tool classification for the shared guard core.
|
|
2
|
+
* Keep host tool names and degradation allowlists out of session-guard.ts.
|
|
3
|
+
* Restoration itself remains transactional and fail-closed in the core.
|
|
4
|
+
*/
|
|
5
|
+
import { types } from "node:util";
|
|
6
|
+
import { isShellTool, isShellKey, isCodeKey, keyPolicy, READ_ONLY_TOOLS, } from "../../core/tool-restore-policy.js";
|
|
7
|
+
/** OpenCode v2.2.5 Code Mode tool, with input {code: string}. */
|
|
8
|
+
const CODE_MODE_TOOL = "execute";
|
|
9
|
+
export const opencodeToolPolicy = {
|
|
10
|
+
isCodeModeCall(event) {
|
|
11
|
+
if (event.tool !== CODE_MODE_TOOL || event.input === null || typeof event.input !== "object" || types.isProxy(event.input))
|
|
12
|
+
return false;
|
|
13
|
+
const descriptor = Object.getOwnPropertyDescriptor(event.input, "code");
|
|
14
|
+
return descriptor !== undefined && "value" in descriptor && typeof descriptor.value === "string";
|
|
15
|
+
},
|
|
16
|
+
isShellTool,
|
|
17
|
+
classifyField: keyPolicy,
|
|
18
|
+
allowsDegradedRestore(rawTool, input) {
|
|
19
|
+
return READ_ONLY_TOOLS.has(rawTool.toLowerCase()) && !isShellTool(rawTool) &&
|
|
20
|
+
!(input !== null && typeof input === "object" &&
|
|
21
|
+
Object.keys(input).some((key) => isShellKey(key) || isCodeKey(key)));
|
|
22
|
+
},
|
|
23
|
+
};
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* This is NOT a network sandbox: SDKs that ignore options.fetch are outside
|
|
5
5
|
* the supported contract (including any private sockets/global-fetch path). */
|
|
6
6
|
import { types } from "node:util";
|
|
7
|
-
import { classifyModelRoute } from "
|
|
7
|
+
import { classifyModelRoute } from "../../core/wire.js";
|
|
8
8
|
const ADMISSION_ERROR = "LeakShield blocked an unsupported route. The provider must use the fetch OpenCode injects.";
|
|
9
9
|
const DISPOSED_ERROR = "LeakShield blocked a request on an inactive AI SDK transport.";
|
|
10
10
|
const PROTECTION_ERROR = "LeakShield blocked an AI SDK request. Check its protocol, metadata and content, then try again.";
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode v2 transparent pseudonymization session guard (issue #22).
|
|
3
|
+
*
|
|
4
|
+
* One guard owns exactly ONE pseudonymizer service (bounded per setup, no
|
|
5
|
+
* session fallback, no TTL, no eviction) and its own hook registrations and
|
|
6
|
+
* disposal. Protection model:
|
|
7
|
+
*
|
|
8
|
+
* - The four model-request kinds (`context`, `compaction`, `generate`,
|
|
9
|
+
* `title`) protect an atomic snapshot (system, messages, options, tools
|
|
10
|
+
* schema) with `protectJson` and publish it back only after the whole
|
|
11
|
+
* transaction succeeds — never piecewise in place, never partial.
|
|
12
|
+
* - Wire protection registers outbound HTTP/WS and SDK admission hooks.
|
|
13
|
+
* Explicit false is hook-only: none of those outbound hooks is registered.
|
|
14
|
+
* Inbound HTTP/WS restoration is best-effort in both modes; hook-only uses
|
|
15
|
+
* the host's session/kind/model and successful content preparation, not an
|
|
16
|
+
* outgoing transport registration, to select the local mapping.
|
|
17
|
+
* - Native Responses-family WebSocket routes restore display frames; the same
|
|
18
|
+
* wireProtection switch controls outbound admission and masking. Unknown
|
|
19
|
+
* inbound protocols stay literal. SDKs honoring injected HTTP fetch reuse
|
|
20
|
+
* the wire-protected HTTP hooks; hook-only makes no transport guarantee.
|
|
21
|
+
* - `tool:execute.before` restores registered tokens in tool arguments so local
|
|
22
|
+
* tools run with the real values (the model never sees them). Restoration is
|
|
23
|
+
* deep over the argument tree and keeps keys/types. Shell-like tools accept
|
|
24
|
+
* complete literal argument words in a single simple command; POSIX quoting
|
|
25
|
+
* and one static trailing output redirect are supported. Expansion, control
|
|
26
|
+
* syntax, unsafe quote-breaking originals and tokenized redirect targets
|
|
27
|
+
* refuse the affected call. Token-free calls pass through unchanged.
|
|
28
|
+
*
|
|
29
|
+
* Deliberately NOT registered in transparent mode: `session:prompt` (prompt
|
|
30
|
+
* admission and local persistence keep originals by design — protection is at
|
|
31
|
+
* the model boundary), `session:model.request` (routing/headers only; no
|
|
32
|
+
* content is exposed there to scan), `tool:execute.after` (local tool results
|
|
33
|
+
* stay original; their outbound replay is protected by the request kinds).
|
|
34
|
+
*
|
|
35
|
+
* The public V2 `session.deleted` event releases that session's memory and
|
|
36
|
+
* response attribution. Idle/completed sessions retain mappings for resume;
|
|
37
|
+
* there is no TTL or LRU eviction of live mappings. Disposal clears all RAM.
|
|
38
|
+
*/
|
|
39
|
+
import type { Plugin as PluginNamespace } from "@opencode/plugin";
|
|
40
|
+
import { type GuardPersistenceOptions } from "../../core/session-guard.js";
|
|
41
|
+
import type { GuardConfig } from "../../types.js";
|
|
42
|
+
export type { GuardPersistenceOptions } from "../../core/session-guard.js";
|
|
43
|
+
type V2Plugin = PluginNamespace.Plugin;
|
|
44
|
+
export interface TransparentSessionGuard {
|
|
45
|
+
/** OpenCode v2 `setup(ctx)` implementation. */
|
|
46
|
+
readonly setup: V2Plugin["setup"];
|
|
47
|
+
/**
|
|
48
|
+
* Disposes every registration this setup made (reverse order) and clears
|
|
49
|
+
* every session mapping the guard issued. Idempotent.
|
|
50
|
+
*/
|
|
51
|
+
readonly dispose: () => Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Creates a fail-closed guard whose every hook refuses all operations. Exported
|
|
55
|
+
* so the plugin entry can arm it for transparent mode when setup fails before
|
|
56
|
+
* (or during) guard construction: a transparent fallback must cover the
|
|
57
|
+
* transport routes (http/ws/aisdk) in wire mode. Hook-only failures refuse
|
|
58
|
+
* content/tool dispatch without introducing new transport registrations.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createFailClosedTransparentGuard(wireProtection?: boolean,
|
|
61
|
+
/** Why setup failed, appended to the refusal so the user sees how to fix it.
|
|
62
|
+
* Must not carry user content: option validation messages or the fixed
|
|
63
|
+
* config-load notice only. */
|
|
64
|
+
reason?: string): TransparentSessionGuard;
|
|
65
|
+
/**
|
|
66
|
+
* Creates the transparent session guard for one plugin setup (= one OpenCode
|
|
67
|
+
* process): the host-independent core (`core/session-guard.ts`) plus this
|
|
68
|
+
* layer's hook registrations and disposal.
|
|
69
|
+
*/
|
|
70
|
+
export declare function createTransparentSessionGuard(config: GuardConfig, attachmentsPolicy?: "block" | "allow", wireProtection?: boolean, persistence?: GuardPersistenceOptions): TransparentSessionGuard;
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode v2 transparent pseudonymization session guard (issue #22).
|
|
3
|
+
*
|
|
4
|
+
* One guard owns exactly ONE pseudonymizer service (bounded per setup, no
|
|
5
|
+
* session fallback, no TTL, no eviction) and its own hook registrations and
|
|
6
|
+
* disposal. Protection model:
|
|
7
|
+
*
|
|
8
|
+
* - The four model-request kinds (`context`, `compaction`, `generate`,
|
|
9
|
+
* `title`) protect an atomic snapshot (system, messages, options, tools
|
|
10
|
+
* schema) with `protectJson` and publish it back only after the whole
|
|
11
|
+
* transaction succeeds — never piecewise in place, never partial.
|
|
12
|
+
* - Wire protection registers outbound HTTP/WS and SDK admission hooks.
|
|
13
|
+
* Explicit false is hook-only: none of those outbound hooks is registered.
|
|
14
|
+
* Inbound HTTP/WS restoration is best-effort in both modes; hook-only uses
|
|
15
|
+
* the host's session/kind/model and successful content preparation, not an
|
|
16
|
+
* outgoing transport registration, to select the local mapping.
|
|
17
|
+
* - Native Responses-family WebSocket routes restore display frames; the same
|
|
18
|
+
* wireProtection switch controls outbound admission and masking. Unknown
|
|
19
|
+
* inbound protocols stay literal. SDKs honoring injected HTTP fetch reuse
|
|
20
|
+
* the wire-protected HTTP hooks; hook-only makes no transport guarantee.
|
|
21
|
+
* - `tool:execute.before` restores registered tokens in tool arguments so local
|
|
22
|
+
* tools run with the real values (the model never sees them). Restoration is
|
|
23
|
+
* deep over the argument tree and keeps keys/types. Shell-like tools accept
|
|
24
|
+
* complete literal argument words in a single simple command; POSIX quoting
|
|
25
|
+
* and one static trailing output redirect are supported. Expansion, control
|
|
26
|
+
* syntax, unsafe quote-breaking originals and tokenized redirect targets
|
|
27
|
+
* refuse the affected call. Token-free calls pass through unchanged.
|
|
28
|
+
*
|
|
29
|
+
* Deliberately NOT registered in transparent mode: `session:prompt` (prompt
|
|
30
|
+
* admission and local persistence keep originals by design — protection is at
|
|
31
|
+
* the model boundary), `session:model.request` (routing/headers only; no
|
|
32
|
+
* content is exposed there to scan), `tool:execute.after` (local tool results
|
|
33
|
+
* stay original; their outbound replay is protected by the request kinds).
|
|
34
|
+
*
|
|
35
|
+
* The public V2 `session.deleted` event releases that session's memory and
|
|
36
|
+
* response attribution. Idle/completed sessions retain mappings for resume;
|
|
37
|
+
* there is no TTL or LRU eviction of live mappings. Disposal clears all RAM.
|
|
38
|
+
*/
|
|
39
|
+
import { types } from "node:util";
|
|
40
|
+
import { ATTRIBUTION_ERROR, createGuardCore, INITIALIZATION_ERROR, NO_REASON_HINT, PROTECT_FAILED_ERROR, requireSessionID, UNSUPPORTED_ROUTE_ERROR, } from "../../core/session-guard.js";
|
|
41
|
+
import { createAISDKTransportAdmission } from "./transparent-aisdk.js";
|
|
42
|
+
import { opencodeToolPolicy } from "./tool-policy.js";
|
|
43
|
+
/** Runs pending disposals (best effort, reverse order) without throwing. */
|
|
44
|
+
async function runDisposals(disposals) {
|
|
45
|
+
for (let i = disposals.length - 1; i >= 0; i--) {
|
|
46
|
+
try {
|
|
47
|
+
await disposals[i]();
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// Continue clearing remaining registrations.
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
disposals.length = 0;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Creates a fail-closed guard whose every hook refuses all operations. Exported
|
|
57
|
+
* so the plugin entry can arm it for transparent mode when setup fails before
|
|
58
|
+
* (or during) guard construction: a transparent fallback must cover the
|
|
59
|
+
* transport routes (http/ws/aisdk) in wire mode. Hook-only failures refuse
|
|
60
|
+
* content/tool dispatch without introducing new transport registrations.
|
|
61
|
+
*/
|
|
62
|
+
export function createFailClosedTransparentGuard(wireProtection = true,
|
|
63
|
+
/** Why setup failed, appended to the refusal so the user sees how to fix it.
|
|
64
|
+
* Must not carry user content: option validation messages or the fixed
|
|
65
|
+
* config-load notice only. */
|
|
66
|
+
reason) {
|
|
67
|
+
const disposals = [];
|
|
68
|
+
const message = reason ? `${INITIALIZATION_ERROR} ${reason}` : `${INITIALIZATION_ERROR} ${NO_REASON_HINT}`;
|
|
69
|
+
const refuse = () => {
|
|
70
|
+
throw new Error(message);
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
setup: async (ctx) => {
|
|
74
|
+
try {
|
|
75
|
+
const contentHooks = ["context", "compaction", "generate", "title"];
|
|
76
|
+
const wireHooks = [
|
|
77
|
+
"http.request",
|
|
78
|
+
"http.response",
|
|
79
|
+
"experimental.ws.handshake",
|
|
80
|
+
"experimental.ws.send",
|
|
81
|
+
"experimental.ws.receive",
|
|
82
|
+
];
|
|
83
|
+
for (const name of [...contentHooks, ...(wireProtection ? wireHooks : [])]) {
|
|
84
|
+
disposals.push((await ctx.session.hook(name, refuse)).dispose);
|
|
85
|
+
}
|
|
86
|
+
if (wireProtection) {
|
|
87
|
+
disposals.push((await ctx.aisdk.hook("sdk", refuse)).dispose);
|
|
88
|
+
disposals.push((await ctx.aisdk.hook("language", refuse)).dispose);
|
|
89
|
+
}
|
|
90
|
+
disposals.push((await ctx.tool.hook("execute.before", refuse)).dispose);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
await runDisposals(disposals);
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
dispose: () => runDisposals(disposals),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Creates the transparent session guard for one plugin setup (= one OpenCode
|
|
102
|
+
* process): the host-independent core (`core/session-guard.ts`) plus this
|
|
103
|
+
* layer's hook registrations and disposal.
|
|
104
|
+
*/
|
|
105
|
+
export function createTransparentSessionGuard(config, attachmentsPolicy = "block", wireProtection = true, persistence) {
|
|
106
|
+
const core = createGuardCore(config, attachmentsPolicy, wireProtection, persistence, {}, opencodeToolPolicy);
|
|
107
|
+
if (core === null)
|
|
108
|
+
return createFailClosedTransparentGuard(wireProtection);
|
|
109
|
+
const disposals = [];
|
|
110
|
+
const aiSDK = createAISDKTransportAdmission(wireProtection);
|
|
111
|
+
return {
|
|
112
|
+
setup: async (ctx) => {
|
|
113
|
+
try {
|
|
114
|
+
for (const kind of ["context", "compaction", "generate", "title"]) {
|
|
115
|
+
disposals.push((await ctx.session.hook(kind, (event) => {
|
|
116
|
+
core.protectRequestKind(event, kind === "context" ? "primary" : kind);
|
|
117
|
+
})).dispose);
|
|
118
|
+
}
|
|
119
|
+
if (wireProtection) {
|
|
120
|
+
disposals.push((await ctx.session.hook("http.request", (event) => {
|
|
121
|
+
return core.onHttpRequest(event);
|
|
122
|
+
})).dispose);
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
disposals.push((await ctx.session.hook("http.response", (event) => {
|
|
126
|
+
return core.onHttpResponse(event);
|
|
127
|
+
})).dispose);
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (wireProtection)
|
|
131
|
+
throw error;
|
|
132
|
+
core.noticeOnce("HTTP reply restoration hook unavailable; content and tool hooks remain active");
|
|
133
|
+
}
|
|
134
|
+
const socketHooks = wireProtection
|
|
135
|
+
? ["experimental.ws.handshake", "experimental.ws.send", "experimental.ws.receive"]
|
|
136
|
+
: ["experimental.ws.receive"];
|
|
137
|
+
for (const name of socketHooks) {
|
|
138
|
+
try {
|
|
139
|
+
disposals.push((await ctx.session.hook(name, async (input) => {
|
|
140
|
+
const event = input;
|
|
141
|
+
try {
|
|
142
|
+
const sessionID = requireSessionID(event);
|
|
143
|
+
core.assertTrackable(sessionID);
|
|
144
|
+
if (name === "experimental.ws.receive" && !core.hasSession(sessionID))
|
|
145
|
+
throw new Error(ATTRIBUTION_ERROR);
|
|
146
|
+
core.ensureSeeded(sessionID);
|
|
147
|
+
if (types.isProxy(event))
|
|
148
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
149
|
+
if (name === "experimental.ws.handshake")
|
|
150
|
+
core.webSocket.handshake(event);
|
|
151
|
+
else {
|
|
152
|
+
core.assertWritableDataProperty(event, "frame");
|
|
153
|
+
event.frame = name === "experimental.ws.send" ? await core.webSocket.send(event)
|
|
154
|
+
: wireProtection ? core.webSocket.receive(event) : core.webSocket.receiveOnly(event);
|
|
155
|
+
}
|
|
156
|
+
core.track(sessionID);
|
|
157
|
+
if (name === "experimental.ws.send")
|
|
158
|
+
core.persistIfChanged(sessionID);
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (name === "experimental.ws.receive") {
|
|
162
|
+
try {
|
|
163
|
+
const frame = core.webSocket.abandonResponse(event);
|
|
164
|
+
if (frame !== undefined)
|
|
165
|
+
event.frame = frame;
|
|
166
|
+
}
|
|
167
|
+
catch { /* Unwritable or invalid input stays untouched. */ }
|
|
168
|
+
core.noticeOnce("WS reply kept original after attribution or restoration failure; placeholders may remain literal");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
core.webSocket.reset(event);
|
|
173
|
+
}
|
|
174
|
+
catch { /* Invalid attribution has no lane to reset. */ }
|
|
175
|
+
// Adapter diagnostics are static. Do not surface native URL/
|
|
176
|
+
// Headers errors, which may embed a credential or raw value.
|
|
177
|
+
const message = error instanceof Error && error.message.startsWith("LeakShield ")
|
|
178
|
+
? error.message : PROTECT_FAILED_ERROR;
|
|
179
|
+
throw new Error(`${message} [hook=${name}]`);
|
|
180
|
+
}
|
|
181
|
+
})).dispose);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if (wireProtection)
|
|
185
|
+
throw error;
|
|
186
|
+
core.noticeOnce("WS reply restoration hook unavailable; content and tool hooks remain active");
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
for (const name of wireProtection ? ["sdk", "language"] : []) {
|
|
190
|
+
disposals.push((await ctx.aisdk.hook(name, (event) => {
|
|
191
|
+
try {
|
|
192
|
+
aiSDK.admit(event);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
throw new Error(`${UNSUPPORTED_ROUTE_ERROR} AI SDK providers must honor OpenCode's injected HTTP fetch. [hook=aisdk.${name}]`);
|
|
196
|
+
}
|
|
197
|
+
})).dispose);
|
|
198
|
+
}
|
|
199
|
+
disposals.push((await ctx.tool.hook("execute.before", (event) => {
|
|
200
|
+
core.onToolBefore(event);
|
|
201
|
+
})).dispose);
|
|
202
|
+
// Public V2 events are an optional reclamation optimization: an absent
|
|
203
|
+
// or failed stream retains mappings rather than evicting live state.
|
|
204
|
+
// Subscribe only after all protection hooks have been armed.
|
|
205
|
+
if (ctx.event?.subscribe) {
|
|
206
|
+
const controller = new AbortController();
|
|
207
|
+
disposals.push(async () => { controller.abort(); });
|
|
208
|
+
void (async () => {
|
|
209
|
+
try {
|
|
210
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
211
|
+
if (controller.signal.aborted)
|
|
212
|
+
break;
|
|
213
|
+
if (event.type === "session.deleted")
|
|
214
|
+
core.releaseSession(event.data.sessionID);
|
|
215
|
+
}
|
|
216
|
+
if (!controller.signal.aborted)
|
|
217
|
+
core.noticeOnce("session lifecycle stream ended; mappings retained until unload");
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
if (!controller.signal.aborted)
|
|
221
|
+
core.noticeOnce("session lifecycle stream unavailable; mappings retained until unload");
|
|
222
|
+
}
|
|
223
|
+
})();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
// Registration failed partway: undo what was armed, then surface the
|
|
228
|
+
// failure so the caller can fall back to its fail-closed setup.
|
|
229
|
+
// R-round (F4.5): the store handle must not leak on this path.
|
|
230
|
+
await runDisposals(disposals);
|
|
231
|
+
core.closeResources();
|
|
232
|
+
aiSDK.dispose();
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
dispose: async () => {
|
|
237
|
+
await runDisposals(disposals);
|
|
238
|
+
aiSDK.dispose();
|
|
239
|
+
core.dispose();
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Plugin as PluginNamespace } from "@opencode/plugin";
|
|
2
|
+
import { type IngressMode } from "../../decision/ingress.js";
|
|
3
|
+
import type { EnvQueryService } from "./env-queries.js";
|
|
4
|
+
import type { GuardConfig } from "../../types.js";
|
|
5
|
+
type V2Plugin = PluginNamespace.Plugin;
|
|
6
|
+
export interface DeidentifyOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Master key, one per plugin setup (= one OpenCode server process); held in
|
|
9
|
+
* memory only. Per-session placeholder keys are derived from it via
|
|
10
|
+
* HMAC-SHA256 so placeholders from different sessions cannot be linked.
|
|
11
|
+
*/
|
|
12
|
+
sessionKey: Buffer;
|
|
13
|
+
}
|
|
14
|
+
/** Creates the OpenCode v2 `setup(ctx)` implementation for the given configuration. */
|
|
15
|
+
export declare function createV2Setup(config: GuardConfig, mode: IngressMode, deidentify?: DeidentifyOptions,
|
|
16
|
+
/** When set, the readonly env query tools are registered (opt-in `envQueries`). */
|
|
17
|
+
envQueries?: EnvQueryService): V2Plugin["setup"];
|
|
18
|
+
/** Creates a fail-closed OpenCode v2 `setup(ctx)` that blocks every protected
|
|
19
|
+
* operation. `reason`, when given, is appended to the refusal; it must not carry
|
|
20
|
+
* user content (option validation messages or the fixed config-load notice
|
|
21
|
+
* only). */
|
|
22
|
+
export declare function createFailClosedV2Setup(reason?: string): V2Plugin["setup"];
|
|
23
|
+
export {};
|