@maskera/core 0.8.4 → 0.8.5
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 +6 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @maskera/core
|
|
2
2
|
|
|
3
|
+
## 0.8.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 53c7aa7: The contextual `kontonummer` detector now masks a clearing number and account written apart by a comma and a space, as Swedbank prints them ("konto 3300-0, 032 3232 3232" with the registered test account). Before, only the clearing number was masked (as `PLUSGIRO`) and the account number leaked. A comma without a following space still ends the account.
|
|
8
|
+
|
|
3
9
|
## 0.8.3
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -318,7 +318,7 @@ var plusgiro = regexDetector(
|
|
|
318
318
|
var iban = regexDetector("IBAN", /\bSE\d{2}(?:\s?\d){20}\b/gi);
|
|
319
319
|
var kontonummer = regexDetector(
|
|
320
320
|
"KONTONUMMER",
|
|
321
|
-
/(?:^|[^\p{L}\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\s+nr\.?)?\s*[:#-]?\s*((?:\d[ -]?){6,19}\d)\b/giu,
|
|
321
|
+
/(?:^|[^\p{L}\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\s+nr\.?)?\s*[:#-]?\s*(\d{4}(?:\s?-\s?\d)?,\s+(?:\d[ -]?){5,14}\d|(?:\d[ -]?){6,19}\d)\b/giu,
|
|
322
322
|
(value) => {
|
|
323
323
|
const digits = value.replace(/\D/g, "");
|
|
324
324
|
return digits.length >= 7 && digits.length <= 20;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
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A,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). 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 * Personnummer shape: 10 or 12 digit form with optional `-`/`+` separator and\n * a real calendar date, but NO Luhn check. The date check is a real calendar\n * check: a flat day <= 31 would accept \"850230-…\" (Feb 30) and non-leap\n * Feb 29, spending the false-positive budget on dates that can never be\n * issued.\n *\n * This — not the strict validator — is what the personnummer detector runs\n * on. In real customer data people routinely mistype their own personnummer,\n * and a typo lands in the control digit as often as anywhere else; rejecting\n * on Luhn then leaks the single most sensitive identifier Sweden has. With\n * the checksum gone the date check carries the precision burden: it rejects\n * ~96% of arbitrary digit runs on its own (month 1-12, day valid in that\n * month), which is what keeps order ids and account numbers from masking.\n */\nexport function isPersonnummerShape(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 return day >= 1 && day <= daysInMonth(year, month)\n}\n\n/** Samordningsnummer shape: like `isPersonnummerShape` but day has +60. */\nexport function isSamordningsnummerShape(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 return day >= 61 && day - 60 <= daysInMonth(year, month)\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 if (!isPersonnummerShape(value)) 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 if (!isSamordningsnummerShape(value)) 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 isPersonnummerShape,\n isSamordningsnummerShape,\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. On such\n // an engine the fallback is only used when it is SAFE: when the value occurs\n // more than once inside its own match the position is ambiguous, and a wrong\n // guess masks the wrong slice while the value stays in the clear, so the\n // detection is refused loudly instead (see detect() below).\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 // matchAll clones the regex but copies the clone's lastIndex FROM the\n // original, and when the caller's regex already carried the \"d\" flag\n // `scanner` IS the caller's object. A lastIndex their own exec()/test()\n // moved elsewhere would then start the scan mid-string and silently\n // skip every detection before it — a leak. Always restart at zero.\n scanner.lastIndex = 0\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 let start: number\n if (span) {\n start = span[0]\n } else {\n const first = m[0].indexOf(value)\n if (first !== m[0].lastIndexOf(value)) {\n // Fail closed rather than guess: reporting the first occurrence of\n // a repeated group text would have redact() mask the wrong slice\n // and leak the value itself. Only reachable on engines without\n // the \"d\" flag, with a custom pattern whose capture repeats inside\n // its own match.\n throw new Error(\n `maskera: detector \"${label}\" matched a value that occurs more than once inside ` +\n 'its own match, and this engine lacks regex match indices (the \"d\" flag, ' +\n \"Chrome 90 / Safari 15 / Node 16) to tell which occurrence is the value. \" +\n \"Upgrade the runtime, or rewrite the pattern so the captured value appears \" +\n \"only once per match.\",\n )\n }\n start = m.index + first\n }\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 whitespace lookahead accepts a digit OR the `-`/`+` separator: \"811218\n * -9876\" (space before the dash) is a realistic typed form and was the same\n * one-character bypass one step earlier — the run split at the space and both\n * halves were too short to window. The window check in checksumWindowDetector\n * still confines whitespace to the separator position, so \"4711 - 2203\" style\n * table neighbours do not fuse into a candidate.\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 identifiers by sliding a window over every digit run, with no\n * 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 the\n * format check has to carry that weight instead. It can, but only where the\n * format is selective enough: personnummer and samordningsnummer constrain\n * month and day, which rejects ~96% of candidates on its own.\n *\n * Note that personnummer and samordningsnummer deliberately validate on the\n * DATE SHAPE ONLY (isPersonnummerShape), not on the Luhn control digit: in\n * real customer data people mistype their own number, and rejecting on Luhn\n * leaks the very identifier this filter exists to protect. The date check\n * carries the precision burden instead. Measured on 20,000 sentences of\n * number-dense Swedish business text containing no personal identifiers,\n * dropping the boundary costs 0.4 false positives per 100 sentences against\n * 0.1 for the boundary version; the Luhn-free policy spends a little more of\n * that same budget on typo-shaped numbers that happen to parse as dates.\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 * and their checksums.\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 format checks 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/**\n * Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional.\n * Validates on date shape only, NOT Luhn: a mistyped control digit is the most\n * common way a real personnummer appears in customer data, and rejecting it\n * leaks exactly what we are here to mask (see isPersonnummerShape).\n */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummerShape)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. Same no-Luhn policy. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummerShape,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n // Whitespace is tolerated around the dash (\"556036 -0793\"), but a space\n // WITHOUT the dash stays unmatched: that shape is far more often two\n // unrelated numbers than an org number, and Luhn only filters ~92% of them.\n /\\b\\d{6}(?:\\s{1,2}-\\s?|-\\s?)?\\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.\nconst EMAIL_PATTERN = /[\\p{L}\\p{N}._%+-]{1,64}@[\\p{L}\\p{N}.-]{1,255}\\.\\p{L}{2,63}\\b/giu\nconst EMAIL_LOCAL_CHAR = /[\\p{L}\\p{N}._%+-]/u\nconst EMAIL_DOMAIN_CHAR = /[\\p{L}\\p{N}.-]/u\nconst EMAIL_ALNUM = /[\\p{L}\\p{N}]/u\n\n/**\n * E-post: `anna@example.com`, Unicode letters on both sides of the @.\n *\n * Not built with regexDetector, because the bounded quantifiers above\n * reintroduced a leak of their own: a local part or domain LONGER than its\n * window still matches, but only the window was reported and the rest of the\n * address stayed in the clear - \"anna.svensson.\" + 70 x's masked as\n * \"anna.svensson.xxxxxxxx[EPOST_1]\", and `anna@` + \"sub.\"×80 + \"example.com\"\n * masked as \"[EPOST_1].sub.sub…example.com\". So after each match the span is\n * widened to the whole contiguous run: LEFT while the characters belong to\n * the local-part class, RIGHT while they belong to the domain class. The two\n * classes differ (`_`, `%`, `+` are local-only), and which one applies is\n * decided by position, not by where the window was cut: the pattern requires\n * at least one local-part character before the literal `@`, so the match\n * always starts inside the local part and always ends inside the domain, and\n * `@` itself is in neither class - which also bounds each walk at the nearest\n * `@`, keeping detection linear on hostile runs. Over-masking the rest of the\n * run is the right side to err on for a redaction tool: a clipped run is\n * never safe to leave visible, and `resolveOverlaps()` in redact already\n * arbitrates any span this grows into. The one exception is the trailing\n * edge: a \".\" or \"-\" can never end a domain label, so characters like the\n * sentence period in \"mejlar anna@example.com.\" are trimmed back off the\n * span - masking them would mangle the prose around the token for no\n * redaction gain.\n */\nexport const email: Detector = {\n label: \"EPOST\",\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n EMAIL_PATTERN.lastIndex = 0\n for (const m of input.matchAll(EMAIL_PATTERN)) {\n if (m.index === undefined) continue\n let start = m.index\n let end = m.index + m[0].length\n while (start > 0 && EMAIL_LOCAL_CHAR.test(input[start - 1] as string)) start--\n while (end < input.length && EMAIL_DOMAIN_CHAR.test(input[end] as string)) end++\n // Trim trailing \".\" / \"-\" the right walk picked up: they can never end\n // a domain label, so they are punctuation touching the run, not part of\n // the address. The raw match always ends alphanumeric, so this cannot\n // pull the span back inside it.\n while (end > start && !EMAIL_ALNUM.test(input[end - 1] as string)) end--\n out.push({ start, end, value: input.slice(start, end) })\n }\n return out\n },\n}\n\n/**\n * Phone numbers. Swedish: +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. International: a `+<1-3 digit country code>` prefix\n * followed by 6-12 digits with optional spaces/dashes (\"+33 6 12 34 56 78\",\n * \"+47 9123456\"). The `+` is required for the international form — without\n * it a bare digit run is far more often an order id or account number than a\n * foreign phone number, so the unprefixed branch stays Swedish-only.\n * The consumed left guard (capture group carries the value) stops the match\n * from starting inside a longer digit run like \"kundnummer TEST-100200-3000\".\n * Up to three separator characters sit between digits so \"070 - 174 06 58\"\n * (whitespace around the dash) is masked whole instead of leaking its ends.\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]{0,3}\\d){6,8}|\\+\\d{1,3}(?:[\\s-]{0,3}\\d){6,12})\\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}\\s{0,2}-\\s{0,2}\\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}\\s{0,2}-\\s{0,2}\\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/**\n * Contextual domestic account number. Sweden has no single checksum-backed\n * syntax for ordinary bank accounts, so the digit shape alone is much too\n * broad: it also describes customer, order and journal identifiers. Requiring\n * an explicit account label keeps this useful without turning every grouped\n * number into PII. This detector is opt-in for rules-only callers and enabled\n * by the hybrid pipeline, whose input is normally free-form customer text.\n */\nexport const kontonummer = regexDetector(\n \"KONTONUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\\s+nr\\.?)?\\s*[:#-]?\\s*((?:\\d[ -]?){6,19}\\d)\\b/giu,\n (value) => {\n const digits = value.replace(/\\D/g, \"\")\n return digits.length >= 7 && digits.length <= 20\n },\n)\n\n/**\n * Context-labeled journal identifier. The identifier format is provider-\n * specific, but the explicit Swedish field label is strong evidence and keeps\n * checksum-shaped values from being misclassified as payment identifiers.\n */\nexport const journalnummer = regexDetector(\n \"JOURNALNUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:journalnummer|journalnr|journal-id|journalid)\\s*[:#-]?\\s*((?:[\\p{L}\\p{N}]{2,12}[-/]){1,3}[\\p{L}\\p{N}]{2,12}|\\d{5,20})\\b/giu,\n)\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|gången|kajen|stranden|terrassen|leden|stråket|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|GÅNGEN|KAJEN|STRANDEN|TERRASSEN|LEDEN|STRÅKET|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/** Context-dependent formats that are safe only when their label is present. */\nexport const contextualDetectors: Detector[] = [kontonummer, journalnummer]\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// Context-labeled identifiers outrank generic numeric shapes. A Swedish phone\n// number can also have the same ten-digit shape as a samordningsnummer (for\n// example `070174-0658`), so prefer the phone label there: it is the more\n// specific lexical format and avoids reclassifying an ordinary phone number\n// merely because personnummer detection is intentionally typo-tolerant.\nconst SAME_SPAN_PRIORITY: Partial<Record<PiiLabel, number>> = {\n JOURNALNUMMER: -10,\n KONTONUMMER: -10,\n TELEFON: 0,\n PERSONNUMMER: 10,\n SAMORDNINGSNUMMER: 11,\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 const priorityA = SAME_SPAN_PRIORITY[a.label] ?? 5\n const priorityB = SAME_SPAN_PRIORITY[b.label] ?? 5\n if (priorityA !== priorityB) return priorityA - priorityB\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 //\n // The message deliberately reports lengths, not content: `input.slice()`\n // here IS the PII someone is redacting, and an Error message is exactly\n // the kind of string that ends up in crash reporting and log aggregation.\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 `span length is ${d.end - d.start}, value length is ${d.value.length}, and the content differs`,\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 shortestToken = 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 const shortest = Math.min(shortestToken.get(d.label) ?? Infinity, token.length)\n shortestToken.set(d.label, shortest)\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 OF ONE LENGTH,\n // but the colliding tokens in the input need not share the length of\n // the token being probed: counter-shaped placeholders grow with the\n // index (\"[PERSONNUMMER_1001]\" is longer than \"[PERSONNUMMER_1]\"), so\n // dividing by the CURRENT token's length underestimates how many\n // collisions fit - 1000 concatenated short tokens occupy ~17 KB while\n // the bound computed from the longer 1001st token came out below 1000,\n // and redact() threw on an input it should simply have worked through.\n // Dividing by the SHORTEST token this label has produced is the safe\n // bound: it never underestimates the collision count. Past it the\n // placeholder() itself is broken (it ignores the index) and no\n // further index will help.\n if (token.length === 0 || attempts > 8 + input.length / shortest) {\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,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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,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.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 * Personnummer shape: 10 or 12 digit form with optional `-`/`+` separator and\n * a real calendar date, but NO Luhn check. The date check is a real calendar\n * check: a flat day <= 31 would accept \"850230-…\" (Feb 30) and non-leap\n * Feb 29, spending the false-positive budget on dates that can never be\n * issued.\n *\n * This — not the strict validator — is what the personnummer detector runs\n * on. In real customer data people routinely mistype their own personnummer,\n * and a typo lands in the control digit as often as anywhere else; rejecting\n * on Luhn then leaks the single most sensitive identifier Sweden has. With\n * the checksum gone the date check carries the precision burden: it rejects\n * ~96% of arbitrary digit runs on its own (month 1-12, day valid in that\n * month), which is what keeps order ids and account numbers from masking.\n */\nexport function isPersonnummerShape(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 return day >= 1 && day <= daysInMonth(year, month)\n}\n\n/** Samordningsnummer shape: like `isPersonnummerShape` but day has +60. */\nexport function isSamordningsnummerShape(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 return day >= 61 && day - 60 <= daysInMonth(year, month)\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 if (!isPersonnummerShape(value)) 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 if (!isSamordningsnummerShape(value)) 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 isPersonnummerShape,\n isSamordningsnummerShape,\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. On such\n // an engine the fallback is only used when it is SAFE: when the value occurs\n // more than once inside its own match the position is ambiguous, and a wrong\n // guess masks the wrong slice while the value stays in the clear, so the\n // detection is refused loudly instead (see detect() below).\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 // matchAll clones the regex but copies the clone's lastIndex FROM the\n // original, and when the caller's regex already carried the \"d\" flag\n // `scanner` IS the caller's object. A lastIndex their own exec()/test()\n // moved elsewhere would then start the scan mid-string and silently\n // skip every detection before it — a leak. Always restart at zero.\n scanner.lastIndex = 0\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 let start: number\n if (span) {\n start = span[0]\n } else {\n const first = m[0].indexOf(value)\n if (first !== m[0].lastIndexOf(value)) {\n // Fail closed rather than guess: reporting the first occurrence of\n // a repeated group text would have redact() mask the wrong slice\n // and leak the value itself. Only reachable on engines without\n // the \"d\" flag, with a custom pattern whose capture repeats inside\n // its own match.\n throw new Error(\n `maskera: detector \"${label}\" matched a value that occurs more than once inside ` +\n 'its own match, and this engine lacks regex match indices (the \"d\" flag, ' +\n \"Chrome 90 / Safari 15 / Node 16) to tell which occurrence is the value. \" +\n \"Upgrade the runtime, or rewrite the pattern so the captured value appears \" +\n \"only once per match.\",\n )\n }\n start = m.index + first\n }\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 whitespace lookahead accepts a digit OR the `-`/`+` separator: \"811218\n * -9876\" (space before the dash) is a realistic typed form and was the same\n * one-character bypass one step earlier — the run split at the space and both\n * halves were too short to window. The window check in checksumWindowDetector\n * still confines whitespace to the separator position, so \"4711 - 2203\" style\n * table neighbours do not fuse into a candidate.\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 identifiers by sliding a window over every digit run, with no\n * 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 the\n * format check has to carry that weight instead. It can, but only where the\n * format is selective enough: personnummer and samordningsnummer constrain\n * month and day, which rejects ~96% of candidates on its own.\n *\n * Note that personnummer and samordningsnummer deliberately validate on the\n * DATE SHAPE ONLY (isPersonnummerShape), not on the Luhn control digit: in\n * real customer data people mistype their own number, and rejecting on Luhn\n * leaks the very identifier this filter exists to protect. The date check\n * carries the precision burden instead. Measured on 20,000 sentences of\n * number-dense Swedish business text containing no personal identifiers,\n * dropping the boundary costs 0.4 false positives per 100 sentences against\n * 0.1 for the boundary version; the Luhn-free policy spends a little more of\n * that same budget on typo-shaped numbers that happen to parse as dates.\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 * and their checksums.\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 format checks 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/**\n * Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional.\n * Validates on date shape only, NOT Luhn: a mistyped control digit is the most\n * common way a real personnummer appears in customer data, and rejecting it\n * leaks exactly what we are here to mask (see isPersonnummerShape).\n */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummerShape)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. Same no-Luhn policy. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummerShape,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n // Whitespace is tolerated around the dash (\"556036 -0793\"), but a space\n // WITHOUT the dash stays unmatched: that shape is far more often two\n // unrelated numbers than an org number, and Luhn only filters ~92% of them.\n /\\b\\d{6}(?:\\s{1,2}-\\s?|-\\s?)?\\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.\nconst EMAIL_PATTERN = /[\\p{L}\\p{N}._%+-]{1,64}@[\\p{L}\\p{N}.-]{1,255}\\.\\p{L}{2,63}\\b/giu\nconst EMAIL_LOCAL_CHAR = /[\\p{L}\\p{N}._%+-]/u\nconst EMAIL_DOMAIN_CHAR = /[\\p{L}\\p{N}.-]/u\nconst EMAIL_ALNUM = /[\\p{L}\\p{N}]/u\n\n/**\n * E-post: `anna@example.com`, Unicode letters on both sides of the @.\n *\n * Not built with regexDetector, because the bounded quantifiers above\n * reintroduced a leak of their own: a local part or domain LONGER than its\n * window still matches, but only the window was reported and the rest of the\n * address stayed in the clear - \"anna.svensson.\" + 70 x's masked as\n * \"anna.svensson.xxxxxxxx[EPOST_1]\", and `anna@` + \"sub.\"×80 + \"example.com\"\n * masked as \"[EPOST_1].sub.sub…example.com\". So after each match the span is\n * widened to the whole contiguous run: LEFT while the characters belong to\n * the local-part class, RIGHT while they belong to the domain class. The two\n * classes differ (`_`, `%`, `+` are local-only), and which one applies is\n * decided by position, not by where the window was cut: the pattern requires\n * at least one local-part character before the literal `@`, so the match\n * always starts inside the local part and always ends inside the domain, and\n * `@` itself is in neither class - which also bounds each walk at the nearest\n * `@`, keeping detection linear on hostile runs. Over-masking the rest of the\n * run is the right side to err on for a redaction tool: a clipped run is\n * never safe to leave visible, and `resolveOverlaps()` in redact already\n * arbitrates any span this grows into. The one exception is the trailing\n * edge: a \".\" or \"-\" can never end a domain label, so characters like the\n * sentence period in \"mejlar anna@example.com.\" are trimmed back off the\n * span - masking them would mangle the prose around the token for no\n * redaction gain.\n */\nexport const email: Detector = {\n label: \"EPOST\",\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n EMAIL_PATTERN.lastIndex = 0\n for (const m of input.matchAll(EMAIL_PATTERN)) {\n if (m.index === undefined) continue\n let start = m.index\n let end = m.index + m[0].length\n while (start > 0 && EMAIL_LOCAL_CHAR.test(input[start - 1] as string)) start--\n while (end < input.length && EMAIL_DOMAIN_CHAR.test(input[end] as string)) end++\n // Trim trailing \".\" / \"-\" the right walk picked up: they can never end\n // a domain label, so they are punctuation touching the run, not part of\n // the address. The raw match always ends alphanumeric, so this cannot\n // pull the span back inside it.\n while (end > start && !EMAIL_ALNUM.test(input[end - 1] as string)) end--\n out.push({ start, end, value: input.slice(start, end) })\n }\n return out\n },\n}\n\n/**\n * Phone numbers. Swedish: +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. International: a `+<1-3 digit country code>` prefix\n * followed by 6-12 digits with optional spaces/dashes (\"+33 6 12 34 56 78\",\n * \"+47 9123456\"). The `+` is required for the international form — without\n * it a bare digit run is far more often an order id or account number than a\n * foreign phone number, so the unprefixed branch stays Swedish-only.\n * The consumed left guard (capture group carries the value) stops the match\n * from starting inside a longer digit run like \"kundnummer TEST-100200-3000\".\n * Up to three separator characters sit between digits so \"070 - 174 06 58\"\n * (whitespace around the dash) is masked whole instead of leaking its ends.\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]{0,3}\\d){6,8}|\\+\\d{1,3}(?:[\\s-]{0,3}\\d){6,12})\\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}\\s{0,2}-\\s{0,2}\\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}\\s{0,2}-\\s{0,2}\\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/**\n * Contextual domestic account number. Sweden has no single checksum-backed\n * syntax for ordinary bank accounts, so the digit shape alone is much too\n * broad: it also describes customer, order and journal identifiers. Requiring\n * an explicit account label keeps this useful without turning every grouped\n * number into PII. This detector is opt-in for rules-only callers and enabled\n * by the hybrid pipeline, whose input is normally free-form customer text.\n */\n// A clearing number may be written apart from the account by a comma, as in\n// Swedbank's \"8327-9, 123 456 789-0\". The comma must be followed by a space,\n// so a decimal amount (\"12 345,50\") is never read as one account.\nexport const kontonummer = regexDetector(\n \"KONTONUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\\s+nr\\.?)?\\s*[:#-]?\\s*(\\d{4}(?:\\s?-\\s?\\d)?,\\s+(?:\\d[ -]?){5,14}\\d|(?:\\d[ -]?){6,19}\\d)\\b/giu,\n (value) => {\n const digits = value.replace(/\\D/g, \"\")\n return digits.length >= 7 && digits.length <= 20\n },\n)\n\n/**\n * Context-labeled journal identifier. The identifier format is provider-\n * specific, but the explicit Swedish field label is strong evidence and keeps\n * checksum-shaped values from being misclassified as payment identifiers.\n */\nexport const journalnummer = regexDetector(\n \"JOURNALNUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:journalnummer|journalnr|journal-id|journalid)\\s*[:#-]?\\s*((?:[\\p{L}\\p{N}]{2,12}[-/]){1,3}[\\p{L}\\p{N}]{2,12}|\\d{5,20})\\b/giu,\n)\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|gången|kajen|stranden|terrassen|leden|stråket|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|GÅNGEN|KAJEN|STRANDEN|TERRASSEN|LEDEN|STRÅKET|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/** Context-dependent formats that are safe only when their label is present. */\nexport const contextualDetectors: Detector[] = [kontonummer, journalnummer]\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// Context-labeled identifiers outrank generic numeric shapes. A Swedish phone\n// number can also have the same ten-digit shape as a samordningsnummer (for\n// example `070174-0658`), so prefer the phone label there: it is the more\n// specific lexical format and avoids reclassifying an ordinary phone number\n// merely because personnummer detection is intentionally typo-tolerant.\nconst SAME_SPAN_PRIORITY: Partial<Record<PiiLabel, number>> = {\n JOURNALNUMMER: -10,\n KONTONUMMER: -10,\n TELEFON: 0,\n PERSONNUMMER: 10,\n SAMORDNINGSNUMMER: 11,\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 const priorityA = SAME_SPAN_PRIORITY[a.label] ?? 5\n const priorityB = SAME_SPAN_PRIORITY[b.label] ?? 5\n if (priorityA !== priorityB) return priorityA - priorityB\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 //\n // The message deliberately reports lengths, not content: `input.slice()`\n // here IS the PII someone is redacting, and an Error message is exactly\n // the kind of string that ends up in crash reporting and log aggregation.\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 `span length is ${d.end - d.start}, value length is ${d.value.length}, and the content differs`,\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 shortestToken = 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 const shortest = Math.min(shortestToken.get(d.label) ?? Infinity, token.length)\n shortestToken.set(d.label, shortest)\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 OF ONE LENGTH,\n // but the colliding tokens in the input need not share the length of\n // the token being probed: counter-shaped placeholders grow with the\n // index (\"[PERSONNUMMER_1001]\" is longer than \"[PERSONNUMMER_1]\"), so\n // dividing by the CURRENT token's length underestimates how many\n // collisions fit - 1000 concatenated short tokens occupy ~17 KB while\n // the bound computed from the longer 1001st token came out below 1000,\n // and redact() threw on an input it should simply have worked through.\n // Dividing by the SHORTEST token this label has produced is the safe\n // bound: it never underestimates the collision count. Past it the\n // placeholder() itself is broken (it ignores the index) and no\n // further index will help.\n if (token.length === 0 || attempts > 8 + input.length / shortest) {\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.js
CHANGED
|
@@ -316,7 +316,7 @@ var plusgiro = regexDetector(
|
|
|
316
316
|
var iban = regexDetector("IBAN", /\bSE\d{2}(?:\s?\d){20}\b/gi);
|
|
317
317
|
var kontonummer = regexDetector(
|
|
318
318
|
"KONTONUMMER",
|
|
319
|
-
/(?:^|[^\p{L}\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\s+nr\.?)?\s*[:#-]?\s*((?:\d[ -]?){6,19}\d)\b/giu,
|
|
319
|
+
/(?:^|[^\p{L}\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\s+nr\.?)?\s*[:#-]?\s*(\d{4}(?:\s?-\s?\d)?,\s+(?:\d[ -]?){5,14}\d|(?:\d[ -]?){6,19}\d)\b/giu,
|
|
320
320
|
(value) => {
|
|
321
321
|
const digits = value.replace(/\D/g, "");
|
|
322
322
|
return digits.length >= 7 && digits.length <= 20;
|
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":";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,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,KAAK,CAAA,IAAK,KAAA,CAAM,SAAA,CAAU,MAAM,CAAA,KAAM,KAAA,EAAO,OAAO,YAAA,CAAa,KAAK,CAAA;AAE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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). 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 * Personnummer shape: 10 or 12 digit form with optional `-`/`+` separator and\n * a real calendar date, but NO Luhn check. The date check is a real calendar\n * check: a flat day <= 31 would accept \"850230-…\" (Feb 30) and non-leap\n * Feb 29, spending the false-positive budget on dates that can never be\n * issued.\n *\n * This — not the strict validator — is what the personnummer detector runs\n * on. In real customer data people routinely mistype their own personnummer,\n * and a typo lands in the control digit as often as anywhere else; rejecting\n * on Luhn then leaks the single most sensitive identifier Sweden has. With\n * the checksum gone the date check carries the precision burden: it rejects\n * ~96% of arbitrary digit runs on its own (month 1-12, day valid in that\n * month), which is what keeps order ids and account numbers from masking.\n */\nexport function isPersonnummerShape(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 return day >= 1 && day <= daysInMonth(year, month)\n}\n\n/** Samordningsnummer shape: like `isPersonnummerShape` but day has +60. */\nexport function isSamordningsnummerShape(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 return day >= 61 && day - 60 <= daysInMonth(year, month)\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 if (!isPersonnummerShape(value)) 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 if (!isSamordningsnummerShape(value)) 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 isPersonnummerShape,\n isSamordningsnummerShape,\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. On such\n // an engine the fallback is only used when it is SAFE: when the value occurs\n // more than once inside its own match the position is ambiguous, and a wrong\n // guess masks the wrong slice while the value stays in the clear, so the\n // detection is refused loudly instead (see detect() below).\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 // matchAll clones the regex but copies the clone's lastIndex FROM the\n // original, and when the caller's regex already carried the \"d\" flag\n // `scanner` IS the caller's object. A lastIndex their own exec()/test()\n // moved elsewhere would then start the scan mid-string and silently\n // skip every detection before it — a leak. Always restart at zero.\n scanner.lastIndex = 0\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 let start: number\n if (span) {\n start = span[0]\n } else {\n const first = m[0].indexOf(value)\n if (first !== m[0].lastIndexOf(value)) {\n // Fail closed rather than guess: reporting the first occurrence of\n // a repeated group text would have redact() mask the wrong slice\n // and leak the value itself. Only reachable on engines without\n // the \"d\" flag, with a custom pattern whose capture repeats inside\n // its own match.\n throw new Error(\n `maskera: detector \"${label}\" matched a value that occurs more than once inside ` +\n 'its own match, and this engine lacks regex match indices (the \"d\" flag, ' +\n \"Chrome 90 / Safari 15 / Node 16) to tell which occurrence is the value. \" +\n \"Upgrade the runtime, or rewrite the pattern so the captured value appears \" +\n \"only once per match.\",\n )\n }\n start = m.index + first\n }\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 whitespace lookahead accepts a digit OR the `-`/`+` separator: \"811218\n * -9876\" (space before the dash) is a realistic typed form and was the same\n * one-character bypass one step earlier — the run split at the space and both\n * halves were too short to window. The window check in checksumWindowDetector\n * still confines whitespace to the separator position, so \"4711 - 2203\" style\n * table neighbours do not fuse into a candidate.\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 identifiers by sliding a window over every digit run, with no\n * 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 the\n * format check has to carry that weight instead. It can, but only where the\n * format is selective enough: personnummer and samordningsnummer constrain\n * month and day, which rejects ~96% of candidates on its own.\n *\n * Note that personnummer and samordningsnummer deliberately validate on the\n * DATE SHAPE ONLY (isPersonnummerShape), not on the Luhn control digit: in\n * real customer data people mistype their own number, and rejecting on Luhn\n * leaks the very identifier this filter exists to protect. The date check\n * carries the precision burden instead. Measured on 20,000 sentences of\n * number-dense Swedish business text containing no personal identifiers,\n * dropping the boundary costs 0.4 false positives per 100 sentences against\n * 0.1 for the boundary version; the Luhn-free policy spends a little more of\n * that same budget on typo-shaped numbers that happen to parse as dates.\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 * and their checksums.\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 format checks 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/**\n * Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional.\n * Validates on date shape only, NOT Luhn: a mistyped control digit is the most\n * common way a real personnummer appears in customer data, and rejecting it\n * leaks exactly what we are here to mask (see isPersonnummerShape).\n */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummerShape)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. Same no-Luhn policy. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummerShape,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n // Whitespace is tolerated around the dash (\"556036 -0793\"), but a space\n // WITHOUT the dash stays unmatched: that shape is far more often two\n // unrelated numbers than an org number, and Luhn only filters ~92% of them.\n /\\b\\d{6}(?:\\s{1,2}-\\s?|-\\s?)?\\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.\nconst EMAIL_PATTERN = /[\\p{L}\\p{N}._%+-]{1,64}@[\\p{L}\\p{N}.-]{1,255}\\.\\p{L}{2,63}\\b/giu\nconst EMAIL_LOCAL_CHAR = /[\\p{L}\\p{N}._%+-]/u\nconst EMAIL_DOMAIN_CHAR = /[\\p{L}\\p{N}.-]/u\nconst EMAIL_ALNUM = /[\\p{L}\\p{N}]/u\n\n/**\n * E-post: `anna@example.com`, Unicode letters on both sides of the @.\n *\n * Not built with regexDetector, because the bounded quantifiers above\n * reintroduced a leak of their own: a local part or domain LONGER than its\n * window still matches, but only the window was reported and the rest of the\n * address stayed in the clear - \"anna.svensson.\" + 70 x's masked as\n * \"anna.svensson.xxxxxxxx[EPOST_1]\", and `anna@` + \"sub.\"×80 + \"example.com\"\n * masked as \"[EPOST_1].sub.sub…example.com\". So after each match the span is\n * widened to the whole contiguous run: LEFT while the characters belong to\n * the local-part class, RIGHT while they belong to the domain class. The two\n * classes differ (`_`, `%`, `+` are local-only), and which one applies is\n * decided by position, not by where the window was cut: the pattern requires\n * at least one local-part character before the literal `@`, so the match\n * always starts inside the local part and always ends inside the domain, and\n * `@` itself is in neither class - which also bounds each walk at the nearest\n * `@`, keeping detection linear on hostile runs. Over-masking the rest of the\n * run is the right side to err on for a redaction tool: a clipped run is\n * never safe to leave visible, and `resolveOverlaps()` in redact already\n * arbitrates any span this grows into. The one exception is the trailing\n * edge: a \".\" or \"-\" can never end a domain label, so characters like the\n * sentence period in \"mejlar anna@example.com.\" are trimmed back off the\n * span - masking them would mangle the prose around the token for no\n * redaction gain.\n */\nexport const email: Detector = {\n label: \"EPOST\",\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n EMAIL_PATTERN.lastIndex = 0\n for (const m of input.matchAll(EMAIL_PATTERN)) {\n if (m.index === undefined) continue\n let start = m.index\n let end = m.index + m[0].length\n while (start > 0 && EMAIL_LOCAL_CHAR.test(input[start - 1] as string)) start--\n while (end < input.length && EMAIL_DOMAIN_CHAR.test(input[end] as string)) end++\n // Trim trailing \".\" / \"-\" the right walk picked up: they can never end\n // a domain label, so they are punctuation touching the run, not part of\n // the address. The raw match always ends alphanumeric, so this cannot\n // pull the span back inside it.\n while (end > start && !EMAIL_ALNUM.test(input[end - 1] as string)) end--\n out.push({ start, end, value: input.slice(start, end) })\n }\n return out\n },\n}\n\n/**\n * Phone numbers. Swedish: +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. International: a `+<1-3 digit country code>` prefix\n * followed by 6-12 digits with optional spaces/dashes (\"+33 6 12 34 56 78\",\n * \"+47 9123456\"). The `+` is required for the international form — without\n * it a bare digit run is far more often an order id or account number than a\n * foreign phone number, so the unprefixed branch stays Swedish-only.\n * The consumed left guard (capture group carries the value) stops the match\n * from starting inside a longer digit run like \"kundnummer TEST-100200-3000\".\n * Up to three separator characters sit between digits so \"070 - 174 06 58\"\n * (whitespace around the dash) is masked whole instead of leaking its ends.\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]{0,3}\\d){6,8}|\\+\\d{1,3}(?:[\\s-]{0,3}\\d){6,12})\\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}\\s{0,2}-\\s{0,2}\\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}\\s{0,2}-\\s{0,2}\\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/**\n * Contextual domestic account number. Sweden has no single checksum-backed\n * syntax for ordinary bank accounts, so the digit shape alone is much too\n * broad: it also describes customer, order and journal identifiers. Requiring\n * an explicit account label keeps this useful without turning every grouped\n * number into PII. This detector is opt-in for rules-only callers and enabled\n * by the hybrid pipeline, whose input is normally free-form customer text.\n */\nexport const kontonummer = regexDetector(\n \"KONTONUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\\s+nr\\.?)?\\s*[:#-]?\\s*((?:\\d[ -]?){6,19}\\d)\\b/giu,\n (value) => {\n const digits = value.replace(/\\D/g, \"\")\n return digits.length >= 7 && digits.length <= 20\n },\n)\n\n/**\n * Context-labeled journal identifier. The identifier format is provider-\n * specific, but the explicit Swedish field label is strong evidence and keeps\n * checksum-shaped values from being misclassified as payment identifiers.\n */\nexport const journalnummer = regexDetector(\n \"JOURNALNUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:journalnummer|journalnr|journal-id|journalid)\\s*[:#-]?\\s*((?:[\\p{L}\\p{N}]{2,12}[-/]){1,3}[\\p{L}\\p{N}]{2,12}|\\d{5,20})\\b/giu,\n)\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|gången|kajen|stranden|terrassen|leden|stråket|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|GÅNGEN|KAJEN|STRANDEN|TERRASSEN|LEDEN|STRÅKET|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/** Context-dependent formats that are safe only when their label is present. */\nexport const contextualDetectors: Detector[] = [kontonummer, journalnummer]\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// Context-labeled identifiers outrank generic numeric shapes. A Swedish phone\n// number can also have the same ten-digit shape as a samordningsnummer (for\n// example `070174-0658`), so prefer the phone label there: it is the more\n// specific lexical format and avoids reclassifying an ordinary phone number\n// merely because personnummer detection is intentionally typo-tolerant.\nconst SAME_SPAN_PRIORITY: Partial<Record<PiiLabel, number>> = {\n JOURNALNUMMER: -10,\n KONTONUMMER: -10,\n TELEFON: 0,\n PERSONNUMMER: 10,\n SAMORDNINGSNUMMER: 11,\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 const priorityA = SAME_SPAN_PRIORITY[a.label] ?? 5\n const priorityB = SAME_SPAN_PRIORITY[b.label] ?? 5\n if (priorityA !== priorityB) return priorityA - priorityB\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 //\n // The message deliberately reports lengths, not content: `input.slice()`\n // here IS the PII someone is redacting, and an Error message is exactly\n // the kind of string that ends up in crash reporting and log aggregation.\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 `span length is ${d.end - d.start}, value length is ${d.value.length}, and the content differs`,\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 shortestToken = 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 const shortest = Math.min(shortestToken.get(d.label) ?? Infinity, token.length)\n shortestToken.set(d.label, shortest)\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 OF ONE LENGTH,\n // but the colliding tokens in the input need not share the length of\n // the token being probed: counter-shaped placeholders grow with the\n // index (\"[PERSONNUMMER_1001]\" is longer than \"[PERSONNUMMER_1]\"), so\n // dividing by the CURRENT token's length underestimates how many\n // collisions fit - 1000 concatenated short tokens occupy ~17 KB while\n // the bound computed from the longer 1001st token came out below 1000,\n // and redact() threw on an input it should simply have worked through.\n // Dividing by the SHORTEST token this label has produced is the safe\n // bound: it never underestimates the collision count. Past it the\n // placeholder() itself is broken (it ignores the index) and no\n // further index will help.\n if (token.length === 0 || attempts > 8 + input.length / shortest) {\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,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,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ACzB;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). 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 * Personnummer shape: 10 or 12 digit form with optional `-`/`+` separator and\n * a real calendar date, but NO Luhn check. The date check is a real calendar\n * check: a flat day <= 31 would accept \"850230-…\" (Feb 30) and non-leap\n * Feb 29, spending the false-positive budget on dates that can never be\n * issued.\n *\n * This — not the strict validator — is what the personnummer detector runs\n * on. In real customer data people routinely mistype their own personnummer,\n * and a typo lands in the control digit as often as anywhere else; rejecting\n * on Luhn then leaks the single most sensitive identifier Sweden has. With\n * the checksum gone the date check carries the precision burden: it rejects\n * ~96% of arbitrary digit runs on its own (month 1-12, day valid in that\n * month), which is what keeps order ids and account numbers from masking.\n */\nexport function isPersonnummerShape(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 return day >= 1 && day <= daysInMonth(year, month)\n}\n\n/** Samordningsnummer shape: like `isPersonnummerShape` but day has +60. */\nexport function isSamordningsnummerShape(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 return day >= 61 && day - 60 <= daysInMonth(year, month)\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 if (!isPersonnummerShape(value)) 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 if (!isSamordningsnummerShape(value)) 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 isPersonnummerShape,\n isSamordningsnummerShape,\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. On such\n // an engine the fallback is only used when it is SAFE: when the value occurs\n // more than once inside its own match the position is ambiguous, and a wrong\n // guess masks the wrong slice while the value stays in the clear, so the\n // detection is refused loudly instead (see detect() below).\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 // matchAll clones the regex but copies the clone's lastIndex FROM the\n // original, and when the caller's regex already carried the \"d\" flag\n // `scanner` IS the caller's object. A lastIndex their own exec()/test()\n // moved elsewhere would then start the scan mid-string and silently\n // skip every detection before it — a leak. Always restart at zero.\n scanner.lastIndex = 0\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 let start: number\n if (span) {\n start = span[0]\n } else {\n const first = m[0].indexOf(value)\n if (first !== m[0].lastIndexOf(value)) {\n // Fail closed rather than guess: reporting the first occurrence of\n // a repeated group text would have redact() mask the wrong slice\n // and leak the value itself. Only reachable on engines without\n // the \"d\" flag, with a custom pattern whose capture repeats inside\n // its own match.\n throw new Error(\n `maskera: detector \"${label}\" matched a value that occurs more than once inside ` +\n 'its own match, and this engine lacks regex match indices (the \"d\" flag, ' +\n \"Chrome 90 / Safari 15 / Node 16) to tell which occurrence is the value. \" +\n \"Upgrade the runtime, or rewrite the pattern so the captured value appears \" +\n \"only once per match.\",\n )\n }\n start = m.index + first\n }\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 whitespace lookahead accepts a digit OR the `-`/`+` separator: \"811218\n * -9876\" (space before the dash) is a realistic typed form and was the same\n * one-character bypass one step earlier — the run split at the space and both\n * halves were too short to window. The window check in checksumWindowDetector\n * still confines whitespace to the separator position, so \"4711 - 2203\" style\n * table neighbours do not fuse into a candidate.\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 identifiers by sliding a window over every digit run, with no\n * 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 the\n * format check has to carry that weight instead. It can, but only where the\n * format is selective enough: personnummer and samordningsnummer constrain\n * month and day, which rejects ~96% of candidates on its own.\n *\n * Note that personnummer and samordningsnummer deliberately validate on the\n * DATE SHAPE ONLY (isPersonnummerShape), not on the Luhn control digit: in\n * real customer data people mistype their own number, and rejecting on Luhn\n * leaks the very identifier this filter exists to protect. The date check\n * carries the precision burden instead. Measured on 20,000 sentences of\n * number-dense Swedish business text containing no personal identifiers,\n * dropping the boundary costs 0.4 false positives per 100 sentences against\n * 0.1 for the boundary version; the Luhn-free policy spends a little more of\n * that same budget on typo-shaped numbers that happen to parse as dates.\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 * and their checksums.\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 format checks 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/**\n * Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional.\n * Validates on date shape only, NOT Luhn: a mistyped control digit is the most\n * common way a real personnummer appears in customer data, and rejecting it\n * leaks exactly what we are here to mask (see isPersonnummerShape).\n */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummerShape)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. Same no-Luhn policy. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummerShape,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n // Whitespace is tolerated around the dash (\"556036 -0793\"), but a space\n // WITHOUT the dash stays unmatched: that shape is far more often two\n // unrelated numbers than an org number, and Luhn only filters ~92% of them.\n /\\b\\d{6}(?:\\s{1,2}-\\s?|-\\s?)?\\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.\nconst EMAIL_PATTERN = /[\\p{L}\\p{N}._%+-]{1,64}@[\\p{L}\\p{N}.-]{1,255}\\.\\p{L}{2,63}\\b/giu\nconst EMAIL_LOCAL_CHAR = /[\\p{L}\\p{N}._%+-]/u\nconst EMAIL_DOMAIN_CHAR = /[\\p{L}\\p{N}.-]/u\nconst EMAIL_ALNUM = /[\\p{L}\\p{N}]/u\n\n/**\n * E-post: `anna@example.com`, Unicode letters on both sides of the @.\n *\n * Not built with regexDetector, because the bounded quantifiers above\n * reintroduced a leak of their own: a local part or domain LONGER than its\n * window still matches, but only the window was reported and the rest of the\n * address stayed in the clear - \"anna.svensson.\" + 70 x's masked as\n * \"anna.svensson.xxxxxxxx[EPOST_1]\", and `anna@` + \"sub.\"×80 + \"example.com\"\n * masked as \"[EPOST_1].sub.sub…example.com\". So after each match the span is\n * widened to the whole contiguous run: LEFT while the characters belong to\n * the local-part class, RIGHT while they belong to the domain class. The two\n * classes differ (`_`, `%`, `+` are local-only), and which one applies is\n * decided by position, not by where the window was cut: the pattern requires\n * at least one local-part character before the literal `@`, so the match\n * always starts inside the local part and always ends inside the domain, and\n * `@` itself is in neither class - which also bounds each walk at the nearest\n * `@`, keeping detection linear on hostile runs. Over-masking the rest of the\n * run is the right side to err on for a redaction tool: a clipped run is\n * never safe to leave visible, and `resolveOverlaps()` in redact already\n * arbitrates any span this grows into. The one exception is the trailing\n * edge: a \".\" or \"-\" can never end a domain label, so characters like the\n * sentence period in \"mejlar anna@example.com.\" are trimmed back off the\n * span - masking them would mangle the prose around the token for no\n * redaction gain.\n */\nexport const email: Detector = {\n label: \"EPOST\",\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n EMAIL_PATTERN.lastIndex = 0\n for (const m of input.matchAll(EMAIL_PATTERN)) {\n if (m.index === undefined) continue\n let start = m.index\n let end = m.index + m[0].length\n while (start > 0 && EMAIL_LOCAL_CHAR.test(input[start - 1] as string)) start--\n while (end < input.length && EMAIL_DOMAIN_CHAR.test(input[end] as string)) end++\n // Trim trailing \".\" / \"-\" the right walk picked up: they can never end\n // a domain label, so they are punctuation touching the run, not part of\n // the address. The raw match always ends alphanumeric, so this cannot\n // pull the span back inside it.\n while (end > start && !EMAIL_ALNUM.test(input[end - 1] as string)) end--\n out.push({ start, end, value: input.slice(start, end) })\n }\n return out\n },\n}\n\n/**\n * Phone numbers. Swedish: +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. International: a `+<1-3 digit country code>` prefix\n * followed by 6-12 digits with optional spaces/dashes (\"+33 6 12 34 56 78\",\n * \"+47 9123456\"). The `+` is required for the international form — without\n * it a bare digit run is far more often an order id or account number than a\n * foreign phone number, so the unprefixed branch stays Swedish-only.\n * The consumed left guard (capture group carries the value) stops the match\n * from starting inside a longer digit run like \"kundnummer TEST-100200-3000\".\n * Up to three separator characters sit between digits so \"070 - 174 06 58\"\n * (whitespace around the dash) is masked whole instead of leaking its ends.\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]{0,3}\\d){6,8}|\\+\\d{1,3}(?:[\\s-]{0,3}\\d){6,12})\\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}\\s{0,2}-\\s{0,2}\\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}\\s{0,2}-\\s{0,2}\\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/**\n * Contextual domestic account number. Sweden has no single checksum-backed\n * syntax for ordinary bank accounts, so the digit shape alone is much too\n * broad: it also describes customer, order and journal identifiers. Requiring\n * an explicit account label keeps this useful without turning every grouped\n * number into PII. This detector is opt-in for rules-only callers and enabled\n * by the hybrid pipeline, whose input is normally free-form customer text.\n */\n// A clearing number may be written apart from the account by a comma, as in\n// Swedbank's \"8327-9, 123 456 789-0\". The comma must be followed by a space,\n// so a decimal amount (\"12 345,50\") is never read as one account.\nexport const kontonummer = regexDetector(\n \"KONTONUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:bankkonto|kontonummer|utbetalningskonto|konto)(?:\\s+nr\\.?)?\\s*[:#-]?\\s*(\\d{4}(?:\\s?-\\s?\\d)?,\\s+(?:\\d[ -]?){5,14}\\d|(?:\\d[ -]?){6,19}\\d)\\b/giu,\n (value) => {\n const digits = value.replace(/\\D/g, \"\")\n return digits.length >= 7 && digits.length <= 20\n },\n)\n\n/**\n * Context-labeled journal identifier. The identifier format is provider-\n * specific, but the explicit Swedish field label is strong evidence and keeps\n * checksum-shaped values from being misclassified as payment identifiers.\n */\nexport const journalnummer = regexDetector(\n \"JOURNALNUMMER\",\n /(?:^|[^\\p{L}\\p{N}])(?:journalnummer|journalnr|journal-id|journalid)\\s*[:#-]?\\s*((?:[\\p{L}\\p{N}]{2,12}[-/]){1,3}[\\p{L}\\p{N}]{2,12}|\\d{5,20})\\b/giu,\n)\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|gången|kajen|stranden|terrassen|leden|stråket|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|GÅNGEN|KAJEN|STRANDEN|TERRASSEN|LEDEN|STRÅKET|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/** Context-dependent formats that are safe only when their label is present. */\nexport const contextualDetectors: Detector[] = [kontonummer, journalnummer]\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// Context-labeled identifiers outrank generic numeric shapes. A Swedish phone\n// number can also have the same ten-digit shape as a samordningsnummer (for\n// example `070174-0658`), so prefer the phone label there: it is the more\n// specific lexical format and avoids reclassifying an ordinary phone number\n// merely because personnummer detection is intentionally typo-tolerant.\nconst SAME_SPAN_PRIORITY: Partial<Record<PiiLabel, number>> = {\n JOURNALNUMMER: -10,\n KONTONUMMER: -10,\n TELEFON: 0,\n PERSONNUMMER: 10,\n SAMORDNINGSNUMMER: 11,\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 const priorityA = SAME_SPAN_PRIORITY[a.label] ?? 5\n const priorityB = SAME_SPAN_PRIORITY[b.label] ?? 5\n if (priorityA !== priorityB) return priorityA - priorityB\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 //\n // The message deliberately reports lengths, not content: `input.slice()`\n // here IS the PII someone is redacting, and an Error message is exactly\n // the kind of string that ends up in crash reporting and log aggregation.\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 `span length is ${d.end - d.start}, value length is ${d.value.length}, and the content differs`,\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 shortestToken = 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 const shortest = Math.min(shortestToken.get(d.label) ?? Infinity, token.length)\n shortestToken.set(d.label, shortest)\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 OF ONE LENGTH,\n // but the colliding tokens in the input need not share the length of\n // the token being probed: counter-shaped placeholders grow with the\n // index (\"[PERSONNUMMER_1001]\" is longer than \"[PERSONNUMMER_1]\"), so\n // dividing by the CURRENT token's length underestimates how many\n // collisions fit - 1000 concatenated short tokens occupy ~17 KB while\n // the bound computed from the longer 1001st token came out below 1000,\n // and redact() threw on an input it should simply have worked through.\n // Dividing by the SHORTEST token this label has produced is the safe\n // bound: it never underestimates the collision count. Past it the\n // placeholder() itself is broken (it ignores the index) and no\n // further index will help.\n if (token.length === 0 || attempts > 8 + input.length / shortest) {\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"]}
|