@maskera/core 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # @maskera/core
2
2
 
3
+ ## 0.7.1
4
+
5
+ ### Patch Changes
6
+
7
+ - core: Fix a redaction bypass where a U+1680 OGHAM SPACE MARK inside a digit run hid personnummer/samordningsnummer from the detectors. The character renders as whitespace but is untouched by Unicode canonicalization, so `850601\u{1680}2387` passed through unredacted while the same number with any other space was masked. The digit-run gap class now covers it.
8
+
9
+ ner: Fix a quadratic clipping loop in `redactWithNer` that re-walked the segment list once per rule detection for every model span, blocking the event loop for seconds on documents with thousands of rule hits (measured 3.3 s on a 79 KB input). Clipping now uses single-cursor interval subtraction against the rule spans sorted once, which is linear in practice (4 ms on the same input).
10
+
11
+ ## 0.7.0
12
+
13
+ ### Minor Changes
14
+
15
+ - Security: see through invisible-character and compatibility-character obfuscation, and reject detections that cannot be trusted.
16
+
17
+ Detectors match ASCII-ish shapes, which made any character that renders as
18
+ nothing, or renders as a digit without being one, a one-character bypass of the
19
+ whole rule layer. A personnummer split by a zero-width space, a soft hyphen, a
20
+ word joiner, a narrow no-break space or written in fullwidth digits was reported
21
+ as clean, while a human and an LLM tokenizer both still read the number. This
22
+ was not only reachable by an adversary: U+00AD is what PDF de-hyphenation leaves
23
+ behind and U+202F is what Word and typographic number formatting insert.
24
+
25
+ Detectors now run against a canonical view of the input (invisible characters
26
+ removed, NFKC folded) and their spans are mapped back, so `restore()` still
27
+ round trips the original text byte for byte and `value` is always the real
28
+ substring. Ordinary text takes an identity fast path and is unaffected.
29
+
30
+ - `canonicalize()` and `runDetectors()` are exported from `@maskera/core` for
31
+ callers building their own detection pipeline.
32
+ - `redactFromDetections()` now rejects a detection whose `value` disagrees with
33
+ its own span. Such a detection did not fail, it silently rewrote the document
34
+ on `restore()`.
35
+ - `redactFromDetections()` now rejects a label containing `[` or `]` when using
36
+ the default placeholder. Such a label nests one placeholder inside another
37
+ ("[X] [PERSONNUMMER_1_1]"), which puts the literal text of a _different_
38
+ token into the document an LLM sees; echoing that fragment back made
39
+ `restore()` write the real value into it. `maskera`'s own `defaultLabelMap`
40
+ already stripped this at the source.
41
+ - Crafted placeholder collisions no longer take quadratic time. An input seeded
42
+ with `[EPOST_1]`..`[EPOST_N]` forced the placeholder loop to probe N indices,
43
+ and each probe walked the list of prefix positions, so 427 kB of seeded tokens
44
+ spent 7.7 s of blocked event loop (24 kB took 37 ms, 101 kB took 521 ms). The
45
+ positions are now indexed by token length, which answers each probe in O(1);
46
+ the same input takes 22 ms. Re-redacting an already redacted document hits the
47
+ same path.
48
+
3
49
  ## 0.6.0
4
50
 
5
51
  ### 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, "");
@@ -78,7 +174,7 @@ function regexDetector(label, regex, validate) {
78
174
  }
79
175
  };
80
176
  }
81
- var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0]{1,2}(?=\d))*\d|\d/g;
177
+ var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0\u1680]{1,2}(?=\d))*\d|\d/g;
82
178
  var isDigit = (code) => code >= 48 && code <= 57;
83
179
  var WS = /\s/;
84
180
  function checksumWindowDetector(label, widths, validate) {
@@ -247,6 +343,7 @@ function tokenKey(label, value) {
247
343
  return `${label.length}:${label}:${value}`;
248
344
  }
249
345
  function createInputProbe(input, placeholder) {
346
+ const MAX_CACHED_LENGTHS = 24;
250
347
  const prefixes = /* @__PURE__ */ new Map();
251
348
  return (label, token) => {
252
349
  let entry = prefixes.get(label);
@@ -260,34 +357,64 @@ function createInputProbe(input, placeholder) {
260
357
  if (prefix.length > 0) {
261
358
  const at = [];
262
359
  for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i);
263
- entry = { prefix, at };
360
+ entry = { prefix, at, byLength: /* @__PURE__ */ new Map() };
264
361
  }
265
362
  prefixes.set(label, entry);
266
363
  }
267
364
  if (entry !== null && token.startsWith(entry.prefix)) {
268
- return entry.at.some((i) => input.startsWith(token, i));
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);
269
377
  }
270
378
  return input.includes(token);
271
379
  };
272
380
  }
273
381
  function redact(input, options = {}) {
274
- 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);
275
386
  const all = [];
276
387
  for (const detector of detectors) {
277
- for (const m of detector.detect(input)) {
278
- 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 });
279
395
  }
280
396
  }
281
- return redactFromDetections(input, all, options);
397
+ return all;
282
398
  }
283
399
  function redactFromDetections(input, detections, options = {}) {
284
400
  const placeholder = options.placeholder ?? defaultPlaceholder;
401
+ const ownPlaceholder = options.placeholder === void 0;
285
402
  for (const d of detections) {
286
403
  if (!Number.isInteger(d.start) || !Number.isInteger(d.end) || d.start < 0 || d.end > input.length || d.start >= d.end) {
287
404
  throw new Error(
288
405
  `maskera: detection span out of range for "${d.label}": [${d.start}, ${d.end}) in an input of length ${input.length}`
289
406
  );
290
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
+ }
291
418
  }
292
419
  const resolved = resolveOverlaps(detections, input);
293
420
  const counters = /* @__PURE__ */ new Map();
@@ -379,6 +506,7 @@ function restore(text, map) {
379
506
 
380
507
  exports.adress = adress;
381
508
  exports.bankgiro = bankgiro;
509
+ exports.canonicalize = canonicalize;
382
510
  exports.creditCard = creditCard;
383
511
  exports.defaultDetectors = defaultDetectors;
384
512
  exports.email = email;
@@ -400,6 +528,7 @@ exports.redactFromDetections = redactFromDetections;
400
528
  exports.regexDetector = regexDetector;
401
529
  exports.regnummer = regnummer;
402
530
  exports.restore = restore;
531
+ exports.runDetectors = runDetectors;
403
532
  exports.samordningsnummer = samordningsnummer;
404
533
  exports.url = url;
405
534
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";;;AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IAAK,CAAA;AACL,MAAA,IAAI,CAAA,GAAI,GAAG,CAAA,IAAK,CAAA;AAAA,IAClB;AACA,IAAA,GAAA,IAAO,CAAA;AACP,IAAA,MAAA,GAAS,CAAC,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,MAAM,EAAA,KAAO,CAAA;AACtB;AAOO,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,KAAA,CAAM,6CAA6C,CAAA;AACnE,EAAA,IAA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,IAAA,IAAI,UAAA;AACJ,IAAA,IAAI,CAAA,GAAI,CAAA;AACR,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,CAAA,EAAA;AACA,MAAA,IAAI,IAAA,CAAK,UAAU,MAAA,EAAW;AAC5B,QAAA,QAAA,GAAW,CAAA;AACX,QAAA,UAAA,GAAa,IAAA,CAAK,KAAA;AAAA,MACpB;AACA,MAAA,IAAA,GAAO,CAAA,GAAI,KAAK,MAAA,GAAS,IAAA,CAAK,KAAK,GAAA,CAAI,IAAA,CAAK,CAAC,CAAW,CAAA,GAAI,MAAA;AAAA,IAC9D;AACA,IAAA,IAAI,eAAe,MAAA,EAAW;AAC5B,MAAA,CAAA,EAAA;AACA,MAAA;AAAA,IACF;AACA,IAAA,GAAA,IAAO,IAAA,CAAK,KAAA,CAAM,IAAA,EAAM,CAAC,CAAA,GAAI,UAAA;AAC7B,IAAA,CAAA,GAAI,QAAA;AACJ,IAAA,IAAA,GAAO,CAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC9B","file":"index.cjs","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n // Match indices (\"d\") give the capture group's real position. Looking the\n // group text up inside m[0] instead (`m[0].indexOf(value)`) finds its first\n // *occurrence*, which is a different place whenever that text also appears\n // earlier in the match: a custom detector like /kontakt (\\S+) mejl \\1/ then\n // reports a span four characters too far left, and redact() masks the wrong\n // slice and leaves the value itself in the clear. The built-in detectors all\n // capture at an unambiguous position, but this is public API.\n //\n // The flag is added to a copy, which also keeps `lastIndex` off the caller's\n // regex. Engines predating the flag (it needs Chrome 90 / Safari 15 / Node\n // 16) throw on construction, and these detectors are built at module scope,\n // so the fallback is what keeps `import` itself from failing there.\n let scanner = regex\n let hasIndices = regex.flags.includes(\"d\")\n if (!hasIndices) {\n try {\n scanner = new RegExp(regex.source, `${regex.flags}d`)\n hasIndices = true\n } catch {\n scanner = regex\n }\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n for (const m of input.matchAll(scanner)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const group = m[1] !== undefined ? 1 : 0\n const value = m[group] as string\n if (value.length === 0) continue\n const span = hasIndices ? (m as MatchWithIndices).indices?.[group] : undefined\n const start = span ? span[0] : m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n/** `RegExpMatchArray.indices` is ES2022; the package compiles against ES2021. */\ntype MatchWithIndices = RegExpMatchArray & {\n indices?: Array<[number, number] | undefined>\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/**\n * A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain\n * and the horizontal whitespace it is routinely typed with (\"811218 9876\",\n * \"19 811218 9876\" in forms and journal notes). Stopping the run at a space\n * made one space a reliable one-character bypass, the same failure the missing\n * word boundary was fixed for. Newlines are NOT included, so two numbers in a\n * column never merge, and the whitespace run is bounded so the pattern cannot\n * backtrack over a long gap.\n */\nconst DIGIT_RUN = /\\d(?:[\\d+-]|[ \\t\\u00a0]{1,2}(?=\\d))*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\nconst WS = /\\s/\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * A run may contain whitespace (\"811218 9876\"), but a window is only allowed to\n * cross it at the position the separator actually belongs, four digits from the\n * end. Anything else would let two unrelated numbers in a table (\"Belopp 4711\n * 220345\") fuse into a candidate, and it is the cheap check that keeps the\n * widened run from spending the false-positive budget the checksum bought.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span. `spaced[k]` records that whitespace sits\n // between digit k-1 and digit k.\n const offsets: number[] = []\n const spaced: boolean[] = []\n let digits = \"\"\n let gapSpaced = false\n let anySpaced = false\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n spaced.push(gapSpaced)\n digits += text[i]\n gapSpaced = false\n } else if (WS.test(text[i] as string)) {\n gapSpaced = true\n anySpaced = true\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n // Whitespace may only sit where the identifier's own separator\n // does: four digits from the end of the window.\n if (anySpaced) {\n let ok = true\n for (let k = i + 1; k < i + w; k++) {\n if (spaced[k] && k !== i + w - 4) {\n ok = false\n break\n }\n }\n if (!ok) continue\n }\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * Key for the stable-placeholder cache. Length-prefixed rather than\n * `${label}::${value}`, which is ambiguous the moment a custom label contains\n * `::`: (\"A::B\", \"c\") and (\"A\", \"B::c\") would share one placeholder, and\n * restore() would then write the first value where the second one stood.\n */\nfunction tokenKey(label: PiiLabel, value: string): string {\n return `${label.length}:${label}:${value}`\n}\n\n/**\n * Answers \"does this generated token already occur in the input?\" without\n * scanning the input once per redacted value.\n *\n * The plain scan is O(values × input): 4k distinct values in a 150 KB log spent\n * 237 ms in this check alone, and both factors grow with the document, so a\n * megabyte-sized log dump (the paste this library exists for) blocks for\n * seconds. The placeholders of one label share a prefix (\"[EPOST_\"), so one\n * scan per label settles all of them: a token carrying that prefix can only\n * occur where the prefix occurs, which is usually nowhere and is a short list\n * even when re-redacting an already redacted document. A token that does not\n * carry the prefix - `placeholder` is an arbitrary caller function, it need not\n * be prefix-stable - still takes the full scan, so the answer stays exact.\n */\nfunction createInputProbe(\n input: string,\n placeholder: (label: PiiLabel, index: number) => string,\n): (label: PiiLabel, token: string) => boolean {\n const prefixes = new Map<PiiLabel, { prefix: string; at: number[] } | null>()\n return (label, token) => {\n let entry = prefixes.get(label)\n if (entry === undefined) {\n const first = placeholder(label, 1)\n const second = placeholder(label, 2)\n let n = 0\n while (n < first.length && n < second.length && first[n] === second[n]) n++\n const prefix = first.slice(0, n)\n entry = null\n if (prefix.length > 0) {\n const at: number[] = []\n for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i)\n entry = { prefix, at }\n }\n prefixes.set(label, entry)\n }\n if (entry !== null && token.startsWith(entry.prefix)) {\n return entry.at.some((i) => input.startsWith(token, i))\n }\n return input.includes(token)\n }\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n // Spans arrive from callers too (`redactWithNer`, anything model-shaped), and\n // a malformed one does not fail loudly on its own: `resolveOverlaps` sorts a\n // reversed span into place and the rebuild loop below then *duplicates* the\n // text between `last` and `r.start` instead of removing it, which is silent\n // corruption of a document someone is redacting. Reject it instead.\n for (const d of detections) {\n if (\n !Number.isInteger(d.start) ||\n !Number.isInteger(d.end) ||\n d.start < 0 ||\n d.end > input.length ||\n d.start >= d.end\n ) {\n throw new Error(\n `maskera: detection span out of range for \"${d.label}\": [${d.start}, ${d.end}) ` +\n `in an input of length ${input.length}`,\n )\n }\n }\n\n const resolved = resolveOverlaps(detections, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n const occursInInput = createInputProbe(input, placeholder)\n\n for (const d of resolved) {\n const key = tokenKey(d.label, d.value)\n let token = tokenByKey.get(key)\n if (!token) {\n // Never hand out a token that already occurs literally in the input\n // (a crafted \"[NAMN_1]\" in the input would collide with a generated\n // placeholder, and restore() would write the real value into positions\n // the author of the input chose), and never a token another value\n // already owns (a custom placeholder() that ignores the index would\n // otherwise silently map two values to one token and corrupt restore).\n let next = counters.get(d.label) ?? 0\n let attempts = 0\n for (;;) {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break\n // Giving up after a fixed number of tries made a crafted input a denial\n // of service: seeding \"[EPOST_1]\"..\"[EPOST_100]\" was enough to make\n // every later redact() throw. An input can only hold\n // input.length / token.length distinct colliding tokens, so past that\n // bound the placeholder() itself is broken (it ignores the index) and\n // no further index will help.\n if (token.length === 0 || attempts > 8 + input.length / token.length) {\n throw new Error(\n \"maskera: placeholder() must return a token that is unique per (label, index) \" +\n \"and does not occur in the input\",\n )\n }\n }\n counters.set(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n const tokens = Object.keys(map).filter((t) => t.length > 0)\n if (tokens.length === 0) return text\n\n // One left-to-right pass over a trie of the tokens, rather than a\n // split/join per token. Two reasons, and the first one is correctness:\n // replacing token by token re-scans text that was already restored, so a\n // value that happens to contain another token (\"Anna [EPOST_1]\" as a NAMN\n // value handed in via redactFromDetections) got substituted a second time\n // and the output was neither the placeholder nor the original. A single pass\n // never revisits what it wrote. The second is cost: split/join is O(tokens ×\n // text), which is the same product that made redaction slow on large logs.\n // Matching the deepest node at each position keeps the old longest-first\n // rule, so `[X_10]` still wins over `[X_1]`.\n const root: TrieNode = { next: new Map() }\n for (const token of tokens) {\n let node = root\n // Indexed by UTF-16 unit, the same way the scan below reads the text: a\n // code-point walk here would key a surrogate pair as one two-unit string\n // and never match.\n for (let k = 0; k < token.length; k++) {\n const ch = token[k] as string\n let child = node.next.get(ch)\n if (!child) {\n child = { next: new Map() }\n node.next.set(ch, child)\n }\n node = child\n }\n node.value = map[token]\n }\n\n let out = \"\"\n let last = 0\n let i = 0\n while (i < text.length) {\n let node = root.next.get(text[i] as string)\n let matchEnd = -1\n let matchValue: string | undefined\n let j = i\n while (node) {\n j++\n if (node.value !== undefined) {\n matchEnd = j\n matchValue = node.value\n }\n node = j < text.length ? node.next.get(text[j] as string) : undefined\n }\n if (matchValue === undefined) {\n i++\n continue\n }\n out += text.slice(last, i) + matchValue\n i = matchEnd\n last = i\n }\n return out + text.slice(last)\n}\n\ntype TrieNode = { value?: string; next: Map<string, TrieNode> }\n"]}
1
+ {"version":3,"sources":["../src/canonicalize.ts","../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";;;AAsDA,IAAM,gBAAA,GAAmB,sDAAA;AACzB,IAAM,SAAA,GAAY,IAAI,MAAA,CAAO,gBAAA,EAAkB,GAAG,CAAA;AAClD,IAAM,gBAAgB,IAAI,MAAA,CAAO,CAAA,EAAG,gBAAgB,KAAK,IAAI,CAAA;AAC7D,IAAM,IAAA,GAAO,QAAA;AAiBb,IAAM,YAAA,GAAe,CAAC,KAAA,MAAkC;AAAA,EACtD,IAAA,EAAM,KAAA;AAAA,EACN,QAAA,EAAU,IAAA;AAAA,EACV,IAAA,CAAK,OAAO,GAAA,EAAK;AAKf,IAAA,OAAO,SAAA,CAAU,KAAA,EAAO,GAAA,EAAK,KAAA,CAAM,MAAM,CAAA;AAAA,EAC3C;AACF,CAAA,CAAA;AAEA,SAAS,SAAA,CAAU,KAAA,EAAe,GAAA,EAAa,MAAA,EAAkC;AAC/E,EAAA,MAAM,EAAA,GAAK,KAAA,GAAQ,CAAA,IAAK,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,GAAI,CAAA,GAAI,KAAA,GAAQ,MAAA,GAAS,MAAA,GAAS,KAAA;AAChF,EAAA,MAAM,EAAA,GAAK,GAAA,GAAM,MAAA,IAAU,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,GAAI,MAAA,GAAS,GAAA,GAAM,EAAA,GAAK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;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC9B","file":"index.cjs","sourcesContent":["/**\n * The detection-time view of an input string, plus a map back to the original\n * offsets.\n *\n * Detectors are pattern matchers over ASCII-ish shapes: `\\d`, `[A-ZÅÄÖ]`, a\n * literal space. That makes every character that renders as nothing, or renders\n * as a digit without being one, a one-character bypass of the whole rule layer.\n * Measured before this existed, on `redact()` defaults:\n *\n * \"850601-2387\" -> PERSONNUMMER\n * \"850601\" + U+200B + \"2387\" -> nothing\n * \"8506\" + U+00AD + \"012387\" -> nothing\n * \"850601\" + U+2060 + \"2387\" -> nothing\n * \"850601\" + U+2009/U+202F + \"2387\" -> nothing\n * \"8506012387\" (fullwidth) -> nothing\n * \"anna@exa\" + U+200B + \"mple.com\" -> nothing\n *\n * All of those render identically (or near enough) to the real thing, and an\n * LLM tokenizer drops the invisible ones outright, so the model downstream reads\n * the personnummer that maskera reported as clean. It is not only an adversary\n * either: U+00AD is what PDF de-hyphenation leaves behind and U+202F is what\n * Word and typographic number formatting insert, so ordinary document pipelines\n * hit this without anyone trying.\n *\n * So detectors run against a canonical view instead: invisible characters\n * removed, compatibility characters folded via NFKC. The ORIGINAL string is\n * still what gets rebuilt and what `value` is sliced from, so `restore()` round\n * trips byte for byte; only the matching sees the folded text.\n */\nexport interface CanonicalText {\n /** The folded text to run detectors against. */\n readonly text: string\n /** True when {@link text} is the input unchanged, i.e. nothing was folded. */\n readonly identity: boolean\n /**\n * Map a `[start, end)` span in {@link text} to the span in the original input\n * that produced it. An invisible character sitting INSIDE the span is covered\n * by the result (so the mask swallows it); one sitting just outside is not.\n */\n span(start: number, end: number): [number, number]\n}\n\n/**\n * Characters that occupy no visual space but split a digit or letter run in two.\n *\n * `\\p{Cf}` is the bulk of them: U+00AD SOFT HYPHEN, U+200B ZERO WIDTH SPACE,\n * U+200C/U+200D the joiners, U+2060 WORD JOINER, U+FEFF, and the bidi controls\n * U+200E..U+200F / U+202A..U+202E (the Trojan Source family). The rest are the\n * invisible combining marks, which are `\\p{M}` and therefore survive NFKC:\n * U+034F COMBINING GRAPHEME JOINER and the variation selectors.\n *\n * Dropping the joiners costs nothing here because this view is never rendered\n * and never restored from; it only decides where a detector matches.\n */\nconst INVISIBLE_SOURCE = \"[\\\\p{Cf}\\\\u034f\\\\ufe00-\\\\ufe0f\\\\u{e0100}-\\\\u{e01ef}]\"\nconst INVISIBLE = new RegExp(INVISIBLE_SOURCE, \"u\")\nconst INVISIBLE_RUN = new RegExp(`${INVISIBLE_SOURCE}+`, \"gu\")\nconst MARK = /\\p{M}/u\n\n/**\n * One stretch of the mapping. `linear` segments came through untouched, so an\n * offset inside them shifts by a constant; folded ones changed length or shape,\n * so every canonical offset inside them maps to the whole original range.\n */\ninterface Segment {\n /** Start of this segment in the canonical text. */\n c: number\n /** Start of the original range that produced it. */\n o: number\n /** End of that original range. */\n oEnd: number\n linear: boolean\n}\n\nconst identityView = (input: string): CanonicalText => ({\n text: input,\n identity: true,\n span(start, end) {\n // Clamped exactly like the folded path below. A detector handing back an\n // out-of-range span is a bug either way, but it must not be a bug whose\n // symptoms depend on whether the input happened to contain a zero-width\n // space: that is the kind of difference that shows up once, in production.\n return clampSpan(start, end, input.length)\n },\n})\n\nfunction clampSpan(start: number, end: number, length: number): [number, number] {\n const lo = start < 0 || !Number.isFinite(start) ? 0 : start > length ? length : start\n const hi = end > length || !Number.isFinite(end) ? length : end < lo ? lo : end\n return [lo, hi]\n}\n\n/**\n * Build the canonical view of `input`.\n *\n * The common case (no invisible characters, already NFKC) returns the input\n * itself with an identity map and costs one regex scan plus one `normalize`\n * quick check, so ordinary Swedish prose pays almost nothing.\n */\nexport function canonicalize(input: string): CanonicalText {\n if (!INVISIBLE.test(input) && input.normalize(\"NFKC\") === input) return identityView(input)\n\n const segments: Segment[] = []\n // Folding one code point at a time is only equivalent to folding the whole\n // string because NFKC never composes across two starters (Hangul jamo aside,\n // which no PII shape cares about). Combining marks DO compose with the\n // starter before them, so a base plus its marks is folded as one unit.\n const folded = new Map<number, string>()\n let text = \"\"\n let runStart = -1\n let i = 0\n\n const closeRun = (end: number) => {\n if (runStart < 0) return\n segments.push({ c: text.length, o: runStart, oEnd: end, linear: true })\n text += input.slice(runStart, end)\n runStart = -1\n }\n\n while (i < input.length) {\n const cp = input.codePointAt(i) as number\n // ASCII is never invisible, never a mark and always NFKC-stable, and it is\n // most of any document. Skipping the per-character work here is what keeps\n // the folded path from costing more than the detection it feeds.\n //\n // Unless a combining mark follows it: \"Åsa\" arrives from PDF extraction and\n // from macOS paths as A + U+030A, and folding that pair is how it becomes\n // something `[A-ZÅÄÖ]` can match at all. Marks start at U+0300, so one\n // comparison keeps ordinary text (including å, ä and ö, which are far\n // below that) on the fast path.\n if (cp < 0x80 && (i + 1 >= input.length || input.charCodeAt(i + 1) < 0x300)) {\n if (runStart < 0) runStart = i\n i++\n continue\n }\n\n const size = cp > 0xffff ? 2 : 1\n let j = i + size\n while (j < input.length) {\n const next = input.codePointAt(j) as number\n if (next < 0x80) break\n const nextSize = next > 0xffff ? 2 : 1\n if (!MARK.test(input.slice(j, j + nextSize))) break\n j += nextSize\n }\n\n const raw = input.slice(i, j)\n let result: string\n if (j === i + size) {\n let cached = folded.get(cp)\n if (cached === undefined) {\n cached = INVISIBLE.test(raw) ? \"\" : raw.normalize(\"NFKC\")\n folded.set(cp, cached)\n }\n result = cached\n } else {\n result = raw.replace(INVISIBLE_RUN, \"\").normalize(\"NFKC\")\n }\n\n if (result === raw) {\n if (runStart < 0) runStart = i\n } else {\n closeRun(i)\n if (result.length > 0) {\n segments.push({ c: text.length, o: i, oEnd: j, linear: false })\n text += result\n }\n // A dropped character contributes no segment at all. The next segment's\n // `o` therefore starts after it, which is what makes an invisible sitting\n // inside a detection fall inside the mapped span.\n }\n i = j\n }\n closeRun(input.length)\n\n return {\n text,\n identity: text === input,\n span(start, end) {\n const [lo, hi] = clampSpan(start, end, text.length)\n // Every visible character was dropped, so there is nothing to map from.\n if (segments.length === 0) return [0, 0]\n const head = segments[segmentAt(segments, lo)] as Segment\n const mappedStart = head.linear ? head.o + (lo - head.c) : head.o\n if (hi <= lo) return [mappedStart, mappedStart]\n const tail = segments[segmentAt(segments, hi - 1)] as Segment\n const mappedEnd = tail.linear ? tail.o + (hi - tail.c) : tail.oEnd\n return [mappedStart, mappedEnd < mappedStart ? mappedStart : mappedEnd]\n },\n }\n}\n\n/** Index of the last segment starting at or before canonical offset `c`. */\nfunction segmentAt(segments: Segment[], c: number): number {\n let lo = 0\n let hi = segments.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if ((segments[mid] as Segment).c <= c) lo = mid\n else hi = mid - 1\n }\n return lo\n}\n","/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n // Match indices (\"d\") give the capture group's real position. Looking the\n // group text up inside m[0] instead (`m[0].indexOf(value)`) finds its first\n // *occurrence*, which is a different place whenever that text also appears\n // earlier in the match: a custom detector like /kontakt (\\S+) mejl \\1/ then\n // reports a span four characters too far left, and redact() masks the wrong\n // slice and leaves the value itself in the clear. The built-in detectors all\n // capture at an unambiguous position, but this is public API.\n //\n // The flag is added to a copy, which also keeps `lastIndex` off the caller's\n // regex. Engines predating the flag (it needs Chrome 90 / Safari 15 / Node\n // 16) throw on construction, and these detectors are built at module scope,\n // so the fallback is what keeps `import` itself from failing there.\n let scanner = regex\n let hasIndices = regex.flags.includes(\"d\")\n if (!hasIndices) {\n try {\n scanner = new RegExp(regex.source, `${regex.flags}d`)\n hasIndices = true\n } catch {\n scanner = regex\n }\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n for (const m of input.matchAll(scanner)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const group = m[1] !== undefined ? 1 : 0\n const value = m[group] as string\n if (value.length === 0) continue\n const span = hasIndices ? (m as MatchWithIndices).indices?.[group] : undefined\n const start = span ? span[0] : m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n/** `RegExpMatchArray.indices` is ES2022; the package compiles against ES2021. */\ntype MatchWithIndices = RegExpMatchArray & {\n indices?: Array<[number, number] | undefined>\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/**\n * A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain\n * and the horizontal whitespace it is routinely typed with (\"811218 9876\",\n * \"19 811218 9876\" in forms and journal notes). Stopping the run at a space\n * made one space a reliable one-character bypass, the same failure the missing\n * word boundary was fixed for. Newlines are NOT included, so two numbers in a\n * column never merge, and the whitespace run is bounded so the pattern cannot\n * backtrack over a long gap.\n *\n * The class names U+1680 OGHAM SPACE MARK explicitly: it is the one horizontal\n * whitespace NFKC does not fold to U+0020 (canonicalize folds the rest, so the\n * plain space covers them), yet it matches JS `\\s` and renders as a space, so\n * without it a single character split the run and walked a personnummer past\n * the checksum detectors.\n */\nconst DIGIT_RUN = /\\d(?:[\\d+-]|[ \\t\\u00a0\\u1680]{1,2}(?=\\d))*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\nconst WS = /\\s/\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * A run may contain whitespace (\"811218 9876\"), but a window is only allowed to\n * cross it at the position the separator actually belongs, four digits from the\n * end. Anything else would let two unrelated numbers in a table (\"Belopp 4711\n * 220345\") fuse into a candidate, and it is the cheap check that keeps the\n * widened run from spending the false-positive budget the checksum bought.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span. `spaced[k]` records that whitespace sits\n // between digit k-1 and digit k.\n const offsets: number[] = []\n const spaced: boolean[] = []\n let digits = \"\"\n let gapSpaced = false\n let anySpaced = false\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n spaced.push(gapSpaced)\n digits += text[i]\n gapSpaced = false\n } else if (WS.test(text[i] as string)) {\n gapSpaced = true\n anySpaced = true\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n // Whitespace may only sit where the identifier's own separator\n // does: four digits from the end of the window.\n if (anySpaced) {\n let ok = true\n for (let k = i + 1; k < i + w; k++) {\n if (spaced[k] && k !== i + w - 4) {\n ok = false\n break\n }\n }\n if (!ok) continue\n }\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { canonicalize } from \"./canonicalize\"\nimport { defaultDetectors } from \"./detectors\"\nimport type { Detection, Detector, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * Key for the stable-placeholder cache. Length-prefixed rather than\n * `${label}::${value}`, which is ambiguous the moment a custom label contains\n * `::`: (\"A::B\", \"c\") and (\"A\", \"B::c\") would share one placeholder, and\n * restore() would then write the first value where the second one stood.\n */\nfunction tokenKey(label: PiiLabel, value: string): string {\n return `${label.length}:${label}:${value}`\n}\n\n/**\n * Answers \"does this generated token already occur in the input?\" without\n * scanning the input once per redacted value.\n *\n * The plain scan is O(values × input): 4k distinct values in a 150 KB log spent\n * 237 ms in this check alone, and both factors grow with the document, so a\n * megabyte-sized log dump (the paste this library exists for) blocks for\n * seconds. The placeholders of one label share a prefix (\"[EPOST_\"), so one\n * scan per label settles all of them: a token carrying that prefix can only\n * occur where the prefix occurs, which is usually nowhere and is a short list\n * even when re-redacting an already redacted document. A token that does not\n * carry the prefix - `placeholder` is an arbitrary caller function, it need not\n * be prefix-stable - still takes the full scan, so the answer stays exact.\n *\n * The positions are then indexed BY TOKEN LENGTH rather than walked per query.\n * Walking them is quadratic in the number of seeded tokens, and the retry loop\n * in `redactFromDetections` is what supplies the second factor: an input seeded\n * with \"[EPOST_1]\"..\"[EPOST_N]\" forces N probes, and probe k walks about k\n * positions before it finds its collision. Measured on the walk, with one real\n * e-mail in the document: 24 kB of seeded tokens took 37 ms, 50 kB took 131 ms,\n * 101 kB took 521 ms, 208 kB took 1.9 s and 427 kB took 7.7 s, a clean n^2 that\n * blocks the event loop (or freezes the tab) on an input a redaction tool is\n * expected to swallow. Grouping by length costs one pass per distinct length\n * (about six for any counter-shaped placeholder) and answers each probe in O(1).\n */\nfunction createInputProbe(\n input: string,\n placeholder: (label: PiiLabel, index: number) => string,\n): (label: PiiLabel, token: string) => boolean {\n interface Probe {\n prefix: string\n at: number[]\n /** Candidate substrings at `at`, per token length. */\n byLength: Map<number, Set<string>>\n }\n // Distinct token lengths per label, past which we stop caching and walk\n // instead. A counter-shaped placeholder produces one length per decade, so\n // this is far above any real one; it only bounds the memory a crafted\n // `placeholder` could make us hold.\n const MAX_CACHED_LENGTHS = 24\n const prefixes = new Map<PiiLabel, Probe | null>()\n return (label, token) => {\n let entry = prefixes.get(label)\n if (entry === undefined) {\n const first = placeholder(label, 1)\n const second = placeholder(label, 2)\n let n = 0\n while (n < first.length && n < second.length && first[n] === second[n]) n++\n const prefix = first.slice(0, n)\n entry = null\n if (prefix.length > 0) {\n const at: number[] = []\n for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i)\n entry = { prefix, at, byLength: new Map() }\n }\n prefixes.set(label, entry)\n }\n if (entry !== null && token.startsWith(entry.prefix)) {\n let candidates = entry.byLength.get(token.length)\n if (candidates === undefined) {\n if (entry.byLength.size >= MAX_CACHED_LENGTHS) {\n return entry.at.some((i) => input.startsWith(token, i))\n }\n candidates = new Set<string>()\n for (const i of entry.at) {\n if (i + token.length <= input.length) candidates.add(input.slice(i, i + token.length))\n }\n entry.byLength.set(token.length, candidates)\n }\n return candidates.has(token)\n }\n return input.includes(token)\n }\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n return redactFromDetections(input, runDetectors(input, options.detectors), options)\n}\n\n/**\n * Run rule detectors over `input` and return their detections, with spans in\n * `input`'s own coordinates.\n *\n * Detectors do NOT see `input`; they see its canonical view (see\n * {@link canonicalize}), because a zero-width space or a fullwidth digit would\n * otherwise walk a personnummer straight past every pattern. Spans come back\n * mapped, and `value` is re-sliced from the original, so a detection always\n * describes real text: `input.slice(d.start, d.end) === d.value` holds even\n * when the folded text the detector matched looked nothing like it.\n *\n * Exported because the hybrid entry point in `maskera` needs the rule\n * detections separately from the model's, and both must fold identically.\n */\nexport function runDetectors(input: string, detectors: Detector[] = defaultDetectors): Detection[] {\n const canonical = canonicalize(input)\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(canonical.text)) {\n if (canonical.identity) {\n all.push({ ...m, label: detector.label })\n continue\n }\n const [start, end] = canonical.span(m.start, m.end)\n all.push({ start, end, value: input.slice(start, end), label: detector.label })\n }\n }\n return all\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n const ownPlaceholder = options.placeholder === undefined\n\n // Spans arrive from callers too (`redactWithNer`, anything model-shaped), and\n // a malformed one does not fail loudly on its own: `resolveOverlaps` sorts a\n // reversed span into place and the rebuild loop below then *duplicates* the\n // text between `last` and `r.start` instead of removing it, which is silent\n // corruption of a document someone is redacting. Reject it instead.\n for (const d of detections) {\n if (\n !Number.isInteger(d.start) ||\n !Number.isInteger(d.end) ||\n d.start < 0 ||\n d.end > input.length ||\n d.start >= d.end\n ) {\n throw new Error(\n `maskera: detection span out of range for \"${d.label}\": [${d.start}, ${d.end}) ` +\n `in an input of length ${input.length}`,\n )\n }\n // `value` is what `restore()` writes back, and nothing downstream ever\n // re-derives it from the span. A detection whose value disagrees with its\n // own span therefore does not fail, it silently rewrites the document:\n // ({start: 5, end: 18, value: \"HELT ANNAT\"}) restores \"Ring HELT ANNAT\n // imorgon.\" over \"Ring Anna Svensson imorgon.\". Same argument as the span\n // check above, so the same treatment.\n if (d.value !== input.slice(d.start, d.end)) {\n throw new Error(\n `maskera: detection value for \"${d.label}\" does not match its span [${d.start}, ${d.end}): ` +\n `expected ${JSON.stringify(input.slice(d.start, d.end))}, got ${JSON.stringify(d.value)}`,\n )\n }\n // The default placeholder wraps the label in brackets, which only delimits\n // anything as long as the label carries none of its own. A label from an\n // external model (\"X] [PERSONNUMMER_1\", say) otherwise produces the token\n // \"[X] [PERSONNUMMER_1_1]\", and the redacted text an LLM sees then contains\n // the literal string \"[PERSONNUMMER_1]\" at a place the real personnummer\n // never stood. Echo that fragment back and `restore()` writes the real\n // value into it: a document-controlled exfiltration primitive.\n //\n // Banning both brackets is exactly enough for this placeholder. A token is\n // \"[\" + label + \"_\" + digits + \"]\"; with no bracket inside the label its\n // only \"[\" is the first character and its only \"]\" the last, so any other\n // token contained in it would have to be the token itself. `maskera`'s\n // `defaultLabelMap` already strips this at the source; this is the guard\n // for everyone calling core directly, which the doc comment invites.\n if (ownPlaceholder && (d.label.includes(\"[\") || d.label.includes(\"]\"))) {\n throw new Error(\n `maskera: label ${JSON.stringify(d.label)} contains a bracket, which would nest inside ` +\n \"the default placeholder and let one token be read as another. Sanitise the label \" +\n \"(see defaultLabelMap in maskera) or pass your own placeholder().\",\n )\n }\n }\n\n const resolved = resolveOverlaps(detections, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n const occursInInput = createInputProbe(input, placeholder)\n\n for (const d of resolved) {\n const key = tokenKey(d.label, d.value)\n let token = tokenByKey.get(key)\n if (!token) {\n // Never hand out a token that already occurs literally in the input\n // (a crafted \"[NAMN_1]\" in the input would collide with a generated\n // placeholder, and restore() would write the real value into positions\n // the author of the input chose), and never a token another value\n // already owns (a custom placeholder() that ignores the index would\n // otherwise silently map two values to one token and corrupt restore).\n let next = counters.get(d.label) ?? 0\n let attempts = 0\n for (;;) {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break\n // Giving up after a fixed number of tries made a crafted input a denial\n // of service: seeding \"[EPOST_1]\"..\"[EPOST_100]\" was enough to make\n // every later redact() throw. An input can only hold\n // input.length / token.length distinct colliding tokens, so past that\n // bound the placeholder() itself is broken (it ignores the index) and\n // no further index will help.\n if (token.length === 0 || attempts > 8 + input.length / token.length) {\n throw new Error(\n \"maskera: placeholder() must return a token that is unique per (label, index) \" +\n \"and does not occur in the input\",\n )\n }\n }\n counters.set(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n const tokens = Object.keys(map).filter((t) => t.length > 0)\n if (tokens.length === 0) return text\n\n // One left-to-right pass over a trie of the tokens, rather than a\n // split/join per token. Two reasons, and the first one is correctness:\n // replacing token by token re-scans text that was already restored, so a\n // value that happens to contain another token (\"Anna [EPOST_1]\" as a NAMN\n // value handed in via redactFromDetections) got substituted a second time\n // and the output was neither the placeholder nor the original. A single pass\n // never revisits what it wrote. The second is cost: split/join is O(tokens ×\n // text), which is the same product that made redaction slow on large logs.\n // Matching the deepest node at each position keeps the old longest-first\n // rule, so `[X_10]` still wins over `[X_1]`.\n const root: TrieNode = { next: new Map() }\n for (const token of tokens) {\n let node = root\n // Indexed by UTF-16 unit, the same way the scan below reads the text: a\n // code-point walk here would key a surrogate pair as one two-unit string\n // and never match.\n for (let k = 0; k < token.length; k++) {\n const ch = token[k] as string\n let child = node.next.get(ch)\n if (!child) {\n child = { next: new Map() }\n node.next.set(ch, child)\n }\n node = child\n }\n node.value = map[token]\n }\n\n let out = \"\"\n let last = 0\n let i = 0\n while (i < text.length) {\n let node = root.next.get(text[i] as string)\n let matchEnd = -1\n let matchValue: string | undefined\n let j = i\n while (node) {\n j++\n if (node.value !== undefined) {\n matchEnd = j\n matchValue = node.value\n }\n node = j < text.length ? node.next.get(text[j] as string) : undefined\n }\n if (matchValue === undefined) {\n i++\n continue\n }\n out += text.slice(last, i) + matchValue\n i = matchEnd\n last = i\n }\n return out + text.slice(last)\n}\n\ntype TrieNode = { value?: string; next: Map<string, TrieNode> }\n"]}
package/dist/index.d.cts CHANGED
@@ -1,3 +1,53 @@
1
+ /**
2
+ * The detection-time view of an input string, plus a map back to the original
3
+ * offsets.
4
+ *
5
+ * Detectors are pattern matchers over ASCII-ish shapes: `\d`, `[A-ZÅÄÖ]`, a
6
+ * literal space. That makes every character that renders as nothing, or renders
7
+ * as a digit without being one, a one-character bypass of the whole rule layer.
8
+ * Measured before this existed, on `redact()` defaults:
9
+ *
10
+ * "850601-2387" -> PERSONNUMMER
11
+ * "850601" + U+200B + "2387" -> nothing
12
+ * "8506" + U+00AD + "012387" -> nothing
13
+ * "850601" + U+2060 + "2387" -> nothing
14
+ * "850601" + U+2009/U+202F + "2387" -> nothing
15
+ * "8506012387" (fullwidth) -> nothing
16
+ * "anna@exa" + U+200B + "mple.com" -> nothing
17
+ *
18
+ * All of those render identically (or near enough) to the real thing, and an
19
+ * LLM tokenizer drops the invisible ones outright, so the model downstream reads
20
+ * the personnummer that maskera reported as clean. It is not only an adversary
21
+ * either: U+00AD is what PDF de-hyphenation leaves behind and U+202F is what
22
+ * Word and typographic number formatting insert, so ordinary document pipelines
23
+ * hit this without anyone trying.
24
+ *
25
+ * So detectors run against a canonical view instead: invisible characters
26
+ * removed, compatibility characters folded via NFKC. The ORIGINAL string is
27
+ * still what gets rebuilt and what `value` is sliced from, so `restore()` round
28
+ * trips byte for byte; only the matching sees the folded text.
29
+ */
30
+ interface CanonicalText {
31
+ /** The folded text to run detectors against. */
32
+ readonly text: string;
33
+ /** True when {@link text} is the input unchanged, i.e. nothing was folded. */
34
+ readonly identity: boolean;
35
+ /**
36
+ * Map a `[start, end)` span in {@link text} to the span in the original input
37
+ * that produced it. An invisible character sitting INSIDE the span is covered
38
+ * by the result (so the mask swallows it); one sitting just outside is not.
39
+ */
40
+ span(start: number, end: number): [number, number];
41
+ }
42
+ /**
43
+ * Build the canonical view of `input`.
44
+ *
45
+ * The common case (no invisible characters, already NFKC) returns the input
46
+ * itself with an identity map and costs one regex scan plus one `normalize`
47
+ * quick check, so ordinary Swedish prose pays almost nothing.
48
+ */
49
+ declare function canonicalize(input: string): CanonicalText;
50
+
1
51
  /**
2
52
  * Built-in PII labels. The `string` fallback lets you add custom detectors
3
53
  * with arbitrary labels without fighting the type system.
@@ -133,6 +183,21 @@ declare const defaultDetectors: Detector[];
133
183
  * consistently and you can map results back afterwards.
134
184
  */
135
185
  declare function redact(input: string, options?: RedactOptions): RedactResult;
186
+ /**
187
+ * Run rule detectors over `input` and return their detections, with spans in
188
+ * `input`'s own coordinates.
189
+ *
190
+ * Detectors do NOT see `input`; they see its canonical view (see
191
+ * {@link canonicalize}), because a zero-width space or a fullwidth digit would
192
+ * otherwise walk a personnummer straight past every pattern. Spans come back
193
+ * mapped, and `value` is re-sliced from the original, so a detection always
194
+ * describes real text: `input.slice(d.start, d.end) === d.value` holds even
195
+ * when the folded text the detector matched looked nothing like it.
196
+ *
197
+ * Exported because the hybrid entry point in `maskera` needs the rule
198
+ * detections separately from the model's, and both must fold identically.
199
+ */
200
+ declare function runDetectors(input: string, detectors?: Detector[]): Detection[];
136
201
  /**
137
202
  * Lower-level entry point: turn a pre-computed list of detections into a
138
203
  * {@link RedactResult}. Use this when detections come from somewhere async or
@@ -162,4 +227,4 @@ declare function isSamordningsnummer(value: string): boolean;
162
227
  /** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */
163
228
  declare function isOrganisationsnummer(value: string): boolean;
164
229
 
165
- export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, adress, bankgiro, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, samordningsnummer, url };
230
+ export { type CanonicalText, type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, adress, bankgiro, canonicalize, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, runDetectors, samordningsnummer, url };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,53 @@
1
+ /**
2
+ * The detection-time view of an input string, plus a map back to the original
3
+ * offsets.
4
+ *
5
+ * Detectors are pattern matchers over ASCII-ish shapes: `\d`, `[A-ZÅÄÖ]`, a
6
+ * literal space. That makes every character that renders as nothing, or renders
7
+ * as a digit without being one, a one-character bypass of the whole rule layer.
8
+ * Measured before this existed, on `redact()` defaults:
9
+ *
10
+ * "850601-2387" -> PERSONNUMMER
11
+ * "850601" + U+200B + "2387" -> nothing
12
+ * "8506" + U+00AD + "012387" -> nothing
13
+ * "850601" + U+2060 + "2387" -> nothing
14
+ * "850601" + U+2009/U+202F + "2387" -> nothing
15
+ * "8506012387" (fullwidth) -> nothing
16
+ * "anna@exa" + U+200B + "mple.com" -> nothing
17
+ *
18
+ * All of those render identically (or near enough) to the real thing, and an
19
+ * LLM tokenizer drops the invisible ones outright, so the model downstream reads
20
+ * the personnummer that maskera reported as clean. It is not only an adversary
21
+ * either: U+00AD is what PDF de-hyphenation leaves behind and U+202F is what
22
+ * Word and typographic number formatting insert, so ordinary document pipelines
23
+ * hit this without anyone trying.
24
+ *
25
+ * So detectors run against a canonical view instead: invisible characters
26
+ * removed, compatibility characters folded via NFKC. The ORIGINAL string is
27
+ * still what gets rebuilt and what `value` is sliced from, so `restore()` round
28
+ * trips byte for byte; only the matching sees the folded text.
29
+ */
30
+ interface CanonicalText {
31
+ /** The folded text to run detectors against. */
32
+ readonly text: string;
33
+ /** True when {@link text} is the input unchanged, i.e. nothing was folded. */
34
+ readonly identity: boolean;
35
+ /**
36
+ * Map a `[start, end)` span in {@link text} to the span in the original input
37
+ * that produced it. An invisible character sitting INSIDE the span is covered
38
+ * by the result (so the mask swallows it); one sitting just outside is not.
39
+ */
40
+ span(start: number, end: number): [number, number];
41
+ }
42
+ /**
43
+ * Build the canonical view of `input`.
44
+ *
45
+ * The common case (no invisible characters, already NFKC) returns the input
46
+ * itself with an identity map and costs one regex scan plus one `normalize`
47
+ * quick check, so ordinary Swedish prose pays almost nothing.
48
+ */
49
+ declare function canonicalize(input: string): CanonicalText;
50
+
1
51
  /**
2
52
  * Built-in PII labels. The `string` fallback lets you add custom detectors
3
53
  * with arbitrary labels without fighting the type system.
@@ -133,6 +183,21 @@ declare const defaultDetectors: Detector[];
133
183
  * consistently and you can map results back afterwards.
134
184
  */
135
185
  declare function redact(input: string, options?: RedactOptions): RedactResult;
186
+ /**
187
+ * Run rule detectors over `input` and return their detections, with spans in
188
+ * `input`'s own coordinates.
189
+ *
190
+ * Detectors do NOT see `input`; they see its canonical view (see
191
+ * {@link canonicalize}), because a zero-width space or a fullwidth digit would
192
+ * otherwise walk a personnummer straight past every pattern. Spans come back
193
+ * mapped, and `value` is re-sliced from the original, so a detection always
194
+ * describes real text: `input.slice(d.start, d.end) === d.value` holds even
195
+ * when the folded text the detector matched looked nothing like it.
196
+ *
197
+ * Exported because the hybrid entry point in `maskera` needs the rule
198
+ * detections separately from the model's, and both must fold identically.
199
+ */
200
+ declare function runDetectors(input: string, detectors?: Detector[]): Detection[];
136
201
  /**
137
202
  * Lower-level entry point: turn a pre-computed list of detections into a
138
203
  * {@link RedactResult}. Use this when detections come from somewhere async or
@@ -162,4 +227,4 @@ declare function isSamordningsnummer(value: string): boolean;
162
227
  /** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */
163
228
  declare function isOrganisationsnummer(value: string): boolean;
164
229
 
165
- export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, adress, bankgiro, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, samordningsnummer, url };
230
+ export { type CanonicalText, type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, adress, bankgiro, canonicalize, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, runDetectors, samordningsnummer, url };
package/dist/index.js CHANGED
@@ -1,3 +1,99 @@
1
+ // src/canonicalize.ts
2
+ var INVISIBLE_SOURCE = "[\\p{Cf}\\u034f\\ufe00-\\ufe0f\\u{e0100}-\\u{e01ef}]";
3
+ var INVISIBLE = new RegExp(INVISIBLE_SOURCE, "u");
4
+ var INVISIBLE_RUN = new RegExp(`${INVISIBLE_SOURCE}+`, "gu");
5
+ var MARK = /\p{M}/u;
6
+ var identityView = (input) => ({
7
+ text: input,
8
+ identity: true,
9
+ span(start, end) {
10
+ return clampSpan(start, end, input.length);
11
+ }
12
+ });
13
+ function clampSpan(start, end, length) {
14
+ const lo = start < 0 || !Number.isFinite(start) ? 0 : start > length ? length : start;
15
+ const hi = end > length || !Number.isFinite(end) ? length : end < lo ? lo : end;
16
+ return [lo, hi];
17
+ }
18
+ function canonicalize(input) {
19
+ if (!INVISIBLE.test(input) && input.normalize("NFKC") === input) return identityView(input);
20
+ const segments = [];
21
+ const folded = /* @__PURE__ */ new Map();
22
+ let text = "";
23
+ let runStart = -1;
24
+ let i = 0;
25
+ const closeRun = (end) => {
26
+ if (runStart < 0) return;
27
+ segments.push({ c: text.length, o: runStart, oEnd: end, linear: true });
28
+ text += input.slice(runStart, end);
29
+ runStart = -1;
30
+ };
31
+ while (i < input.length) {
32
+ const cp = input.codePointAt(i);
33
+ if (cp < 128 && (i + 1 >= input.length || input.charCodeAt(i + 1) < 768)) {
34
+ if (runStart < 0) runStart = i;
35
+ i++;
36
+ continue;
37
+ }
38
+ const size = cp > 65535 ? 2 : 1;
39
+ let j = i + size;
40
+ while (j < input.length) {
41
+ const next = input.codePointAt(j);
42
+ if (next < 128) break;
43
+ const nextSize = next > 65535 ? 2 : 1;
44
+ if (!MARK.test(input.slice(j, j + nextSize))) break;
45
+ j += nextSize;
46
+ }
47
+ const raw = input.slice(i, j);
48
+ let result;
49
+ if (j === i + size) {
50
+ let cached = folded.get(cp);
51
+ if (cached === void 0) {
52
+ cached = INVISIBLE.test(raw) ? "" : raw.normalize("NFKC");
53
+ folded.set(cp, cached);
54
+ }
55
+ result = cached;
56
+ } else {
57
+ result = raw.replace(INVISIBLE_RUN, "").normalize("NFKC");
58
+ }
59
+ if (result === raw) {
60
+ if (runStart < 0) runStart = i;
61
+ } else {
62
+ closeRun(i);
63
+ if (result.length > 0) {
64
+ segments.push({ c: text.length, o: i, oEnd: j, linear: false });
65
+ text += result;
66
+ }
67
+ }
68
+ i = j;
69
+ }
70
+ closeRun(input.length);
71
+ return {
72
+ text,
73
+ identity: text === input,
74
+ span(start, end) {
75
+ const [lo, hi] = clampSpan(start, end, text.length);
76
+ if (segments.length === 0) return [0, 0];
77
+ const head = segments[segmentAt(segments, lo)];
78
+ const mappedStart = head.linear ? head.o + (lo - head.c) : head.o;
79
+ if (hi <= lo) return [mappedStart, mappedStart];
80
+ const tail = segments[segmentAt(segments, hi - 1)];
81
+ const mappedEnd = tail.linear ? tail.o + (hi - tail.c) : tail.oEnd;
82
+ return [mappedStart, mappedEnd < mappedStart ? mappedStart : mappedEnd];
83
+ }
84
+ };
85
+ }
86
+ function segmentAt(segments, c) {
87
+ let lo = 0;
88
+ let hi = segments.length - 1;
89
+ while (lo < hi) {
90
+ const mid = lo + hi + 1 >> 1;
91
+ if (segments[mid].c <= c) lo = mid;
92
+ else hi = mid - 1;
93
+ }
94
+ return lo;
95
+ }
96
+
1
97
  // src/validators.ts
2
98
  function luhnValid(digits) {
3
99
  const only = digits.replace(/\D/g, "");
@@ -76,7 +172,7 @@ function regexDetector(label, regex, validate) {
76
172
  }
77
173
  };
78
174
  }
79
- var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0]{1,2}(?=\d))*\d|\d/g;
175
+ var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0\u1680]{1,2}(?=\d))*\d|\d/g;
80
176
  var isDigit = (code) => code >= 48 && code <= 57;
81
177
  var WS = /\s/;
82
178
  function checksumWindowDetector(label, widths, validate) {
@@ -245,6 +341,7 @@ function tokenKey(label, value) {
245
341
  return `${label.length}:${label}:${value}`;
246
342
  }
247
343
  function createInputProbe(input, placeholder) {
344
+ const MAX_CACHED_LENGTHS = 24;
248
345
  const prefixes = /* @__PURE__ */ new Map();
249
346
  return (label, token) => {
250
347
  let entry = prefixes.get(label);
@@ -258,34 +355,64 @@ function createInputProbe(input, placeholder) {
258
355
  if (prefix.length > 0) {
259
356
  const at = [];
260
357
  for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i);
261
- entry = { prefix, at };
358
+ entry = { prefix, at, byLength: /* @__PURE__ */ new Map() };
262
359
  }
263
360
  prefixes.set(label, entry);
264
361
  }
265
362
  if (entry !== null && token.startsWith(entry.prefix)) {
266
- return entry.at.some((i) => input.startsWith(token, i));
363
+ let candidates = entry.byLength.get(token.length);
364
+ if (candidates === void 0) {
365
+ if (entry.byLength.size >= MAX_CACHED_LENGTHS) {
366
+ return entry.at.some((i) => input.startsWith(token, i));
367
+ }
368
+ candidates = /* @__PURE__ */ new Set();
369
+ for (const i of entry.at) {
370
+ if (i + token.length <= input.length) candidates.add(input.slice(i, i + token.length));
371
+ }
372
+ entry.byLength.set(token.length, candidates);
373
+ }
374
+ return candidates.has(token);
267
375
  }
268
376
  return input.includes(token);
269
377
  };
270
378
  }
271
379
  function redact(input, options = {}) {
272
- const detectors = options.detectors ?? defaultDetectors;
380
+ return redactFromDetections(input, runDetectors(input, options.detectors), options);
381
+ }
382
+ function runDetectors(input, detectors = defaultDetectors) {
383
+ const canonical = canonicalize(input);
273
384
  const all = [];
274
385
  for (const detector of detectors) {
275
- for (const m of detector.detect(input)) {
276
- all.push({ ...m, label: detector.label });
386
+ for (const m of detector.detect(canonical.text)) {
387
+ if (canonical.identity) {
388
+ all.push({ ...m, label: detector.label });
389
+ continue;
390
+ }
391
+ const [start, end] = canonical.span(m.start, m.end);
392
+ all.push({ start, end, value: input.slice(start, end), label: detector.label });
277
393
  }
278
394
  }
279
- return redactFromDetections(input, all, options);
395
+ return all;
280
396
  }
281
397
  function redactFromDetections(input, detections, options = {}) {
282
398
  const placeholder = options.placeholder ?? defaultPlaceholder;
399
+ const ownPlaceholder = options.placeholder === void 0;
283
400
  for (const d of detections) {
284
401
  if (!Number.isInteger(d.start) || !Number.isInteger(d.end) || d.start < 0 || d.end > input.length || d.start >= d.end) {
285
402
  throw new Error(
286
403
  `maskera: detection span out of range for "${d.label}": [${d.start}, ${d.end}) in an input of length ${input.length}`
287
404
  );
288
405
  }
406
+ if (d.value !== input.slice(d.start, d.end)) {
407
+ throw new Error(
408
+ `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)}`
409
+ );
410
+ }
411
+ if (ownPlaceholder && (d.label.includes("[") || d.label.includes("]"))) {
412
+ throw new Error(
413
+ `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().`
414
+ );
415
+ }
289
416
  }
290
417
  const resolved = resolveOverlaps(detections, input);
291
418
  const counters = /* @__PURE__ */ new Map();
@@ -375,6 +502,6 @@ function restore(text, map) {
375
502
  return out + text.slice(last);
376
503
  }
377
504
 
378
- export { adress, bankgiro, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, samordningsnummer, url };
505
+ export { adress, bankgiro, canonicalize, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, runDetectors, samordningsnummer, url };
379
506
  //# sourceMappingURL=index.js.map
380
507
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IAAK,CAAA;AACL,MAAA,IAAI,CAAA,GAAI,GAAG,CAAA,IAAK,CAAA;AAAA,IAClB;AACA,IAAA,GAAA,IAAO,CAAA;AACP,IAAA,MAAA,GAAS,CAAC,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,MAAM,EAAA,KAAO,CAAA;AACtB;AAOO,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,KAAA,CAAM,6CAA6C,CAAA;AACnE,EAAA,IAAI,CAAC,GAAG,OAAO,KA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,IAAA,IAAI,CAAA,GAAI,CAAA;AACR,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,CAAA,EAAA;AACA,MAAA,IAAI,IAAA,CAAK,UAAU,MAAA,EAAW;AAC5B,QAAA,QAAA,GAAW,CAAA;AACX,QAAA,UAAA,GAAa,IAAA,CAAK,KAAA;AAAA,MACpB;AACA,MAAA,IAAA,GAAO,CAAA,GAAI,KAAK,MAAA,GAAS,IAAA,CAAK,KAAK,GAAA,CAAI,IAAA,CAAK,CAAC,CAAW,CAAA,GAAI,MAAA;AAAA,IAC9D;AACA,IAAA,IAAI,eAAe,MAAA,EAAW;AAC5B,MAAA,CAAA,EAAA;AACA,MAAA;AAAA,IACF;AACA,IAAA,GAAA,IAAO,IAAA,CAAK,KAAA,CAAM,IAAA,EAAM,CAAC,CAAA,GAAI,UAAA;AAC7B,IAAA,CAAA,GAAI,QAAA;AACJ,IAAA,IAAA,GAAO,CAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC9B","file":"index.js","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n // Match indices (\"d\") give the capture group's real position. Looking the\n // group text up inside m[0] instead (`m[0].indexOf(value)`) finds its first\n // *occurrence*, which is a different place whenever that text also appears\n // earlier in the match: a custom detector like /kontakt (\\S+) mejl \\1/ then\n // reports a span four characters too far left, and redact() masks the wrong\n // slice and leaves the value itself in the clear. The built-in detectors all\n // capture at an unambiguous position, but this is public API.\n //\n // The flag is added to a copy, which also keeps `lastIndex` off the caller's\n // regex. Engines predating the flag (it needs Chrome 90 / Safari 15 / Node\n // 16) throw on construction, and these detectors are built at module scope,\n // so the fallback is what keeps `import` itself from failing there.\n let scanner = regex\n let hasIndices = regex.flags.includes(\"d\")\n if (!hasIndices) {\n try {\n scanner = new RegExp(regex.source, `${regex.flags}d`)\n hasIndices = true\n } catch {\n scanner = regex\n }\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n for (const m of input.matchAll(scanner)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const group = m[1] !== undefined ? 1 : 0\n const value = m[group] as string\n if (value.length === 0) continue\n const span = hasIndices ? (m as MatchWithIndices).indices?.[group] : undefined\n const start = span ? span[0] : m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n/** `RegExpMatchArray.indices` is ES2022; the package compiles against ES2021. */\ntype MatchWithIndices = RegExpMatchArray & {\n indices?: Array<[number, number] | undefined>\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/**\n * A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain\n * and the horizontal whitespace it is routinely typed with (\"811218 9876\",\n * \"19 811218 9876\" in forms and journal notes). Stopping the run at a space\n * made one space a reliable one-character bypass, the same failure the missing\n * word boundary was fixed for. Newlines are NOT included, so two numbers in a\n * column never merge, and the whitespace run is bounded so the pattern cannot\n * backtrack over a long gap.\n */\nconst DIGIT_RUN = /\\d(?:[\\d+-]|[ \\t\\u00a0]{1,2}(?=\\d))*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\nconst WS = /\\s/\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * A run may contain whitespace (\"811218 9876\"), but a window is only allowed to\n * cross it at the position the separator actually belongs, four digits from the\n * end. Anything else would let two unrelated numbers in a table (\"Belopp 4711\n * 220345\") fuse into a candidate, and it is the cheap check that keeps the\n * widened run from spending the false-positive budget the checksum bought.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span. `spaced[k]` records that whitespace sits\n // between digit k-1 and digit k.\n const offsets: number[] = []\n const spaced: boolean[] = []\n let digits = \"\"\n let gapSpaced = false\n let anySpaced = false\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n spaced.push(gapSpaced)\n digits += text[i]\n gapSpaced = false\n } else if (WS.test(text[i] as string)) {\n gapSpaced = true\n anySpaced = true\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n // Whitespace may only sit where the identifier's own separator\n // does: four digits from the end of the window.\n if (anySpaced) {\n let ok = true\n for (let k = i + 1; k < i + w; k++) {\n if (spaced[k] && k !== i + w - 4) {\n ok = false\n break\n }\n }\n if (!ok) continue\n }\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * Key for the stable-placeholder cache. Length-prefixed rather than\n * `${label}::${value}`, which is ambiguous the moment a custom label contains\n * `::`: (\"A::B\", \"c\") and (\"A\", \"B::c\") would share one placeholder, and\n * restore() would then write the first value where the second one stood.\n */\nfunction tokenKey(label: PiiLabel, value: string): string {\n return `${label.length}:${label}:${value}`\n}\n\n/**\n * Answers \"does this generated token already occur in the input?\" without\n * scanning the input once per redacted value.\n *\n * The plain scan is O(values × input): 4k distinct values in a 150 KB log spent\n * 237 ms in this check alone, and both factors grow with the document, so a\n * megabyte-sized log dump (the paste this library exists for) blocks for\n * seconds. The placeholders of one label share a prefix (\"[EPOST_\"), so one\n * scan per label settles all of them: a token carrying that prefix can only\n * occur where the prefix occurs, which is usually nowhere and is a short list\n * even when re-redacting an already redacted document. A token that does not\n * carry the prefix - `placeholder` is an arbitrary caller function, it need not\n * be prefix-stable - still takes the full scan, so the answer stays exact.\n */\nfunction createInputProbe(\n input: string,\n placeholder: (label: PiiLabel, index: number) => string,\n): (label: PiiLabel, token: string) => boolean {\n const prefixes = new Map<PiiLabel, { prefix: string; at: number[] } | null>()\n return (label, token) => {\n let entry = prefixes.get(label)\n if (entry === undefined) {\n const first = placeholder(label, 1)\n const second = placeholder(label, 2)\n let n = 0\n while (n < first.length && n < second.length && first[n] === second[n]) n++\n const prefix = first.slice(0, n)\n entry = null\n if (prefix.length > 0) {\n const at: number[] = []\n for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i)\n entry = { prefix, at }\n }\n prefixes.set(label, entry)\n }\n if (entry !== null && token.startsWith(entry.prefix)) {\n return entry.at.some((i) => input.startsWith(token, i))\n }\n return input.includes(token)\n }\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n // Spans arrive from callers too (`redactWithNer`, anything model-shaped), and\n // a malformed one does not fail loudly on its own: `resolveOverlaps` sorts a\n // reversed span into place and the rebuild loop below then *duplicates* the\n // text between `last` and `r.start` instead of removing it, which is silent\n // corruption of a document someone is redacting. Reject it instead.\n for (const d of detections) {\n if (\n !Number.isInteger(d.start) ||\n !Number.isInteger(d.end) ||\n d.start < 0 ||\n d.end > input.length ||\n d.start >= d.end\n ) {\n throw new Error(\n `maskera: detection span out of range for \"${d.label}\": [${d.start}, ${d.end}) ` +\n `in an input of length ${input.length}`,\n )\n }\n }\n\n const resolved = resolveOverlaps(detections, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n const occursInInput = createInputProbe(input, placeholder)\n\n for (const d of resolved) {\n const key = tokenKey(d.label, d.value)\n let token = tokenByKey.get(key)\n if (!token) {\n // Never hand out a token that already occurs literally in the input\n // (a crafted \"[NAMN_1]\" in the input would collide with a generated\n // placeholder, and restore() would write the real value into positions\n // the author of the input chose), and never a token another value\n // already owns (a custom placeholder() that ignores the index would\n // otherwise silently map two values to one token and corrupt restore).\n let next = counters.get(d.label) ?? 0\n let attempts = 0\n for (;;) {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break\n // Giving up after a fixed number of tries made a crafted input a denial\n // of service: seeding \"[EPOST_1]\"..\"[EPOST_100]\" was enough to make\n // every later redact() throw. An input can only hold\n // input.length / token.length distinct colliding tokens, so past that\n // bound the placeholder() itself is broken (it ignores the index) and\n // no further index will help.\n if (token.length === 0 || attempts > 8 + input.length / token.length) {\n throw new Error(\n \"maskera: placeholder() must return a token that is unique per (label, index) \" +\n \"and does not occur in the input\",\n )\n }\n }\n counters.set(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n const tokens = Object.keys(map).filter((t) => t.length > 0)\n if (tokens.length === 0) return text\n\n // One left-to-right pass over a trie of the tokens, rather than a\n // split/join per token. Two reasons, and the first one is correctness:\n // replacing token by token re-scans text that was already restored, so a\n // value that happens to contain another token (\"Anna [EPOST_1]\" as a NAMN\n // value handed in via redactFromDetections) got substituted a second time\n // and the output was neither the placeholder nor the original. A single pass\n // never revisits what it wrote. The second is cost: split/join is O(tokens ×\n // text), which is the same product that made redaction slow on large logs.\n // Matching the deepest node at each position keeps the old longest-first\n // rule, so `[X_10]` still wins over `[X_1]`.\n const root: TrieNode = { next: new Map() }\n for (const token of tokens) {\n let node = root\n // Indexed by UTF-16 unit, the same way the scan below reads the text: a\n // code-point walk here would key a surrogate pair as one two-unit string\n // and never match.\n for (let k = 0; k < token.length; k++) {\n const ch = token[k] as string\n let child = node.next.get(ch)\n if (!child) {\n child = { next: new Map() }\n node.next.set(ch, child)\n }\n node = child\n }\n node.value = map[token]\n }\n\n let out = \"\"\n let last = 0\n let i = 0\n while (i < text.length) {\n let node = root.next.get(text[i] as string)\n let matchEnd = -1\n let matchValue: string | undefined\n let j = i\n while (node) {\n j++\n if (node.value !== undefined) {\n matchEnd = j\n matchValue = node.value\n }\n node = j < text.length ? node.next.get(text[j] as string) : undefined\n }\n if (matchValue === undefined) {\n i++\n continue\n }\n out += text.slice(last, i) + matchValue\n i = matchEnd\n last = i\n }\n return out + text.slice(last)\n}\n\ntype TrieNode = { value?: string; next: Map<string, TrieNode> }\n"]}
1
+ {"version":3,"sources":["../src/canonicalize.ts","../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";AAsDA,IAAM,gBAAA,GAAmB,sDAAA;AACzB,IAAM,SAAA,GAAY,IAAI,MAAA,CAAO,gBAAA,EAAkB,GAAG,CAAA;AAClD,IAAM,gBAAgB,IAAI,MAAA,CAAO,CAAA,EAAG,gBAAgB,KAAK,IAAI,CAAA;AAC7D,IAAM,IAAA,GAAO,QAAA;AAiBb,IAAM,YAAA,GAAe,CAAC,KAAA,MAAkC;AAAA,EACtD,IAAA,EAAM,KAAA;AAAA,EACN,QAAA,EAAU,IAAA;AAAA,EACV,IAAA,CAAK,OAAO,GAAA,EAAK;AAKf,IAAA,OAAO,SAAA,CAAU,KAAA,EAAO,GAAA,EAAK,KAAA,CAAM,MAAM,CAAA;AAAA,EAC3C;AACF,CAAA,CAAA;AAEA,SAAS,SAAA,CAAU,KAAA,EAAe,GAAA,EAAa,MAAA,EAAkC;AAC/E,EAAA,MAAM,EAAA,GAAK,KAAA,GAAQ,CAAA,IAAK,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,GAAI,CAAA,GAAI,KAAA,GAAQ,MAAA,GAAS,MAAA,GAAS,KAAA;AAChF,EAAA,MAAM,EAAA,GAAK,GAAA,GAAM,MAAA,IAAU,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,GAAI,MAAA,GAAS,GAAA,GAAM,EAAA,GAAK,EAAA,GAAK,GAAA;AAC5E,E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,GAAA,GAAM,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC9B","file":"index.js","sourcesContent":["/**\n * The detection-time view of an input string, plus a map back to the original\n * offsets.\n *\n * Detectors are pattern matchers over ASCII-ish shapes: `\\d`, `[A-ZÅÄÖ]`, a\n * literal space. That makes every character that renders as nothing, or renders\n * as a digit without being one, a one-character bypass of the whole rule layer.\n * Measured before this existed, on `redact()` defaults:\n *\n * \"850601-2387\" -> PERSONNUMMER\n * \"850601\" + U+200B + \"2387\" -> nothing\n * \"8506\" + U+00AD + \"012387\" -> nothing\n * \"850601\" + U+2060 + \"2387\" -> nothing\n * \"850601\" + U+2009/U+202F + \"2387\" -> nothing\n * \"8506012387\" (fullwidth) -> nothing\n * \"anna@exa\" + U+200B + \"mple.com\" -> nothing\n *\n * All of those render identically (or near enough) to the real thing, and an\n * LLM tokenizer drops the invisible ones outright, so the model downstream reads\n * the personnummer that maskera reported as clean. It is not only an adversary\n * either: U+00AD is what PDF de-hyphenation leaves behind and U+202F is what\n * Word and typographic number formatting insert, so ordinary document pipelines\n * hit this without anyone trying.\n *\n * So detectors run against a canonical view instead: invisible characters\n * removed, compatibility characters folded via NFKC. The ORIGINAL string is\n * still what gets rebuilt and what `value` is sliced from, so `restore()` round\n * trips byte for byte; only the matching sees the folded text.\n */\nexport interface CanonicalText {\n /** The folded text to run detectors against. */\n readonly text: string\n /** True when {@link text} is the input unchanged, i.e. nothing was folded. */\n readonly identity: boolean\n /**\n * Map a `[start, end)` span in {@link text} to the span in the original input\n * that produced it. An invisible character sitting INSIDE the span is covered\n * by the result (so the mask swallows it); one sitting just outside is not.\n */\n span(start: number, end: number): [number, number]\n}\n\n/**\n * Characters that occupy no visual space but split a digit or letter run in two.\n *\n * `\\p{Cf}` is the bulk of them: U+00AD SOFT HYPHEN, U+200B ZERO WIDTH SPACE,\n * U+200C/U+200D the joiners, U+2060 WORD JOINER, U+FEFF, and the bidi controls\n * U+200E..U+200F / U+202A..U+202E (the Trojan Source family). The rest are the\n * invisible combining marks, which are `\\p{M}` and therefore survive NFKC:\n * U+034F COMBINING GRAPHEME JOINER and the variation selectors.\n *\n * Dropping the joiners costs nothing here because this view is never rendered\n * and never restored from; it only decides where a detector matches.\n */\nconst INVISIBLE_SOURCE = \"[\\\\p{Cf}\\\\u034f\\\\ufe00-\\\\ufe0f\\\\u{e0100}-\\\\u{e01ef}]\"\nconst INVISIBLE = new RegExp(INVISIBLE_SOURCE, \"u\")\nconst INVISIBLE_RUN = new RegExp(`${INVISIBLE_SOURCE}+`, \"gu\")\nconst MARK = /\\p{M}/u\n\n/**\n * One stretch of the mapping. `linear` segments came through untouched, so an\n * offset inside them shifts by a constant; folded ones changed length or shape,\n * so every canonical offset inside them maps to the whole original range.\n */\ninterface Segment {\n /** Start of this segment in the canonical text. */\n c: number\n /** Start of the original range that produced it. */\n o: number\n /** End of that original range. */\n oEnd: number\n linear: boolean\n}\n\nconst identityView = (input: string): CanonicalText => ({\n text: input,\n identity: true,\n span(start, end) {\n // Clamped exactly like the folded path below. A detector handing back an\n // out-of-range span is a bug either way, but it must not be a bug whose\n // symptoms depend on whether the input happened to contain a zero-width\n // space: that is the kind of difference that shows up once, in production.\n return clampSpan(start, end, input.length)\n },\n})\n\nfunction clampSpan(start: number, end: number, length: number): [number, number] {\n const lo = start < 0 || !Number.isFinite(start) ? 0 : start > length ? length : start\n const hi = end > length || !Number.isFinite(end) ? length : end < lo ? lo : end\n return [lo, hi]\n}\n\n/**\n * Build the canonical view of `input`.\n *\n * The common case (no invisible characters, already NFKC) returns the input\n * itself with an identity map and costs one regex scan plus one `normalize`\n * quick check, so ordinary Swedish prose pays almost nothing.\n */\nexport function canonicalize(input: string): CanonicalText {\n if (!INVISIBLE.test(input) && input.normalize(\"NFKC\") === input) return identityView(input)\n\n const segments: Segment[] = []\n // Folding one code point at a time is only equivalent to folding the whole\n // string because NFKC never composes across two starters (Hangul jamo aside,\n // which no PII shape cares about). Combining marks DO compose with the\n // starter before them, so a base plus its marks is folded as one unit.\n const folded = new Map<number, string>()\n let text = \"\"\n let runStart = -1\n let i = 0\n\n const closeRun = (end: number) => {\n if (runStart < 0) return\n segments.push({ c: text.length, o: runStart, oEnd: end, linear: true })\n text += input.slice(runStart, end)\n runStart = -1\n }\n\n while (i < input.length) {\n const cp = input.codePointAt(i) as number\n // ASCII is never invisible, never a mark and always NFKC-stable, and it is\n // most of any document. Skipping the per-character work here is what keeps\n // the folded path from costing more than the detection it feeds.\n //\n // Unless a combining mark follows it: \"Åsa\" arrives from PDF extraction and\n // from macOS paths as A + U+030A, and folding that pair is how it becomes\n // something `[A-ZÅÄÖ]` can match at all. Marks start at U+0300, so one\n // comparison keeps ordinary text (including å, ä and ö, which are far\n // below that) on the fast path.\n if (cp < 0x80 && (i + 1 >= input.length || input.charCodeAt(i + 1) < 0x300)) {\n if (runStart < 0) runStart = i\n i++\n continue\n }\n\n const size = cp > 0xffff ? 2 : 1\n let j = i + size\n while (j < input.length) {\n const next = input.codePointAt(j) as number\n if (next < 0x80) break\n const nextSize = next > 0xffff ? 2 : 1\n if (!MARK.test(input.slice(j, j + nextSize))) break\n j += nextSize\n }\n\n const raw = input.slice(i, j)\n let result: string\n if (j === i + size) {\n let cached = folded.get(cp)\n if (cached === undefined) {\n cached = INVISIBLE.test(raw) ? \"\" : raw.normalize(\"NFKC\")\n folded.set(cp, cached)\n }\n result = cached\n } else {\n result = raw.replace(INVISIBLE_RUN, \"\").normalize(\"NFKC\")\n }\n\n if (result === raw) {\n if (runStart < 0) runStart = i\n } else {\n closeRun(i)\n if (result.length > 0) {\n segments.push({ c: text.length, o: i, oEnd: j, linear: false })\n text += result\n }\n // A dropped character contributes no segment at all. The next segment's\n // `o` therefore starts after it, which is what makes an invisible sitting\n // inside a detection fall inside the mapped span.\n }\n i = j\n }\n closeRun(input.length)\n\n return {\n text,\n identity: text === input,\n span(start, end) {\n const [lo, hi] = clampSpan(start, end, text.length)\n // Every visible character was dropped, so there is nothing to map from.\n if (segments.length === 0) return [0, 0]\n const head = segments[segmentAt(segments, lo)] as Segment\n const mappedStart = head.linear ? head.o + (lo - head.c) : head.o\n if (hi <= lo) return [mappedStart, mappedStart]\n const tail = segments[segmentAt(segments, hi - 1)] as Segment\n const mappedEnd = tail.linear ? tail.o + (hi - tail.c) : tail.oEnd\n return [mappedStart, mappedEnd < mappedStart ? mappedStart : mappedEnd]\n },\n }\n}\n\n/** Index of the last segment starting at or before canonical offset `c`. */\nfunction segmentAt(segments: Segment[], c: number): number {\n let lo = 0\n let hi = segments.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if ((segments[mid] as Segment).c <= c) lo = mid\n else hi = mid - 1\n }\n return lo\n}\n","/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n // Match indices (\"d\") give the capture group's real position. Looking the\n // group text up inside m[0] instead (`m[0].indexOf(value)`) finds its first\n // *occurrence*, which is a different place whenever that text also appears\n // earlier in the match: a custom detector like /kontakt (\\S+) mejl \\1/ then\n // reports a span four characters too far left, and redact() masks the wrong\n // slice and leaves the value itself in the clear. The built-in detectors all\n // capture at an unambiguous position, but this is public API.\n //\n // The flag is added to a copy, which also keeps `lastIndex` off the caller's\n // regex. Engines predating the flag (it needs Chrome 90 / Safari 15 / Node\n // 16) throw on construction, and these detectors are built at module scope,\n // so the fallback is what keeps `import` itself from failing there.\n let scanner = regex\n let hasIndices = regex.flags.includes(\"d\")\n if (!hasIndices) {\n try {\n scanner = new RegExp(regex.source, `${regex.flags}d`)\n hasIndices = true\n } catch {\n scanner = regex\n }\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n for (const m of input.matchAll(scanner)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const group = m[1] !== undefined ? 1 : 0\n const value = m[group] as string\n if (value.length === 0) continue\n const span = hasIndices ? (m as MatchWithIndices).indices?.[group] : undefined\n const start = span ? span[0] : m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n/** `RegExpMatchArray.indices` is ES2022; the package compiles against ES2021. */\ntype MatchWithIndices = RegExpMatchArray & {\n indices?: Array<[number, number] | undefined>\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/**\n * A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain\n * and the horizontal whitespace it is routinely typed with (\"811218 9876\",\n * \"19 811218 9876\" in forms and journal notes). Stopping the run at a space\n * made one space a reliable one-character bypass, the same failure the missing\n * word boundary was fixed for. Newlines are NOT included, so two numbers in a\n * column never merge, and the whitespace run is bounded so the pattern cannot\n * backtrack over a long gap.\n *\n * The class names U+1680 OGHAM SPACE MARK explicitly: it is the one horizontal\n * whitespace NFKC does not fold to U+0020 (canonicalize folds the rest, so the\n * plain space covers them), yet it matches JS `\\s` and renders as a space, so\n * without it a single character split the run and walked a personnummer past\n * the checksum detectors.\n */\nconst DIGIT_RUN = /\\d(?:[\\d+-]|[ \\t\\u00a0\\u1680]{1,2}(?=\\d))*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\nconst WS = /\\s/\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * A run may contain whitespace (\"811218 9876\"), but a window is only allowed to\n * cross it at the position the separator actually belongs, four digits from the\n * end. Anything else would let two unrelated numbers in a table (\"Belopp 4711\n * 220345\") fuse into a candidate, and it is the cheap check that keeps the\n * widened run from spending the false-positive budget the checksum bought.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span. `spaced[k]` records that whitespace sits\n // between digit k-1 and digit k.\n const offsets: number[] = []\n const spaced: boolean[] = []\n let digits = \"\"\n let gapSpaced = false\n let anySpaced = false\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n spaced.push(gapSpaced)\n digits += text[i]\n gapSpaced = false\n } else if (WS.test(text[i] as string)) {\n gapSpaced = true\n anySpaced = true\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n // Whitespace may only sit where the identifier's own separator\n // does: four digits from the end of the window.\n if (anySpaced) {\n let ok = true\n for (let k = i + 1; k < i + w; k++) {\n if (spaced[k] && k !== i + w - 4) {\n ok = false\n break\n }\n }\n if (!ok) continue\n }\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { canonicalize } from \"./canonicalize\"\nimport { defaultDetectors } from \"./detectors\"\nimport type { Detection, Detector, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * Key for the stable-placeholder cache. Length-prefixed rather than\n * `${label}::${value}`, which is ambiguous the moment a custom label contains\n * `::`: (\"A::B\", \"c\") and (\"A\", \"B::c\") would share one placeholder, and\n * restore() would then write the first value where the second one stood.\n */\nfunction tokenKey(label: PiiLabel, value: string): string {\n return `${label.length}:${label}:${value}`\n}\n\n/**\n * Answers \"does this generated token already occur in the input?\" without\n * scanning the input once per redacted value.\n *\n * The plain scan is O(values × input): 4k distinct values in a 150 KB log spent\n * 237 ms in this check alone, and both factors grow with the document, so a\n * megabyte-sized log dump (the paste this library exists for) blocks for\n * seconds. The placeholders of one label share a prefix (\"[EPOST_\"), so one\n * scan per label settles all of them: a token carrying that prefix can only\n * occur where the prefix occurs, which is usually nowhere and is a short list\n * even when re-redacting an already redacted document. A token that does not\n * carry the prefix - `placeholder` is an arbitrary caller function, it need not\n * be prefix-stable - still takes the full scan, so the answer stays exact.\n *\n * The positions are then indexed BY TOKEN LENGTH rather than walked per query.\n * Walking them is quadratic in the number of seeded tokens, and the retry loop\n * in `redactFromDetections` is what supplies the second factor: an input seeded\n * with \"[EPOST_1]\"..\"[EPOST_N]\" forces N probes, and probe k walks about k\n * positions before it finds its collision. Measured on the walk, with one real\n * e-mail in the document: 24 kB of seeded tokens took 37 ms, 50 kB took 131 ms,\n * 101 kB took 521 ms, 208 kB took 1.9 s and 427 kB took 7.7 s, a clean n^2 that\n * blocks the event loop (or freezes the tab) on an input a redaction tool is\n * expected to swallow. Grouping by length costs one pass per distinct length\n * (about six for any counter-shaped placeholder) and answers each probe in O(1).\n */\nfunction createInputProbe(\n input: string,\n placeholder: (label: PiiLabel, index: number) => string,\n): (label: PiiLabel, token: string) => boolean {\n interface Probe {\n prefix: string\n at: number[]\n /** Candidate substrings at `at`, per token length. */\n byLength: Map<number, Set<string>>\n }\n // Distinct token lengths per label, past which we stop caching and walk\n // instead. A counter-shaped placeholder produces one length per decade, so\n // this is far above any real one; it only bounds the memory a crafted\n // `placeholder` could make us hold.\n const MAX_CACHED_LENGTHS = 24\n const prefixes = new Map<PiiLabel, Probe | null>()\n return (label, token) => {\n let entry = prefixes.get(label)\n if (entry === undefined) {\n const first = placeholder(label, 1)\n const second = placeholder(label, 2)\n let n = 0\n while (n < first.length && n < second.length && first[n] === second[n]) n++\n const prefix = first.slice(0, n)\n entry = null\n if (prefix.length > 0) {\n const at: number[] = []\n for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i)\n entry = { prefix, at, byLength: new Map() }\n }\n prefixes.set(label, entry)\n }\n if (entry !== null && token.startsWith(entry.prefix)) {\n let candidates = entry.byLength.get(token.length)\n if (candidates === undefined) {\n if (entry.byLength.size >= MAX_CACHED_LENGTHS) {\n return entry.at.some((i) => input.startsWith(token, i))\n }\n candidates = new Set<string>()\n for (const i of entry.at) {\n if (i + token.length <= input.length) candidates.add(input.slice(i, i + token.length))\n }\n entry.byLength.set(token.length, candidates)\n }\n return candidates.has(token)\n }\n return input.includes(token)\n }\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n return redactFromDetections(input, runDetectors(input, options.detectors), options)\n}\n\n/**\n * Run rule detectors over `input` and return their detections, with spans in\n * `input`'s own coordinates.\n *\n * Detectors do NOT see `input`; they see its canonical view (see\n * {@link canonicalize}), because a zero-width space or a fullwidth digit would\n * otherwise walk a personnummer straight past every pattern. Spans come back\n * mapped, and `value` is re-sliced from the original, so a detection always\n * describes real text: `input.slice(d.start, d.end) === d.value` holds even\n * when the folded text the detector matched looked nothing like it.\n *\n * Exported because the hybrid entry point in `maskera` needs the rule\n * detections separately from the model's, and both must fold identically.\n */\nexport function runDetectors(input: string, detectors: Detector[] = defaultDetectors): Detection[] {\n const canonical = canonicalize(input)\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(canonical.text)) {\n if (canonical.identity) {\n all.push({ ...m, label: detector.label })\n continue\n }\n const [start, end] = canonical.span(m.start, m.end)\n all.push({ start, end, value: input.slice(start, end), label: detector.label })\n }\n }\n return all\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n const ownPlaceholder = options.placeholder === undefined\n\n // Spans arrive from callers too (`redactWithNer`, anything model-shaped), and\n // a malformed one does not fail loudly on its own: `resolveOverlaps` sorts a\n // reversed span into place and the rebuild loop below then *duplicates* the\n // text between `last` and `r.start` instead of removing it, which is silent\n // corruption of a document someone is redacting. Reject it instead.\n for (const d of detections) {\n if (\n !Number.isInteger(d.start) ||\n !Number.isInteger(d.end) ||\n d.start < 0 ||\n d.end > input.length ||\n d.start >= d.end\n ) {\n throw new Error(\n `maskera: detection span out of range for \"${d.label}\": [${d.start}, ${d.end}) ` +\n `in an input of length ${input.length}`,\n )\n }\n // `value` is what `restore()` writes back, and nothing downstream ever\n // re-derives it from the span. A detection whose value disagrees with its\n // own span therefore does not fail, it silently rewrites the document:\n // ({start: 5, end: 18, value: \"HELT ANNAT\"}) restores \"Ring HELT ANNAT\n // imorgon.\" over \"Ring Anna Svensson imorgon.\". Same argument as the span\n // check above, so the same treatment.\n if (d.value !== input.slice(d.start, d.end)) {\n throw new Error(\n `maskera: detection value for \"${d.label}\" does not match its span [${d.start}, ${d.end}): ` +\n `expected ${JSON.stringify(input.slice(d.start, d.end))}, got ${JSON.stringify(d.value)}`,\n )\n }\n // The default placeholder wraps the label in brackets, which only delimits\n // anything as long as the label carries none of its own. A label from an\n // external model (\"X] [PERSONNUMMER_1\", say) otherwise produces the token\n // \"[X] [PERSONNUMMER_1_1]\", and the redacted text an LLM sees then contains\n // the literal string \"[PERSONNUMMER_1]\" at a place the real personnummer\n // never stood. Echo that fragment back and `restore()` writes the real\n // value into it: a document-controlled exfiltration primitive.\n //\n // Banning both brackets is exactly enough for this placeholder. A token is\n // \"[\" + label + \"_\" + digits + \"]\"; with no bracket inside the label its\n // only \"[\" is the first character and its only \"]\" the last, so any other\n // token contained in it would have to be the token itself. `maskera`'s\n // `defaultLabelMap` already strips this at the source; this is the guard\n // for everyone calling core directly, which the doc comment invites.\n if (ownPlaceholder && (d.label.includes(\"[\") || d.label.includes(\"]\"))) {\n throw new Error(\n `maskera: label ${JSON.stringify(d.label)} contains a bracket, which would nest inside ` +\n \"the default placeholder and let one token be read as another. Sanitise the label \" +\n \"(see defaultLabelMap in maskera) or pass your own placeholder().\",\n )\n }\n }\n\n const resolved = resolveOverlaps(detections, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n const occursInInput = createInputProbe(input, placeholder)\n\n for (const d of resolved) {\n const key = tokenKey(d.label, d.value)\n let token = tokenByKey.get(key)\n if (!token) {\n // Never hand out a token that already occurs literally in the input\n // (a crafted \"[NAMN_1]\" in the input would collide with a generated\n // placeholder, and restore() would write the real value into positions\n // the author of the input chose), and never a token another value\n // already owns (a custom placeholder() that ignores the index would\n // otherwise silently map two values to one token and corrupt restore).\n let next = counters.get(d.label) ?? 0\n let attempts = 0\n for (;;) {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break\n // Giving up after a fixed number of tries made a crafted input a denial\n // of service: seeding \"[EPOST_1]\"..\"[EPOST_100]\" was enough to make\n // every later redact() throw. An input can only hold\n // input.length / token.length distinct colliding tokens, so past that\n // bound the placeholder() itself is broken (it ignores the index) and\n // no further index will help.\n if (token.length === 0 || attempts > 8 + input.length / token.length) {\n throw new Error(\n \"maskera: placeholder() must return a token that is unique per (label, index) \" +\n \"and does not occur in the input\",\n )\n }\n }\n counters.set(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n const tokens = Object.keys(map).filter((t) => t.length > 0)\n if (tokens.length === 0) return text\n\n // One left-to-right pass over a trie of the tokens, rather than a\n // split/join per token. Two reasons, and the first one is correctness:\n // replacing token by token re-scans text that was already restored, so a\n // value that happens to contain another token (\"Anna [EPOST_1]\" as a NAMN\n // value handed in via redactFromDetections) got substituted a second time\n // and the output was neither the placeholder nor the original. A single pass\n // never revisits what it wrote. The second is cost: split/join is O(tokens ×\n // text), which is the same product that made redaction slow on large logs.\n // Matching the deepest node at each position keeps the old longest-first\n // rule, so `[X_10]` still wins over `[X_1]`.\n const root: TrieNode = { next: new Map() }\n for (const token of tokens) {\n let node = root\n // Indexed by UTF-16 unit, the same way the scan below reads the text: a\n // code-point walk here would key a surrogate pair as one two-unit string\n // and never match.\n for (let k = 0; k < token.length; k++) {\n const ch = token[k] as string\n let child = node.next.get(ch)\n if (!child) {\n child = { next: new Map() }\n node.next.set(ch, child)\n }\n node = child\n }\n node.value = map[token]\n }\n\n let out = \"\"\n let last = 0\n let i = 0\n while (i < text.length) {\n let node = root.next.get(text[i] as string)\n let matchEnd = -1\n let matchValue: string | undefined\n let j = i\n while (node) {\n j++\n if (node.value !== undefined) {\n matchEnd = j\n matchValue = node.value\n }\n node = j < text.length ? node.next.get(text[j] as string) : undefined\n }\n if (matchValue === undefined) {\n i++\n continue\n }\n out += text.slice(last, i) + matchValue\n i = matchEnd\n last = i\n }\n return out + text.slice(last)\n}\n\ntype TrieNode = { value?: string; next: Map<string, TrieNode> }\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maskera/core",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "Swedish-first, zero-dependency PII detection & redaction. Runs in the browser, Node, and edge.",
5
5
  "type": "module",
6
6
  "license": "MIT",