leakshield 0.4.0 → 0.5.1

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.
@@ -633,7 +633,7 @@ export async function runDoctor(deps) {
633
633
  id: "options",
634
634
  state: "fail",
635
635
  detail: `Plugin options are invalid for "${entry.ref}" (${entry.source}) — every protected request would fail closed at runtime: ${validation.error}`,
636
- fix: "Correct the options in opencode.json (see README for valid combinations).",
636
+ fix: 'Correct the options in opencode.json (valid combinations: the "OpenCode Plugin" section of README.md and docs/plugin/env-queries.md).',
637
637
  });
638
638
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
639
639
  }
@@ -655,9 +655,17 @@ export async function runDoctor(deps) {
655
655
  checks.push({
656
656
  id: "options",
657
657
  state: "ok",
658
- detail: `mode=${options.mode}${weakest.entry.options?.mode === undefined ? " (default)" : ""}${options.mode === "transparent" ? ` wireProtection=${options.wireProtection ?? true}` : ""}${options.attachments === "allow" ? " attachments=allow" : ""}${options.deidentify ? " +deidentify" : ""}${options.envQueries ? " +envQueries" : ""}${options.configPath ? ` configPath=${options.configPath}` : ""}${across}`,
658
+ detail: `mode=${options.mode}${weakest.entry.options?.mode === undefined ? " (default)" : ""}${options.mode === "transparent" ? ` wireProtection=${options.wireProtection ?? true}` : ""}${options.attachments === "allow" ? " attachments=allow" : ""}${options.deidentify ? " +deidentify" : ""}${options.envQueries ? (options.mode === "transparent" ? " +envQueries(ignored)" : " +envQueries") : ""}${options.configPath ? ` configPath=${options.configPath}` : ""}${across}`,
659
659
  });
660
660
  checks.push(persistenceCheck(options, deps));
661
+ if (validated.some((candidate) => candidate.options.mode === "transparent" && candidate.options.envQueries)) {
662
+ checks.push({
663
+ id: "env-queries",
664
+ state: "warn",
665
+ detail: "envQueries is ignored in transparent mode; the guard_env_* tools are not registered.",
666
+ fix: 'Remove envQueries, or set mode to "block" or "redact" to use the env query tools.',
667
+ });
668
+ }
661
669
  // Guard config load. Every configured entry's guard config must load: the
662
670
  // weakest entry supplies the summary, but a broken configPath in another
663
671
  // entry still breaks the install it would run under (#67).
@@ -5,7 +5,7 @@ import { EnvQueryService } from "./env-queries.js";
5
5
  import { createFailClosedHooks } from "./hooks.js";
6
6
  import { createFailClosedV2Setup, createV2Setup } from "./v2.js";
7
7
  import { createFailClosedTransparentGuard, createTransparentSessionGuard } from "./transparent.js";
8
- import { PluginOptionsSchema, withDefaultMode } from "../../guard-options.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 options = PluginOptionsSchema.parse(withDefaultMode(ctx.options));
47
- const loaded = loadConfigWithFingerprint(options.configPath, ctx.location.directory);
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; deidentify/envQueries combos were
52
- // already rejected at the option schema. W2: persistence options flow
53
- // into the guard only when explicitly enabled (default memory-only,
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.";
@@ -57,7 +57,11 @@ export interface TransparentSessionGuard {
57
57
  * transport routes (http/ws/aisdk) in wire mode. Hook-only failures refuse
58
58
  * content/tool dispatch without introducing new transport registrations.
59
59
  */
60
- export declare function createFailClosedTransparentGuard(wireProtection?: boolean): TransparentSessionGuard;
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;
61
65
  /**
62
66
  * Creates the transparent session guard for one plugin setup (= one OpenCode
63
67
  * process): the host-independent core (`core/session-guard.ts`) plus this
@@ -37,7 +37,7 @@
37
37
  * there is no TTL or LRU eviction of live mappings. Disposal clears all RAM.
38
38
  */
39
39
  import { types } from "node:util";
40
- import { ATTRIBUTION_ERROR, createGuardCore, INITIALIZATION_ERROR, PROTECT_FAILED_ERROR, requireSessionID, UNSUPPORTED_ROUTE_ERROR, } from "../../core/session-guard.js";
40
+ import { ATTRIBUTION_ERROR, createGuardCore, INITIALIZATION_ERROR, NO_REASON_HINT, PROTECT_FAILED_ERROR, requireSessionID, UNSUPPORTED_ROUTE_ERROR, } from "../../core/session-guard.js";
41
41
  import { createAISDKTransportAdmission } from "./transparent-aisdk.js";
42
42
  import { opencodeToolPolicy } from "./tool-policy.js";
43
43
  /** Runs pending disposals (best effort, reverse order) without throwing. */
@@ -59,10 +59,15 @@ async function runDisposals(disposals) {
59
59
  * transport routes (http/ws/aisdk) in wire mode. Hook-only failures refuse
60
60
  * content/tool dispatch without introducing new transport registrations.
61
61
  */
62
- export function createFailClosedTransparentGuard(wireProtection = true) {
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) {
63
67
  const disposals = [];
68
+ const message = reason ? `${INITIALIZATION_ERROR} ${reason}` : `${INITIALIZATION_ERROR} ${NO_REASON_HINT}`;
64
69
  const refuse = () => {
65
- throw new Error(INITIALIZATION_ERROR);
70
+ throw new Error(message);
66
71
  };
67
72
  return {
68
73
  setup: async (ctx) => {
@@ -15,6 +15,9 @@ export interface DeidentifyOptions {
15
15
  export declare function createV2Setup(config: GuardConfig, mode: IngressMode, deidentify?: DeidentifyOptions,
16
16
  /** When set, the readonly env query tools are registered (opt-in `envQueries`). */
17
17
  envQueries?: EnvQueryService): V2Plugin["setup"];
18
- /** Creates a fail-closed OpenCode v2 `setup(ctx)` that blocks every protected operation. */
19
- export declare function createFailClosedV2Setup(): 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"];
20
23
  export {};
@@ -2,6 +2,7 @@ import { createHmac } from "node:crypto";
2
2
  import { ContentHashCache, protectUnknownStrings, } from "../../decision/ingress.js";
3
3
  import { deidentifyText } from "../../decision/deidentify.js";
4
4
  import { registerV2EnvTools } from "./env-tools.js";
5
+ import { NO_REASON_HINT } from "../../core/session-guard.js";
5
6
  const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
6
7
  const BLOCKED_ATTACHMENT_NOTICE = "[LeakShield blocked an attachment: its content cannot be scanned, so it was not sent.]";
7
8
  function isRecordLike(value) {
@@ -128,9 +129,10 @@ async function registerProtectionHooks(ctx, config, mode, protectorForEvent) {
128
129
  protectToolAfterEvent(event, config, mode, protectorForEvent(event));
129
130
  });
130
131
  }
131
- async function registerFailClosedHooks(ctx) {
132
+ async function registerFailClosedHooks(ctx, reason) {
133
+ const message = reason ? `${INITIALIZATION_ERROR} ${reason}` : `${INITIALIZATION_ERROR} ${NO_REASON_HINT}`;
132
134
  const blockRequest = async () => {
133
- throw new Error(INITIALIZATION_ERROR);
135
+ throw new Error(message);
134
136
  };
135
137
  await ctx.session.hook("prompt", blockRequest);
136
138
  await ctx.session.hook("context", blockRequest);
@@ -210,7 +212,10 @@ envQueries) {
210
212
  }
211
213
  };
212
214
  }
213
- /** Creates a fail-closed OpenCode v2 `setup(ctx)` that blocks every protected operation. */
214
- export function createFailClosedV2Setup() {
215
- return registerFailClosedHooks;
215
+ /** Creates a fail-closed OpenCode v2 `setup(ctx)` that blocks every protected
216
+ * operation. `reason`, when given, is appended to the refusal; it must not carry
217
+ * user content (option validation messages or the fixed config-load notice
218
+ * only). */
219
+ export function createFailClosedV2Setup(reason) {
220
+ return (ctx) => registerFailClosedHooks(ctx, reason);
216
221
  }
@@ -129,6 +129,14 @@ export function findConfigPath(overridePath) {
129
129
  * authorize against content that never existed at a single point in time.
130
130
  */
131
131
  export function loadConfigWithFingerprint(overridePath, workspaceRoot = process.cwd()) {
132
+ // An explicit path (OpenCode configPath, pi LEAKSHIELD_CONFIG, proxy --config)
133
+ // that does not exist fails the load. Falling back to the built-in defaults
134
+ // would silently drop the user's keywords, domains, rules and env_files.
135
+ // Hosts fail closed on this error; only the doctor and terminal output show
136
+ // the path.
137
+ if (overridePath && !fs.existsSync(overridePath)) {
138
+ throw new Error(`guard config file not found: ${overridePath}`);
139
+ }
132
140
  const configPath = findConfigPath(overridePath);
133
141
  if (!configPath) {
134
142
  return {
@@ -6,4 +6,4 @@
6
6
  *
7
7
  * Do not import OpenCode or Claude Code adapters from this module.
8
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";
9
+ export { createGuardCore, requireSessionID, INITIALIZATION_ERROR, NO_REASON_HINT, PROTECT_FAILED_ERROR, ATTRIBUTION_ERROR, UNSUPPORTED_ROUTE_ERROR, type GuardCore, type GuardPersistenceOptions, type HostToolPolicy, type RecordLike, } from "./session-guard.js";
@@ -6,4 +6,4 @@
6
6
  *
7
7
  * Do not import OpenCode or Claude Code adapters from this module.
8
8
  */
9
- export { createGuardCore, requireSessionID, INITIALIZATION_ERROR, PROTECT_FAILED_ERROR, ATTRIBUTION_ERROR, UNSUPPORTED_ROUTE_ERROR, } from "./session-guard.js";
9
+ export { createGuardCore, requireSessionID, INITIALIZATION_ERROR, NO_REASON_HINT, PROTECT_FAILED_ERROR, ATTRIBUTION_ERROR, UNSUPPORTED_ROUTE_ERROR, } from "./session-guard.js";
@@ -6,6 +6,7 @@ export type RecordLike = {
6
6
  [key: string]: unknown;
7
7
  };
8
8
  export declare const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
9
+ export declare const NO_REASON_HINT = "Run `leakshield --doctor` to see why, fix it and restart OpenCode.";
9
10
  export declare const PROTECT_FAILED_ERROR = "LeakShield blocked a model request because it could not be masked safely.";
10
11
  export declare const ATTRIBUTION_ERROR = "LeakShield blocked a response because it could not be matched to a request.";
11
12
  export declare const UNSUPPORTED_ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
@@ -9,6 +9,7 @@ import { parseSupportedShellArguments, warnDegradation, isShellSafeOriginal, com
9
9
  import { BUILTIN_RULES } from "../rules/builtin.js";
10
10
  // ─── Static failure messages (no content ever included) ─────────────────────
11
11
  export const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
12
+ export const NO_REASON_HINT = "Run `leakshield --doctor` to see why, fix it and restart OpenCode.";
12
13
  export const PROTECT_FAILED_ERROR = "LeakShield blocked a model request because it could not be masked safely.";
13
14
  export const ATTRIBUTION_ERROR = "LeakShield blocked a response because it could not be matched to a request.";
14
15
  export const UNSUPPORTED_ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
@@ -20,6 +20,10 @@
20
20
  * - Transport metadata is inspected: decoded non-auth headers and query
21
21
  * parameters, and numeric body values, must not scan as sensitive;
22
22
  * legitimate authentication headers are preserved.
23
+ * - A declared request body coding (gzip, deflate, br, zstd) is decoded before
24
+ * scanning, under the same byte cap; an unknown or undecodable coding
25
+ * refuses rather than being scanned as text. A decoded request is forwarded
26
+ * as plain JSON without the stale coding and length headers.
23
27
  * - The whole body is validated BEFORE any token is issued, then protected in
24
28
  * ONE atomic transaction, so a rejected request commits no mapping or
25
29
  * session capacity.
@@ -102,7 +106,8 @@ export declare function withOpaqueAttachments<T extends Record<string, unknown>>
102
106
  * whole body protected in a SINGLE transaction, so a rejected request commits
103
107
  * no mapping or session capacity. The original request is consumed only through
104
108
  * `clone()`; the ORIGINAL request object is returned only when its body already
105
- * is the canonical serialization of what was scanned. A rebuilt request inherits every transport control (method, url,
109
+ * is the canonical serialization of what was scanned and was not content-encoded.
110
+ * A rebuilt request inherits every transport control (method, url,
106
111
  * mode, credentials, cache, redirect, referrer, integrity, keepalive, signal,
107
112
  * authentication headers) and recomputes body headers.
108
113
  */
package/dist/core/wire.js CHANGED
@@ -20,6 +20,10 @@
20
20
  * - Transport metadata is inspected: decoded non-auth headers and query
21
21
  * parameters, and numeric body values, must not scan as sensitive;
22
22
  * legitimate authentication headers are preserved.
23
+ * - A declared request body coding (gzip, deflate, br, zstd) is decoded before
24
+ * scanning, under the same byte cap; an unknown or undecodable coding
25
+ * refuses rather than being scanned as text. A decoded request is forwarded
26
+ * as plain JSON without the stale coding and length headers.
23
27
  * - The whole body is validated BEFORE any token is issued, then protected in
24
28
  * ONE atomic transaction, so a rejected request commits no mapping or
25
29
  * session capacity.
@@ -191,6 +195,86 @@ async function readCappedText(source, limit, failure) {
191
195
  throw new Error(failure);
192
196
  return out + tail;
193
197
  }
198
+ /** Request-body codings this module can decode before scanning. A request
199
+ * declaring anything else is refused: compressed bytes are not scannable as
200
+ * text, and guessing their meaning would hide content from the scanner. */
201
+ const REQUEST_BODY_ENCODINGS = new Set(["gzip", "deflate", "br", "zstd"]);
202
+ /** zlib method per coding. zstd exists only on hosts built with it; a missing
203
+ * decoder refuses instead of forwarding an uninspected body. */
204
+ const REQUEST_BODY_DECODERS = {
205
+ gzip: "gunzip",
206
+ deflate: "inflate",
207
+ br: "brotliDecompress",
208
+ zstd: "zstdDecompress",
209
+ };
210
+ /** Reads the raw bytes of a cloned body, capped before accumulation. */
211
+ async function readCappedBytes(source, limit, failure) {
212
+ const clone = source.clone();
213
+ if (clone.body === null)
214
+ return new Uint8Array(0);
215
+ const reader = clone.body.getReader();
216
+ const chunks = [];
217
+ let size = 0;
218
+ for (;;) {
219
+ let step;
220
+ try {
221
+ step = await reader.read();
222
+ }
223
+ catch {
224
+ throw new Error(failure);
225
+ }
226
+ if (step.done)
227
+ break;
228
+ size += step.value.byteLength;
229
+ if (size > limit) {
230
+ void reader.cancel().catch(() => { });
231
+ throw new Error(failure);
232
+ }
233
+ chunks.push(step.value);
234
+ }
235
+ const out = new Uint8Array(size);
236
+ let offset = 0;
237
+ for (const chunk of chunks) {
238
+ out.set(chunk, offset);
239
+ offset += chunk.byteLength;
240
+ }
241
+ return out;
242
+ }
243
+ /** Decodes a declared request coding under the scanner's byte cap. zlib
244
+ * enforces the cap while inflating, so a small body cannot expand past it. */
245
+ async function decodeRequestBody(bytes, encoding) {
246
+ const zlib = (await import("node:zlib"));
247
+ const decompress = zlib[REQUEST_BODY_DECODERS[encoding]];
248
+ if (typeof decompress !== "function")
249
+ throw new Error(refusal("body-encoding"));
250
+ const decoded = await new Promise((resolve, reject) => {
251
+ decompress(bytes, { maxOutputLength: MAX_BODY_BYTES }, (error, result) => {
252
+ if (error)
253
+ reject(error);
254
+ else
255
+ resolve(result);
256
+ });
257
+ }).catch((error) => {
258
+ const code = error?.code;
259
+ throw new Error(refusal(code === "ERR_BUFFER_TOO_LARGE" ? "body-cap" : "body-encoding"));
260
+ });
261
+ return new TextDecoder().decode(decoded);
262
+ }
263
+ /** Reads a request body as text, decoding a declared content-coding. `decoded`
264
+ * tells the caller the original compressed Request cannot be the forwarded
265
+ * one, even when the scanned serialization equals the text. */
266
+ async function readRequestBody(request) {
267
+ const encoding = (request.headers.get("content-encoding") ?? "").trim().toLowerCase();
268
+ if (encoding === "" || encoding === "identity") {
269
+ return { text: await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap")), decoded: false };
270
+ }
271
+ if (!REQUEST_BODY_ENCODINGS.has(encoding))
272
+ throw new Error(refusal("body-encoding"));
273
+ const bytes = await readCappedBytes(request, MAX_BODY_BYTES, refusal("body-cap"));
274
+ if (bytes.byteLength === 0)
275
+ return { text: "", decoded: true };
276
+ return { text: await decodeRequestBody(bytes, encoding), decoded: true };
277
+ }
194
278
  /** Visits every numeric value in a strict-JSON tree. */
195
279
  function walkNumbers(value, visit) {
196
280
  if (typeof value === "number") {
@@ -606,12 +690,14 @@ function collectWireStructuralStrings(body) {
606
690
  return out;
607
691
  }
608
692
  /** Forwards exactly the value that was scanned. The original bytes are kept
609
- * only when they already are that serialization: a body that parses to
610
- * something else (a duplicate key keeps only its last occurrence, invalid
611
- * UTF-8 decodes to U+FFFD) would otherwise carry content the scanner never
612
- * saw. Keeping the original Request otherwise preserves its identity. */
613
- function forwardSerialized(request, raw, serialized) {
614
- if (serialized === raw && !raw.includes("\uFFFD"))
693
+ * only when they already are that serialization and are not content-encoded: a
694
+ * body that parses to something else (a duplicate key keeps only its last
695
+ * occurrence, invalid UTF-8 decodes to U+FFFD) would otherwise carry content
696
+ * the scanner never saw. A decoded body is always rebuilt plain, because the
697
+ * original bytes are compressed and no longer match what was scanned. Keeping
698
+ * the original Request otherwise preserves its identity. */
699
+ function forwardSerialized(request, raw, serialized, decoded = false) {
700
+ if (!decoded && serialized === raw && !raw.includes("\uFFFD"))
615
701
  return request;
616
702
  const headers = new Headers(request.headers);
617
703
  headers.delete("content-encoding");
@@ -628,7 +714,8 @@ function forwardSerialized(request, raw, serialized) {
628
714
  * whole body protected in a SINGLE transaction, so a rejected request commits
629
715
  * no mapping or session capacity. The original request is consumed only through
630
716
  * `clone()`; the ORIGINAL request object is returned only when its body already
631
- * is the canonical serialization of what was scanned. A rebuilt request inherits every transport control (method, url,
717
+ * is the canonical serialization of what was scanned and was not content-encoded.
718
+ * A rebuilt request inherits every transport control (method, url,
632
719
  * mode, credentials, cache, redirect, referrer, integrity, keepalive, signal,
633
720
  * authentication headers) and recomputes body headers.
634
721
  */
@@ -648,7 +735,7 @@ export async function remaskChatCompletionsRequest(service, sessionID, request)
648
735
  // for arbitrary content, so a bodyless request has no verifiable boundary.
649
736
  if (request.body === null)
650
737
  throw new Error(refusal("body-missing"));
651
- const raw = await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap"));
738
+ const { text: raw, decoded } = await readRequestBody(request);
652
739
  if (raw.length === 0)
653
740
  throw new Error(refusal("body-empty"));
654
741
  let body;
@@ -755,7 +842,7 @@ export async function remaskChatCompletionsRequest(service, sessionID, request)
755
842
  }
756
843
  }
757
844
  const serialized = JSON.stringify(next);
758
- return forwardSerialized(request, raw, serialized);
845
+ return forwardSerialized(request, raw, serialized, decoded);
759
846
  }
760
847
  // ─── Anthropic Messages request (wire dialect) ──────────────────────────────
761
848
  /**
@@ -981,7 +1068,7 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
981
1068
  inspectTransportMetadata(service, sessionID, request);
982
1069
  if (request.body === null)
983
1070
  throw new Error(refusal("body-missing"));
984
- const raw = await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap"));
1071
+ const { text: raw, decoded } = await readRequestBody(request);
985
1072
  if (raw.length === 0)
986
1073
  throw new Error(refusal("body-empty"));
987
1074
  let body;
@@ -1024,7 +1111,7 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
1024
1111
  throw new Error(refusal("structural-drift"));
1025
1112
  }
1026
1113
  const serialized = JSON.stringify(next);
1027
- return forwardSerialized(request, raw, serialized);
1114
+ return forwardSerialized(request, raw, serialized, decoded);
1028
1115
  }
1029
1116
  // ─── OpenAI Responses request (wire dialect) ────────────────────────────────
1030
1117
  /**
@@ -1219,7 +1306,7 @@ export async function remaskResponsesRequest(service, sessionID, request) {
1219
1306
  inspectTransportMetadata(service, sessionID, request);
1220
1307
  if (request.body === null)
1221
1308
  throw new Error(refusal("body-missing"));
1222
- const raw = await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap"));
1309
+ const { text: raw, decoded } = await readRequestBody(request);
1223
1310
  if (raw.length === 0)
1224
1311
  throw new Error(refusal("body-empty"));
1225
1312
  let body;
@@ -1285,7 +1372,7 @@ export async function remaskResponsesRequest(service, sessionID, request) {
1285
1372
  }
1286
1373
  }
1287
1374
  const serialized = JSON.stringify(next);
1288
- return forwardSerialized(request, raw, serialized);
1375
+ return forwardSerialized(request, raw, serialized, decoded);
1289
1376
  }
1290
1377
  function isRecordArgumentsString(item) {
1291
1378
  return typeof item.arguments === "string";
@@ -47,6 +47,9 @@ const PLACEHOLDER_MAP = {
47
47
  PII_PHONE_TW: "[REDACTED_PHONE]",
48
48
  PII_PHONE_INTL: "[REDACTED_PHONE]",
49
49
  PII_ID_TW: "[REDACTED_ID]",
50
+ PII_PASSPORT: "[REDACTED_PASSPORT]",
51
+ PII_SSN: "[REDACTED_SSN]",
52
+ TW_BUSINESS_NO: "[REDACTED_BUSINESS_NO]",
50
53
  DB_CONNECTION: "[REDACTED_DB_CONNECTION]",
51
54
  PRIVATE_DOMAIN: "[REDACTED_PRIVATE_DOMAIN]",
52
55
  NDA_KEYWORD: "[REDACTED_NDA_TERM]",
@@ -12,8 +12,10 @@ export const PERSISTENCE_TTL_MAX_DAYS = 3650;
12
12
  // makes the parse throw, and every entry path already fails closed on that.
13
13
  // transparent is the reversible pseudonymization mode (issue #22):
14
14
  // it owns its own bounded session service and transport hooks, so combining
15
- // it with the second (deidentify) protection pipeline or the env query
16
- // tools is rejected here — every entry path fails closed on the parse error.
15
+ // it with the second (deidentify) protection pipeline is rejected here —
16
+ // every entry path fails closed on the parse error. envQueries is accepted
17
+ // but ignored in transparent mode (the OpenCode plugin logs a warning and
18
+ // does not register the env tools).
17
19
  export const PluginOptionsSchema = z
18
20
  .object({
19
21
  // No schema default: callers fill it in with withDefaultMode() before
@@ -62,9 +64,6 @@ export const PluginOptionsSchema = z
62
64
  })
63
65
  .refine((options) => !options.deidentify || options.mode === "redact", {
64
66
  message: "deidentify requires mode 'redact'",
65
- })
66
- .refine((options) => options.mode !== "transparent" || !options.envQueries, {
67
- message: "envQueries is not supported in mode 'transparent'",
68
67
  })
69
68
  .refine((options) => options.attachments === "block" || options.mode === "transparent", {
70
69
  message: 'attachments "allow" requires mode "transparent"',
@@ -46,6 +46,46 @@ function ibanValid(raw) {
46
46
  }
47
47
  return remainder === 1;
48
48
  }
49
+ /** ICAO 9303 檢查碼:字元權重 7,3,1 循環,`<` 為 0、A=10…Z=35。 */
50
+ function mrzCheckDigit(span) {
51
+ let sum = 0;
52
+ for (let i = 0; i < span.length; i++) {
53
+ const ch = span[i];
54
+ const value = ch === "<" ? 0 : ch >= "0" && ch <= "9" ? ch.charCodeAt(0) - 48 : ch.charCodeAt(0) - 55;
55
+ sum += value * (i % 3 === 0 ? 7 : i % 3 === 1 ? 3 : 1);
56
+ }
57
+ return String(sum % 10);
58
+ }
59
+ /**
60
+ * TD3(護照)第 2 列:護照號碼、出生日期、到期日與複合欄各有一個檢查碼。
61
+ * 只接受「44 個大寫英數/`<`」的整行再驗這四碼,所以一般大寫字串不會誤命中。
62
+ */
63
+ function mrzLine2Valid(raw) {
64
+ if (raw.length !== 44)
65
+ return false;
66
+ return (mrzCheckDigit(raw.slice(0, 9)) === raw[9] &&
67
+ mrzCheckDigit(raw.slice(13, 19)) === raw[19] &&
68
+ mrzCheckDigit(raw.slice(21, 27)) === raw[27] &&
69
+ mrzCheckDigit(raw.slice(0, 10) + raw.slice(13, 20) + raw.slice(21, 43)) === raw[43]);
70
+ }
71
+ /**
72
+ * 台灣統一編號:乘積的各位數字和可被 5 整除(財政部 2023-04 起;被 10 整除的舊號碼必定
73
+ * 也通過,所以不另外判斷舊制)。第 7 碼為 7 時乘積是 28,官方允許把「2+8=10」再視為 1,
74
+ * 因此那一種算法也接受。全部同一個數字(含 00000000)不算:檢查碼對它沒有鑑別力。
75
+ */
76
+ function twBusinessNoValid(raw) {
77
+ if (!/^[0-9]{8}$/.test(raw) || /^(\d)\1{7}$/.test(raw))
78
+ return false;
79
+ const weights = [1, 2, 1, 2, 1, 2, 4, 1];
80
+ let sum = 0;
81
+ for (let i = 0; i < 8; i++) {
82
+ const product = Number(raw[i]) * weights[i];
83
+ sum += Math.floor(product / 10) + (product % 10);
84
+ }
85
+ if (sum % 5 === 0)
86
+ return true;
87
+ return raw[6] === "7" && (sum - 9) % 5 === 0;
88
+ }
49
89
  /** 僅公共可路由 IPv4 視為敏感;私有/回環/鏈路本地/CGNAT/保留段不命中(config 常見值)。 */
50
90
  function publicIPv4(raw) {
51
91
  const octets = raw.split(".").map(Number);
@@ -322,7 +362,7 @@ export const BUILTIN_RULES = [
322
362
  // token 類字串的誤報是量測到的主要 FP 源(0.294%)。要開啟:
323
363
  // settings.rule_overrides["phone-tw"]: true。漏真電話風險見 README。
324
364
  optIn: true,
325
- pattern: /(?:(?:\+886)|0)9\d{2}[-\s]?\d{3}[-\s]?\d{3}/g,
365
+ pattern: /(?:\+886[-\s]?|0)9\d{2}[-\s]?\d{3}[-\s]?\d{3}/g,
326
366
  },
327
367
  {
328
368
  id: "phone-intl",
@@ -331,7 +371,9 @@ export const BUILTIN_RULES = [
331
371
  description: "國際電話號碼",
332
372
  // Opt-in,同 phone-tw(P2)。要開啟:settings.rule_overrides["phone-intl"]: true
333
373
  optIn: true,
334
- pattern: /\+[1-9]\d{6,14}\b/g,
374
+ // 數字之間可有一個空格或連字號(+44 20 7946 0958、+1-202-555-0143),總位數 7–15(E.164)。
375
+ // + 前緊接英數字、底線或點時不算(版本號建置編號 1.2.3+20261125、算式 2+2)。
376
+ pattern: /(?<![\w.])\+[1-9](?:[ -]?\d){6,14}\b/g,
335
377
  },
336
378
  {
337
379
  id: "id-tw",
@@ -341,6 +383,37 @@ export const BUILTIN_RULES = [
341
383
  // 加上 word boundary 避免擷取較長字串的片段
342
384
  pattern: /\b[A-Z][12]\d{8}\b/g,
343
385
  },
386
+ {
387
+ id: "passport-mrz",
388
+ type: "PII_PASSPORT",
389
+ severity: "HIGH",
390
+ description: "護照號碼(MRZ 第 2 列)",
391
+ // 護照號碼沒有通用格式,猜「標籤+號碼」會命中任何 6–9 位英數;只有 MRZ 那一行
392
+ // 自帶四個檢查碼,能用形狀以外的證據判斷,所以只收 TD3 第 2 列。
393
+ pattern: /^[A-Z0-9<]{44}(?=\r?$)/gm,
394
+ validate: mrzLine2Valid,
395
+ },
396
+ {
397
+ id: "ssn-us",
398
+ type: "PII_SSN",
399
+ severity: "HIGH",
400
+ description: "美國社會安全號碼(SSN)",
401
+ // Opt-in:只有形狀、沒有檢查碼。000/666/9xx 區段、00 群組、0000 序號都不是有效 SSN。
402
+ // 要開啟:settings.rule_overrides["ssn-us"]: true
403
+ optIn: true,
404
+ pattern: /\b(?!000|666|9\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b/g,
405
+ },
406
+ {
407
+ id: "tw-business-no",
408
+ type: "TW_BUSINESS_NO",
409
+ severity: "MEDIUM",
410
+ description: "台灣統一編號",
411
+ // Opt-in:新制檢查碼只約掉八成,日期、流水號與版本號都可能通過,不算低誤報。
412
+ // 要開啟:settings.rule_overrides["tw-business-no"]: true
413
+ optIn: true,
414
+ pattern: /(?<!\d)[0-9]{8}(?!\d)/g,
415
+ validate: twBusinessNoValid,
416
+ },
344
417
  // ── 資料庫連線字串 ────────────────────────────────────────────────────────
345
418
  {
346
419
  id: "db-connection",
package/dist/types.d.ts CHANGED
@@ -54,7 +54,7 @@ export interface GuardConfig {
54
54
  * enforced at persisted-seed intake, so the legal labels must exist as a
55
55
  * value, not just a type. Keep list and type in one place.
56
56
  */
57
- export declare const FINDING_TYPES: readonly ["API_KEY", "SECRET", "TOKEN", "PII_EMAIL", "PII_PHONE_TW", "PII_PHONE_INTL", "PII_ID_TW", "DB_CONNECTION", "PRIVATE_DOMAIN", "NDA_KEYWORD", "ENV_SECRET", "CUSTOM", "PII_CREDIT_CARD", "PII_IBAN", "PII_IP", "PII_URL", "ENCODED"];
57
+ export declare const FINDING_TYPES: readonly ["API_KEY", "SECRET", "TOKEN", "PII_EMAIL", "PII_PHONE_TW", "PII_PHONE_INTL", "PII_ID_TW", "PII_PASSPORT", "PII_SSN", "TW_BUSINESS_NO", "DB_CONNECTION", "PRIVATE_DOMAIN", "NDA_KEYWORD", "ENV_SECRET", "CUSTOM", "PII_CREDIT_CARD", "PII_IBAN", "PII_IP", "PII_URL", "ENCODED"];
58
58
  export type FindingType = (typeof FINDING_TYPES)[number];
59
59
  export interface Finding {
60
60
  type: FindingType;
package/dist/types.js CHANGED
@@ -11,6 +11,9 @@ export const FINDING_TYPES = [
11
11
  "PII_PHONE_TW",
12
12
  "PII_PHONE_INTL",
13
13
  "PII_ID_TW",
14
+ "PII_PASSPORT",
15
+ "PII_SSN",
16
+ "TW_BUSINESS_NO",
14
17
  "DB_CONNECTION",
15
18
  "PRIVATE_DOMAIN",
16
19
  "NDA_KEYWORD",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "leakshield",
3
- "version": "0.4.0",
4
- "description": "OpenCode plugin, pi adapter, CLI, and web scanner for sensitive content before sending it to AI",
3
+ "version": "0.5.1",
4
+ "description": "Masks sensitive content before it reaches an AI model: OpenCode plugin, pi extension, Claude Code proxy, CLI, and web scanner",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Jared Wang",
7
7
  "repository": {
@@ -16,6 +16,8 @@
16
16
  "opencode",
17
17
  "opencode-plugin",
18
18
  "pi-package",
19
+ "pi",
20
+ "claude-code",
19
21
  "secrets",
20
22
  "pii",
21
23
  "redaction",
@@ -38,7 +40,9 @@
38
40
  "NOTICE"
39
41
  ],
40
42
  "pi": {
41
- "extensions": ["./dist/adapters/pi/extension.js"]
43
+ "extensions": [
44
+ "./dist/adapters/pi/extension.js"
45
+ ]
42
46
  },
43
47
  "engines": {
44
48
  "node": ">=20"