leakshield 0.1.3 → 0.3.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 +294 -173
- package/README.zh-TW.md +290 -164
- package/dist/config/loader.js +14 -10
- package/dist/config/plain-object.js +14 -0
- package/dist/decision/pseudonymization.js +133 -82
- package/dist/decision/redaction.js +2 -0
- package/dist/decision/value-search.js +250 -0
- package/dist/doctor.js +429 -138
- 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 +582 -89
- package/dist/opencode.js +12 -54
- package/dist/plugin-options.js +15 -21
- package/dist/scanner/encoding.js +291 -7
- package/dist/scanner/engine.js +68 -40
- 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
|
@@ -8,6 +8,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
10
|
import { customRulePattern } from "../rules/dynamic.js";
|
|
11
|
+
import { plainObject } from "./plain-object.js";
|
|
11
12
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
12
13
|
const MAX_DYNAMIC_RULE_LENGTH = 200;
|
|
13
14
|
const MAX_PRIVATE_DOMAIN_LENGTH = 255;
|
|
@@ -17,6 +18,9 @@ const MAX_RULE_ALLOW_ENTRIES = 32;
|
|
|
17
18
|
const MAX_GLOBAL_ALLOW_ENTRIES = 64;
|
|
18
19
|
const MAX_RULE_PATH_ENTRIES = 16;
|
|
19
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;
|
|
20
24
|
// `g` is always added by the scanner; the rest is the documented subset.
|
|
21
25
|
const CUSTOM_FLAG_CHARS = /^[gimsuy]*$/;
|
|
22
26
|
const AllowEntry = z.string().min(1).max(MAX_ALLOW_ENTRY_LENGTH);
|
|
@@ -33,11 +37,11 @@ const CustomRuleSchema = z.object({
|
|
|
33
37
|
allow: z.array(AllowEntry).max(MAX_RULE_ALLOW_ENTRIES).optional(),
|
|
34
38
|
path: z.array(z.string().min(1).max(MAX_RULE_PATH_LENGTH)).max(MAX_RULE_PATH_ENTRIES).optional(),
|
|
35
39
|
});
|
|
36
|
-
export const GuardConfigSchema = z.object({
|
|
37
|
-
nda_keywords: z.array(z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH)).default(["CONFIDENTIAL", "INTERNAL ONLY", "DO NOT SHARE", "NDA"]),
|
|
38
|
-
private_domains: z.array(z.string().min(1).max(MAX_PRIVATE_DOMAIN_LENGTH)).default([]),
|
|
39
|
-
custom_rules: z.array(CustomRuleSchema).nullable().default([]).transform((v) => v ?? []),
|
|
40
|
-
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({
|
|
41
45
|
max_chars: z.number().int().positive().default(200000),
|
|
42
46
|
show_line_numbers: z.boolean().default(true),
|
|
43
47
|
preview_length: z.number().int().positive().default(60),
|
|
@@ -46,15 +50,15 @@ export const GuardConfigSchema = z.object({
|
|
|
46
50
|
rule_overrides: z.record(z.string().min(1), z.boolean()).default({}),
|
|
47
51
|
private_cidrs: z.array(z.string().min(1).max(64)).max(64).default([]),
|
|
48
52
|
allowlist: z.array(AllowEntry).max(MAX_GLOBAL_ALLOW_ENTRIES).default([]),
|
|
49
|
-
}).
|
|
50
|
-
}).superRefine((config, ctx) => {
|
|
53
|
+
})).prefault({}),
|
|
54
|
+
})).superRefine((config, ctx) => {
|
|
51
55
|
// Unknown rule ids in `rule_overrides` fail the parse (fail-closed): a typo
|
|
52
56
|
// must never silently leave a rule in the wrong state.
|
|
53
57
|
const overrides = config.settings.rule_overrides ?? {};
|
|
54
58
|
for (const id of Object.keys(overrides)) {
|
|
55
59
|
if (!BUILTIN_RULE_IDS.has(id)) {
|
|
56
60
|
ctx.addIssue({
|
|
57
|
-
code:
|
|
61
|
+
code: "custom",
|
|
58
62
|
path: ["settings", "rule_overrides", id],
|
|
59
63
|
message: `unknown builtin rule id "${id}" (see src/rules/builtin.ts BUILTIN_RULE_IDS)`,
|
|
60
64
|
});
|
|
@@ -65,7 +69,7 @@ export const GuardConfigSchema = z.object({
|
|
|
65
69
|
(config.settings.private_cidrs ?? []).forEach((entry, index) => {
|
|
66
70
|
if (parseCidr(entry) === null) {
|
|
67
71
|
ctx.addIssue({
|
|
68
|
-
code:
|
|
72
|
+
code: "custom",
|
|
69
73
|
path: ["settings", "private_cidrs", index],
|
|
70
74
|
message: `private_cidrs[${index}] is not a valid IPv4 CIDR (expected a.b.c.d/prefix)`,
|
|
71
75
|
});
|
|
@@ -85,7 +89,7 @@ export const GuardConfigSchema = z.object({
|
|
|
85
89
|
const message = error.message;
|
|
86
90
|
const reason = message.includes(": ") ? message.split(": ").pop() : message;
|
|
87
91
|
ctx.addIssue({
|
|
88
|
-
code:
|
|
92
|
+
code: "custom",
|
|
89
93
|
path: ["custom_rules", index, "pattern"],
|
|
90
94
|
message: `custom_rules[${index}] "${rule.description}": pattern does not compile (${reason})`,
|
|
91
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
|
}
|
|
@@ -484,10 +526,9 @@ function validateFindingSpans(text, findings) {
|
|
|
484
526
|
* that overlaps a finding, a validated token or a preserved marker is left
|
|
485
527
|
* alone and still fails the absence check.
|
|
486
528
|
*/
|
|
487
|
-
function repeatOccurrences(text,
|
|
529
|
+
function repeatOccurrences(text, categories, search, blocked) {
|
|
488
530
|
// One flag per UTF-16 unit: overlap checks cost the span's length, not the
|
|
489
|
-
// number of spans already taken.
|
|
490
|
-
// the same as the absence check that follows.
|
|
531
|
+
// number of spans already taken.
|
|
491
532
|
const taken = new Uint8Array(text.length);
|
|
492
533
|
const mark = (span) => {
|
|
493
534
|
taken.fill(1, span.start, span.end);
|
|
@@ -501,41 +542,24 @@ function repeatOccurrences(text, sources, blocked) {
|
|
|
501
542
|
for (const span of blocked)
|
|
502
543
|
mark(span);
|
|
503
544
|
const repeats = [];
|
|
504
|
-
const seen = new Set();
|
|
505
545
|
// Longest value first, so a shorter value never splits a longer repeat.
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
break;
|
|
516
|
-
const span = { start: at, end: at + source.value.length };
|
|
517
|
-
if (!free(span)) {
|
|
518
|
-
from = at + 1;
|
|
519
|
-
continue;
|
|
520
|
-
}
|
|
521
|
-
repeats.push({ ...span, value: source.value, type: source.type, severity: source.severity });
|
|
522
|
-
mark(span);
|
|
523
|
-
from = span.end;
|
|
524
|
-
}
|
|
525
|
-
}
|
|
546
|
+
search.visitOccurrences(text, (start, end, value) => {
|
|
547
|
+
const span = { start, end };
|
|
548
|
+
const category = categories.get(value);
|
|
549
|
+
if (category === undefined || !free(span))
|
|
550
|
+
return false;
|
|
551
|
+
repeats.push({ ...span, value, ...category });
|
|
552
|
+
mark(span);
|
|
553
|
+
return true;
|
|
554
|
+
});
|
|
526
555
|
return repeats;
|
|
527
556
|
}
|
|
528
|
-
/**
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
return true;
|
|
535
|
-
if (!containedInAnySpan({ start: at, end: at + original.length }, tokenSpans))
|
|
536
|
-
return false;
|
|
537
|
-
from = at + 1;
|
|
538
|
-
}
|
|
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);
|
|
539
563
|
}
|
|
540
564
|
// ─── Protect pipeline (per string, inside a transaction) ─────────────────────
|
|
541
565
|
/**
|
|
@@ -561,12 +585,40 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
561
585
|
// segment, so issued-token epochs are never decoded as user content,
|
|
562
586
|
// while URL-context windows crossing tokens are checked with the token
|
|
563
587
|
// fragments retained verbatim (see scanForModelBoundary).
|
|
564
|
-
|
|
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);
|
|
565
594
|
if (!scanned.ok)
|
|
566
595
|
return scanned;
|
|
567
596
|
const collected = validateFindingSpans(text, scanned.original.findings);
|
|
568
597
|
if (!collected.ok)
|
|
569
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
|
+
}
|
|
570
622
|
// P1 (2026-10-06b): parse uncertainty degrades to best-effort masking.
|
|
571
623
|
// (1) Findings wholly inside a validated owned token are that token's own
|
|
572
624
|
// interior: already pseudonymized, exempt (unchanged).
|
|
@@ -585,6 +637,10 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
585
637
|
continue;
|
|
586
638
|
candidates.push(span);
|
|
587
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);
|
|
588
644
|
const extended = [];
|
|
589
645
|
for (const span of candidates) {
|
|
590
646
|
let bounds = span;
|
|
@@ -647,10 +703,8 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
647
703
|
tx.detectedValues.set(span.value, { type: span.type, severity: span.severity });
|
|
648
704
|
}
|
|
649
705
|
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
known.push({ start: 0, end: 0, value, ...category });
|
|
653
|
-
const repeats = repeatOccurrences(text, known, [
|
|
706
|
+
tx.valuesSearch = searchOver(tx.valuesSearch, tx.detectedValues.keys(), tx.detectedValues.size);
|
|
707
|
+
const repeats = repeatOccurrences(text, tx.detectedValues, tx.valuesSearch, [
|
|
654
708
|
...actionable,
|
|
655
709
|
...owned.spans,
|
|
656
710
|
...owned.preserved,
|
|
@@ -718,10 +772,9 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
|
|
|
718
772
|
}
|
|
719
773
|
// Independent absence check of every detected original outside validated
|
|
720
774
|
// owned tokens (covers key/value strings for JSON operations too).
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
}
|
|
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");
|
|
725
778
|
}
|
|
726
779
|
return { ok: true, text: substituted };
|
|
727
780
|
}
|
|
@@ -859,7 +912,8 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
859
912
|
return null;
|
|
860
913
|
};
|
|
861
914
|
let from = 0;
|
|
862
|
-
|
|
915
|
+
const findTokenPrefix = tokenPrefixFinder(text);
|
|
916
|
+
let cursor = findTokenPrefix(0);
|
|
863
917
|
while (cursor !== undefined) {
|
|
864
918
|
const { at, prefix } = cursor;
|
|
865
919
|
const token = matchTokenShape(text, at, prefix);
|
|
@@ -867,7 +921,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
867
921
|
if (token === undefined || original === undefined) {
|
|
868
922
|
if (!preserveUnknownMarkers)
|
|
869
923
|
return fail(token === undefined ? "malformed_token" : "unknown_token");
|
|
870
|
-
const next = findTokenPrefix(
|
|
924
|
+
const next = findTokenPrefix(at + prefix.length);
|
|
871
925
|
const close = text.indexOf("]", at + prefix.length);
|
|
872
926
|
const end = token !== undefined
|
|
873
927
|
? at + token.length
|
|
@@ -880,7 +934,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
880
934
|
if (literalFailed !== null)
|
|
881
935
|
return literalFailed;
|
|
882
936
|
from = end;
|
|
883
|
-
cursor = findTokenPrefix(
|
|
937
|
+
cursor = findTokenPrefix(from);
|
|
884
938
|
continue;
|
|
885
939
|
}
|
|
886
940
|
const literalFailed = appendPiece(text.slice(from, at));
|
|
@@ -890,7 +944,7 @@ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarker
|
|
|
890
944
|
if (replacementFailed !== null)
|
|
891
945
|
return replacementFailed;
|
|
892
946
|
from = at + token.length;
|
|
893
|
-
cursor = findTokenPrefix(
|
|
947
|
+
cursor = findTokenPrefix(from);
|
|
894
948
|
}
|
|
895
949
|
const tailFailed = appendPiece(text.slice(from));
|
|
896
950
|
if (tailFailed !== null)
|
|
@@ -1128,14 +1182,11 @@ function buildService(config, limits) {
|
|
|
1128
1182
|
const tokenSpans = scanOwnedTokenSpans(outputString, (token) => tx.live?.reverse.get(token) !== undefined || tx.staged?.reverse.get(token) !== undefined, preserveUnknownMarkers);
|
|
1129
1183
|
if (!tokenSpans.ok)
|
|
1130
1184
|
return tokenSpans;
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
break;
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
if (residual)
|
|
1185
|
+
tx.originalsSearch = searchOver(tx.originalsSearch, tx.detectedOriginals, tx.detectedOriginals.size);
|
|
1186
|
+
if (!tx.originalsSearch.everyOccurrenceCovered(outputString, tokenSpans.spans)) {
|
|
1187
|
+
residual = true;
|
|
1138
1188
|
break;
|
|
1189
|
+
}
|
|
1139
1190
|
}
|
|
1140
1191
|
if (residual) {
|
|
1141
1192
|
seed = tx.detectedValues;
|
|
@@ -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 ────────────────────────────────────────────────────────
|