leakshield 0.5.1 → 0.5.3

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.
@@ -15,7 +15,7 @@
15
15
  * Claude Code sends outside the base URL.
16
16
  */
17
17
  import { type Server } from "node:http";
18
- import type { GuardConfig } from "../../types.js";
18
+ import { type GuardConfig } from "../../types.js";
19
19
  export declare const DEFAULT_PROXY_HOST = "127.0.0.1";
20
20
  export declare const DEFAULT_PROXY_PORT = 8787;
21
21
  export declare const DEFAULT_UPSTREAM = "https://api.anthropic.com";
@@ -18,6 +18,7 @@ import { createServer } from "node:http";
18
18
  import { Readable } from "node:stream";
19
19
  import { createGuardCore, PROTECT_FAILED_ERROR } from "../../core/session-guard.js";
20
20
  import { containsTokenPrefix, createPseudonymizer } from "../../decision/pseudonymization.js";
21
+ import { DEFAULT_MAX_BODY_BYTES } from "../../types.js";
21
22
  export const DEFAULT_PROXY_HOST = "127.0.0.1";
22
23
  export const DEFAULT_PROXY_PORT = 8787;
23
24
  export const DEFAULT_UPSTREAM = "https://api.anthropic.com";
@@ -127,7 +128,7 @@ function headersCarryFinding(headers, unsafe) {
127
128
  * well keeps that guarantee independent of the core and lets an oversized or
128
129
  * non-JSON body be refused before the core reads it.
129
130
  */
130
- async function canonicalJsonBody(request) {
131
+ async function canonicalJsonBody(request, limit) {
131
132
  if (request.body === null)
132
133
  return null;
133
134
  const reader = request.body.getReader();
@@ -138,7 +139,7 @@ async function canonicalJsonBody(request) {
138
139
  if (step.done)
139
140
  break;
140
141
  total += step.value.byteLength;
141
- if (total > MAX_BODY_BYTES) {
142
+ if (total > limit) {
142
143
  void reader.cancel().catch(() => { });
143
144
  return null;
144
145
  }
@@ -224,7 +225,7 @@ export function createClaudeCodeProxy(options) {
224
225
  const response = await send(new Request(targetOf(incoming), { method, headers }), signal);
225
226
  return response === null ? anthropicError(502, UPSTREAM_UNREACHABLE) : relay(response, method);
226
227
  }
227
- const body = await canonicalJsonBody(request).catch(() => null);
228
+ const body = await canonicalJsonBody(request, options.config.settings.max_body_bytes ?? DEFAULT_MAX_BODY_BYTES).catch(() => null);
228
229
  if (body === null)
229
230
  return refuse(method, route, UNREADABLE_BODY);
230
231
  if (route === "count_tokens") {
@@ -20,7 +20,7 @@
20
20
  */
21
21
  import { type PluginOptions } from "../../guard-options.js";
22
22
  import type { DoctorCheck, DoctorReport } from "../../doctor-report.js";
23
- import type { GuardConfig } from "../../types.js";
23
+ import { type GuardConfig } from "../../types.js";
24
24
  export interface DoctorDeps {
25
25
  opencodeVersion(): string | null;
26
26
  readIfExists(filePath: string): string | null;
@@ -31,6 +31,7 @@ import { BUILTIN_RULE_IDS } from "../../rules/builtin.js";
31
31
  import { skippedCustomRules, customRuleBoundaries } from "../../rules/dynamic.js";
32
32
  import { allowlistSuppressions } from "../../scanner/allowlist.js";
33
33
  import { scanText } from "../../scanner/engine.js";
34
+ import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_OPERATION_UNITS, } from "../../types.js";
34
35
  const SMOKE_CANARY = "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA";
35
36
  /**
36
37
  * Severity-agnostic probe for the allowlist diagnostics: every finding, plus
@@ -707,6 +708,12 @@ export async function runDoctor(deps) {
707
708
  ? `Guard configs resolved for ${validated.length} entries.`
708
709
  : "Default guard config resolved.",
709
710
  });
711
+ const guardSettings = guardConfig.settings;
712
+ checks.push({
713
+ id: "limits",
714
+ state: "ok",
715
+ detail: `Request body ${Math.round(((guardSettings?.max_body_bytes ?? DEFAULT_MAX_BODY_BYTES) / (1024 * 1024)) * 10) / 10} MiB, one masking operation ${Math.round((guardSettings?.max_operation_units ?? DEFAULT_MAX_OPERATION_UNITS) / (1024 * 1024))} Mi units of combined input+output. Raise them in settings for a long session.`,
716
+ });
710
717
  // Custom rules the scanner skips (the ReDoS timing heuristic; uncompileable
711
718
  // patterns already failed the load above). Descriptions only, never patterns.
712
719
  const skipped = skippedCustomRules(guardConfig);
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import type { GuardConfig } from "../types.js";
2
+ import { type GuardConfig } from "../types.js";
3
3
  export declare const GuardConfigSchema: z.ZodPipe<z.ZodCustom<unknown, unknown>, z.ZodObject<{
4
4
  nda_keywords: z.ZodDefault<z.ZodArray<z.ZodString>>;
5
5
  private_domains: z.ZodDefault<z.ZodArray<z.ZodString>>;
@@ -34,6 +34,8 @@ export declare const GuardConfigSchema: z.ZodPipe<z.ZodCustom<unknown, unknown>,
34
34
  }[] | null>>;
35
35
  settings: z.ZodPrefault<z.ZodPipe<z.ZodCustom<unknown, unknown>, z.ZodObject<{
36
36
  max_chars: z.ZodDefault<z.ZodNumber>;
37
+ max_body_bytes: z.ZodDefault<z.ZodNumber>;
38
+ max_operation_units: z.ZodDefault<z.ZodNumber>;
37
39
  show_line_numbers: z.ZodDefault<z.ZodBoolean>;
38
40
  preview_length: z.ZodDefault<z.ZodNumber>;
39
41
  encoding_detection: z.ZodDefault<z.ZodBoolean>;
@@ -9,6 +9,7 @@ import { parseCidr } from "../scanner/cidr.js";
9
9
  import { BUILTIN_RULE_IDS } from "../rules/builtin.js";
10
10
  import { customRulePattern } from "../rules/dynamic.js";
11
11
  import { plainObject } from "./plain-object.js";
12
+ import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_OPERATION_UNITS, MAX_MAX_BODY_BYTES, MAX_MAX_OPERATION_UNITS, MIN_MAX_BODY_BYTES, MIN_MAX_OPERATION_UNITS, } from "../types.js";
12
13
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
14
  const MAX_DYNAMIC_RULE_LENGTH = 200;
14
15
  const MAX_PRIVATE_DOMAIN_LENGTH = 255;
@@ -43,6 +44,8 @@ export const GuardConfigSchema = plainObject(z.object({
43
44
  custom_rules: z.array(CustomRuleSchema).max(MAX_CUSTOM_RULES).nullable().default([]).transform((v) => v ?? []),
44
45
  settings: plainObject(z.object({
45
46
  max_chars: z.number().int().positive().default(200000),
47
+ max_body_bytes: z.number().int().min(MIN_MAX_BODY_BYTES).max(MAX_MAX_BODY_BYTES).default(DEFAULT_MAX_BODY_BYTES),
48
+ max_operation_units: z.number().int().min(MIN_MAX_OPERATION_UNITS).max(MAX_MAX_OPERATION_UNITS).default(DEFAULT_MAX_OPERATION_UNITS),
46
49
  show_line_numbers: z.boolean().default(true),
47
50
  preview_length: z.number().int().positive().default(60),
48
51
  encoding_detection: z.boolean().default(false),
@@ -1,7 +1,7 @@
1
1
  import { type MappingKeyProvider } from "../decision/mapping-store.js";
2
2
  import { createResponsesWebSocketAdapter } from "./ws.js";
3
3
  import { ToolLeafPolicy } from "./tool-restore-policy.js";
4
- import type { GuardConfig } from "../types.js";
4
+ import { type GuardConfig } from "../types.js";
5
5
  export type RecordLike = {
6
6
  [key: string]: unknown;
7
7
  };
@@ -6,7 +6,7 @@ import { walkSchemaStrings } from "../decision/schema-strings.js";
6
6
  import { classifyModelRoute, remaskModelRequest, restoreModelResponse, withOpaqueAttachments, } from "./wire.js";
7
7
  import { createResponsesWebSocketAdapter } from "./ws.js";
8
8
  import { parseSupportedShellArguments, warnDegradation, isShellSafeOriginal, commandAllowsEmbeddedTokens, isWgetExecuteCommand, TOKEN_SCAN, NEAR_MISS_V2_HEAD, NEAR_MISS_V2_SEGMENT_LETTERS, NEAR_MISS_V2_CATEGORIES, collectNearMissLetters, createInertPositionCheck, } from "./tool-restore-policy.js";
9
- import { BUILTIN_RULES } from "../rules/builtin.js";
9
+ import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_OPERATION_UNITS } from "../types.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
12
  export const NO_REASON_HINT = "Run `leakshield --doctor` to see why, fix it and restart OpenCode.";
@@ -54,6 +54,24 @@ function prepareMaskError(reason, config) {
54
54
  const maxChars = config.settings.max_chars;
55
55
  return `${marker} A string, before or after masking, exceeded settings.max_chars (${maxChars}). Raise settings.max_chars or split the content.`;
56
56
  }
57
+ /** Content-free diagnostics for a refused prepare.mask: fixed counter names and
58
+ * UTF-16 character counts, never the refused text. */
59
+ function maskFailureDetail(failure, input) {
60
+ const limit = failure.limit === undefined ? "" : ` limit=${failure.limit.kind} value=${failure.limit.value}`;
61
+ const sizes = ["system", "messages", "options", "tools"]
62
+ .map((field) => {
63
+ if (input[field] === undefined)
64
+ return `${field}=0`;
65
+ try {
66
+ return `${field}=${JSON.stringify(input[field])?.length ?? 0}`;
67
+ }
68
+ catch {
69
+ return `${field}=?`;
70
+ }
71
+ })
72
+ .join(" ");
73
+ return `prepare.mask reason=${failure.reason}${limit} chars ${sizes}`;
74
+ }
57
75
  /**
58
76
  * Bound on distinct session identities retained for disposal. The core already
59
77
  * caps committed sessions; this bounds identities seen with safe-only content
@@ -64,15 +82,15 @@ const MAX_TRACKED_SESSIONS = 4096;
64
82
  /**
65
83
  * The core's small standalone defaults are not a whole model-history budget.
66
84
  * Match its mapping-session ceiling to the guard's existing bookkeeping cap.
67
- * HTTP bodies and WS frames are already capped at 4 MiB; allow 8 Mi UTF-16
68
- * units of combined input/output work for assembled requests. The node cap
69
- * bounds schema-heavy histories independently. Per-string scanner bounds,
85
+ * HTTP bodies and WS frames default to 8 MiB; allow 16 Mi UTF-16 units of
86
+ * combined input/output work for assembled requests. Both are configurable
87
+ * within bounds. The node cap bounds schema-heavy histories independently. Per-string scanner bounds,
70
88
  * depth and aggregate mapping-byte/entry caps remain unchanged.
71
89
  */
72
90
  const TRANSPARENT_LIMITS = {
73
91
  maxSessions: MAX_TRACKED_SESSIONS,
74
92
  maxNodes: 100000,
75
- maxUnitsPerOperation: 8 * 1024 * 1024,
93
+ maxUnitsPerOperation: DEFAULT_MAX_OPERATION_UNITS,
76
94
  };
77
95
  // ─── Structural validation ───────────────────────────────────────────────────
78
96
  function isRecordLike(value) {
@@ -364,7 +382,10 @@ function inputCarriesToken(value, seen) {
364
382
  * the only erasure path). Returns null when the pseudonymizer cannot be built.
365
383
  */
366
384
  export function createGuardCore(config, attachmentsPolicy = "block", wireProtection = true, persistence, dialect = {}, hostToolPolicy) {
367
- const created = createPseudonymizer(config, TRANSPARENT_LIMITS);
385
+ const created = createPseudonymizer(config, {
386
+ ...TRANSPARENT_LIMITS,
387
+ maxUnitsPerOperation: config.settings.max_operation_units ?? TRANSPARENT_LIMITS.maxUnitsPerOperation,
388
+ });
368
389
  if (!created.ok)
369
390
  return null;
370
391
  const pseudonymizer = created;
@@ -625,40 +646,17 @@ export function createGuardCore(config, attachmentsPolicy = "block", wireProtect
625
646
  for (const item of Object.values(value))
626
647
  assertNumbersSafe(item);
627
648
  };
628
- /**
629
- * Field-aware transport exemption for the opt-in URL rule. Transport
630
- * positions (request URL, query values, header values) are infrastructure:
631
- * masking or refusing an endpoint URL would break every request once the
632
- * URL rule is enabled. Neutralizing URL matches BEFORE the strict checks
633
- * removes both the direct findings and the percent-decoding hazard windows
634
- * that would otherwise re-surface the URL text — while non-URL secrets
635
- * (e.g. an API key encoded in a query value outside a URL match) still
636
- * refuse. Only active when the URL rule itself is enabled; body-content
637
- * URLs are unaffected (they are masked like any other finding).
638
- */
639
- const urlRule = BUILTIN_RULES.find((rule) => rule.id === "url");
640
- const urlRuleId = urlRule?.id;
641
- const urlRuleOptIn = urlRule?.optIn === true;
642
- const urlRuleActive = urlRuleId !== undefined &&
643
- (urlRuleId in (config.settings.rule_overrides ?? {})
644
- ? config.settings.rule_overrides?.[urlRuleId] === true
645
- : !urlRuleOptIn);
646
- const neutralizeTransportUrls = (text) => {
647
- if (!urlRuleActive || urlRule === undefined)
648
- return text;
649
- // Fresh RegExp per call: the shared rule pattern is stateful (/g).
650
- return text.replace(new RegExp(urlRule.pattern.source, urlRule.pattern.flags), "url");
651
- };
652
649
  const transportService = {
653
650
  protectJsonForModel: (sid, value) => pseudonymizer.protectJsonForModel(sid, value),
654
651
  restoreText: (sid, text) => pseudonymizer.restoreText(sid, text),
655
652
  restoreTextForDisplay: (sid, text) => pseudonymizer.restoreTextForDisplay(sid, text),
656
653
  detectSensitive,
657
654
  isStructuralIdentifierSafe: (sid, text) => pseudonymizer.isStructuralIdentifierSafe(sid, text),
658
- transportDetectSensitive: (text) => detectSensitive(neutralizeTransportUrls(text)),
659
- isTransportIdentifierSafe: (sid, text) => pseudonymizer.isStructuralIdentifierSafe(sid, neutralizeTransportUrls(text)),
655
+ transportDetectSensitive: (text) => !pseudonymizer.isTextSafe(text, "transport"),
656
+ isTransportIdentifierSafe: (sid, text) => pseudonymizer.isStructuralIdentifierSafe(sid, text, "transport"),
660
657
  attachmentsPolicy,
661
658
  anthropicThinking: dialect.anthropicThinking ?? "refuse",
659
+ maxBodyBytes: config.settings.max_body_bytes ?? DEFAULT_MAX_BODY_BYTES,
662
660
  };
663
661
  const webSocket = createResponsesWebSocketAdapter(transportService, wireProtection, hasProtectedContext);
664
662
  /** Release only an explicitly deleted session; persisted rows keep their TTL. */
@@ -849,8 +847,10 @@ export function createGuardCore(config, attachmentsPolicy = "block", wireProtect
849
847
  // encoded-content detection.
850
848
  const protectTree = (input) => {
851
849
  const masked = pseudonymizer.protectJsonForModel(sessionID, input);
852
- if (!masked.ok)
850
+ if (!masked.ok) {
851
+ warnDegradation(maskFailureDetail(masked, input));
853
852
  throw new Error(prepareMaskError(masked.reason, config));
853
+ }
854
854
  if (!isRecordLike(masked.value))
855
855
  throw new Error(PROTECT_FAILED_ERROR);
856
856
  return masked.value;
@@ -47,6 +47,8 @@ export interface TransportMaskingService {
47
47
  protectJsonForModel(sessionID: string, value: unknown): PseudonymJsonResult;
48
48
  restoreText(sessionID: string, text: string): PseudonymTextResult;
49
49
  restoreTextForDisplay(sessionID: string, text: string): PseudonymTextResult;
50
+ /** Request body and WS frame byte cap. Response reads keep the fixed cap. */
51
+ readonly maxBodyBytes: number;
50
52
  /** Non-committing sensitivity detection: no mapping, no mutation. */
51
53
  detectSensitive(text: string): boolean;
52
54
  /**
package/dist/core/wire.js CHANGED
@@ -75,7 +75,7 @@ function refusal(code) {
75
75
  * bound, and a code-unit cap would allow up to ~4× the stated bytes for
76
76
  * multi-byte text. Each cap is charged BEFORE the value is accumulated.
77
77
  */
78
- const MAX_BODY_BYTES = 4 * 1024 * 1024;
78
+ const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
79
79
  // SSE framing and original-event retention caps live in the shared recovery
80
80
  // stream; protocol adapters only own their bounded text/channel state.
81
81
  /** A single choice's held-back content channel. */
@@ -242,13 +242,13 @@ async function readCappedBytes(source, limit, failure) {
242
242
  }
243
243
  /** Decodes a declared request coding under the scanner's byte cap. zlib
244
244
  * enforces the cap while inflating, so a small body cannot expand past it. */
245
- async function decodeRequestBody(bytes, encoding) {
245
+ async function decodeRequestBody(bytes, encoding, limit) {
246
246
  const zlib = (await import("node:zlib"));
247
247
  const decompress = zlib[REQUEST_BODY_DECODERS[encoding]];
248
248
  if (typeof decompress !== "function")
249
249
  throw new Error(refusal("body-encoding"));
250
250
  const decoded = await new Promise((resolve, reject) => {
251
- decompress(bytes, { maxOutputLength: MAX_BODY_BYTES }, (error, result) => {
251
+ decompress(bytes, { maxOutputLength: limit }, (error, result) => {
252
252
  if (error)
253
253
  reject(error);
254
254
  else
@@ -263,17 +263,17 @@ async function decodeRequestBody(bytes, encoding) {
263
263
  /** Reads a request body as text, decoding a declared content-coding. `decoded`
264
264
  * tells the caller the original compressed Request cannot be the forwarded
265
265
  * one, even when the scanned serialization equals the text. */
266
- async function readRequestBody(request) {
266
+ async function readRequestBody(request, limit) {
267
267
  const encoding = (request.headers.get("content-encoding") ?? "").trim().toLowerCase();
268
268
  if (encoding === "" || encoding === "identity") {
269
- return { text: await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap")), decoded: false };
269
+ return { text: await readCappedText(request, limit, refusal("body-cap")), decoded: false };
270
270
  }
271
271
  if (!REQUEST_BODY_ENCODINGS.has(encoding))
272
272
  throw new Error(refusal("body-encoding"));
273
- const bytes = await readCappedBytes(request, MAX_BODY_BYTES, refusal("body-cap"));
273
+ const bytes = await readCappedBytes(request, limit, refusal("body-cap"));
274
274
  if (bytes.byteLength === 0)
275
275
  return { text: "", decoded: true };
276
- return { text: await decodeRequestBody(bytes, encoding), decoded: true };
276
+ return { text: await decodeRequestBody(bytes, encoding, limit), decoded: true };
277
277
  }
278
278
  /** Visits every numeric value in a strict-JSON tree. */
279
279
  function walkNumbers(value, visit) {
@@ -358,6 +358,22 @@ function strayTokenIn(value, path = []) {
358
358
  */
359
359
  function inspectTransportMetadata(service, sessionID, request) {
360
360
  const url = new URL(request.url);
361
+ let pathname;
362
+ try {
363
+ pathname = decodeURIComponent(url.pathname);
364
+ }
365
+ catch {
366
+ throw new Error(refusal("metadata-path-encoding"));
367
+ }
368
+ if (containsTokenPrefix(pathname)) {
369
+ if (!service.isTransportIdentifierSafe(sessionID, pathname)) {
370
+ throw new Error(refusal("metadata-path-token"));
371
+ }
372
+ warnDegradation("request path preserved with a literal placeholder");
373
+ }
374
+ else if (service.transportDetectSensitive(pathname)) {
375
+ throw new Error(refusal("metadata-path-sensitive"));
376
+ }
361
377
  for (const [name, value] of url.searchParams) {
362
378
  if (containsTokenPrefix(name) || containsTokenPrefix(value)) {
363
379
  if (!service.isStructuralIdentifierSafe(sessionID, name) ||
@@ -372,6 +388,11 @@ function inspectTransportMetadata(service, sessionID, request) {
372
388
  }
373
389
  }
374
390
  for (const [name, value] of request.headers) {
391
+ const authentication = AUTH_HEADER_NAMES.has(name.toLowerCase());
392
+ // A literal placeholder in the value cannot exempt the header name.
393
+ if (!authentication && service.detectSensitive(name)) {
394
+ throw new Error(refusal("metadata-header-sensitive"));
395
+ }
375
396
  if (containsTokenPrefix(value)) {
376
397
  if (!service.isTransportIdentifierSafe(sessionID, value)) {
377
398
  throw new Error(refusal("metadata-header-token"));
@@ -379,9 +400,9 @@ function inspectTransportMetadata(service, sessionID, request) {
379
400
  warnDegradation("transport metadata preserved with a literal placeholder");
380
401
  continue;
381
402
  }
382
- if (AUTH_HEADER_NAMES.has(name.toLowerCase()))
403
+ if (authentication)
383
404
  continue;
384
- if (service.detectSensitive(name) || service.transportDetectSensitive(value)) {
405
+ if (service.transportDetectSensitive(value)) {
385
406
  throw new Error(refusal("metadata-header-sensitive"));
386
407
  }
387
408
  }
@@ -735,7 +756,7 @@ export async function remaskChatCompletionsRequest(service, sessionID, request)
735
756
  // for arbitrary content, so a bodyless request has no verifiable boundary.
736
757
  if (request.body === null)
737
758
  throw new Error(refusal("body-missing"));
738
- const { text: raw, decoded } = await readRequestBody(request);
759
+ const { text: raw, decoded } = await readRequestBody(request, service.maxBodyBytes);
739
760
  if (raw.length === 0)
740
761
  throw new Error(refusal("body-empty"));
741
762
  let body;
@@ -1068,7 +1089,7 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
1068
1089
  inspectTransportMetadata(service, sessionID, request);
1069
1090
  if (request.body === null)
1070
1091
  throw new Error(refusal("body-missing"));
1071
- const { text: raw, decoded } = await readRequestBody(request);
1092
+ const { text: raw, decoded } = await readRequestBody(request, service.maxBodyBytes);
1072
1093
  if (raw.length === 0)
1073
1094
  throw new Error(refusal("body-empty"));
1074
1095
  let body;
@@ -1306,7 +1327,7 @@ export async function remaskResponsesRequest(service, sessionID, request) {
1306
1327
  inspectTransportMetadata(service, sessionID, request);
1307
1328
  if (request.body === null)
1308
1329
  throw new Error(refusal("body-missing"));
1309
- const { text: raw, decoded } = await readRequestBody(request);
1330
+ const { text: raw, decoded } = await readRequestBody(request, service.maxBodyBytes);
1310
1331
  if (raw.length === 0)
1311
1332
  throw new Error(refusal("body-empty"));
1312
1333
  let body;
@@ -1431,13 +1452,13 @@ export async function restoreChatCompletionsResponse(service, sessionID, respons
1431
1452
  async function passThroughIfTokenBearing(response) {
1432
1453
  if (response.body === null)
1433
1454
  return response;
1434
- const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
1455
+ const raw = await readCappedText(response, MAX_RESPONSE_BYTES, UNSUPPORTED_RESPONSE);
1435
1456
  if (containsTokenPrefix(raw))
1436
1457
  warnDegradation("response body carries an unplaceable placeholder; kept literal");
1437
1458
  return response;
1438
1459
  }
1439
1460
  async function restoreJsonResponse(service, sessionID, response) {
1440
- const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
1461
+ const raw = await readCappedText(response, MAX_RESPONSE_BYTES, UNSUPPORTED_RESPONSE);
1441
1462
  if (raw.length === 0)
1442
1463
  return response;
1443
1464
  let body;
@@ -1823,7 +1844,7 @@ function anthropicStrayTokenIn(value, fields, tokenizedThinking = false) {
1823
1844
  return false;
1824
1845
  }
1825
1846
  async function restoreAnthropicJsonResponse(service, sessionID, response) {
1826
- const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
1847
+ const raw = await readCappedText(response, MAX_RESPONSE_BYTES, UNSUPPORTED_RESPONSE);
1827
1848
  if (raw.length === 0)
1828
1849
  return response;
1829
1850
  let body;
@@ -2248,7 +2269,7 @@ export function restoreResponsesEventDisplay(service, sessionID, chunk) {
2248
2269
  warnDegradation("responses frame carries an unplaceable placeholder; kept literal");
2249
2270
  }
2250
2271
  async function restoreResponsesJsonResponse(service, sessionID, response) {
2251
- const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
2272
+ const raw = await readCappedText(response, MAX_RESPONSE_BYTES, UNSUPPORTED_RESPONSE);
2252
2273
  if (raw.length === 0)
2253
2274
  return response;
2254
2275
  let body;
package/dist/core/ws.js CHANGED
@@ -8,7 +8,6 @@ const ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
8
8
  const FRAME_ERROR = "LeakShield blocked an unsupported or malformed WebSocket frame.";
9
9
  const ATTRIBUTION_ERROR = "LeakShield blocked a WebSocket frame that could not be matched to a request.";
10
10
  const LIMIT_ERROR = "LeakShield blocked an oversized WebSocket buffer.";
11
- const MAX_FRAME_BYTES = 4 * 1024 * 1024;
12
11
  const MAX_LANES = 1024;
13
12
  const MAX_CHANNELS = 256;
14
13
  const MAX_CHANNEL_BYTES = 65_536;
@@ -27,10 +26,10 @@ function laneKey(event) {
27
26
  throw new Error(LIMIT_ERROR);
28
27
  return key;
29
28
  }
30
- function parseFrame(frame) {
29
+ function parseFrame(frame, limit) {
31
30
  if (typeof frame !== "string")
32
31
  throw new Error(FRAME_ERROR);
33
- if (bytes(frame) > MAX_FRAME_BYTES)
32
+ if (bytes(frame) > limit)
34
33
  throw new Error(LIMIT_ERROR);
35
34
  let value;
36
35
  try {
@@ -44,6 +43,7 @@ function parseFrame(frame) {
44
43
  return value;
45
44
  }
46
45
  export function createResponsesWebSocketAdapter(service, wireProtection, hasProtectedContext = () => false) {
46
+ const maxFrameBytes = service.maxBodyBytes;
47
47
  const lanes = new Map();
48
48
  let hookOnlyNoticed = false;
49
49
  let totalBytes = 0;
@@ -130,7 +130,7 @@ export function createResponsesWebSocketAdapter(service, wireProtection, hasProt
130
130
  lane.sent = true;
131
131
  return event.frame;
132
132
  }
133
- const body = parseFrame(event.frame);
133
+ const body = parseFrame(event.frame, maxFrameBytes);
134
134
  if (body.type !== "response.create")
135
135
  throw new Error(FRAME_ERROR);
136
136
  let frame = String(event.frame);
@@ -168,7 +168,7 @@ export function createResponsesWebSocketAdapter(service, wireProtection, hasProt
168
168
  }
169
169
  if (!lane.sent || lane.terminal)
170
170
  throw new Error(ATTRIBUTION_ERROR);
171
- const chunk = parseFrame(event.frame);
171
+ const chunk = parseFrame(event.frame, maxFrameBytes);
172
172
  const type = String(chunk.type);
173
173
  const response = record(chunk.response) ? chunk.response : undefined;
174
174
  if (type === "response.created") {
@@ -237,7 +237,7 @@ export function createResponsesWebSocketAdapter(service, wireProtection, hasProt
237
237
  if (wireProtection || !hasProtectedContext(event))
238
238
  throw new Error(ATTRIBUTION_ERROR);
239
239
  const key = laneKey(event);
240
- const chunk = parseFrame(event.frame);
240
+ const chunk = parseFrame(event.frame, maxFrameBytes);
241
241
  if (chunk.type === "response.created") {
242
242
  const previous = lanes.get(key);
243
243
  if (!previous || !previous.sent || previous.terminal) {
@@ -261,7 +261,7 @@ export function createResponsesWebSocketAdapter(service, wireProtection, hasProt
261
261
  return undefined;
262
262
  let frame;
263
263
  try {
264
- const chunk = parseFrame(event.frame);
264
+ const chunk = parseFrame(event.frame, maxFrameBytes);
265
265
  const id = record(chunk.response) ? chunk.response.id : chunk.response_id;
266
266
  if (lane.sent && !lane.terminal && lane.responseID !== undefined && (id === undefined || id === lane.responseID) &&
267
267
  RESPONSES_TEXT_DELTA_TYPES.has(String(chunk.type)) && typeof chunk.delta === "string") {
@@ -44,9 +44,16 @@ import type { GuardConfig } from "../types.js";
44
44
  export type PseudonymFailureReason = "invalid_session" | "invalid_input" | "session_limit" | "entry_limit" | "session_capacity" | "aggregate_capacity" | "operation_limit" | "truncated_content" | "encoded_content"
45
45
  /** Zero-width characters hide a value the scanner would otherwise detect. */
46
46
  | "unicode_evasion" | "invalid_finding_span" | "token_overlap" | "malformed_token" | "unknown_token" | "residual_sensitive_content" | "unsafe_structure" | "key_collision" | "epoch_collision" | "token_collision" | "scanner_failure" | "internal_failure";
47
+ /** Which per-operation counter tripped, and its value at the refusal. */
48
+ export interface OperationLimitDetail {
49
+ readonly kind: "units" | "nodes" | "depth";
50
+ readonly value: number;
51
+ }
47
52
  export interface PseudonymFailure {
48
53
  ok: false;
49
54
  reason: PseudonymFailureReason;
55
+ /** Present only with operation_limit; counts carry no content. */
56
+ limit?: OperationLimitDetail;
50
57
  }
51
58
  export type PseudonymTextResult = {
52
59
  ok: true;
@@ -96,7 +103,8 @@ export interface SessionSeed {
96
103
  }>;
97
104
  }
98
105
  export interface PseudonymizerService {
99
- isTextSafe(text: string): boolean;
106
+ /** Transport scope excludes only the opt-in URL rule, retaining all other detectors. */
107
+ isTextSafe(text: string, scope?: "transport"): boolean;
100
108
  /**
101
109
  * Session-aware safety check for structural positions (identifiers,
102
110
  * transport metadata). Marker-shaped content is never unsafe per se:
@@ -104,7 +112,7 @@ export interface PseudonymizerService {
104
112
  * payloads scan as ordinary text. Unsafe only on a scanner finding (the
105
113
  * position cannot be masked or renamed) or a scanning failure.
106
114
  */
107
- isStructuralIdentifierSafe(sessionId: string, text: string): boolean;
115
+ isStructuralIdentifierSafe(sessionId: string, text: string, scope?: "transport"): boolean;
108
116
  /**
109
117
  * Rebuilds a session from persisted mappings (W2/B3, decision
110
118
  * 2026-10-07-db-over-t2). All-or-nothing: on any failure the registry is
@@ -105,8 +105,8 @@ const DEFAULT_LIMITS = {
105
105
  maxUnitsPerOperation: 1024 * 1024,
106
106
  };
107
107
  // ─── Small helpers ───────────────────────────────────────────────────────────
108
- function fail(reason) {
109
- return { ok: false, reason };
108
+ function fail(reason, limit) {
109
+ return limit === undefined ? { ok: false, reason } : { ok: false, reason, limit };
110
110
  }
111
111
  function isValidSessionId(value) {
112
112
  // Exact identity: no trimming, no normalization, no shared fallback.
@@ -736,7 +736,7 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
736
736
  prospectiveUnits += staged.token.length - (staged.end - staged.start);
737
737
  }
738
738
  if (chargedUnits + prospectiveUnits > limits.maxUnitsPerOperation) {
739
- return fail("operation_limit");
739
+ return fail("operation_limit", { kind: "units", value: chargedUnits + prospectiveUnits });
740
740
  }
741
741
  // Assemble the output once from checked pieces instead of repeated
742
742
  // large-slice concatenations.
@@ -897,7 +897,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
897
897
  // exactly like the replacement path (budget 10 must refuse "abcdef").
898
898
  if (!containsTokenPrefix(text)) {
899
899
  if (chargedUnits + text.length > limits.maxUnitsPerOperation) {
900
- return fail("operation_limit");
900
+ return fail("operation_limit", { kind: "units", value: chargedUnits + text.length });
901
901
  }
902
902
  return { ok: true, text };
903
903
  }
@@ -905,7 +905,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
905
905
  let outputUnits = 0;
906
906
  const appendPiece = (piece) => {
907
907
  if (chargedUnits + outputUnits + piece.length > limits.maxUnitsPerOperation) {
908
- return fail("operation_limit");
908
+ return fail("operation_limit", { kind: "units", value: chargedUnits + outputUnits + piece.length });
909
909
  }
910
910
  outputUnits += piece.length;
911
911
  pieces.push(piece);
@@ -965,20 +965,25 @@ function walkStrictJson(value, depth, path, budget, limits, transform) {
965
965
  budget.nodes += 1;
966
966
  budget.units += NODE_OVERHEAD_UNITS;
967
967
  if (budget.nodes > limits.maxNodes || budget.units > limits.maxUnitsPerOperation) {
968
- return fail("operation_limit");
968
+ return budget.nodes > limits.maxNodes
969
+ ? fail("operation_limit", { kind: "nodes", value: budget.nodes })
970
+ : fail("operation_limit", { kind: "units", value: budget.units });
971
+ }
972
+ if (depth > limits.maxDepth) {
973
+ return fail("operation_limit", { kind: "depth", value: depth });
969
974
  }
970
- if (depth > limits.maxDepth)
971
- return fail("operation_limit");
972
975
  if (typeof value === "string") {
973
976
  budget.units += value.length;
974
- if (budget.units > limits.maxUnitsPerOperation)
975
- return fail("operation_limit");
977
+ if (budget.units > limits.maxUnitsPerOperation) {
978
+ return fail("operation_limit", { kind: "units", value: budget.units });
979
+ }
976
980
  const transformed = transform(value);
977
981
  if (!transformed.ok)
978
982
  return transformed;
979
983
  budget.units += transformed.text.length;
980
- if (budget.units > limits.maxUnitsPerOperation)
981
- return fail("operation_limit");
984
+ if (budget.units > limits.maxUnitsPerOperation) {
985
+ return fail("operation_limit", { kind: "units", value: budget.units });
986
+ }
982
987
  return { ok: true, value: transformed.text };
983
988
  }
984
989
  if (value === null || typeof value === "boolean")
@@ -1008,7 +1013,7 @@ function walkStrictJson(value, depth, path, budget, limits, transform) {
1008
1013
  return fail("unsafe_structure");
1009
1014
  const length = value.length;
1010
1015
  if (length > limits.maxNodes)
1011
- return fail("operation_limit");
1016
+ return fail("operation_limit", { kind: "nodes", value: length });
1012
1017
  const indexKeys = keys.filter((key) => key !== "length");
1013
1018
  if (indexKeys.length !== length) {
1014
1019
  return fail("unsafe_structure"); // sparse array and/or unexpected properties
@@ -1037,14 +1042,16 @@ function walkStrictJson(value, depth, path, budget, limits, transform) {
1037
1042
  const seenKeys = new Set();
1038
1043
  for (const key of keys) {
1039
1044
  budget.units += key.length;
1040
- if (budget.units > limits.maxUnitsPerOperation)
1041
- return fail("operation_limit");
1045
+ if (budget.units > limits.maxUnitsPerOperation) {
1046
+ return fail("operation_limit", { kind: "units", value: budget.units });
1047
+ }
1042
1048
  const transformedKey = transform(key);
1043
1049
  if (!transformedKey.ok)
1044
1050
  return transformedKey;
1045
1051
  budget.units += transformedKey.text.length;
1046
- if (budget.units > limits.maxUnitsPerOperation)
1047
- return fail("operation_limit");
1052
+ if (budget.units > limits.maxUnitsPerOperation) {
1053
+ return fail("operation_limit", { kind: "units", value: budget.units });
1054
+ }
1048
1055
  if (seenKeys.has(transformedKey.text))
1049
1056
  return fail("key_collision");
1050
1057
  seenKeys.add(transformedKey.text);
@@ -1062,6 +1069,17 @@ function walkStrictJson(value, depth, path, budget, limits, transform) {
1062
1069
  return { ok: true, value: output };
1063
1070
  }
1064
1071
  function buildService(config, limits) {
1072
+ // Disable the URL detector instead of removing URL text: a URL can also
1073
+ // contain a credential, private domain, keyword or configured exact value.
1074
+ // Both scopes use the same registry, so owned-marker exemptions stay local
1075
+ // to the session that issued them.
1076
+ const transportConfig = {
1077
+ ...config,
1078
+ settings: {
1079
+ ...config.settings,
1080
+ rule_overrides: { ...config.settings.rule_overrides, url: false },
1081
+ },
1082
+ };
1065
1083
  const registry = {
1066
1084
  sessions: new Map(),
1067
1085
  epochs: new Set(),
@@ -1078,11 +1096,11 @@ function buildService(config, limits) {
1078
1096
  detectedValues: new Map(),
1079
1097
  outputStrings: [],
1080
1098
  });
1081
- const isTextSafe = (text) => {
1099
+ const isTextSafe = (text, scope) => {
1082
1100
  if (typeof text !== "string" || text.length > limits.maxUnitsPerOperation)
1083
1101
  return false;
1084
1102
  try {
1085
- const result = scanForModelBoundary(text, config, []);
1103
+ const result = scanForModelBoundary(text, scope === "transport" ? transportConfig : config, []);
1086
1104
  return result.ok && result.original.safe;
1087
1105
  }
1088
1106
  catch {
@@ -1098,7 +1116,7 @@ function buildService(config, limits) {
1098
1116
  * position cannot be protected without breaking the protocol) or a
1099
1117
  * scanning failure — P1, 2026-10-06b.
1100
1118
  */
1101
- const isStructuralIdentifierSafe = (sessionId, text) => {
1119
+ const isStructuralIdentifierSafe = (sessionId, text, scope) => {
1102
1120
  if (typeof text !== "string" || text.length > limits.maxUnitsPerOperation)
1103
1121
  return false;
1104
1122
  if (!isValidSessionId(sessionId))
@@ -1108,7 +1126,7 @@ function buildService(config, limits) {
1108
1126
  const owned = scanOwnedTokenSpans(text, (token) => session?.reverse.get(token) !== undefined, true);
1109
1127
  if (!owned.ok)
1110
1128
  return false;
1111
- const scanned = scanForModelBoundary(text, config, owned.spans);
1129
+ const scanned = scanForModelBoundary(text, scope === "transport" ? transportConfig : config, owned.spans);
1112
1130
  return scanned.ok && scanned.original.safe;
1113
1131
  }
1114
1132
  catch {
@@ -1120,15 +1138,16 @@ function buildService(config, limits) {
1120
1138
  return fail("invalid_session");
1121
1139
  if (typeof text !== "string")
1122
1140
  return fail("invalid_input");
1123
- if (text.length > limits.maxUnitsPerOperation)
1124
- return fail("operation_limit");
1141
+ if (text.length > limits.maxUnitsPerOperation) {
1142
+ return fail("operation_limit", { kind: "units", value: text.length });
1143
+ }
1125
1144
  try {
1126
1145
  const tx = newTransaction(sessionId);
1127
1146
  const result = protectStringTx(tx, config, limits, text, text.length, preserveUnknownMarkers);
1128
1147
  if (!result.ok)
1129
1148
  return result;
1130
1149
  if (text.length + result.text.length > limits.maxUnitsPerOperation) {
1131
- return fail("operation_limit");
1150
+ return fail("operation_limit", { kind: "units", value: text.length + result.text.length });
1132
1151
  }
1133
1152
  commitTransaction(tx);
1134
1153
  return result;
@@ -1144,8 +1163,9 @@ function buildService(config, limits) {
1144
1163
  return fail("invalid_session");
1145
1164
  if (typeof text !== "string")
1146
1165
  return fail("invalid_input");
1147
- if (text.length > limits.maxUnitsPerOperation)
1148
- return fail("operation_limit");
1166
+ if (text.length > limits.maxUnitsPerOperation) {
1167
+ return fail("operation_limit", { kind: "units", value: text.length });
1168
+ }
1149
1169
  try {
1150
1170
  return restoreStringTx(registry.sessions.get(sessionId), limits, text, text.length, preserveUnknownMarkers);
1151
1171
  }
@@ -138,8 +138,26 @@ const CODE_CHAIN = new RegExp(`^${IDENT}${STEP}*${TAIL}`);
138
138
  const CONFIG_MEMBER = new RegExp(`^(?:process\\.env|import\\.meta\\.env|os\\.environ|ENV|this|self|config|cfg|conf|settings|options|opts|props|params|args|req|request|ctx|context|env|secrets)${STEP}+${TAIL}`);
139
139
  /** Longer values are not exempted; a real expression on one line is short. */
140
140
  const MAX_EXPRESSION_LENGTH = 256;
141
+ function assignedValue(match) {
142
+ return match.replace(/^[^:=]*[:=]\s*/, "");
143
+ }
144
+ /** A whole issued placeholder as an unquoted value. A quoted value is
145
+ * ambiguous (a shell word can continue after the closing quote), so it stays
146
+ * a finding and refuses as token_overlap rather than risking a hidden suffix. */
147
+ const ISSUED_PLACEHOLDER_VALUE = /^\[SGP(?:1:[0-9a-f]{32}-\d{8,12}|2:[A-Z][A-Z_]{0,31}-[a-z]{4}-[a-z]{4}-[a-z]{4})\]$/;
148
+ function isIssuedPlaceholderValue(match, text, index) {
149
+ if (!ISSUED_PLACEHOLDER_VALUE.test(assignedValue(match).trim()))
150
+ return false;
151
+ // JS `\S` stops at some characters a shell keeps in the word (NBSP, VT, FF,
152
+ // lone CR). Only end-of-text, space, tab, LF and CRLF end the value.
153
+ const end = index + match.length;
154
+ const after = text[end];
155
+ if (after === undefined || after === " " || after === "\t" || after === "\n")
156
+ return true;
157
+ return after === "\r" && text[end + 1] === "\n";
158
+ }
141
159
  function isCodeExpressionValue(match) {
142
- const value = match.replace(/^[^:=]*[:=]\s*/, "");
160
+ const value = assignedValue(match);
143
161
  if (value.length > MAX_EXPRESSION_LENGTH)
144
162
  return false;
145
163
  if (value.startsWith("'") || value.startsWith('"'))
@@ -266,8 +284,9 @@ export const BUILTIN_RULES = [
266
284
  // 同時涵蓋有引號(YAML/JSON)與無引號(.env)寫法
267
285
  // (?!\$\{) 排除環境變數參照 ${VAR};(?!\*) 排除遮罩值 ********
268
286
  pattern: /(?:password|passwd|secret|private_key|client_secret)\s*[:=]\s*(?:['"](?!\$\{)[^'"]{8,}['"]|(?!['"\$\*])\S{8,})/gi,
269
- // 無引號值若是程式碼表達式(process.env.X、z.string()、config.secret)不算機密(#49)
270
- validate: (match) => !isCodeExpressionValue(match),
287
+ // 無引號值若是程式碼表達式(process.env.X、z.string()、config.secret)不算機密(#49);
288
+ // 值「整個」是已發出的 placeholder 時才是已遮罩內容;混入其他文字仍要偵測(可能跨 token 而拒絕)。
289
+ validate: (match, context) => !isCodeExpressionValue(match) && !isIssuedPlaceholderValue(match, context.text, context.index),
271
290
  },
272
291
  {
273
292
  id: "url-userinfo",
package/dist/types.d.ts CHANGED
@@ -22,12 +22,25 @@ export interface CustomRuleConfig {
22
22
  */
23
23
  path?: string[];
24
24
  }
25
+ /** Request body and WS frame cap bounds. The ceiling keeps a finite memory bound
26
+ * even when a config raises the default for long sessions. */
27
+ export declare const MIN_MAX_BODY_BYTES: number;
28
+ export declare const MAX_MAX_BODY_BYTES: number;
29
+ export declare const DEFAULT_MAX_BODY_BYTES: number;
30
+ /** Combined input+output per-operation budget bounds. */
31
+ export declare const MIN_MAX_OPERATION_UNITS: number;
32
+ export declare const MAX_MAX_OPERATION_UNITS: number;
33
+ export declare const DEFAULT_MAX_OPERATION_UNITS: number;
25
34
  export interface GuardConfig {
26
35
  nda_keywords: string[];
27
36
  private_domains: string[];
28
37
  custom_rules: CustomRuleConfig[];
29
38
  settings: {
30
39
  max_chars: number;
40
+ /** Request body and WS frame byte cap. Omitted uses DEFAULT_MAX_BODY_BYTES; response reads stay at 4 MiB. */
41
+ max_body_bytes?: number;
42
+ /** Combined input+output UTF-16 units for one protect/restore operation. Omitted uses DEFAULT_MAX_OPERATION_UNITS. */
43
+ max_operation_units?: number;
31
44
  show_line_numbers: boolean;
32
45
  preview_length: number;
33
46
  encoding_detection: boolean;
package/dist/types.js CHANGED
@@ -1,3 +1,12 @@
1
+ /** Request body and WS frame cap bounds. The ceiling keeps a finite memory bound
2
+ * even when a config raises the default for long sessions. */
3
+ export const MIN_MAX_BODY_BYTES = 1024 * 1024;
4
+ export const MAX_MAX_BODY_BYTES = 32 * 1024 * 1024;
5
+ export const DEFAULT_MAX_BODY_BYTES = 8 * 1024 * 1024;
6
+ /** Combined input+output per-operation budget bounds. */
7
+ export const MIN_MAX_OPERATION_UNITS = 1024 * 1024;
8
+ export const MAX_MAX_OPERATION_UNITS = 64 * 1024 * 1024;
9
+ export const DEFAULT_MAX_OPERATION_UNITS = 16 * 1024 * 1024;
1
10
  /**
2
11
  * Runtime-closed enumeration (R-round F1.2): the SGP2 category whitelist is
3
12
  * enforced at persisted-seed intake, so the legal labels must exist as a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leakshield",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
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",