@maskera/core 0.5.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,76 @@
1
1
  # @maskera/core
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Security: see through invisible-character and compatibility-character obfuscation, and reject detections that cannot be trusted.
8
+
9
+ Detectors match ASCII-ish shapes, which made any character that renders as
10
+ nothing, or renders as a digit without being one, a one-character bypass of the
11
+ whole rule layer. A personnummer split by a zero-width space, a soft hyphen, a
12
+ word joiner, a narrow no-break space or written in fullwidth digits was reported
13
+ as clean, while a human and an LLM tokenizer both still read the number. This
14
+ was not only reachable by an adversary: U+00AD is what PDF de-hyphenation leaves
15
+ behind and U+202F is what Word and typographic number formatting insert.
16
+
17
+ Detectors now run against a canonical view of the input (invisible characters
18
+ removed, NFKC folded) and their spans are mapped back, so `restore()` still
19
+ round trips the original text byte for byte and `value` is always the real
20
+ substring. Ordinary text takes an identity fast path and is unaffected.
21
+
22
+ - `canonicalize()` and `runDetectors()` are exported from `@maskera/core` for
23
+ callers building their own detection pipeline.
24
+ - `redactFromDetections()` now rejects a detection whose `value` disagrees with
25
+ its own span. Such a detection did not fail, it silently rewrote the document
26
+ on `restore()`.
27
+ - `redactFromDetections()` now rejects a label containing `[` or `]` when using
28
+ the default placeholder. Such a label nests one placeholder inside another
29
+ ("[X] [PERSONNUMMER_1_1]"), which puts the literal text of a _different_
30
+ token into the document an LLM sees; echoing that fragment back made
31
+ `restore()` write the real value into it. `maskera`'s own `defaultLabelMap`
32
+ already stripped this at the source.
33
+ - Crafted placeholder collisions no longer take quadratic time. An input seeded
34
+ with `[EPOST_1]`..`[EPOST_N]` forced the placeholder loop to probe N indices,
35
+ and each probe walked the list of prefix positions, so 427 kB of seeded tokens
36
+ spent 7.7 s of blocked event loop (24 kB took 37 ms, 101 kB took 521 ms). The
37
+ positions are now indexed by token length, which answers each probe in O(1);
38
+ the same input takes 22 ms. Re-redacting an already redacted document hits the
39
+ same path.
40
+
41
+ ## 0.6.0
42
+
43
+ ### Minor Changes
44
+
45
+ - 977c524: Security hardening of the redaction core and the NER wrapper.
46
+
47
+ - `personnummer` and `samordningsnummer` now also match the space-separated
48
+ form ("900101 2385", "19900101 2385"). A space where the dash goes was a
49
+ one-character bypass of the most sensitive identifier in the set. The space
50
+ is only accepted where the identifier's own separator sits, four digits from
51
+ the end, so two unrelated numbers in a table never fuse into a candidate;
52
+ detections on the eval corpora are unchanged.
53
+ - `regexDetector` reports the capture group's real position via match indices.
54
+ It previously looked the group text up inside the whole match, which points
55
+ at the wrong place whenever that text also occurs earlier in the match, so a
56
+ custom detector could mask the wrong slice and leave the value in the clear.
57
+ - `redact()` and `restore()` no longer cost O(values x text). The placeholder
58
+ collision check is answered per label instead of per value, and `restore()`
59
+ is a single pass over the tokens; 4k distinct values in a 150 KB document
60
+ went from 237 ms to a few ms.
61
+ - `restore()` no longer substitutes inside a value it just inserted, so a value
62
+ that contains another placeholder token survives the round trip.
63
+ - `redactFromDetections()` rejects malformed spans instead of silently
64
+ duplicating text, and a crafted input seeded with placeholder-shaped strings
65
+ no longer makes redaction throw.
66
+ - `createNerRecognizer()` rejects a `minScore` that is not a finite number in
67
+ [0, 1]. `NaN` silently dropped every model detection, which is fail-open.
68
+ - `defaultLabelMap` constrains an unknown model group to a placeholder-safe
69
+ character set, so a third-party model cannot smuggle bracket syntax into the
70
+ redacted text.
71
+ - The whitespace skipped between two pieces of one entity is bounded, which
72
+ also removes a slow path on text extracted from PDFs.
73
+
3
74
  ## 0.5.0
4
75
 
5
76
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -1,5 +1,101 @@
1
1
  'use strict';
2
2
 
3
+ // src/canonicalize.ts
4
+ var INVISIBLE_SOURCE = "[\\p{Cf}\\u034f\\ufe00-\\ufe0f\\u{e0100}-\\u{e01ef}]";
5
+ var INVISIBLE = new RegExp(INVISIBLE_SOURCE, "u");
6
+ var INVISIBLE_RUN = new RegExp(`${INVISIBLE_SOURCE}+`, "gu");
7
+ var MARK = /\p{M}/u;
8
+ var identityView = (input) => ({
9
+ text: input,
10
+ identity: true,
11
+ span(start, end) {
12
+ return clampSpan(start, end, input.length);
13
+ }
14
+ });
15
+ function clampSpan(start, end, length) {
16
+ const lo = start < 0 || !Number.isFinite(start) ? 0 : start > length ? length : start;
17
+ const hi = end > length || !Number.isFinite(end) ? length : end < lo ? lo : end;
18
+ return [lo, hi];
19
+ }
20
+ function canonicalize(input) {
21
+ if (!INVISIBLE.test(input) && input.normalize("NFKC") === input) return identityView(input);
22
+ const segments = [];
23
+ const folded = /* @__PURE__ */ new Map();
24
+ let text = "";
25
+ let runStart = -1;
26
+ let i = 0;
27
+ const closeRun = (end) => {
28
+ if (runStart < 0) return;
29
+ segments.push({ c: text.length, o: runStart, oEnd: end, linear: true });
30
+ text += input.slice(runStart, end);
31
+ runStart = -1;
32
+ };
33
+ while (i < input.length) {
34
+ const cp = input.codePointAt(i);
35
+ if (cp < 128 && (i + 1 >= input.length || input.charCodeAt(i + 1) < 768)) {
36
+ if (runStart < 0) runStart = i;
37
+ i++;
38
+ continue;
39
+ }
40
+ const size = cp > 65535 ? 2 : 1;
41
+ let j = i + size;
42
+ while (j < input.length) {
43
+ const next = input.codePointAt(j);
44
+ if (next < 128) break;
45
+ const nextSize = next > 65535 ? 2 : 1;
46
+ if (!MARK.test(input.slice(j, j + nextSize))) break;
47
+ j += nextSize;
48
+ }
49
+ const raw = input.slice(i, j);
50
+ let result;
51
+ if (j === i + size) {
52
+ let cached = folded.get(cp);
53
+ if (cached === void 0) {
54
+ cached = INVISIBLE.test(raw) ? "" : raw.normalize("NFKC");
55
+ folded.set(cp, cached);
56
+ }
57
+ result = cached;
58
+ } else {
59
+ result = raw.replace(INVISIBLE_RUN, "").normalize("NFKC");
60
+ }
61
+ if (result === raw) {
62
+ if (runStart < 0) runStart = i;
63
+ } else {
64
+ closeRun(i);
65
+ if (result.length > 0) {
66
+ segments.push({ c: text.length, o: i, oEnd: j, linear: false });
67
+ text += result;
68
+ }
69
+ }
70
+ i = j;
71
+ }
72
+ closeRun(input.length);
73
+ return {
74
+ text,
75
+ identity: text === input,
76
+ span(start, end) {
77
+ const [lo, hi] = clampSpan(start, end, text.length);
78
+ if (segments.length === 0) return [0, 0];
79
+ const head = segments[segmentAt(segments, lo)];
80
+ const mappedStart = head.linear ? head.o + (lo - head.c) : head.o;
81
+ if (hi <= lo) return [mappedStart, mappedStart];
82
+ const tail = segments[segmentAt(segments, hi - 1)];
83
+ const mappedEnd = tail.linear ? tail.o + (hi - tail.c) : tail.oEnd;
84
+ return [mappedStart, mappedEnd < mappedStart ? mappedStart : mappedEnd];
85
+ }
86
+ };
87
+ }
88
+ function segmentAt(segments, c) {
89
+ let lo = 0;
90
+ let hi = segments.length - 1;
91
+ while (lo < hi) {
92
+ const mid = lo + hi + 1 >> 1;
93
+ if (segments[mid].c <= c) lo = mid;
94
+ else hi = mid - 1;
95
+ }
96
+ return lo;
97
+ }
98
+
3
99
  // src/validators.ts
4
100
  function luhnValid(digits) {
5
101
  const only = digits.replace(/\D/g, "");
@@ -50,16 +146,27 @@ function regexDetector(label, regex, validate) {
50
146
  if (!regex.global) {
51
147
  throw new Error(`Detector "${label}" requires a global ("g") regex`);
52
148
  }
149
+ let scanner = regex;
150
+ let hasIndices = regex.flags.includes("d");
151
+ if (!hasIndices) {
152
+ try {
153
+ scanner = new RegExp(regex.source, `${regex.flags}d`);
154
+ hasIndices = true;
155
+ } catch {
156
+ scanner = regex;
157
+ }
158
+ }
53
159
  return {
54
160
  label,
55
161
  detect(input) {
56
162
  const out = [];
57
- regex.lastIndex = 0;
58
- for (const m of input.matchAll(regex)) {
163
+ for (const m of input.matchAll(scanner)) {
59
164
  if (m.index === void 0) continue;
60
- const value = m[1] ?? m[0];
165
+ const group = m[1] !== void 0 ? 1 : 0;
166
+ const value = m[group];
61
167
  if (value.length === 0) continue;
62
- const start = m.index + m[0].indexOf(value);
168
+ const span = hasIndices ? m.indices?.[group] : void 0;
169
+ const start = span ? span[0] : m.index + m[0].indexOf(value);
63
170
  if (validate && !validate(value)) continue;
64
171
  out.push({ start, end: start + value.length, value });
65
172
  }
@@ -67,8 +174,9 @@ function regexDetector(label, regex, validate) {
67
174
  }
68
175
  };
69
176
  }
70
- var DIGIT_RUN = /\d[\d+-]*\d|\d/g;
177
+ var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0]{1,2}(?=\d))*\d|\d/g;
71
178
  var isDigit = (code) => code >= 48 && code <= 57;
179
+ var WS = /\s/;
72
180
  function checksumWindowDetector(label, widths, validate) {
73
181
  return {
74
182
  label,
@@ -80,11 +188,19 @@ function checksumWindowDetector(label, widths, validate) {
80
188
  const base = run.index;
81
189
  if (base === void 0) continue;
82
190
  const offsets = [];
191
+ const spaced = [];
83
192
  let digits = "";
193
+ let gapSpaced = false;
194
+ let anySpaced = false;
84
195
  for (let i2 = 0; i2 < text.length; i2++) {
85
196
  if (isDigit(text.charCodeAt(i2))) {
86
197
  offsets.push(base + i2);
198
+ spaced.push(gapSpaced);
87
199
  digits += text[i2];
200
+ gapSpaced = false;
201
+ } else if (WS.test(text[i2])) {
202
+ gapSpaced = true;
203
+ anySpaced = true;
88
204
  }
89
205
  }
90
206
  let i = 0;
@@ -92,6 +208,16 @@ function checksumWindowDetector(label, widths, validate) {
92
208
  let width = 0;
93
209
  for (const w of widths) {
94
210
  if (i + w > digits.length) continue;
211
+ if (anySpaced) {
212
+ let ok = true;
213
+ for (let k = i + 1; k < i + w; k++) {
214
+ if (spaced[k] && k !== i + w - 4) {
215
+ ok = false;
216
+ break;
217
+ }
218
+ }
219
+ if (!ok) continue;
220
+ }
95
221
  if (!validate(digits.slice(i, i + w))) continue;
96
222
  width = w;
97
223
  break;
@@ -213,38 +339,105 @@ function resolveOverlaps(detections, input) {
213
339
  }
214
340
  return kept;
215
341
  }
342
+ function tokenKey(label, value) {
343
+ return `${label.length}:${label}:${value}`;
344
+ }
345
+ function createInputProbe(input, placeholder) {
346
+ const MAX_CACHED_LENGTHS = 24;
347
+ const prefixes = /* @__PURE__ */ new Map();
348
+ return (label, token) => {
349
+ let entry = prefixes.get(label);
350
+ if (entry === void 0) {
351
+ const first = placeholder(label, 1);
352
+ const second = placeholder(label, 2);
353
+ let n = 0;
354
+ while (n < first.length && n < second.length && first[n] === second[n]) n++;
355
+ const prefix = first.slice(0, n);
356
+ entry = null;
357
+ if (prefix.length > 0) {
358
+ const at = [];
359
+ for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i);
360
+ entry = { prefix, at, byLength: /* @__PURE__ */ new Map() };
361
+ }
362
+ prefixes.set(label, entry);
363
+ }
364
+ if (entry !== null && token.startsWith(entry.prefix)) {
365
+ let candidates = entry.byLength.get(token.length);
366
+ if (candidates === void 0) {
367
+ if (entry.byLength.size >= MAX_CACHED_LENGTHS) {
368
+ return entry.at.some((i) => input.startsWith(token, i));
369
+ }
370
+ candidates = /* @__PURE__ */ new Set();
371
+ for (const i of entry.at) {
372
+ if (i + token.length <= input.length) candidates.add(input.slice(i, i + token.length));
373
+ }
374
+ entry.byLength.set(token.length, candidates);
375
+ }
376
+ return candidates.has(token);
377
+ }
378
+ return input.includes(token);
379
+ };
380
+ }
216
381
  function redact(input, options = {}) {
217
- const detectors = options.detectors ?? defaultDetectors;
382
+ return redactFromDetections(input, runDetectors(input, options.detectors), options);
383
+ }
384
+ function runDetectors(input, detectors = defaultDetectors) {
385
+ const canonical = canonicalize(input);
218
386
  const all = [];
219
387
  for (const detector of detectors) {
220
- for (const m of detector.detect(input)) {
221
- all.push({ ...m, label: detector.label });
388
+ for (const m of detector.detect(canonical.text)) {
389
+ if (canonical.identity) {
390
+ all.push({ ...m, label: detector.label });
391
+ continue;
392
+ }
393
+ const [start, end] = canonical.span(m.start, m.end);
394
+ all.push({ start, end, value: input.slice(start, end), label: detector.label });
222
395
  }
223
396
  }
224
- return redactFromDetections(input, all, options);
397
+ return all;
225
398
  }
226
399
  function redactFromDetections(input, detections, options = {}) {
227
400
  const placeholder = options.placeholder ?? defaultPlaceholder;
401
+ const ownPlaceholder = options.placeholder === void 0;
402
+ for (const d of detections) {
403
+ if (!Number.isInteger(d.start) || !Number.isInteger(d.end) || d.start < 0 || d.end > input.length || d.start >= d.end) {
404
+ throw new Error(
405
+ `maskera: detection span out of range for "${d.label}": [${d.start}, ${d.end}) in an input of length ${input.length}`
406
+ );
407
+ }
408
+ if (d.value !== input.slice(d.start, d.end)) {
409
+ throw new Error(
410
+ `maskera: detection value for "${d.label}" does not match its span [${d.start}, ${d.end}): expected ${JSON.stringify(input.slice(d.start, d.end))}, got ${JSON.stringify(d.value)}`
411
+ );
412
+ }
413
+ if (ownPlaceholder && (d.label.includes("[") || d.label.includes("]"))) {
414
+ throw new Error(
415
+ `maskera: label ${JSON.stringify(d.label)} contains a bracket, which would nest inside the default placeholder and let one token be read as another. Sanitise the label (see defaultLabelMap in maskera) or pass your own placeholder().`
416
+ );
417
+ }
418
+ }
228
419
  const resolved = resolveOverlaps(detections, input);
229
420
  const counters = /* @__PURE__ */ new Map();
230
421
  const tokenByKey = /* @__PURE__ */ new Map();
231
422
  const map = {};
232
423
  const redactions = [];
424
+ const occursInInput = createInputProbe(input, placeholder);
233
425
  for (const d of resolved) {
234
- const key = `${d.label}::${d.value}`;
426
+ const key = tokenKey(d.label, d.value);
235
427
  let token = tokenByKey.get(key);
236
428
  if (!token) {
237
429
  let next = counters.get(d.label) ?? 0;
238
430
  let attempts = 0;
239
- do {
431
+ for (; ; ) {
240
432
  next += 1;
241
433
  token = placeholder(d.label, next);
242
434
  attempts += 1;
243
- } while (attempts < 100 && (input.includes(token) || token in map));
244
- if (input.includes(token) || token in map) {
245
- throw new Error(
246
- "maskera: placeholder() must return a token that is unique per (label, index) and does not occur in the input"
247
- );
435
+ if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break;
436
+ if (token.length === 0 || attempts > 8 + input.length / token.length) {
437
+ throw new Error(
438
+ "maskera: placeholder() must return a token that is unique per (label, index) and does not occur in the input"
439
+ );
440
+ }
248
441
  }
249
442
  counters.set(d.label, next);
250
443
  tokenByKey.set(key, token);
@@ -268,16 +461,52 @@ function redactFromDetections(input, detections, options = {}) {
268
461
  };
269
462
  }
270
463
  function restore(text, map) {
271
- let out = text;
272
- const tokens = Object.keys(map).sort((a, b) => b.length - a.length);
464
+ const tokens = Object.keys(map).filter((t) => t.length > 0);
465
+ if (tokens.length === 0) return text;
466
+ const root = { next: /* @__PURE__ */ new Map() };
273
467
  for (const token of tokens) {
274
- out = out.split(token).join(map[token]);
468
+ let node = root;
469
+ for (let k = 0; k < token.length; k++) {
470
+ const ch = token[k];
471
+ let child = node.next.get(ch);
472
+ if (!child) {
473
+ child = { next: /* @__PURE__ */ new Map() };
474
+ node.next.set(ch, child);
475
+ }
476
+ node = child;
477
+ }
478
+ node.value = map[token];
479
+ }
480
+ let out = "";
481
+ let last = 0;
482
+ let i = 0;
483
+ while (i < text.length) {
484
+ let node = root.next.get(text[i]);
485
+ let matchEnd = -1;
486
+ let matchValue;
487
+ let j = i;
488
+ while (node) {
489
+ j++;
490
+ if (node.value !== void 0) {
491
+ matchEnd = j;
492
+ matchValue = node.value;
493
+ }
494
+ node = j < text.length ? node.next.get(text[j]) : void 0;
495
+ }
496
+ if (matchValue === void 0) {
497
+ i++;
498
+ continue;
499
+ }
500
+ out += text.slice(last, i) + matchValue;
501
+ i = matchEnd;
502
+ last = i;
275
503
  }
276
- return out;
504
+ return out + text.slice(last);
277
505
  }
278
506
 
279
507
  exports.adress = adress;
280
508
  exports.bankgiro = bankgiro;
509
+ exports.canonicalize = canonicalize;
281
510
  exports.creditCard = creditCard;
282
511
  exports.defaultDetectors = defaultDetectors;
283
512
  exports.email = email;
@@ -299,6 +528,7 @@ exports.redactFromDetections = redactFromDetections;
299
528
  exports.regexDetector = regexDetector;
300
529
  exports.regnummer = regnummer;
301
530
  exports.restore = restore;
531
+ exports.runDetectors = runDetectors;
302
532
  exports.samordningsnummer = samordningsnummer;
303
533
  exports.url = url;
304
534
  //# sourceMappingURL=index.cjs.map