@maskera/core 0.2.1 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +18 -1
- package/dist/index.cjs +21 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +33 -4
- package/dist/index.d.ts +33 -4
- package/dist/index.js +18 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @maskera/core
|
|
2
2
|
|
|
3
|
+
## 0.3.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- The phone detector matches the e-mail-signature style `+46(0)70-123 45 67`
|
|
8
|
+
(parenthesized trunk zero after the country code), found leaking in an
|
|
9
|
+
npm-user-input stress test. Negative guards unchanged: years, reference
|
|
10
|
+
numbers and longer digit runs are still rejected.
|
|
11
|
+
|
|
12
|
+
## 0.3.0
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- 42577d2: New opt-in Swedish heuristic detectors: `adress` (street addresses like "Sankt Eriksgatan 12B"), `lagenhetsnummer` ("lgh 1203") and `regnummer` (registration plates, with currency amounts like "SEK 100" excluded). Exported individually and as the `heuristicDetectors` bundle. They are format-based with no checksum, so `defaultDetectors` is unchanged; enable them with `detectors: [...defaultDetectors, ...heuristicDetectors]`. Previously these lived only in the demo app.
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- 42577d2: Three detector fixes found by stress-testing with real user input: the `EMAIL` regex now matches addresses with å/ä/ö ("åsa.öberg@example.se" was previously split and partially leaked), the `PHONE` regex no longer starts matching inside a longer digit run ("kundnummer 100200-3000" fired a false phone match), and the `ADRESS` heuristic covers all-caps and all-lowercase addresses ("STORGATAN 12", "björkvägen 21") so the house number is no longer left exposed when the NER model only catches the street name.
|
|
21
|
+
|
|
3
22
|
## 0.2.1
|
|
4
23
|
|
|
5
24
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# @maskera/core
|
|
2
2
|
|
|
3
3
|
Swedish-first, **zero-dependency** PII detection & redaction. Runs in the
|
|
4
|
-
browser, Node, and edge runtimes. Part of
|
|
4
|
+
browser, Node, and edge runtimes. Part of
|
|
5
|
+
[maskera](https://github.com/joelhagvall/maskera), live demo at
|
|
6
|
+
[maskera.dev](https://maskera.dev).
|
|
5
7
|
|
|
6
8
|
```bash
|
|
7
9
|
pnpm add @maskera/core
|
|
@@ -44,6 +46,21 @@ a checksum exists, so look-alikes (year ranges, reference numbers) don't fire.
|
|
|
44
46
|
Add your own with `regexDetector` (below); mix and match via
|
|
45
47
|
`options.detectors`.
|
|
46
48
|
|
|
49
|
+
### Opt-in heuristics
|
|
50
|
+
|
|
51
|
+
Three more Swedish detectors ship as `heuristicDetectors` (also exported
|
|
52
|
+
individually): `ADRESS` (`Sankt Eriksgatan 12B`), `LAGENHETSNUMMER`
|
|
53
|
+
(`lgh 1203`) and `REGNUMMER` (`ABC 123`, currency amounts like `SEK 100`
|
|
54
|
+
excluded). They are format-based with no checksum to validate against, so
|
|
55
|
+
they stay out of `defaultDetectors`; enable them when free-text addresses and
|
|
56
|
+
plates matter more than the occasional over-redaction:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { defaultDetectors, heuristicDetectors, redact } from "@maskera/core"
|
|
60
|
+
|
|
61
|
+
redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })
|
|
62
|
+
```
|
|
63
|
+
|
|
47
64
|
## API
|
|
48
65
|
|
|
49
66
|
### `redact(input, options?) => RedactResult`
|
package/dist/index.cjs
CHANGED
|
@@ -82,10 +82,10 @@ var organisationsnummer = regexDetector(
|
|
|
82
82
|
/\b\d{6}[-]?\d{4}\b/g,
|
|
83
83
|
isOrganisationsnummer
|
|
84
84
|
);
|
|
85
|
-
var email = regexDetector("EMAIL",
|
|
85
|
+
var email = regexDetector("EMAIL", /[A-ZÅÄÖ0-9._%+-]+@[A-ZÅÄÖ0-9.-]+\.[A-Z]{2,}\b/gi);
|
|
86
86
|
var phone = regexDetector(
|
|
87
87
|
"PHONE",
|
|
88
|
-
/(?:\+46[\s-]?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8}\b/g
|
|
88
|
+
/(?:^|[^\d])((?:\+46[\s-]?(?:\(0\)[\s-]?)?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8})\b/g
|
|
89
89
|
);
|
|
90
90
|
var postnummer = regexDetector("POSTNUMMER", /\b\d{3}\s?\d{2}\b/g);
|
|
91
91
|
var bankgiro = regexDetector(
|
|
@@ -108,6 +108,21 @@ var ipAddress = regexDetector(
|
|
|
108
108
|
/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g
|
|
109
109
|
);
|
|
110
110
|
var url = regexDetector("URL", /\bhttps?:\/\/[^\s<>")]+/gi);
|
|
111
|
+
var adress = regexDetector(
|
|
112
|
+
"ADRESS",
|
|
113
|
+
/(?:^|[^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
|
|
114
|
+
);
|
|
115
|
+
var lagenhetsnummer = regexDetector(
|
|
116
|
+
"LAGENHETSNUMMER",
|
|
117
|
+
/\b(?:lgh|lägenhet)\.?\s?\d{2,4}\b/gi
|
|
118
|
+
);
|
|
119
|
+
var CURRENCY_CODES = /* @__PURE__ */ new Set(["SEK", "USD", "EUR", "NOK", "DKK", "GBP", "CHF", "JPY", "ISK"]);
|
|
120
|
+
var regnummer = regexDetector(
|
|
121
|
+
"REGNUMMER",
|
|
122
|
+
/\b[A-HJ-PR-UW-Z]{3}\s?\d{2}[A-HJ-PR-UW-Z0-9]\b/g,
|
|
123
|
+
(v) => !CURRENCY_CODES.has(v.slice(0, 3))
|
|
124
|
+
);
|
|
125
|
+
var heuristicDetectors = [adress, lagenhetsnummer, regnummer];
|
|
111
126
|
var defaultDetectors = [
|
|
112
127
|
email,
|
|
113
128
|
url,
|
|
@@ -201,15 +216,18 @@ function restore(text, map) {
|
|
|
201
216
|
return out;
|
|
202
217
|
}
|
|
203
218
|
|
|
219
|
+
exports.adress = adress;
|
|
204
220
|
exports.bankgiro = bankgiro;
|
|
205
221
|
exports.creditCard = creditCard;
|
|
206
222
|
exports.defaultDetectors = defaultDetectors;
|
|
207
223
|
exports.email = email;
|
|
224
|
+
exports.heuristicDetectors = heuristicDetectors;
|
|
208
225
|
exports.iban = iban;
|
|
209
226
|
exports.ipAddress = ipAddress;
|
|
210
227
|
exports.isOrganisationsnummer = isOrganisationsnummer;
|
|
211
228
|
exports.isPersonnummer = isPersonnummer;
|
|
212
229
|
exports.isSamordningsnummer = isSamordningsnummer;
|
|
230
|
+
exports.lagenhetsnummer = lagenhetsnummer;
|
|
213
231
|
exports.luhnValid = luhnValid;
|
|
214
232
|
exports.organisationsnummer = organisationsnummer;
|
|
215
233
|
exports.personnummer = personnummer;
|
|
@@ -219,6 +237,7 @@ exports.postnummer = postnummer;
|
|
|
219
237
|
exports.redact = redact;
|
|
220
238
|
exports.redactFromDetections = redactFromDetections;
|
|
221
239
|
exports.regexDetector = regexDetector;
|
|
240
|
+
exports.regnummer = regnummer;
|
|
222
241
|
exports.restore = restore;
|
|
223
242
|
exports.samordningsnummer = samordningsnummer;
|
|
224
243
|
exports.url = url;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/validators.ts","../src/detectors/index.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AA,IAAA,IAAQ,KAAA,CAAM,KAAA,CAAM,IAAA,EAAM,CAAA,CAAE,KAAK,CAAA;AACjC,IAAA,IAAA,IAAQ,CAAA,CAAE,WAAA;AACV,IAAA,IAAA,GAAO,CAAA,CAAE,GAAA;AAAA,EACX;AACA,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\nexport const email = regexDetector(\"EMAIL\", /\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi)\n\n/** Swedish phone numbers: +46 / 0 prefix, mobile and landline. */\nexport const phone = regexDetector(\n \"PHONE\",\n /(?:\\+46[\\s-]?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8}\\b/g,\n)\n\n/** Postnummer: NNN NN (space optional). */\nexport const postnummer = regexDetector(\"POSTNUMMER\", /\\b\\d{3}\\s?\\d{2}\\b/g)\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: 1-7 digits, dash, single check digit, commonly written with\n * space groups (\"90 19 50-6\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){0,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(\"CREDIT_CARD\", /\\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_ADDRESS\",\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\nexport const url = regexDetector(\"URL\", /\\bhttps?:\\/\\/[^\\s<>\")]+/gi)\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, RedactOptions, RedactResult, Redaction } 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 `[PERSON_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/ner`) 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 // Otherwise a crafted input containing e.g. \"[NAMN_1]\" would collide\n // with a generated placeholder, and restore() would write the real\n // value into positions the author of the input chose. The attempt cap\n // guards against a custom placeholder() that ignores the index.\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))\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,CA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A,EACX;AACA,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.se\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\nexport const email = regexDetector(\"EMAIL\", /[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-123 45 67\" 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 \"PHONE\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/** Postnummer: NNN NN (space optional). */\nexport const postnummer = regexDetector(\"POSTNUMMER\", /\\b\\d{3}\\s?\\d{2}\\b/g)\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: 1-7 digits, dash, single check digit, commonly written with\n * space groups (\"90 19 50-6\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){0,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(\"CREDIT_CARD\", /\\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_ADDRESS\",\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\nexport const url = regexDetector(\"URL\", /\\bhttps?:\\/\\/[^\\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: \"Sankt Eriksgatan 12B\", \"Storvägen 3\". Three case\n * shapes on purpose: chat text writes \"björkvägen 21\" and forms write\n * \"STORGATAN 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 \"Östgötagatan 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, RedactOptions, RedactResult, Redaction } 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 `[PERSON_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 // Otherwise a crafted input containing e.g. \"[NAMN_1]\" would collide\n // with a generated placeholder, and restore() would write the real\n // value into positions the author of the input chose. The attempt cap\n // guards against a custom placeholder() that ignores the index.\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))\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.d.cts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Built-in PII labels. The `string` fallback lets you add custom detectors
|
|
3
3
|
* with arbitrary labels without fighting the type system.
|
|
4
4
|
*/
|
|
5
|
-
type PiiLabel = "PERSONNUMMER" | "SAMORDNINGSNUMMER" | "ORGANISATIONSNUMMER" | "EMAIL" | "PHONE" | "POSTNUMMER" | "BANKGIRO" | "PLUSGIRO" | "IBAN" | "IP_ADDRESS" | "URL" | "CREDIT_CARD" | (string & {});
|
|
5
|
+
type PiiLabel = "PERSONNUMMER" | "SAMORDNINGSNUMMER" | "ORGANISATIONSNUMMER" | "EMAIL" | "PHONE" | "POSTNUMMER" | "BANKGIRO" | "PLUSGIRO" | "IBAN" | "IP_ADDRESS" | "URL" | "CREDIT_CARD" | "ADRESS" | "LAGENHETSNUMMER" | "REGNUMMER" | (string & {});
|
|
6
6
|
/** A raw match found by a detector, before placeholder assignment. */
|
|
7
7
|
interface Detection {
|
|
8
8
|
/** Inclusive start index into the source string. */
|
|
@@ -57,7 +57,7 @@ declare function redact(input: string, options?: RedactOptions): RedactResult;
|
|
|
57
57
|
/**
|
|
58
58
|
* Lower-level entry point: turn a pre-computed list of detections into a
|
|
59
59
|
* {@link RedactResult}. Use this when detections come from somewhere async or
|
|
60
|
-
* external (e.g. an NER model in
|
|
60
|
+
* external (e.g. an NER model in `maskera`) and you want the same stable
|
|
61
61
|
* placeholder + overlap-resolution behaviour as {@link redact}.
|
|
62
62
|
*/
|
|
63
63
|
declare function redactFromDetections(input: string, detections: Detection[], options?: Pick<RedactOptions, "placeholder">): RedactResult;
|
|
@@ -79,7 +79,13 @@ declare const samordningsnummer: Detector;
|
|
|
79
79
|
/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */
|
|
80
80
|
declare const organisationsnummer: Detector;
|
|
81
81
|
declare const email: Detector;
|
|
82
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the
|
|
84
|
+
* e-mail-signature style "+46(0)70-123 45 67" where the trunk zero rides
|
|
85
|
+
* along in parentheses. The consumed left guard (capture group carries the
|
|
86
|
+
* value) stops the match from starting inside a longer digit run like
|
|
87
|
+
* "kundnummer 100200-3000".
|
|
88
|
+
*/
|
|
83
89
|
declare const phone: Detector;
|
|
84
90
|
/** Postnummer: NNN NN (space optional). */
|
|
85
91
|
declare const postnummer: Detector;
|
|
@@ -100,6 +106,29 @@ declare const iban: Detector;
|
|
|
100
106
|
declare const creditCard: Detector;
|
|
101
107
|
declare const ipAddress: Detector;
|
|
102
108
|
declare const url: Detector;
|
|
109
|
+
/**
|
|
110
|
+
* Swedish street address: "Sankt Eriksgatan 12B", "Storvägen 3". Three case
|
|
111
|
+
* shapes on purpose: chat text writes "björkvägen 21" and forms write
|
|
112
|
+
* "STORGATAN 12", and an NER model that only catches the street name would
|
|
113
|
+
* leave the house number exposed. The two-word prefix ("Sankt", "Norra")
|
|
114
|
+
* requires a capital so it never swallows a preceding "på"/"till". The
|
|
115
|
+
* consumed left guard replaces \b, which never matches before Å/Ä/Ö (JS \b
|
|
116
|
+
* is ASCII-only), so "Östgötagatan 15" works too.
|
|
117
|
+
*/
|
|
118
|
+
declare const adress: Detector;
|
|
119
|
+
/** Apartment number: "lgh 1203", "lägenhet 42". */
|
|
120
|
+
declare const lagenhetsnummer: Detector;
|
|
121
|
+
/**
|
|
122
|
+
* Swedish car registration plate: "ABC 123", "ABC12D". The letter set matches
|
|
123
|
+
* what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also
|
|
124
|
+
* filters out most acronym look-alikes.
|
|
125
|
+
*/
|
|
126
|
+
declare const regnummer: Detector;
|
|
127
|
+
/**
|
|
128
|
+
* The opt-in heuristics as one bundle:
|
|
129
|
+
* `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.
|
|
130
|
+
*/
|
|
131
|
+
declare const heuristicDetectors: Detector[];
|
|
103
132
|
/**
|
|
104
133
|
* Default detector set, ordered so that the most specific / highest-confidence
|
|
105
134
|
* detectors run first. Overlap resolution keeps the longest, earliest match.
|
|
@@ -122,4 +151,4 @@ declare function isSamordningsnummer(value: string): boolean;
|
|
|
122
151
|
/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */
|
|
123
152
|
declare function isOrganisationsnummer(value: string): boolean;
|
|
124
153
|
|
|
125
|
-
export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, bankgiro, creditCard, defaultDetectors, email, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, restore, samordningsnummer, url };
|
|
154
|
+
export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, adress, bankgiro, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, samordningsnummer, url };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Built-in PII labels. The `string` fallback lets you add custom detectors
|
|
3
3
|
* with arbitrary labels without fighting the type system.
|
|
4
4
|
*/
|
|
5
|
-
type PiiLabel = "PERSONNUMMER" | "SAMORDNINGSNUMMER" | "ORGANISATIONSNUMMER" | "EMAIL" | "PHONE" | "POSTNUMMER" | "BANKGIRO" | "PLUSGIRO" | "IBAN" | "IP_ADDRESS" | "URL" | "CREDIT_CARD" | (string & {});
|
|
5
|
+
type PiiLabel = "PERSONNUMMER" | "SAMORDNINGSNUMMER" | "ORGANISATIONSNUMMER" | "EMAIL" | "PHONE" | "POSTNUMMER" | "BANKGIRO" | "PLUSGIRO" | "IBAN" | "IP_ADDRESS" | "URL" | "CREDIT_CARD" | "ADRESS" | "LAGENHETSNUMMER" | "REGNUMMER" | (string & {});
|
|
6
6
|
/** A raw match found by a detector, before placeholder assignment. */
|
|
7
7
|
interface Detection {
|
|
8
8
|
/** Inclusive start index into the source string. */
|
|
@@ -57,7 +57,7 @@ declare function redact(input: string, options?: RedactOptions): RedactResult;
|
|
|
57
57
|
/**
|
|
58
58
|
* Lower-level entry point: turn a pre-computed list of detections into a
|
|
59
59
|
* {@link RedactResult}. Use this when detections come from somewhere async or
|
|
60
|
-
* external (e.g. an NER model in
|
|
60
|
+
* external (e.g. an NER model in `maskera`) and you want the same stable
|
|
61
61
|
* placeholder + overlap-resolution behaviour as {@link redact}.
|
|
62
62
|
*/
|
|
63
63
|
declare function redactFromDetections(input: string, detections: Detection[], options?: Pick<RedactOptions, "placeholder">): RedactResult;
|
|
@@ -79,7 +79,13 @@ declare const samordningsnummer: Detector;
|
|
|
79
79
|
/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */
|
|
80
80
|
declare const organisationsnummer: Detector;
|
|
81
81
|
declare const email: Detector;
|
|
82
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the
|
|
84
|
+
* e-mail-signature style "+46(0)70-123 45 67" where the trunk zero rides
|
|
85
|
+
* along in parentheses. The consumed left guard (capture group carries the
|
|
86
|
+
* value) stops the match from starting inside a longer digit run like
|
|
87
|
+
* "kundnummer 100200-3000".
|
|
88
|
+
*/
|
|
83
89
|
declare const phone: Detector;
|
|
84
90
|
/** Postnummer: NNN NN (space optional). */
|
|
85
91
|
declare const postnummer: Detector;
|
|
@@ -100,6 +106,29 @@ declare const iban: Detector;
|
|
|
100
106
|
declare const creditCard: Detector;
|
|
101
107
|
declare const ipAddress: Detector;
|
|
102
108
|
declare const url: Detector;
|
|
109
|
+
/**
|
|
110
|
+
* Swedish street address: "Sankt Eriksgatan 12B", "Storvägen 3". Three case
|
|
111
|
+
* shapes on purpose: chat text writes "björkvägen 21" and forms write
|
|
112
|
+
* "STORGATAN 12", and an NER model that only catches the street name would
|
|
113
|
+
* leave the house number exposed. The two-word prefix ("Sankt", "Norra")
|
|
114
|
+
* requires a capital so it never swallows a preceding "på"/"till". The
|
|
115
|
+
* consumed left guard replaces \b, which never matches before Å/Ä/Ö (JS \b
|
|
116
|
+
* is ASCII-only), so "Östgötagatan 15" works too.
|
|
117
|
+
*/
|
|
118
|
+
declare const adress: Detector;
|
|
119
|
+
/** Apartment number: "lgh 1203", "lägenhet 42". */
|
|
120
|
+
declare const lagenhetsnummer: Detector;
|
|
121
|
+
/**
|
|
122
|
+
* Swedish car registration plate: "ABC 123", "ABC12D". The letter set matches
|
|
123
|
+
* what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also
|
|
124
|
+
* filters out most acronym look-alikes.
|
|
125
|
+
*/
|
|
126
|
+
declare const regnummer: Detector;
|
|
127
|
+
/**
|
|
128
|
+
* The opt-in heuristics as one bundle:
|
|
129
|
+
* `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.
|
|
130
|
+
*/
|
|
131
|
+
declare const heuristicDetectors: Detector[];
|
|
103
132
|
/**
|
|
104
133
|
* Default detector set, ordered so that the most specific / highest-confidence
|
|
105
134
|
* detectors run first. Overlap resolution keeps the longest, earliest match.
|
|
@@ -122,4 +151,4 @@ declare function isSamordningsnummer(value: string): boolean;
|
|
|
122
151
|
/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */
|
|
123
152
|
declare function isOrganisationsnummer(value: string): boolean;
|
|
124
153
|
|
|
125
|
-
export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, bankgiro, creditCard, defaultDetectors, email, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, restore, samordningsnummer, url };
|
|
154
|
+
export { type Detection, type Detector, type PiiLabel, type RedactOptions, type RedactResult, type Redaction, adress, bankgiro, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, samordningsnummer, url };
|
package/dist/index.js
CHANGED
|
@@ -80,10 +80,10 @@ var organisationsnummer = regexDetector(
|
|
|
80
80
|
/\b\d{6}[-]?\d{4}\b/g,
|
|
81
81
|
isOrganisationsnummer
|
|
82
82
|
);
|
|
83
|
-
var email = regexDetector("EMAIL",
|
|
83
|
+
var email = regexDetector("EMAIL", /[A-ZÅÄÖ0-9._%+-]+@[A-ZÅÄÖ0-9.-]+\.[A-Z]{2,}\b/gi);
|
|
84
84
|
var phone = regexDetector(
|
|
85
85
|
"PHONE",
|
|
86
|
-
/(?:\+46[\s-]?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8}\b/g
|
|
86
|
+
/(?:^|[^\d])((?:\+46[\s-]?(?:\(0\)[\s-]?)?|0)(?:7[02369]|[1-9]\d?)(?:[\s-]?\d){6,8})\b/g
|
|
87
87
|
);
|
|
88
88
|
var postnummer = regexDetector("POSTNUMMER", /\b\d{3}\s?\d{2}\b/g);
|
|
89
89
|
var bankgiro = regexDetector(
|
|
@@ -106,6 +106,21 @@ var ipAddress = regexDetector(
|
|
|
106
106
|
/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g
|
|
107
107
|
);
|
|
108
108
|
var url = regexDetector("URL", /\bhttps?:\/\/[^\s<>")]+/gi);
|
|
109
|
+
var adress = regexDetector(
|
|
110
|
+
"ADRESS",
|
|
111
|
+
/(?:^|[^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
|
|
112
|
+
);
|
|
113
|
+
var lagenhetsnummer = regexDetector(
|
|
114
|
+
"LAGENHETSNUMMER",
|
|
115
|
+
/\b(?:lgh|lägenhet)\.?\s?\d{2,4}\b/gi
|
|
116
|
+
);
|
|
117
|
+
var CURRENCY_CODES = /* @__PURE__ */ new Set(["SEK", "USD", "EUR", "NOK", "DKK", "GBP", "CHF", "JPY", "ISK"]);
|
|
118
|
+
var regnummer = regexDetector(
|
|
119
|
+
"REGNUMMER",
|
|
120
|
+
/\b[A-HJ-PR-UW-Z]{3}\s?\d{2}[A-HJ-PR-UW-Z0-9]\b/g,
|
|
121
|
+
(v) => !CURRENCY_CODES.has(v.slice(0, 3))
|
|
122
|
+
);
|
|
123
|
+
var heuristicDetectors = [adress, lagenhetsnummer, regnummer];
|
|
109
124
|
var defaultDetectors = [
|
|
110
125
|
email,
|
|
111
126
|
url,
|
|
@@ -199,6 +214,6 @@ function restore(text, map) {
|
|
|
199
214
|
return out;
|
|
200
215
|
}
|
|
201
216
|
|
|
202
|
-
export { bankgiro, creditCard, defaultDetectors, email, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, restore, samordningsnummer, url };
|
|
217
|
+
export { adress, bankgiro, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, samordningsnummer, url };
|
|
203
218
|
//# sourceMappingURL=index.js.map
|
|
204
219
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":[],"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;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MO,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\nexport const email = regexDetector(\"EMAIL\", /\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b/gi)\n\n/** Swedish phone numbers: +46 / 0 prefix, mobile and landline. */\nexport const phone = regexDetector(\n \"PHONE\",\n /(?:\\+46[\\s-]?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8}\\b/g,\n)\n\n/** Postnummer: NNN NN (space optional). */\nexport const postnummer = regexDetector(\"POSTNUMMER\", /\\b\\d{3}\\s?\\d{2}\\b/g)\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: 1-7 digits, dash, single check digit, commonly written with\n * space groups (\"90 19 50-6\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){0,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(\"CREDIT_CARD\", /\\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_ADDRESS\",\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\nexport const url = regexDetector(\"URL\", /\\bhttps?:\\/\\/[^\\s<>\")]+/gi)\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, RedactOptions, RedactResult, Redaction } 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 `[PERSON_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/ner`) 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 // Otherwise a crafted input containing e.g. \"[NAMN_1]\" would collide\n // with a generated placeholder, and restore() would write the real\n // value into positions the author of the input chose. The attempt cap\n // guards against a custom placeholder() that ignores the index.\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))\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,EAAI,OAAO,KAAA;AACpC,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AAA,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.se\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\nexport const email = regexDetector(\"EMAIL\", /[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-123 45 67\" 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 \"PHONE\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/** Postnummer: NNN NN (space optional). */\nexport const postnummer = regexDetector(\"POSTNUMMER\", /\\b\\d{3}\\s?\\d{2}\\b/g)\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: 1-7 digits, dash, single check digit, commonly written with\n * space groups (\"90 19 50-6\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){0,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(\"CREDIT_CARD\", /\\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_ADDRESS\",\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\nexport const url = regexDetector(\"URL\", /\\bhttps?:\\/\\/[^\\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: \"Sankt Eriksgatan 12B\", \"Storvägen 3\". Three case\n * shapes on purpose: chat text writes \"björkvägen 21\" and forms write\n * \"STORGATAN 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 \"Östgötagatan 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, RedactOptions, RedactResult, Redaction } 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 `[PERSON_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 // Otherwise a crafted input containing e.g. \"[NAMN_1]\" would collide\n // with a generated placeholder, and restore() would write the real\n // value into positions the author of the input chose. The attempt cap\n // guards against a custom placeholder() that ignores the index.\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))\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"]}
|