@maskera/core 0.4.4 → 0.4.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 +10 -0
- package/dist/index.cjs +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @maskera/core
|
|
2
2
|
|
|
3
|
+
## 0.4.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fix a quadratic-backtracking (ReDoS) blowup in the `EPOST` detector. The local-part and domain quantifiers are now bounded to the RFC 5321 maxima (64, 255 and 63 characters) instead of being unbounded, which caps how far the pattern can backtrack.
|
|
8
|
+
|
|
9
|
+
Any long unbroken run of `[A-Za-z0-9._%+-]` with no `@` after it forced the previous pattern to rescan the run from every start position: a hex digest, a base64url blob or a JWT segment is exactly that shape. A 250 KB input took roughly 57 seconds to scan and 512 KB took nearly four minutes, so a single pasted or submitted blob could stall a browser tab or a request handler. The same input now scans in tens of milliseconds. Ordinary text was never affected, in either direction.
|
|
10
|
+
|
|
11
|
+
Detection behaviour is unchanged for real addresses (verified against 100,000 fuzzed inputs). Only a local part longer than 64 characters differs: its trailing 64 characters are matched rather than the whole run.
|
|
12
|
+
|
|
3
13
|
## 0.4.4
|
|
4
14
|
|
|
5
15
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -82,7 +82,10 @@ var organisationsnummer = regexDetector(
|
|
|
82
82
|
/\b\d{6}[-]?\d{4}\b/g,
|
|
83
83
|
isOrganisationsnummer
|
|
84
84
|
);
|
|
85
|
-
var email = regexDetector(
|
|
85
|
+
var email = regexDetector(
|
|
86
|
+
"EPOST",
|
|
87
|
+
/[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\.[A-Z]{2,63}\b/gi
|
|
88
|
+
);
|
|
86
89
|
var phone = regexDetector(
|
|
87
90
|
"TELEFON",
|
|
88
91
|
/(?:^|[^\d])((?:\+46[\s-]?(?:\(0\)[\s-]?)?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8})\b/g
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":[],"mappings":";;;AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IAAK,CAAA;AACL,MAAA,IAAI,CAAA,GAAI,GAAG,CAAA,IAAK,CAAA;AAAA,IAClB;AACA,IAAA,GAAA,IAAO,CAAA;AACP,IAAA,MAAA,GAAS,CAAC,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,MAAM,EAAA,KAAO,CAAA;AACtB;AAOO,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,KAAA,CAAM,6CAA6C,CAAA;AACnE,EAAA,IAAI,CAAC,GAAG,OAAO,KAAA;AAEf,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,CAAA,CAAE,CAAC,CAAC,CAAA;AACzB,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,CAAA,CA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;AAAA,IACA,GAAA;AAAA,IACA,OAAA,EAAS,CAAC,CAAA,KAAc,OAAA,CAAQ,GAAG,GAAG;AAAA,GACxC;AACF;AAMO,SAAS,OAAA,CAAQ,MAAc,GAAA,EAAqC;AACzE,EAAA,IAAI,GAAA,GAAM,IAAA;AAEV,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAA,CAAE,MAAM,CAAA;AAClE,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,GAAA,GAAM,IAAI,KAAA,CAAM,KAAK,EAAE,IAAA,CAAK,GAAA,CAAI,KAAK,CAAW,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,GAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n regex.lastIndex = 0\n for (const m of input.matchAll(regex)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const value = m[1] ?? m[0]\n if (value.length === 0) continue\n const start = m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = regexDetector(\n \"PERSONNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isPersonnummer,\n)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = regexDetector(\n \"SAMORDNINGSNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\nexport const email = regexDetector(\"EPOST\", /[A-ZÅÄÖ0-9._%+-]+@[A-ZÅÄÖ0-9.-]+\\.[A-Z]{2,}\\b/gi)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/**\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 */\nfunction resolveOverlaps(detections: Detection[]): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n }\n }\n return kept\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n const resolved = resolveOverlaps(detections)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\n for (const d of resolved) {\n const key = `${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 do {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n } while (attempts < 100 && (input.includes(token) || token in map))\n if (input.includes(token) || token in map) {\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 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 let out = text\n // Replace longer tokens first to avoid `[X_1]` clobbering `[X_10]`.\n const tokens = Object.keys(map).sort((a, b) => b.length - a.length)\n for (const token of tokens) {\n out = out.split(token).join(map[token] as string)\n }\n return out\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":[],"mappings":";;;AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IAAK,CAAA;AACL,MAAA,IAAI,CAAA,GAAI,GAAG,CAAA,IAAK,CAAA;AAAA,IAClB;AACA,IAAA,GAAA,IAAO,CAAA;AACP,IAAA,MAAA,GAAS,CAAC,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,MAAM,EAAA,KAAO,CAAA;AACtB;AAOO,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,KAAA,CAAM,6CAA6C,CAAA;AACnE,EAAA,IAAI,CAAC,GAAG,OAAO,KAAA;AAEf,EAAA,MAAM,KAAA,GAAQ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ACA,EAAA,IAAA,IAAQ,KAAA,CAAM,MAAM,IAAI,CAAA;AAExB,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,UAAA;AAAA,IACA,GAAA;AAAA,IACA,OAAA,EAAS,CAAC,CAAA,KAAc,OAAA,CAAQ,GAAG,GAAG;AAAA,GACxC;AACF;AAMO,SAAS,OAAA,CAAQ,MAAc,GAAA,EAAqC;AACzE,EAAA,IAAI,GAAA,GAAM,IAAA;AAEV,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAA,CAAE,MAAM,CAAA;AAClE,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,GAAA,GAAM,IAAI,KAAA,CAAM,KAAK,EAAE,IAAA,CAAK,GAAA,CAAI,KAAK,CAAW,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,GAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n regex.lastIndex = 0\n for (const m of input.matchAll(regex)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const value = m[1] ?? m[0]\n if (value.length === 0) continue\n const start = m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = regexDetector(\n \"PERSONNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isPersonnummer,\n)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = regexDetector(\n \"SAMORDNINGSNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/**\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 */\nfunction resolveOverlaps(detections: Detection[]): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n }\n }\n return kept\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n const resolved = resolveOverlaps(detections)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\n for (const d of resolved) {\n const key = `${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 do {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n } while (attempts < 100 && (input.includes(token) || token in map))\n if (input.includes(token) || token in map) {\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 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 let out = text\n // Replace longer tokens first to avoid `[X_1]` clobbering `[X_10]`.\n const tokens = Object.keys(map).sort((a, b) => b.length - a.length)\n for (const token of tokens) {\n out = out.split(token).join(map[token] as string)\n }\n return out\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -80,7 +80,10 @@ var organisationsnummer = regexDetector(
|
|
|
80
80
|
/\b\d{6}[-]?\d{4}\b/g,
|
|
81
81
|
isOrganisationsnummer
|
|
82
82
|
);
|
|
83
|
-
var email = regexDetector(
|
|
83
|
+
var email = regexDetector(
|
|
84
|
+
"EPOST",
|
|
85
|
+
/[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\.[A-Z]{2,63}\b/gi
|
|
86
|
+
);
|
|
84
87
|
var phone = regexDetector(
|
|
85
88
|
"TELEFON",
|
|
86
89
|
/(?:^|[^\d])((?:\+46[\s-]?(?:\(0\)[\s-]?)?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8})\b/g
|
package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,IAAA;AAEV,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAA,CAAE,MAAM,CAAA;AAClE,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,GAAA,GAAM,IAAI,KAAA,CAAM,KAAK,EAAE,IAAA,CAAK,GAAA,CAAI,KAAK,CAAW,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n regex.lastIndex = 0\n for (const m of input.matchAll(regex)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const value = m[1] ?? m[0]\n if (value.length === 0) continue\n const start = m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = regexDetector(\n \"PERSONNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isPersonnummer,\n)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = regexDetector(\n \"SAMORDNINGSNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\nexport const email = regexDetector(\"EPOST\", /[A-ZÅÄÖ0-9._%+-]+@[A-ZÅÄÖ0-9.-]+\\.[A-Z]{2,}\\b/gi)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/**\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 */\nfunction resolveOverlaps(detections: Detection[]): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n }\n }\n return kept\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n const resolved = resolveOverlaps(detections)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\n for (const d of resolved) {\n const key = `${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 do {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n } while (attempts < 100 && (input.includes(token) || token in map))\n if (input.includes(token) || token in map) {\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 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 let out = text\n // Replace longer tokens first to avoid `[X_1]` clobbering `[X_10]`.\n const tokens = Object.keys(map).sort((a, b) => b.length - a.length)\n for (const token of tokens) {\n out = out.split(token).join(map[token] as string)\n }\n return out\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":[],"mappings":";AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IAAK,CAAA;AACL,MAAA,IAAI,CAAA,GAAI,GAAG,CAAA,IAAK,CAAA;AAAA,IAClB;AACA,IAAA,GAAA,IAAO,CAAA;AACP,IAAA,MAAA,GAAS,CAAC,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,MAAM,EAAA,KAAO,CAAA;AACtB;AAOO,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,KAAA,CAAM,6CAA6C,CAAA;AACnE,EAAA,IAAI,CAAC,GAAG,OAAO,KAAA;AAEf,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,CAAA,CAAE,CAAC,CAAC,CAAA;AACzB,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,CAAA,CAAE,CAAC,CAAC,CAAA;AAEvB,EAAA,IAAI,KAAA,GAAQ,CAAA,IAAK,KAAA,GAAQ,EAAA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G,GAAG;AAAA,GACxC;AACF;AAMO,SAAS,OAAA,CAAQ,MAAc,GAAA,EAAqC;AACzE,EAAA,IAAI,GAAA,GAAM,IAAA;AAEV,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAA,CAAE,MAAM,CAAA;AAClE,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,GAAA,GAAM,IAAI,KAAA,CAAM,KAAK,EAAE,IAAA,CAAK,GAAA,CAAI,KAAK,CAAW,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n regex.lastIndex = 0\n for (const m of input.matchAll(regex)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const value = m[1] ?? m[0]\n if (value.length === 0) continue\n const start = m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = regexDetector(\n \"PERSONNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isPersonnummer,\n)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = regexDetector(\n \"SAMORDNINGSNUMMER\",\n /\\b(?:19|20)?\\d{6}[-+]?\\d{4}\\b/g,\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/**\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 */\nfunction resolveOverlaps(detections: Detection[]): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n }\n }\n return kept\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n const resolved = resolveOverlaps(detections)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\n for (const d of resolved) {\n const key = `${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 do {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n } while (attempts < 100 && (input.includes(token) || token in map))\n if (input.includes(token) || token in map) {\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 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 let out = text\n // Replace longer tokens first to avoid `[X_1]` clobbering `[X_10]`.\n const tokens = Object.keys(map).sort((a, b) => b.length - a.length)\n for (const token of tokens) {\n out = out.split(token).join(map[token] as string)\n }\n return out\n}\n"]}
|