@maskera/core 0.7.0 → 0.7.2

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,37 @@
1
1
  # @maskera/core
2
2
 
3
+ ## 0.7.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Security fixes for detection bypasses and validator gaps:
8
+
9
+ - canonicalize() now also strips C0/C1 control characters (except \t \n \f \r),
10
+ enclosing combining marks (\p{Me}, e.g. keycap sequences), and blank-rendered
11
+ characters that NFKC does not fold (U+2800 braille blank, U+115F/U+1160/U+3164/
12
+ U+FFA0 hangul fillers). Each of these split a personnummer/card/IBAN into
13
+ pieces the detectors could not see while rendering as the real thing. The
14
+ ASCII fast path in the fold loop is restricted to printable ASCII so the new
15
+ ranges cannot slip through it.
16
+ - The email detector accepts any Unicode letter/number in both parts. A
17
+ diacritic (andré, zoë, münchen) or a Cyrillic confusable next to the @ or in
18
+ the domain previously left no match position and the address leaked.
19
+ - isPersonnummer/isSamordningsnummer validate the date as a real calendar date
20
+ (per-month days, leap years; exact Gregorian rule for the 12-digit form), and
21
+ isOrganisationsnummer requires the "16" prefix on the 12-digit form.
22
+ - maskera: fix a potential O(span^2) slice in the identifier-label-word trim in
23
+ reconstruct() (exported API) by searching only the 25-character tail window
24
+ the pattern can actually match, and count the single-character detection
25
+ filter in code points rather than UTF-16 units.
26
+
27
+ ## 0.7.1
28
+
29
+ ### Patch Changes
30
+
31
+ - 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.
32
+
33
+ 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).
34
+
3
35
  ## 0.7.0
4
36
 
5
37
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/canonicalize.ts
4
- var INVISIBLE_SOURCE = "[\\p{Cf}\\u034f\\ufe00-\\ufe0f\\u{e0100}-\\u{e01ef}]";
4
+ var INVISIBLE_SOURCE = "[\\p{Cf}\\p{Me}\\u034f\\ufe00-\\ufe0f\\u{e0100}-\\u{e01ef}\\u2800\\u115f\\u1160\\u3164\\uffa0\\u0000-\\u0008\\u000b\\u000e-\\u001f\\u007f-\\u009f]";
5
5
  var INVISIBLE = new RegExp(INVISIBLE_SOURCE, "u");
6
6
  var INVISIBLE_RUN = new RegExp(`${INVISIBLE_SOURCE}+`, "gu");
7
7
  var MARK = /\p{M}/u;
@@ -32,7 +32,8 @@ function canonicalize(input) {
32
32
  };
33
33
  while (i < input.length) {
34
34
  const cp = input.codePointAt(i);
35
- if (cp < 128 && (i + 1 >= input.length || input.charCodeAt(i + 1) < 768)) {
35
+ const isPlainAscii = cp >= 32 && cp < 127 || cp === 9 || cp === 10 || cp === 12 || cp === 13;
36
+ if (isPlainAscii && (i + 1 >= input.length || input.charCodeAt(i + 1) < 768)) {
36
37
  if (runStart < 0) runStart = i;
37
38
  i++;
38
39
  continue;
@@ -113,28 +114,35 @@ function luhnValid(digits) {
113
114
  }
114
115
  return sum % 10 === 0;
115
116
  }
117
+ function daysInMonth(year, month) {
118
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
119
+ return [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
120
+ }
116
121
  function isPersonnummer(value) {
117
122
  const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
118
123
  if (!m) return false;
124
+ const year = Number((m[1] ?? "") + m[2]);
119
125
  const month = Number(m[3]);
120
126
  const day = Number(m[4]);
121
127
  if (month < 1 || month > 12) return false;
122
- if (day < 1 || day > 31) return false;
128
+ if (day < 1 || day > daysInMonth(year, month)) return false;
123
129
  const core = value.replace(/[-+]/g, "").slice(-10);
124
130
  return luhnValid(core);
125
131
  }
126
132
  function isSamordningsnummer(value) {
127
133
  const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
128
134
  if (!m) return false;
135
+ const year = Number((m[1] ?? "") + m[2]);
129
136
  const month = Number(m[3]);
130
137
  const day = Number(m[4]);
131
138
  if (month < 1 || month > 12) return false;
132
- if (day < 61 || day > 91) return false;
139
+ if (day < 61 || day - 60 > daysInMonth(year, month)) return false;
133
140
  const core = value.replace(/[-+]/g, "").slice(-10);
134
141
  return luhnValid(core);
135
142
  }
136
143
  function isOrganisationsnummer(value) {
137
144
  const only = value.replace(/\D/g, "");
145
+ if (only.length === 12 && !only.startsWith("16")) return false;
138
146
  const core = only.length === 12 ? only.slice(2) : only;
139
147
  if (core.length !== 10) return false;
140
148
  if (Number(core[2]) < 2) return false;
@@ -174,7 +182,7 @@ function regexDetector(label, regex, validate) {
174
182
  }
175
183
  };
176
184
  }
177
- var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0]{1,2}(?=\d))*\d|\d/g;
185
+ var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0\u1680]{1,2}(?=\d))*\d|\d/g;
178
186
  var isDigit = (code) => code >= 48 && code <= 57;
179
187
  var WS = /\s/;
180
188
  function checksumWindowDetector(label, widths, validate) {
@@ -249,7 +257,7 @@ var organisationsnummer = regexDetector(
249
257
  );
250
258
  var email = regexDetector(
251
259
  "EPOST",
252
- /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\.[A-Z]{2,63}\b/gi
260
+ /[\p{L}\p{N}._%+-]{1,64}@[\p{L}\p{N}.-]{1,255}\.\p{L}{2,63}\b/giu
253
261
  );
254
262
  var phone = regexDetector(
255
263
  "TELEFON",
@@ -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,IAAI,KAAK,CAAA;AAAA,EACxB;AAEA,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,OAAO,CAAA,GAAI,KAAK,MAAA,EAAQ;AACtB,IAAA,IAAI,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,CAAC,CAAW,CAAA;AAC1C,IAAA,IAAI,QAAA,GAAW,EAAA;AACf,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 * 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 */\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 { 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"]}
1
+ {"version":3,"sources":["../src/canonicalize.ts","../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";;;AAsEA,IAAM,gBAAA,GACJ,oJAAA;AACF,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,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,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 * 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). Then:\n *\n * - `\\p{Me}`, the enclosing combining marks. They are `\\p{M}` and therefore\n * survive NFKC, but never compose with their starter: \"8\" + U+20E3 (keycap)\n * stays two code points that RENDER as a boxed 8, so a keycap sequence read\n * as a perfect personnummer while every detector saw noise.\n * - The blank-rendered spaces that are neither `\\p{Cf}` nor JS `\\s` and that\n * NFKC does not fold away: U+2800 BRAILLE PATTERN BLANK and the Hangul\n * fillers U+115F / U+1160 / U+3164 / U+FFA0. \"850601<U+2800>2387\" renders\n * exactly like the canonical spaced form, and U+3164/U+FFA0 fold to U+1160,\n * which stays blank, so folding alone did not close this.\n * - The C0/C1 control characters except \\t \\n \\r \\f: U+0000..U+0008, U+000B,\n * U+000E..U+001F and U+007F..U+009F. They are invisible in most renderers\n * and split every pattern, while \\t \\n \\r \\f stay as genuine separators\n * (DIGIT_RUN deliberately does not fuse numbers across line breaks).\n *\n * What remains of `\\p{M}` is kept on purpose: U+034F and the variation\n * selectors below are invisible combining marks that survive NFKC, while real\n * marks (accents) must stay so they can compose with their starter.\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 =\n \"[\\\\p{Cf}\\\\p{Me}\\\\u034f\\\\ufe00-\\\\ufe0f\\\\u{e0100}-\\\\u{e01ef}\\\\u2800\\\\u115f\\\\u1160\\\\u3164\\\\uffa0\\\\u0000-\\\\u0008\\\\u000b\\\\u000e-\\\\u001f\\\\u007f-\\\\u009f]\"\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 // PRINTABLE ASCII is never invisible, never a mark and always NFKC-stable,\n // and it is most of any document. Skipping the per-character work here is\n // what keeps the folded path from costing more than the detection it\n // feeds. \"Printable\" is load-bearing: the C0/C1 controls are stripped\n // (see INVISIBLE_SOURCE), and 0x00-0x1F / 0x7F are all below 0x80, so a\n // plain `cp < 0x80` fast path smuggled them straight into the folded text\n // and \"850601-23<U+0001>87\" still walked past every detector. \\t \\n \\f \\r\n // are kept on the fast path explicitly: they are separators, not noise.\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 const isPlainAscii =\n (cp >= 0x20 && cp < 0x7f) || cp === 0x09 || cp === 0x0a || cp === 0x0c || cp === 0x0d\n if (isPlainAscii && (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 * Days in `month` of `year`. A 10-digit personnummer carries no century, so\n * the caller passes YY (0-99): YY % 4 === 0 is then the best leap rule there\n * is, and it is exact for every year a living holder can be born in (2000 was\n * a leap year, so even YY = 00 is right until 2100). A 12-digit form passes\n * the full year and gets the exact Gregorian rule.\n */\nfunction daysInMonth(year: number, month: number): number {\n if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28\n return [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] as number\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 * The date check is a real calendar check: a flat day <= 31 accepted\n * \"850230-…\" (Feb 30) and non-leap Feb 29, spending the false-positive\n * budget the checksum bought on dates that can never be issued.\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 year = Number((m[1] ?? \"\") + m[2])\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 > daysInMonth(year, month)) 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 year = Number((m[1] ?? \"\") + m[2])\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 - 60 > daysInMonth(year, month)) 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 // The 12-digit form must carry the \"16\" county prefix for legal entities;\n // without the check any Luhn-valid 12-digit string passed by dropping two\n // arbitrary leading digits.\n if (only.length === 12 && !only.startsWith(\"16\")) return false\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// Letters in both parts are ANY Unicode letter/number, not [A-ZÅÄÖ0-9]:\n// addresses like \"andré@example.com\" and \"anna@münchen.se\" exist in the wild,\n// and a diacritic or confusable (Cyrillic \"а\") sitting next to the @ or in the\n// domain used to leave no match position at all, walking the whole address\n// past the filter while rendering like an ordinary address. A leading \\b is\n// still impossible (JS \\b is ASCII-only), which is why there is none.\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. `[\\p{L}\\p{N}._%+-]+@` 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 /[\\p{L}\\p{N}._%+-]{1,64}@[\\p{L}\\p{N}.-]{1,255}\\.\\p{L}{2,63}\\b/giu,\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
@@ -220,6 +220,9 @@ declare function luhnValid(digits: string): boolean;
220
220
  * Validate a Swedish personnummer.
221
221
  * Accepts 10 or 12 digit forms with optional `-`/`+` separator.
222
222
  * Checks the date part and the Luhn control digit (on the 10-digit core).
223
+ * The date check is a real calendar check: a flat day <= 31 accepted
224
+ * "850230-…" (Feb 30) and non-leap Feb 29, spending the false-positive
225
+ * budget the checksum bought on dates that can never be issued.
223
226
  */
224
227
  declare function isPersonnummer(value: string): boolean;
225
228
  /** Swedish samordningsnummer: like a personnummer but day has +60. */
package/dist/index.d.ts CHANGED
@@ -220,6 +220,9 @@ declare function luhnValid(digits: string): boolean;
220
220
  * Validate a Swedish personnummer.
221
221
  * Accepts 10 or 12 digit forms with optional `-`/`+` separator.
222
222
  * Checks the date part and the Luhn control digit (on the 10-digit core).
223
+ * The date check is a real calendar check: a flat day <= 31 accepted
224
+ * "850230-…" (Feb 30) and non-leap Feb 29, spending the false-positive
225
+ * budget the checksum bought on dates that can never be issued.
223
226
  */
224
227
  declare function isPersonnummer(value: string): boolean;
225
228
  /** Swedish samordningsnummer: like a personnummer but day has +60. */
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/canonicalize.ts
2
- var INVISIBLE_SOURCE = "[\\p{Cf}\\u034f\\ufe00-\\ufe0f\\u{e0100}-\\u{e01ef}]";
2
+ var INVISIBLE_SOURCE = "[\\p{Cf}\\p{Me}\\u034f\\ufe00-\\ufe0f\\u{e0100}-\\u{e01ef}\\u2800\\u115f\\u1160\\u3164\\uffa0\\u0000-\\u0008\\u000b\\u000e-\\u001f\\u007f-\\u009f]";
3
3
  var INVISIBLE = new RegExp(INVISIBLE_SOURCE, "u");
4
4
  var INVISIBLE_RUN = new RegExp(`${INVISIBLE_SOURCE}+`, "gu");
5
5
  var MARK = /\p{M}/u;
@@ -30,7 +30,8 @@ function canonicalize(input) {
30
30
  };
31
31
  while (i < input.length) {
32
32
  const cp = input.codePointAt(i);
33
- if (cp < 128 && (i + 1 >= input.length || input.charCodeAt(i + 1) < 768)) {
33
+ const isPlainAscii = cp >= 32 && cp < 127 || cp === 9 || cp === 10 || cp === 12 || cp === 13;
34
+ if (isPlainAscii && (i + 1 >= input.length || input.charCodeAt(i + 1) < 768)) {
34
35
  if (runStart < 0) runStart = i;
35
36
  i++;
36
37
  continue;
@@ -111,28 +112,35 @@ function luhnValid(digits) {
111
112
  }
112
113
  return sum % 10 === 0;
113
114
  }
115
+ function daysInMonth(year, month) {
116
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
117
+ return [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
118
+ }
114
119
  function isPersonnummer(value) {
115
120
  const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
116
121
  if (!m) return false;
122
+ const year = Number((m[1] ?? "") + m[2]);
117
123
  const month = Number(m[3]);
118
124
  const day = Number(m[4]);
119
125
  if (month < 1 || month > 12) return false;
120
- if (day < 1 || day > 31) return false;
126
+ if (day < 1 || day > daysInMonth(year, month)) return false;
121
127
  const core = value.replace(/[-+]/g, "").slice(-10);
122
128
  return luhnValid(core);
123
129
  }
124
130
  function isSamordningsnummer(value) {
125
131
  const m = value.match(/^(\d{2})?(\d{2})(\d{2})(\d{2})[-+]?(\d{4})$/);
126
132
  if (!m) return false;
133
+ const year = Number((m[1] ?? "") + m[2]);
127
134
  const month = Number(m[3]);
128
135
  const day = Number(m[4]);
129
136
  if (month < 1 || month > 12) return false;
130
- if (day < 61 || day > 91) return false;
137
+ if (day < 61 || day - 60 > daysInMonth(year, month)) return false;
131
138
  const core = value.replace(/[-+]/g, "").slice(-10);
132
139
  return luhnValid(core);
133
140
  }
134
141
  function isOrganisationsnummer(value) {
135
142
  const only = value.replace(/\D/g, "");
143
+ if (only.length === 12 && !only.startsWith("16")) return false;
136
144
  const core = only.length === 12 ? only.slice(2) : only;
137
145
  if (core.length !== 10) return false;
138
146
  if (Number(core[2]) < 2) return false;
@@ -172,7 +180,7 @@ function regexDetector(label, regex, validate) {
172
180
  }
173
181
  };
174
182
  }
175
- var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0]{1,2}(?=\d))*\d|\d/g;
183
+ var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0\u1680]{1,2}(?=\d))*\d|\d/g;
176
184
  var isDigit = (code) => code >= 48 && code <= 57;
177
185
  var WS = /\s/;
178
186
  function checksumWindowDetector(label, widths, validate) {
@@ -247,7 +255,7 @@ var organisationsnummer = regexDetector(
247
255
  );
248
256
  var email = regexDetector(
249
257
  "EPOST",
250
- /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\.[A-Z]{2,63}\b/gi
258
+ /[\p{L}\p{N}._%+-]{1,64}@[\p{L}\p{N}.-]{1,255}\.\p{L}{2,63}\b/giu
251
259
  );
252
260
  var phone = regexDetector(
253
261
  "TELEFON",
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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,EAAA,OAAO,CAAC,IAAI,EAAE,CAAA;AAChB;AASO,SAAS,aAAa,KAAA,EAA8B;AACzD,EAAA,IAAI,CAAC,SAAA,CAAU,IAAA,CAAK,KA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AAE;AAC1B,QAAA,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,EAAA,EAAI,KAAK,CAAA;AAAA,MACzB;AACA,MAAA,IAAA,GAAO,KAAA;AAAA,IACT;AACA,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAI,KAAK,CAAA;AAAA,EACxB;AAEA,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,OAAO,CAAA,GAAI,KAAK,MAAA,EAAQ;AACtB,IAAA,IAAI,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,CAAC,CAAW,CAAA;AAC1C,IAAA,IAAI,QAAA,GAAW,EAAA;AACf,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.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 */\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 { 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"]}
1
+ {"version":3,"sources":["../src/canonicalize.ts","../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";AAsEA,IAAM,gBAAA,GACJ,oJAAA;AACF,IAAM,SAAA,GAAY,IAAI,MAAA,CAAO,gBAAA,EAAkB,GAAG,CAAA;AAClD,IAAM,gBAAgB,IAAI,MAAA,CAAO,CAAA,EAAG,gBAAgB,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A,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 * 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). Then:\n *\n * - `\\p{Me}`, the enclosing combining marks. They are `\\p{M}` and therefore\n * survive NFKC, but never compose with their starter: \"8\" + U+20E3 (keycap)\n * stays two code points that RENDER as a boxed 8, so a keycap sequence read\n * as a perfect personnummer while every detector saw noise.\n * - The blank-rendered spaces that are neither `\\p{Cf}` nor JS `\\s` and that\n * NFKC does not fold away: U+2800 BRAILLE PATTERN BLANK and the Hangul\n * fillers U+115F / U+1160 / U+3164 / U+FFA0. \"850601<U+2800>2387\" renders\n * exactly like the canonical spaced form, and U+3164/U+FFA0 fold to U+1160,\n * which stays blank, so folding alone did not close this.\n * - The C0/C1 control characters except \\t \\n \\r \\f: U+0000..U+0008, U+000B,\n * U+000E..U+001F and U+007F..U+009F. They are invisible in most renderers\n * and split every pattern, while \\t \\n \\r \\f stay as genuine separators\n * (DIGIT_RUN deliberately does not fuse numbers across line breaks).\n *\n * What remains of `\\p{M}` is kept on purpose: U+034F and the variation\n * selectors below are invisible combining marks that survive NFKC, while real\n * marks (accents) must stay so they can compose with their starter.\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 =\n \"[\\\\p{Cf}\\\\p{Me}\\\\u034f\\\\ufe00-\\\\ufe0f\\\\u{e0100}-\\\\u{e01ef}\\\\u2800\\\\u115f\\\\u1160\\\\u3164\\\\uffa0\\\\u0000-\\\\u0008\\\\u000b\\\\u000e-\\\\u001f\\\\u007f-\\\\u009f]\"\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 // PRINTABLE ASCII is never invisible, never a mark and always NFKC-stable,\n // and it is most of any document. Skipping the per-character work here is\n // what keeps the folded path from costing more than the detection it\n // feeds. \"Printable\" is load-bearing: the C0/C1 controls are stripped\n // (see INVISIBLE_SOURCE), and 0x00-0x1F / 0x7F are all below 0x80, so a\n // plain `cp < 0x80` fast path smuggled them straight into the folded text\n // and \"850601-23<U+0001>87\" still walked past every detector. \\t \\n \\f \\r\n // are kept on the fast path explicitly: they are separators, not noise.\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 const isPlainAscii =\n (cp >= 0x20 && cp < 0x7f) || cp === 0x09 || cp === 0x0a || cp === 0x0c || cp === 0x0d\n if (isPlainAscii && (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 * Days in `month` of `year`. A 10-digit personnummer carries no century, so\n * the caller passes YY (0-99): YY % 4 === 0 is then the best leap rule there\n * is, and it is exact for every year a living holder can be born in (2000 was\n * a leap year, so even YY = 00 is right until 2100). A 12-digit form passes\n * the full year and gets the exact Gregorian rule.\n */\nfunction daysInMonth(year: number, month: number): number {\n if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28\n return [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] as number\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 * The date check is a real calendar check: a flat day <= 31 accepted\n * \"850230-…\" (Feb 30) and non-leap Feb 29, spending the false-positive\n * budget the checksum bought on dates that can never be issued.\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 year = Number((m[1] ?? \"\") + m[2])\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 > daysInMonth(year, month)) 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 year = Number((m[1] ?? \"\") + m[2])\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 - 60 > daysInMonth(year, month)) 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 // The 12-digit form must carry the \"16\" county prefix for legal entities;\n // without the check any Luhn-valid 12-digit string passed by dropping two\n // arbitrary leading digits.\n if (only.length === 12 && !only.startsWith(\"16\")) return false\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// Letters in both parts are ANY Unicode letter/number, not [A-ZÅÄÖ0-9]:\n// addresses like \"andré@example.com\" and \"anna@münchen.se\" exist in the wild,\n// and a diacritic or confusable (Cyrillic \"а\") sitting next to the @ or in the\n// domain used to leave no match position at all, walking the whole address\n// past the filter while rendering like an ordinary address. A leading \\b is\n// still impossible (JS \\b is ASCII-only), which is why there is none.\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. `[\\p{L}\\p{N}._%+-]+@` 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 /[\\p{L}\\p{N}._%+-]{1,64}@[\\p{L}\\p{N}.-]{1,255}\\.\\p{L}{2,63}\\b/giu,\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.7.0",
3
+ "version": "0.7.2",
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",