leakshield 0.1.2 → 0.2.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 +346 -173
- package/README.zh-TW.md +290 -164
- package/dist/config/loader.js +38 -14
- package/dist/config/plain-object.js +14 -0
- package/dist/decision/pseudonymization.js +203 -65
- package/dist/decision/redaction.js +2 -0
- package/dist/decision/value-search.js +250 -0
- package/dist/doctor.js +578 -132
- package/dist/i18n/en.js +4 -0
- package/dist/i18n/zh-TW.js +4 -0
- package/dist/index.js +3 -2
- package/dist/opencode-env-tools.js +0 -75
- package/dist/opencode-hooks.js +4 -73
- package/dist/opencode-transparent.js +16 -1
- package/dist/opencode.js +12 -54
- package/dist/plugin-options.js +15 -21
- package/dist/rules/builtin.js +82 -1
- package/dist/rules/dynamic.js +224 -9
- package/dist/scanner/allowlist.js +37 -0
- package/dist/scanner/encoding.js +296 -8
- package/dist/scanner/engine.js +149 -67
- package/dist/scanner/unicode.js +30 -0
- package/dist/scanner/utils.js +26 -2
- package/dist/transports/cli.js +2 -2
- package/dist/transports/web.js +3 -3
- package/dist/types.js +1 -0
- package/package.json +3 -3
package/dist/config/loader.js
CHANGED
|
@@ -7,20 +7,41 @@ import { z } from "zod";
|
|
|
7
7
|
import { loadExactValueDetector } from "../scanner/exact-values.js";
|
|
8
8
|
import { parseCidr } from "../scanner/cidr.js";
|
|
9
9
|
import { BUILTIN_RULE_IDS } from "../rules/builtin.js";
|
|
10
|
+
import { customRulePattern } from "../rules/dynamic.js";
|
|
11
|
+
import { plainObject } from "./plain-object.js";
|
|
10
12
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
11
13
|
const MAX_DYNAMIC_RULE_LENGTH = 200;
|
|
12
14
|
const MAX_PRIVATE_DOMAIN_LENGTH = 255;
|
|
13
15
|
const MAX_ENV_FILE_PATH_LENGTH = 4096;
|
|
16
|
+
const MAX_ALLOW_ENTRY_LENGTH = 200;
|
|
17
|
+
const MAX_RULE_ALLOW_ENTRIES = 32;
|
|
18
|
+
const MAX_GLOBAL_ALLOW_ENTRIES = 64;
|
|
19
|
+
const MAX_RULE_PATH_ENTRIES = 16;
|
|
20
|
+
const MAX_RULE_PATH_LENGTH = 512;
|
|
21
|
+
const MAX_NDA_KEYWORDS = 4096;
|
|
22
|
+
const MAX_PRIVATE_DOMAINS = 4096;
|
|
23
|
+
const MAX_CUSTOM_RULES = 1024;
|
|
24
|
+
// `g` is always added by the scanner; the rest is the documented subset.
|
|
25
|
+
const CUSTOM_FLAG_CHARS = /^[gimsuy]*$/;
|
|
26
|
+
const AllowEntry = z.string().min(1).max(MAX_ALLOW_ENTRY_LENGTH);
|
|
14
27
|
const CustomRuleSchema = z.object({
|
|
15
28
|
description: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
|
|
16
29
|
pattern: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
|
|
17
30
|
severity: z.enum(["HIGH", "MEDIUM", "LOW"]).default("HIGH"),
|
|
31
|
+
flags: z
|
|
32
|
+
.string()
|
|
33
|
+
.max(6)
|
|
34
|
+
.regex(CUSTOM_FLAG_CHARS, "flags must be a subset of gimsuy; g is always implied")
|
|
35
|
+
.optional(),
|
|
36
|
+
word_boundary: z.boolean().optional(),
|
|
37
|
+
allow: z.array(AllowEntry).max(MAX_RULE_ALLOW_ENTRIES).optional(),
|
|
38
|
+
path: z.array(z.string().min(1).max(MAX_RULE_PATH_LENGTH)).max(MAX_RULE_PATH_ENTRIES).optional(),
|
|
18
39
|
});
|
|
19
|
-
export const GuardConfigSchema = z.object({
|
|
20
|
-
nda_keywords: z.array(z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH)).default(["CONFIDENTIAL", "INTERNAL ONLY", "DO NOT SHARE", "NDA"]),
|
|
21
|
-
private_domains: z.array(z.string().min(1).max(MAX_PRIVATE_DOMAIN_LENGTH)).default([]),
|
|
22
|
-
custom_rules: z.array(CustomRuleSchema).nullable().default([]).transform((v) => v ?? []),
|
|
23
|
-
settings: z.object({
|
|
40
|
+
export const GuardConfigSchema = plainObject(z.object({
|
|
41
|
+
nda_keywords: z.array(z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH)).max(MAX_NDA_KEYWORDS).default(["CONFIDENTIAL", "INTERNAL ONLY", "DO NOT SHARE", "NDA"]),
|
|
42
|
+
private_domains: z.array(z.string().min(1).max(MAX_PRIVATE_DOMAIN_LENGTH)).max(MAX_PRIVATE_DOMAINS).default([]),
|
|
43
|
+
custom_rules: z.array(CustomRuleSchema).max(MAX_CUSTOM_RULES).nullable().default([]).transform((v) => v ?? []),
|
|
44
|
+
settings: plainObject(z.object({
|
|
24
45
|
max_chars: z.number().int().positive().default(200000),
|
|
25
46
|
show_line_numbers: z.boolean().default(true),
|
|
26
47
|
preview_length: z.number().int().positive().default(60),
|
|
@@ -28,15 +49,16 @@ export const GuardConfigSchema = z.object({
|
|
|
28
49
|
env_files: z.array(z.string().min(1).max(MAX_ENV_FILE_PATH_LENGTH)).max(16).default([]),
|
|
29
50
|
rule_overrides: z.record(z.string().min(1), z.boolean()).default({}),
|
|
30
51
|
private_cidrs: z.array(z.string().min(1).max(64)).max(64).default([]),
|
|
31
|
-
|
|
32
|
-
}).
|
|
52
|
+
allowlist: z.array(AllowEntry).max(MAX_GLOBAL_ALLOW_ENTRIES).default([]),
|
|
53
|
+
})).prefault({}),
|
|
54
|
+
})).superRefine((config, ctx) => {
|
|
33
55
|
// Unknown rule ids in `rule_overrides` fail the parse (fail-closed): a typo
|
|
34
56
|
// must never silently leave a rule in the wrong state.
|
|
35
57
|
const overrides = config.settings.rule_overrides ?? {};
|
|
36
58
|
for (const id of Object.keys(overrides)) {
|
|
37
59
|
if (!BUILTIN_RULE_IDS.has(id)) {
|
|
38
60
|
ctx.addIssue({
|
|
39
|
-
code:
|
|
61
|
+
code: "custom",
|
|
40
62
|
path: ["settings", "rule_overrides", id],
|
|
41
63
|
message: `unknown builtin rule id "${id}" (see src/rules/builtin.ts BUILTIN_RULE_IDS)`,
|
|
42
64
|
});
|
|
@@ -47,25 +69,27 @@ export const GuardConfigSchema = z.object({
|
|
|
47
69
|
(config.settings.private_cidrs ?? []).forEach((entry, index) => {
|
|
48
70
|
if (parseCidr(entry) === null) {
|
|
49
71
|
ctx.addIssue({
|
|
50
|
-
code:
|
|
72
|
+
code: "custom",
|
|
51
73
|
path: ["settings", "private_cidrs", index],
|
|
52
74
|
message: `private_cidrs[${index}] is not a valid IPv4 CIDR (expected a.b.c.d/prefix)`,
|
|
53
75
|
});
|
|
54
76
|
}
|
|
55
77
|
});
|
|
56
|
-
// A custom rule whose pattern
|
|
57
|
-
// scanner would otherwise drop it and
|
|
78
|
+
// A custom rule whose final pattern (flags and word boundaries included) does
|
|
79
|
+
// not compile fails the parse too: the scanner would otherwise drop it and
|
|
80
|
+
// report clean text as safe.
|
|
58
81
|
config.custom_rules.forEach((rule, index) => {
|
|
59
82
|
try {
|
|
60
|
-
|
|
83
|
+
customRulePattern(rule);
|
|
61
84
|
}
|
|
62
85
|
catch (error) {
|
|
63
86
|
// V8 messages embed the pattern ("Invalid regular expression: /…/gi:
|
|
64
87
|
// reason"); keep only the reason, since a pattern may itself be a
|
|
65
88
|
// literal the rule exists to protect.
|
|
66
|
-
const
|
|
89
|
+
const message = error.message;
|
|
90
|
+
const reason = message.includes(": ") ? message.split(": ").pop() : message;
|
|
67
91
|
ctx.addIssue({
|
|
68
|
-
code:
|
|
92
|
+
code: "custom",
|
|
69
93
|
path: ["custom_rules", index, "pattern"],
|
|
70
94
|
message: `custom_rules[${index}] "${rule.description}": pattern does not compile (${reason})`,
|
|
71
95
|
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// zod 4's z.object() accepts any non-array object (Date, Map, Uint8Array...) and
|
|
3
|
+
// returns its defaults, so a YAML timestamp or !!binary would load as a valid
|
|
4
|
+
// config. Only mappings (plain objects) may reach the inner schema; `abort`
|
|
5
|
+
// stops later refinements from running on the raw value.
|
|
6
|
+
function isPlain(value) {
|
|
7
|
+
if (typeof value !== "object" || value === null)
|
|
8
|
+
return false;
|
|
9
|
+
const proto = Object.getPrototypeOf(value);
|
|
10
|
+
return proto === Object.prototype || proto === null;
|
|
11
|
+
}
|
|
12
|
+
export function plainObject(schema) {
|
|
13
|
+
return z.custom(isPlain, { error: "expected a mapping", abort: true }).pipe(schema);
|
|
14
|
+
}
|
|
@@ -41,9 +41,10 @@
|
|
|
41
41
|
*/
|
|
42
42
|
import { randomBytes } from "node:crypto";
|
|
43
43
|
import { types } from "node:util";
|
|
44
|
-
import { scanTextWithDecoding } from "../scanner/encoding.js";
|
|
44
|
+
import { decodedFindingsAttributable, locateEncodedRuns, scanTextWithDecoding } from "../scanner/encoding.js";
|
|
45
45
|
import { scanTextInternal } from "../scanner/engine.js";
|
|
46
46
|
import { FINDING_TYPES } from "../types.js";
|
|
47
|
+
import { createValueSearch } from "./value-search.js";
|
|
47
48
|
// ─── Constants ───────────────────────────────────────────────────────────────
|
|
48
49
|
/**
|
|
49
50
|
* Reserved, recognizable token namespace — two versions.
|
|
@@ -190,14 +191,23 @@ function containedInAnySpan(inner, spans) {
|
|
|
190
191
|
* touches its payload.
|
|
191
192
|
*/
|
|
192
193
|
/** Earliest reserved-token prefix (either version) at/after `from`. */
|
|
193
|
-
function
|
|
194
|
-
|
|
195
|
-
for
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
194
|
+
function tokenPrefixFinder(text) {
|
|
195
|
+
// Each prefix remembers its last hit, so a prefix that is absent or far ahead
|
|
196
|
+
// is not searched again for every token before it.
|
|
197
|
+
const known = PSEUDONYM_TOKEN_PREFIXES.map((prefix) => ({ prefix, searchedFrom: 0, at: text.indexOf(prefix) }));
|
|
198
|
+
return (from) => {
|
|
199
|
+
let best;
|
|
200
|
+
for (const entry of known) {
|
|
201
|
+
if (from < entry.searchedFrom || (entry.at !== -1 && entry.at < from)) {
|
|
202
|
+
entry.searchedFrom = from;
|
|
203
|
+
entry.at = text.indexOf(entry.prefix, from);
|
|
204
|
+
}
|
|
205
|
+
if (entry.at !== -1 && (best === undefined || entry.at < best.at)) {
|
|
206
|
+
best = { at: entry.at, prefix: entry.prefix };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return best;
|
|
210
|
+
};
|
|
201
211
|
}
|
|
202
212
|
/** Strictly matches the versioned token shape at `at`; undefined otherwise. */
|
|
203
213
|
function matchTokenShape(text, at, prefix) {
|
|
@@ -209,18 +219,19 @@ function matchTokenShape(text, at, prefix) {
|
|
|
209
219
|
function scanOwnedTokenSpans(text, isOwned, preserveUnknown = false) {
|
|
210
220
|
const spans = [];
|
|
211
221
|
const preserved = [];
|
|
212
|
-
|
|
222
|
+
const findTokenPrefix = tokenPrefixFinder(text);
|
|
223
|
+
let cursor = findTokenPrefix(0);
|
|
213
224
|
while (cursor !== undefined) {
|
|
214
225
|
const { at, prefix } = cursor;
|
|
215
226
|
const token = matchTokenShape(text, at, prefix);
|
|
216
227
|
if (token === undefined) {
|
|
217
228
|
if (!preserveUnknown)
|
|
218
229
|
return fail("malformed_token");
|
|
219
|
-
const next = findTokenPrefix(
|
|
230
|
+
const next = findTokenPrefix(at + prefix.length);
|
|
220
231
|
const close = text.indexOf("]", at + prefix.length);
|
|
221
232
|
cursor = next !== undefined && (close === -1 || next.at < close)
|
|
222
233
|
? next
|
|
223
|
-
: findTokenPrefix(
|
|
234
|
+
: findTokenPrefix(close === -1 ? text.length : close + 1);
|
|
224
235
|
continue;
|
|
225
236
|
}
|
|
226
237
|
const end = at + token.length;
|
|
@@ -228,11 +239,11 @@ function scanOwnedTokenSpans(text, isOwned, preserveUnknown = false) {
|
|
|
228
239
|
if (!preserveUnknown)
|
|
229
240
|
return fail("unknown_token");
|
|
230
241
|
preserved.push({ start: at, end });
|
|
231
|
-
cursor = findTokenPrefix(
|
|
242
|
+
cursor = findTokenPrefix(end);
|
|
232
243
|
continue;
|
|
233
244
|
}
|
|
234
245
|
spans.push({ start: at, end });
|
|
235
|
-
cursor = findTokenPrefix(
|
|
246
|
+
cursor = findTokenPrefix(end);
|
|
236
247
|
}
|
|
237
248
|
return { ok: true, spans, preserved };
|
|
238
249
|
}
|
|
@@ -252,7 +263,7 @@ function rawScan(text, config) {
|
|
|
252
263
|
* Any truncated scanned representation or any decoded sensitive finding
|
|
253
264
|
* fails closed with a static reason.
|
|
254
265
|
*/
|
|
255
|
-
function segmentDecodingHazard(segment, config) {
|
|
266
|
+
function segmentDecodingHazard(segment, config, encodedMaskable) {
|
|
256
267
|
if (segment.length === 0)
|
|
257
268
|
return null;
|
|
258
269
|
try {
|
|
@@ -264,9 +275,24 @@ function segmentDecodingHazard(segment, config) {
|
|
|
264
275
|
return fail("truncated_content");
|
|
265
276
|
}
|
|
266
277
|
// `decoded` results only exist when a decoded representation was unsafe,
|
|
267
|
-
// i.e. encoded sensitive content was detected in this segment.
|
|
268
|
-
|
|
269
|
-
|
|
278
|
+
// i.e. encoded sensitive content was detected in this segment. The input
|
|
279
|
+
// scan of protectStringTx tolerates it (encodedMaskable) only when every
|
|
280
|
+
// decoded finding is known to be covered by a located run (see
|
|
281
|
+
// decodedFindingsAttributable); partial masking could otherwise erase the
|
|
282
|
+
// evidence the strict output rescan needs.
|
|
283
|
+
if (scan.decoded.length > 0) {
|
|
284
|
+
if (!encodedMaskable)
|
|
285
|
+
return fail("encoded_content");
|
|
286
|
+
const decodedMatches = scan.decoded.flatMap((result) => result.findings.flatMap((f) => (typeof f.match_text === "string" ? [f.match_text] : [])));
|
|
287
|
+
// A decoded Unicode evasion hides a finding with no source span, so it
|
|
288
|
+
// always refuses, even if another occurrence decodes to the same text.
|
|
289
|
+
const hasUnreadable = scan.decoded.some((result) => result.findings.some((f) => typeof f.match_text !== "string" ||
|
|
290
|
+
f.unicode_detected !== undefined));
|
|
291
|
+
const directMatches = scan.original.findings.flatMap((f) => typeof f.match_text === "string" ? [f.match_text] : []);
|
|
292
|
+
if (hasUnreadable || !decodedFindingsAttributable(segment, config, MODEL_BOUNDARY_SCAN, decodedMatches, directMatches)) {
|
|
293
|
+
return fail("encoded_content");
|
|
294
|
+
}
|
|
295
|
+
}
|
|
270
296
|
return null;
|
|
271
297
|
}
|
|
272
298
|
catch {
|
|
@@ -304,8 +330,10 @@ const URL_CONTEXT_UNITS = 50;
|
|
|
304
330
|
* wholly inside a fragment are that token's own interior and are exempt
|
|
305
331
|
* BEFORE any overlap consideration, exactly like the full-text seam.
|
|
306
332
|
* Every other finding — crossing matches and suspicious-Unicode
|
|
307
|
-
* synthetics included — fails encoded_content
|
|
308
|
-
*
|
|
333
|
+
* synthetics included — fails encoded_content (unless the scan is
|
|
334
|
+
* encodedMaskable, see scanForModelBoundary); malformed ordinary spans
|
|
335
|
+
* fail statically. This function never maps decoded offsets back to the
|
|
336
|
+
* source; that mapping lives only in locateEncodedRuns.
|
|
309
337
|
* - URIError in any piece skips the whole candidate, matching the existing
|
|
310
338
|
* decoder's null return; unexpected exceptions fail scanner_failure.
|
|
311
339
|
*
|
|
@@ -315,7 +343,7 @@ const URL_CONTEXT_UNITS = 50;
|
|
|
315
343
|
* never move backwards), and each reassembled scan covers at most the
|
|
316
344
|
* percent run plus 100 units.
|
|
317
345
|
*/
|
|
318
|
-
function urlContextHazard(text, config, tokenSpans) {
|
|
346
|
+
function urlContextHazard(text, config, tokenSpans, encodedMaskable) {
|
|
319
347
|
if (tokenSpans.length === 0)
|
|
320
348
|
return null;
|
|
321
349
|
URL_PERCENT_RUN.lastIndex = 0;
|
|
@@ -392,8 +420,13 @@ function urlContextHazard(text, config, tokenSpans) {
|
|
|
392
420
|
// Token interior in the changed representation: exempt before overlap.
|
|
393
421
|
if (containedInAnySpan({ start, end }, ownedRanges))
|
|
394
422
|
continue;
|
|
395
|
-
// Everything else
|
|
396
|
-
//
|
|
423
|
+
// Everything else is decoded sensitive content. A maskable (input)
|
|
424
|
+
// scan tolerates only findings that touch no retained token fragment
|
|
425
|
+
// (the locator masks those whole); a match overlapping a fragment
|
|
426
|
+
// crosses a token and can never be masked, so it refuses here
|
|
427
|
+
// regardless of encodedMaskable.
|
|
428
|
+
if (encodedMaskable && !ownedRanges.some((range) => spansOverlap({ start, end }, range)))
|
|
429
|
+
continue;
|
|
397
430
|
return fail("encoded_content");
|
|
398
431
|
}
|
|
399
432
|
}
|
|
@@ -413,8 +446,17 @@ function urlContextHazard(text, config, tokenSpans) {
|
|
|
413
446
|
* behavior. `tokenSpans` must come from scanOwnedTokenSpans (ascending,
|
|
414
447
|
* disjoint) and must already be strictly validated BEFORE this scan runs.
|
|
415
448
|
* Input scan and output verification rescan share this seam.
|
|
449
|
+
*
|
|
450
|
+
* `encodedMaskable` (default false, strict) narrowly relaxes encoded_content:
|
|
451
|
+
* urlContextHazard tolerates only findings touching no retained token
|
|
452
|
+
* fragment, and segmentDecodingHazard tolerates a segment only when
|
|
453
|
+
* decodedFindingsAttributable says every decoded finding is covered by a
|
|
454
|
+
* located run and the segment holds no zero-width or look-alike character.
|
|
455
|
+
* Every other reason still fails. Only the INPUT scan of protectStringTx
|
|
456
|
+
* sets it; that caller masks the located runs and re-verifies the substituted
|
|
457
|
+
* text with the strict default as a second line of defense.
|
|
416
458
|
*/
|
|
417
|
-
function scanForModelBoundary(text, config, tokenSpans) {
|
|
459
|
+
function scanForModelBoundary(text, config, tokenSpans, encodedMaskable = false) {
|
|
418
460
|
const direct = rawScan(text, config);
|
|
419
461
|
if (!direct.ok)
|
|
420
462
|
return direct;
|
|
@@ -422,20 +464,20 @@ function scanForModelBoundary(text, config, tokenSpans) {
|
|
|
422
464
|
// per-segment accounting.
|
|
423
465
|
if (direct.original.was_truncated)
|
|
424
466
|
return fail("truncated_content");
|
|
425
|
-
const urlHazard = urlContextHazard(text, config, tokenSpans);
|
|
467
|
+
const urlHazard = urlContextHazard(text, config, tokenSpans, encodedMaskable);
|
|
426
468
|
if (urlHazard !== null)
|
|
427
469
|
return urlHazard;
|
|
428
470
|
let cursor = 0;
|
|
429
471
|
for (const span of tokenSpans) {
|
|
430
472
|
if (span.start > cursor) {
|
|
431
|
-
const hazard = segmentDecodingHazard(text.slice(cursor, span.start), config);
|
|
473
|
+
const hazard = segmentDecodingHazard(text.slice(cursor, span.start), config, encodedMaskable);
|
|
432
474
|
if (hazard !== null)
|
|
433
475
|
return hazard;
|
|
434
476
|
}
|
|
435
477
|
cursor = span.end;
|
|
436
478
|
}
|
|
437
479
|
if (cursor < text.length) {
|
|
438
|
-
const hazard = segmentDecodingHazard(text.slice(cursor), config);
|
|
480
|
+
const hazard = segmentDecodingHazard(text.slice(cursor), config, encodedMaskable);
|
|
439
481
|
if (hazard !== null)
|
|
440
482
|
return hazard;
|
|
441
483
|
}
|
|
@@ -474,17 +516,50 @@ function validateFindingSpans(text, findings) {
|
|
|
474
516
|
}
|
|
475
517
|
return { ok: true, spans: deduped };
|
|
476
518
|
}
|
|
477
|
-
/**
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
519
|
+
/**
|
|
520
|
+
* Other occurrences of detected values that the rules did not report (#52).
|
|
521
|
+
* Most rules depend on context — `\b` boundaries, validators that look at
|
|
522
|
+
* neighbours — so the same characters can be a finding in one place and not
|
|
523
|
+
* in another (`1318289051000.1` vs `1318289051000n`). The absence check below
|
|
524
|
+
* would then refuse the whole string. Masking those occurrences with the same
|
|
525
|
+
* token masks strictly more, so they are added here instead. An occurrence
|
|
526
|
+
* that overlaps a finding, a validated token or a preserved marker is left
|
|
527
|
+
* alone and still fails the absence check.
|
|
528
|
+
*/
|
|
529
|
+
function repeatOccurrences(text, categories, search, blocked) {
|
|
530
|
+
// One flag per UTF-16 unit: overlap checks cost the span's length, not the
|
|
531
|
+
// number of spans already taken.
|
|
532
|
+
const taken = new Uint8Array(text.length);
|
|
533
|
+
const mark = (span) => {
|
|
534
|
+
taken.fill(1, span.start, span.end);
|
|
535
|
+
};
|
|
536
|
+
const free = (span) => {
|
|
537
|
+
for (let i = span.start; i < span.end; i++)
|
|
538
|
+
if (taken[i] === 1)
|
|
539
|
+
return false;
|
|
540
|
+
return true;
|
|
541
|
+
};
|
|
542
|
+
for (const span of blocked)
|
|
543
|
+
mark(span);
|
|
544
|
+
const repeats = [];
|
|
545
|
+
// Longest value first, so a shorter value never splits a longer repeat.
|
|
546
|
+
search.visitOccurrences(text, (start, end, value) => {
|
|
547
|
+
const span = { start, end };
|
|
548
|
+
const category = categories.get(value);
|
|
549
|
+
if (category === undefined || !free(span))
|
|
485
550
|
return false;
|
|
486
|
-
|
|
487
|
-
|
|
551
|
+
repeats.push({ ...span, value, ...category });
|
|
552
|
+
mark(span);
|
|
553
|
+
return true;
|
|
554
|
+
});
|
|
555
|
+
return repeats;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* The search for a set that only ever grows, reusing `current` while the set
|
|
559
|
+
* has not changed: a request's later strings usually add no new value.
|
|
560
|
+
*/
|
|
561
|
+
function searchOver(current, values, size) {
|
|
562
|
+
return current?.sourceSize === size ? current : createValueSearch(values, size);
|
|
488
563
|
}
|
|
489
564
|
// ─── Protect pipeline (per string, inside a transaction) ─────────────────────
|
|
490
565
|
/**
|
|
@@ -510,12 +585,40 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
510
585
|
// segment, so issued-token epochs are never decoded as user content,
|
|
511
586
|
// while URL-context windows crossing tokens are checked with the token
|
|
512
587
|
// fragments retained verbatim (see scanForModelBoundary).
|
|
513
|
-
|
|
588
|
+
// This INPUT scan tolerates encoded_content (#48) only where every decoded
|
|
589
|
+
// finding is known to be covered by a located run (no token crossing, no
|
|
590
|
+
// zero-width or look-alike character in the segment); those runs are masked
|
|
591
|
+
// below. Anything else is refused here, since partial masking could erase
|
|
592
|
+
// the evidence the strict output rescan relies on.
|
|
593
|
+
const scanned = scanForModelBoundary(text, config, owned.spans, true);
|
|
514
594
|
if (!scanned.ok)
|
|
515
595
|
return scanned;
|
|
516
596
|
const collected = validateFindingSpans(text, scanned.original.findings);
|
|
517
597
|
if (!collected.ok)
|
|
518
598
|
return collected;
|
|
599
|
+
// Locate encoded runs per non-token segment (the same segmentation as
|
|
600
|
+
// scanForModelBoundary) and offset them back into the full text.
|
|
601
|
+
const encodedSpans = [];
|
|
602
|
+
try {
|
|
603
|
+
let segmentStart = 0;
|
|
604
|
+
const locateIn = (from, to) => {
|
|
605
|
+
if (to <= from)
|
|
606
|
+
return;
|
|
607
|
+
for (const run of locateEncodedRuns(text.slice(from, to), config, MODEL_BOUNDARY_SCAN)) {
|
|
608
|
+
const start = from + run.start;
|
|
609
|
+
const end = from + run.end;
|
|
610
|
+
encodedSpans.push({ start, end, value: text.slice(start, end), type: "ENCODED", severity: run.severity });
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
for (const tokenSpan of owned.spans) {
|
|
614
|
+
locateIn(segmentStart, tokenSpan.start);
|
|
615
|
+
segmentStart = tokenSpan.end;
|
|
616
|
+
}
|
|
617
|
+
locateIn(segmentStart, text.length);
|
|
618
|
+
}
|
|
619
|
+
catch {
|
|
620
|
+
return fail("scanner_failure");
|
|
621
|
+
}
|
|
519
622
|
// P1 (2026-10-06b): parse uncertainty degrades to best-effort masking.
|
|
520
623
|
// (1) Findings wholly inside a validated owned token are that token's own
|
|
521
624
|
// interior: already pseudonymized, exempt (unchanged).
|
|
@@ -534,6 +637,10 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
534
637
|
continue;
|
|
535
638
|
candidates.push(span);
|
|
536
639
|
}
|
|
640
|
+
// Located encoded runs join the direct findings and take the same extend,
|
|
641
|
+
// sort and union-merge path (overlap with a direct finding is resolved by
|
|
642
|
+
// the existing severity rule).
|
|
643
|
+
candidates.push(...encodedSpans);
|
|
537
644
|
const extended = [];
|
|
538
645
|
for (const span of candidates) {
|
|
539
646
|
let bounds = span;
|
|
@@ -591,6 +698,21 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
591
698
|
return fail("token_overlap");
|
|
592
699
|
}
|
|
593
700
|
}
|
|
701
|
+
for (const span of [...actionable, ...candidates]) {
|
|
702
|
+
if (!tx.detectedValues.has(span.value)) {
|
|
703
|
+
tx.detectedValues.set(span.value, { type: span.type, severity: span.severity });
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
tx.valuesSearch = searchOver(tx.valuesSearch, tx.detectedValues.keys(), tx.detectedValues.size);
|
|
707
|
+
const repeats = repeatOccurrences(text, tx.detectedValues, tx.valuesSearch, [
|
|
708
|
+
...actionable,
|
|
709
|
+
...owned.spans,
|
|
710
|
+
...owned.preserved,
|
|
711
|
+
]);
|
|
712
|
+
if (repeats.length > 0) {
|
|
713
|
+
actionable.push(...repeats);
|
|
714
|
+
actionable.sort((a, b) => a.start - b.start);
|
|
715
|
+
}
|
|
594
716
|
for (const finding of candidates)
|
|
595
717
|
tx.detectedOriginals.add(finding.value);
|
|
596
718
|
for (const span of actionable)
|
|
@@ -650,10 +772,9 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
650
772
|
}
|
|
651
773
|
// Independent absence check of every detected original outside validated
|
|
652
774
|
// owned tokens (covers key/value strings for JSON operations too).
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
}
|
|
775
|
+
tx.originalsSearch = searchOver(tx.originalsSearch, tx.detectedOriginals, tx.detectedOriginals.size);
|
|
776
|
+
if (!tx.originalsSearch.everyOccurrenceCovered(substituted, outTokens.spans)) {
|
|
777
|
+
return fail("residual_sensitive_content");
|
|
657
778
|
}
|
|
658
779
|
return { ok: true, text: substituted };
|
|
659
780
|
}
|
|
@@ -791,7 +912,8 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
791
912
|
return null;
|
|
792
913
|
};
|
|
793
914
|
let from = 0;
|
|
794
|
-
|
|
915
|
+
const findTokenPrefix = tokenPrefixFinder(text);
|
|
916
|
+
let cursor = findTokenPrefix(0);
|
|
795
917
|
while (cursor !== undefined) {
|
|
796
918
|
const { at, prefix } = cursor;
|
|
797
919
|
const token = matchTokenShape(text, at, prefix);
|
|
@@ -799,7 +921,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
799
921
|
if (token === undefined || original === undefined) {
|
|
800
922
|
if (!preserveUnknownMarkers)
|
|
801
923
|
return fail(token === undefined ? "malformed_token" : "unknown_token");
|
|
802
|
-
const next = findTokenPrefix(
|
|
924
|
+
const next = findTokenPrefix(at + prefix.length);
|
|
803
925
|
const close = text.indexOf("]", at + prefix.length);
|
|
804
926
|
const end = token !== undefined
|
|
805
927
|
? at + token.length
|
|
@@ -812,7 +934,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
812
934
|
if (literalFailed !== null)
|
|
813
935
|
return literalFailed;
|
|
814
936
|
from = end;
|
|
815
|
-
cursor = findTokenPrefix(
|
|
937
|
+
cursor = findTokenPrefix(from);
|
|
816
938
|
continue;
|
|
817
939
|
}
|
|
818
940
|
const literalFailed = appendPiece(text.slice(from, at));
|
|
@@ -822,7 +944,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
822
944
|
if (replacementFailed !== null)
|
|
823
945
|
return replacementFailed;
|
|
824
946
|
from = at + token.length;
|
|
825
|
-
cursor = findTokenPrefix(
|
|
947
|
+
cursor = findTokenPrefix(from);
|
|
826
948
|
}
|
|
827
949
|
const tailFailed = appendPiece(text.slice(from));
|
|
828
950
|
if (tailFailed !== null)
|
|
@@ -953,6 +1075,7 @@ function buildService(config, limits) {
|
|
|
953
1075
|
staged: undefined,
|
|
954
1076
|
baseline: { entries: 0, units: 0 },
|
|
955
1077
|
detectedOriginals: new Set(),
|
|
1078
|
+
detectedValues: new Map(),
|
|
956
1079
|
outputStrings: [],
|
|
957
1080
|
});
|
|
958
1081
|
const isTextSafe = (text) => {
|
|
@@ -1036,28 +1159,43 @@ function buildService(config, limits) {
|
|
|
1036
1159
|
if (!isValidSessionId(sessionId))
|
|
1037
1160
|
return fail("invalid_session");
|
|
1038
1161
|
try {
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1162
|
+
// One pass masks a repeat only in strings walked after the value was
|
|
1163
|
+
// detected. If an earlier string still holds one, the cross-string check
|
|
1164
|
+
// refuses; a single retry seeded with every value the first pass found
|
|
1165
|
+
// covers it (#52). Nothing is committed until a pass verifies.
|
|
1166
|
+
let seed;
|
|
1167
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1168
|
+
const tx = newTransaction(sessionId);
|
|
1169
|
+
if (seed !== undefined)
|
|
1170
|
+
tx.detectedValues = new Map(seed);
|
|
1171
|
+
const budget = { nodes: 0, units: 0 };
|
|
1172
|
+
const result = walkStrictJson(value, 0, new Set(), budget, limits, (text) => {
|
|
1173
|
+
const protectedString = protectStringTx(tx, config, limits, text, budget.units, preserveUnknownMarkers);
|
|
1174
|
+
if (protectedString.ok)
|
|
1175
|
+
tx.outputStrings.push(protectedString.text);
|
|
1176
|
+
return protectedString;
|
|
1177
|
+
});
|
|
1178
|
+
if (!result.ok)
|
|
1179
|
+
return result;
|
|
1180
|
+
let residual = false;
|
|
1181
|
+
for (const outputString of tx.outputStrings) {
|
|
1182
|
+
const tokenSpans = scanOwnedTokenSpans(outputString, (token) => tx.live?.reverse.get(token) !== undefined || tx.staged?.reverse.get(token) !== undefined, preserveUnknownMarkers);
|
|
1183
|
+
if (!tokenSpans.ok)
|
|
1184
|
+
return tokenSpans;
|
|
1185
|
+
tx.originalsSearch = searchOver(tx.originalsSearch, tx.detectedOriginals, tx.detectedOriginals.size);
|
|
1186
|
+
if (!tx.originalsSearch.everyOccurrenceCovered(outputString, tokenSpans.spans)) {
|
|
1187
|
+
residual = true;
|
|
1188
|
+
break;
|
|
1056
1189
|
}
|
|
1057
1190
|
}
|
|
1191
|
+
if (residual) {
|
|
1192
|
+
seed = tx.detectedValues;
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
commitTransaction(tx);
|
|
1196
|
+
return result;
|
|
1058
1197
|
}
|
|
1059
|
-
|
|
1060
|
-
return result;
|
|
1198
|
+
return fail("residual_sensitive_content");
|
|
1061
1199
|
}
|
|
1062
1200
|
catch {
|
|
1063
1201
|
return fail("internal_failure");
|
|
@@ -56,6 +56,8 @@ const PLACEHOLDER_MAP = {
|
|
|
56
56
|
PII_IBAN: "[REDACTED_PII_IBAN]",
|
|
57
57
|
PII_IP: "[REDACTED_PII_IP]",
|
|
58
58
|
PII_URL: "[REDACTED_PII_URL]",
|
|
59
|
+
// 編碼過的片段(Base64 / hex / percent-run);只由 pseudonymization 的定位器產生
|
|
60
|
+
ENCODED: "[REDACTED_ENCODED]",
|
|
59
61
|
CUSTOM: "[REDACTED_CUSTOM]",
|
|
60
62
|
};
|
|
61
63
|
// ─── Internal helpers ────────────────────────────────────────────────────────
|