@maskera/core 0.5.0 → 0.6.0
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 +33 -0
- package/dist/index.cjs +117 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +117 -16
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# @maskera/core
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 977c524: Security hardening of the redaction core and the NER wrapper.
|
|
8
|
+
|
|
9
|
+
- `personnummer` and `samordningsnummer` now also match the space-separated
|
|
10
|
+
form ("900101 2385", "19900101 2385"). A space where the dash goes was a
|
|
11
|
+
one-character bypass of the most sensitive identifier in the set. The space
|
|
12
|
+
is only accepted where the identifier's own separator sits, four digits from
|
|
13
|
+
the end, so two unrelated numbers in a table never fuse into a candidate;
|
|
14
|
+
detections on the eval corpora are unchanged.
|
|
15
|
+
- `regexDetector` reports the capture group's real position via match indices.
|
|
16
|
+
It previously looked the group text up inside the whole match, which points
|
|
17
|
+
at the wrong place whenever that text also occurs earlier in the match, so a
|
|
18
|
+
custom detector could mask the wrong slice and leave the value in the clear.
|
|
19
|
+
- `redact()` and `restore()` no longer cost O(values x text). The placeholder
|
|
20
|
+
collision check is answered per label instead of per value, and `restore()`
|
|
21
|
+
is a single pass over the tokens; 4k distinct values in a 150 KB document
|
|
22
|
+
went from 237 ms to a few ms.
|
|
23
|
+
- `restore()` no longer substitutes inside a value it just inserted, so a value
|
|
24
|
+
that contains another placeholder token survives the round trip.
|
|
25
|
+
- `redactFromDetections()` rejects malformed spans instead of silently
|
|
26
|
+
duplicating text, and a crafted input seeded with placeholder-shaped strings
|
|
27
|
+
no longer makes redaction throw.
|
|
28
|
+
- `createNerRecognizer()` rejects a `minScore` that is not a finite number in
|
|
29
|
+
[0, 1]. `NaN` silently dropped every model detection, which is fail-open.
|
|
30
|
+
- `defaultLabelMap` constrains an unknown model group to a placeholder-safe
|
|
31
|
+
character set, so a third-party model cannot smuggle bracket syntax into the
|
|
32
|
+
redacted text.
|
|
33
|
+
- The whitespace skipped between two pieces of one entity is bounded, which
|
|
34
|
+
also removes a slow path on text extracted from PDFs.
|
|
35
|
+
|
|
3
36
|
## 0.5.0
|
|
4
37
|
|
|
5
38
|
### Minor Changes
|
package/dist/index.cjs
CHANGED
|
@@ -50,16 +50,27 @@ function regexDetector(label, regex, validate) {
|
|
|
50
50
|
if (!regex.global) {
|
|
51
51
|
throw new Error(`Detector "${label}" requires a global ("g") regex`);
|
|
52
52
|
}
|
|
53
|
+
let scanner = regex;
|
|
54
|
+
let hasIndices = regex.flags.includes("d");
|
|
55
|
+
if (!hasIndices) {
|
|
56
|
+
try {
|
|
57
|
+
scanner = new RegExp(regex.source, `${regex.flags}d`);
|
|
58
|
+
hasIndices = true;
|
|
59
|
+
} catch {
|
|
60
|
+
scanner = regex;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
53
63
|
return {
|
|
54
64
|
label,
|
|
55
65
|
detect(input) {
|
|
56
66
|
const out = [];
|
|
57
|
-
|
|
58
|
-
for (const m of input.matchAll(regex)) {
|
|
67
|
+
for (const m of input.matchAll(scanner)) {
|
|
59
68
|
if (m.index === void 0) continue;
|
|
60
|
-
const
|
|
69
|
+
const group = m[1] !== void 0 ? 1 : 0;
|
|
70
|
+
const value = m[group];
|
|
61
71
|
if (value.length === 0) continue;
|
|
62
|
-
const
|
|
72
|
+
const span = hasIndices ? m.indices?.[group] : void 0;
|
|
73
|
+
const start = span ? span[0] : m.index + m[0].indexOf(value);
|
|
63
74
|
if (validate && !validate(value)) continue;
|
|
64
75
|
out.push({ start, end: start + value.length, value });
|
|
65
76
|
}
|
|
@@ -67,8 +78,9 @@ function regexDetector(label, regex, validate) {
|
|
|
67
78
|
}
|
|
68
79
|
};
|
|
69
80
|
}
|
|
70
|
-
var DIGIT_RUN = /\d[\d+-]*\d|\d/g;
|
|
81
|
+
var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0]{1,2}(?=\d))*\d|\d/g;
|
|
71
82
|
var isDigit = (code) => code >= 48 && code <= 57;
|
|
83
|
+
var WS = /\s/;
|
|
72
84
|
function checksumWindowDetector(label, widths, validate) {
|
|
73
85
|
return {
|
|
74
86
|
label,
|
|
@@ -80,11 +92,19 @@ function checksumWindowDetector(label, widths, validate) {
|
|
|
80
92
|
const base = run.index;
|
|
81
93
|
if (base === void 0) continue;
|
|
82
94
|
const offsets = [];
|
|
95
|
+
const spaced = [];
|
|
83
96
|
let digits = "";
|
|
97
|
+
let gapSpaced = false;
|
|
98
|
+
let anySpaced = false;
|
|
84
99
|
for (let i2 = 0; i2 < text.length; i2++) {
|
|
85
100
|
if (isDigit(text.charCodeAt(i2))) {
|
|
86
101
|
offsets.push(base + i2);
|
|
102
|
+
spaced.push(gapSpaced);
|
|
87
103
|
digits += text[i2];
|
|
104
|
+
gapSpaced = false;
|
|
105
|
+
} else if (WS.test(text[i2])) {
|
|
106
|
+
gapSpaced = true;
|
|
107
|
+
anySpaced = true;
|
|
88
108
|
}
|
|
89
109
|
}
|
|
90
110
|
let i = 0;
|
|
@@ -92,6 +112,16 @@ function checksumWindowDetector(label, widths, validate) {
|
|
|
92
112
|
let width = 0;
|
|
93
113
|
for (const w of widths) {
|
|
94
114
|
if (i + w > digits.length) continue;
|
|
115
|
+
if (anySpaced) {
|
|
116
|
+
let ok = true;
|
|
117
|
+
for (let k = i + 1; k < i + w; k++) {
|
|
118
|
+
if (spaced[k] && k !== i + w - 4) {
|
|
119
|
+
ok = false;
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!ok) continue;
|
|
124
|
+
}
|
|
95
125
|
if (!validate(digits.slice(i, i + w))) continue;
|
|
96
126
|
width = w;
|
|
97
127
|
break;
|
|
@@ -213,6 +243,33 @@ function resolveOverlaps(detections, input) {
|
|
|
213
243
|
}
|
|
214
244
|
return kept;
|
|
215
245
|
}
|
|
246
|
+
function tokenKey(label, value) {
|
|
247
|
+
return `${label.length}:${label}:${value}`;
|
|
248
|
+
}
|
|
249
|
+
function createInputProbe(input, placeholder) {
|
|
250
|
+
const prefixes = /* @__PURE__ */ new Map();
|
|
251
|
+
return (label, token) => {
|
|
252
|
+
let entry = prefixes.get(label);
|
|
253
|
+
if (entry === void 0) {
|
|
254
|
+
const first = placeholder(label, 1);
|
|
255
|
+
const second = placeholder(label, 2);
|
|
256
|
+
let n = 0;
|
|
257
|
+
while (n < first.length && n < second.length && first[n] === second[n]) n++;
|
|
258
|
+
const prefix = first.slice(0, n);
|
|
259
|
+
entry = null;
|
|
260
|
+
if (prefix.length > 0) {
|
|
261
|
+
const at = [];
|
|
262
|
+
for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i);
|
|
263
|
+
entry = { prefix, at };
|
|
264
|
+
}
|
|
265
|
+
prefixes.set(label, entry);
|
|
266
|
+
}
|
|
267
|
+
if (entry !== null && token.startsWith(entry.prefix)) {
|
|
268
|
+
return entry.at.some((i) => input.startsWith(token, i));
|
|
269
|
+
}
|
|
270
|
+
return input.includes(token);
|
|
271
|
+
};
|
|
272
|
+
}
|
|
216
273
|
function redact(input, options = {}) {
|
|
217
274
|
const detectors = options.detectors ?? defaultDetectors;
|
|
218
275
|
const all = [];
|
|
@@ -225,26 +282,35 @@ function redact(input, options = {}) {
|
|
|
225
282
|
}
|
|
226
283
|
function redactFromDetections(input, detections, options = {}) {
|
|
227
284
|
const placeholder = options.placeholder ?? defaultPlaceholder;
|
|
285
|
+
for (const d of detections) {
|
|
286
|
+
if (!Number.isInteger(d.start) || !Number.isInteger(d.end) || d.start < 0 || d.end > input.length || d.start >= d.end) {
|
|
287
|
+
throw new Error(
|
|
288
|
+
`maskera: detection span out of range for "${d.label}": [${d.start}, ${d.end}) in an input of length ${input.length}`
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
228
292
|
const resolved = resolveOverlaps(detections, input);
|
|
229
293
|
const counters = /* @__PURE__ */ new Map();
|
|
230
294
|
const tokenByKey = /* @__PURE__ */ new Map();
|
|
231
295
|
const map = {};
|
|
232
296
|
const redactions = [];
|
|
297
|
+
const occursInInput = createInputProbe(input, placeholder);
|
|
233
298
|
for (const d of resolved) {
|
|
234
|
-
const key =
|
|
299
|
+
const key = tokenKey(d.label, d.value);
|
|
235
300
|
let token = tokenByKey.get(key);
|
|
236
301
|
if (!token) {
|
|
237
302
|
let next = counters.get(d.label) ?? 0;
|
|
238
303
|
let attempts = 0;
|
|
239
|
-
|
|
304
|
+
for (; ; ) {
|
|
240
305
|
next += 1;
|
|
241
306
|
token = placeholder(d.label, next);
|
|
242
307
|
attempts += 1;
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
308
|
+
if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break;
|
|
309
|
+
if (token.length === 0 || attempts > 8 + input.length / token.length) {
|
|
310
|
+
throw new Error(
|
|
311
|
+
"maskera: placeholder() must return a token that is unique per (label, index) and does not occur in the input"
|
|
312
|
+
);
|
|
313
|
+
}
|
|
248
314
|
}
|
|
249
315
|
counters.set(d.label, next);
|
|
250
316
|
tokenByKey.set(key, token);
|
|
@@ -268,12 +334,47 @@ function redactFromDetections(input, detections, options = {}) {
|
|
|
268
334
|
};
|
|
269
335
|
}
|
|
270
336
|
function restore(text, map) {
|
|
271
|
-
|
|
272
|
-
|
|
337
|
+
const tokens = Object.keys(map).filter((t) => t.length > 0);
|
|
338
|
+
if (tokens.length === 0) return text;
|
|
339
|
+
const root = { next: /* @__PURE__ */ new Map() };
|
|
273
340
|
for (const token of tokens) {
|
|
274
|
-
|
|
341
|
+
let node = root;
|
|
342
|
+
for (let k = 0; k < token.length; k++) {
|
|
343
|
+
const ch = token[k];
|
|
344
|
+
let child = node.next.get(ch);
|
|
345
|
+
if (!child) {
|
|
346
|
+
child = { next: /* @__PURE__ */ new Map() };
|
|
347
|
+
node.next.set(ch, child);
|
|
348
|
+
}
|
|
349
|
+
node = child;
|
|
350
|
+
}
|
|
351
|
+
node.value = map[token];
|
|
352
|
+
}
|
|
353
|
+
let out = "";
|
|
354
|
+
let last = 0;
|
|
355
|
+
let i = 0;
|
|
356
|
+
while (i < text.length) {
|
|
357
|
+
let node = root.next.get(text[i]);
|
|
358
|
+
let matchEnd = -1;
|
|
359
|
+
let matchValue;
|
|
360
|
+
let j = i;
|
|
361
|
+
while (node) {
|
|
362
|
+
j++;
|
|
363
|
+
if (node.value !== void 0) {
|
|
364
|
+
matchEnd = j;
|
|
365
|
+
matchValue = node.value;
|
|
366
|
+
}
|
|
367
|
+
node = j < text.length ? node.next.get(text[j]) : void 0;
|
|
368
|
+
}
|
|
369
|
+
if (matchValue === void 0) {
|
|
370
|
+
i++;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
out += text.slice(last, i) + matchValue;
|
|
374
|
+
i = matchEnd;
|
|
375
|
+
last = i;
|
|
275
376
|
}
|
|
276
|
-
return out;
|
|
377
|
+
return out + text.slice(last);
|
|
277
378
|
}
|
|
278
379
|
|
|
279
380
|
exports.adress = adress;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";;;AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAA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um, 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/** A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain. */\nconst DIGIT_RUN = /\\d[\\d+-]*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span.\n const offsets: number[] = []\n let digits = \"\"\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n digits += text[i]\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * 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, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\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":["i"],"mappings":";;;AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAA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AAA;AAAA,IACT;AACA,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAI,KAAK,CAAA;AAAA,EACxB;AAEA,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,OAAO,CAAA,GAAI,KAAK,MAAA,EAAQ;AACtB,IAAA,IAAI,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,CAAC,CAAW,CAAA;AAC1C,IAAA,IAAI,QAAA,GAAW,EAAA;AACf,IAAA,IAAI,UAAA;AACJ,IAAA,IAAI,CAAA,GAAI,CAAA;AACR,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,CAAA,EAAA;AACA,MAAA,IAAI,IAAA,CAAK,UAAU,MAAA,EAAW;AAC5B,QAAA,QAAA,GAAW,CAAA;AACX,QAAA,UAAA,GAAa,IAAA,CAAK,KAAA;AAAA,MACpB;AACA,MAAA,IAAA,GAAO,CAAA,GAAI,KAAK,MAAA,GAAS,IAAA,CAAK,KAAK,GAAA,CAAI,IAAA,CAAK,CAAC,CAAW,CAAA,GAAI,MAAA;AAAA,IAC9D;AACA,IAAA,IAAI,eAAe,MAAA,EAAW;AAC5B,MAAA,CAAA,EAAA;AACA,MAAA;AAAA,IACF;AACA,IAAA,GAAA,IAAO,IAAA,CAAK,KAAA,CAAM,IAAA,EAAM,CAAC,CAAA,GAAI,UAAA;AAC7B,IAAA,CAAA,GAAI,QAAA;AACJ,IAAA,IAAA,GAAO,CAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC9B","file":"index.cjs","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n // Match indices (\"d\") give the capture group's real position. Looking the\n // group text up inside m[0] instead (`m[0].indexOf(value)`) finds its first\n // *occurrence*, which is a different place whenever that text also appears\n // earlier in the match: a custom detector like /kontakt (\\S+) mejl \\1/ then\n // reports a span four characters too far left, and redact() masks the wrong\n // slice and leaves the value itself in the clear. The built-in detectors all\n // capture at an unambiguous position, but this is public API.\n //\n // The flag is added to a copy, which also keeps `lastIndex` off the caller's\n // regex. Engines predating the flag (it needs Chrome 90 / Safari 15 / Node\n // 16) throw on construction, and these detectors are built at module scope,\n // so the fallback is what keeps `import` itself from failing there.\n let scanner = regex\n let hasIndices = regex.flags.includes(\"d\")\n if (!hasIndices) {\n try {\n scanner = new RegExp(regex.source, `${regex.flags}d`)\n hasIndices = true\n } catch {\n scanner = regex\n }\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n for (const m of input.matchAll(scanner)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const group = m[1] !== undefined ? 1 : 0\n const value = m[group] as string\n if (value.length === 0) continue\n const span = hasIndices ? (m as MatchWithIndices).indices?.[group] : undefined\n const start = span ? span[0] : m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n/** `RegExpMatchArray.indices` is ES2022; the package compiles against ES2021. */\ntype MatchWithIndices = RegExpMatchArray & {\n indices?: Array<[number, number] | undefined>\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/**\n * A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain\n * and the horizontal whitespace it is routinely typed with (\"811218 9876\",\n * \"19 811218 9876\" in forms and journal notes). Stopping the run at a space\n * made one space a reliable one-character bypass, the same failure the missing\n * word boundary was fixed for. Newlines are NOT included, so two numbers in a\n * column never merge, and the whitespace run is bounded so the pattern cannot\n * backtrack over a long gap.\n */\nconst DIGIT_RUN = /\\d(?:[\\d+-]|[ \\t\\u00a0]{1,2}(?=\\d))*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\nconst WS = /\\s/\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * A run may contain whitespace (\"811218 9876\"), but a window is only allowed to\n * cross it at the position the separator actually belongs, four digits from the\n * end. Anything else would let two unrelated numbers in a table (\"Belopp 4711\n * 220345\") fuse into a candidate, and it is the cheap check that keeps the\n * widened run from spending the false-positive budget the checksum bought.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span. `spaced[k]` records that whitespace sits\n // between digit k-1 and digit k.\n const offsets: number[] = []\n const spaced: boolean[] = []\n let digits = \"\"\n let gapSpaced = false\n let anySpaced = false\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n spaced.push(gapSpaced)\n digits += text[i]\n gapSpaced = false\n } else if (WS.test(text[i] as string)) {\n gapSpaced = true\n anySpaced = true\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n // Whitespace may only sit where the identifier's own separator\n // does: four digits from the end of the window.\n if (anySpaced) {\n let ok = true\n for (let k = i + 1; k < i + w; k++) {\n if (spaced[k] && k !== i + w - 4) {\n ok = false\n break\n }\n }\n if (!ok) continue\n }\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * Key for the stable-placeholder cache. Length-prefixed rather than\n * `${label}::${value}`, which is ambiguous the moment a custom label contains\n * `::`: (\"A::B\", \"c\") and (\"A\", \"B::c\") would share one placeholder, and\n * restore() would then write the first value where the second one stood.\n */\nfunction tokenKey(label: PiiLabel, value: string): string {\n return `${label.length}:${label}:${value}`\n}\n\n/**\n * Answers \"does this generated token already occur in the input?\" without\n * scanning the input once per redacted value.\n *\n * The plain scan is O(values × input): 4k distinct values in a 150 KB log spent\n * 237 ms in this check alone, and both factors grow with the document, so a\n * megabyte-sized log dump (the paste this library exists for) blocks for\n * seconds. The placeholders of one label share a prefix (\"[EPOST_\"), so one\n * scan per label settles all of them: a token carrying that prefix can only\n * occur where the prefix occurs, which is usually nowhere and is a short list\n * even when re-redacting an already redacted document. A token that does not\n * carry the prefix - `placeholder` is an arbitrary caller function, it need not\n * be prefix-stable - still takes the full scan, so the answer stays exact.\n */\nfunction createInputProbe(\n input: string,\n placeholder: (label: PiiLabel, index: number) => string,\n): (label: PiiLabel, token: string) => boolean {\n const prefixes = new Map<PiiLabel, { prefix: string; at: number[] } | null>()\n return (label, token) => {\n let entry = prefixes.get(label)\n if (entry === undefined) {\n const first = placeholder(label, 1)\n const second = placeholder(label, 2)\n let n = 0\n while (n < first.length && n < second.length && first[n] === second[n]) n++\n const prefix = first.slice(0, n)\n entry = null\n if (prefix.length > 0) {\n const at: number[] = []\n for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i)\n entry = { prefix, at }\n }\n prefixes.set(label, entry)\n }\n if (entry !== null && token.startsWith(entry.prefix)) {\n return entry.at.some((i) => input.startsWith(token, i))\n }\n return input.includes(token)\n }\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n // Spans arrive from callers too (`redactWithNer`, anything model-shaped), and\n // a malformed one does not fail loudly on its own: `resolveOverlaps` sorts a\n // reversed span into place and the rebuild loop below then *duplicates* the\n // text between `last` and `r.start` instead of removing it, which is silent\n // corruption of a document someone is redacting. Reject it instead.\n for (const d of detections) {\n if (\n !Number.isInteger(d.start) ||\n !Number.isInteger(d.end) ||\n d.start < 0 ||\n d.end > input.length ||\n d.start >= d.end\n ) {\n throw new Error(\n `maskera: detection span out of range for \"${d.label}\": [${d.start}, ${d.end}) ` +\n `in an input of length ${input.length}`,\n )\n }\n }\n\n const resolved = resolveOverlaps(detections, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n const occursInInput = createInputProbe(input, placeholder)\n\n for (const d of resolved) {\n const key = tokenKey(d.label, d.value)\n let token = tokenByKey.get(key)\n if (!token) {\n // Never hand out a token that already occurs literally in the input\n // (a crafted \"[NAMN_1]\" in the input would collide with a generated\n // placeholder, and restore() would write the real value into positions\n // the author of the input chose), and never a token another value\n // already owns (a custom placeholder() that ignores the index would\n // otherwise silently map two values to one token and corrupt restore).\n let next = counters.get(d.label) ?? 0\n let attempts = 0\n for (;;) {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break\n // Giving up after a fixed number of tries made a crafted input a denial\n // of service: seeding \"[EPOST_1]\"..\"[EPOST_100]\" was enough to make\n // every later redact() throw. An input can only hold\n // input.length / token.length distinct colliding tokens, so past that\n // bound the placeholder() itself is broken (it ignores the index) and\n // no further index will help.\n if (token.length === 0 || attempts > 8 + input.length / token.length) {\n throw new Error(\n \"maskera: placeholder() must return a token that is unique per (label, index) \" +\n \"and does not occur in the input\",\n )\n }\n }\n counters.set(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n const tokens = Object.keys(map).filter((t) => t.length > 0)\n if (tokens.length === 0) return text\n\n // One left-to-right pass over a trie of the tokens, rather than a\n // split/join per token. Two reasons, and the first one is correctness:\n // replacing token by token re-scans text that was already restored, so a\n // value that happens to contain another token (\"Anna [EPOST_1]\" as a NAMN\n // value handed in via redactFromDetections) got substituted a second time\n // and the output was neither the placeholder nor the original. A single pass\n // never revisits what it wrote. The second is cost: split/join is O(tokens ×\n // text), which is the same product that made redaction slow on large logs.\n // Matching the deepest node at each position keeps the old longest-first\n // rule, so `[X_10]` still wins over `[X_1]`.\n const root: TrieNode = { next: new Map() }\n for (const token of tokens) {\n let node = root\n // Indexed by UTF-16 unit, the same way the scan below reads the text: a\n // code-point walk here would key a surrogate pair as one two-unit string\n // and never match.\n for (let k = 0; k < token.length; k++) {\n const ch = token[k] as string\n let child = node.next.get(ch)\n if (!child) {\n child = { next: new Map() }\n node.next.set(ch, child)\n }\n node = child\n }\n node.value = map[token]\n }\n\n let out = \"\"\n let last = 0\n let i = 0\n while (i < text.length) {\n let node = root.next.get(text[i] as string)\n let matchEnd = -1\n let matchValue: string | undefined\n let j = i\n while (node) {\n j++\n if (node.value !== undefined) {\n matchEnd = j\n matchValue = node.value\n }\n node = j < text.length ? node.next.get(text[j] as string) : undefined\n }\n if (matchValue === undefined) {\n i++\n continue\n }\n out += text.slice(last, i) + matchValue\n i = matchEnd\n last = i\n }\n return out + text.slice(last)\n}\n\ntype TrieNode = { value?: string; next: Map<string, TrieNode> }\n"]}
|
package/dist/index.js
CHANGED
|
@@ -48,16 +48,27 @@ function regexDetector(label, regex, validate) {
|
|
|
48
48
|
if (!regex.global) {
|
|
49
49
|
throw new Error(`Detector "${label}" requires a global ("g") regex`);
|
|
50
50
|
}
|
|
51
|
+
let scanner = regex;
|
|
52
|
+
let hasIndices = regex.flags.includes("d");
|
|
53
|
+
if (!hasIndices) {
|
|
54
|
+
try {
|
|
55
|
+
scanner = new RegExp(regex.source, `${regex.flags}d`);
|
|
56
|
+
hasIndices = true;
|
|
57
|
+
} catch {
|
|
58
|
+
scanner = regex;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
51
61
|
return {
|
|
52
62
|
label,
|
|
53
63
|
detect(input) {
|
|
54
64
|
const out = [];
|
|
55
|
-
|
|
56
|
-
for (const m of input.matchAll(regex)) {
|
|
65
|
+
for (const m of input.matchAll(scanner)) {
|
|
57
66
|
if (m.index === void 0) continue;
|
|
58
|
-
const
|
|
67
|
+
const group = m[1] !== void 0 ? 1 : 0;
|
|
68
|
+
const value = m[group];
|
|
59
69
|
if (value.length === 0) continue;
|
|
60
|
-
const
|
|
70
|
+
const span = hasIndices ? m.indices?.[group] : void 0;
|
|
71
|
+
const start = span ? span[0] : m.index + m[0].indexOf(value);
|
|
61
72
|
if (validate && !validate(value)) continue;
|
|
62
73
|
out.push({ start, end: start + value.length, value });
|
|
63
74
|
}
|
|
@@ -65,8 +76,9 @@ function regexDetector(label, regex, validate) {
|
|
|
65
76
|
}
|
|
66
77
|
};
|
|
67
78
|
}
|
|
68
|
-
var DIGIT_RUN = /\d[\d+-]*\d|\d/g;
|
|
79
|
+
var DIGIT_RUN = /\d(?:[\d+-]|[ \t\u00a0]{1,2}(?=\d))*\d|\d/g;
|
|
69
80
|
var isDigit = (code) => code >= 48 && code <= 57;
|
|
81
|
+
var WS = /\s/;
|
|
70
82
|
function checksumWindowDetector(label, widths, validate) {
|
|
71
83
|
return {
|
|
72
84
|
label,
|
|
@@ -78,11 +90,19 @@ function checksumWindowDetector(label, widths, validate) {
|
|
|
78
90
|
const base = run.index;
|
|
79
91
|
if (base === void 0) continue;
|
|
80
92
|
const offsets = [];
|
|
93
|
+
const spaced = [];
|
|
81
94
|
let digits = "";
|
|
95
|
+
let gapSpaced = false;
|
|
96
|
+
let anySpaced = false;
|
|
82
97
|
for (let i2 = 0; i2 < text.length; i2++) {
|
|
83
98
|
if (isDigit(text.charCodeAt(i2))) {
|
|
84
99
|
offsets.push(base + i2);
|
|
100
|
+
spaced.push(gapSpaced);
|
|
85
101
|
digits += text[i2];
|
|
102
|
+
gapSpaced = false;
|
|
103
|
+
} else if (WS.test(text[i2])) {
|
|
104
|
+
gapSpaced = true;
|
|
105
|
+
anySpaced = true;
|
|
86
106
|
}
|
|
87
107
|
}
|
|
88
108
|
let i = 0;
|
|
@@ -90,6 +110,16 @@ function checksumWindowDetector(label, widths, validate) {
|
|
|
90
110
|
let width = 0;
|
|
91
111
|
for (const w of widths) {
|
|
92
112
|
if (i + w > digits.length) continue;
|
|
113
|
+
if (anySpaced) {
|
|
114
|
+
let ok = true;
|
|
115
|
+
for (let k = i + 1; k < i + w; k++) {
|
|
116
|
+
if (spaced[k] && k !== i + w - 4) {
|
|
117
|
+
ok = false;
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!ok) continue;
|
|
122
|
+
}
|
|
93
123
|
if (!validate(digits.slice(i, i + w))) continue;
|
|
94
124
|
width = w;
|
|
95
125
|
break;
|
|
@@ -211,6 +241,33 @@ function resolveOverlaps(detections, input) {
|
|
|
211
241
|
}
|
|
212
242
|
return kept;
|
|
213
243
|
}
|
|
244
|
+
function tokenKey(label, value) {
|
|
245
|
+
return `${label.length}:${label}:${value}`;
|
|
246
|
+
}
|
|
247
|
+
function createInputProbe(input, placeholder) {
|
|
248
|
+
const prefixes = /* @__PURE__ */ new Map();
|
|
249
|
+
return (label, token) => {
|
|
250
|
+
let entry = prefixes.get(label);
|
|
251
|
+
if (entry === void 0) {
|
|
252
|
+
const first = placeholder(label, 1);
|
|
253
|
+
const second = placeholder(label, 2);
|
|
254
|
+
let n = 0;
|
|
255
|
+
while (n < first.length && n < second.length && first[n] === second[n]) n++;
|
|
256
|
+
const prefix = first.slice(0, n);
|
|
257
|
+
entry = null;
|
|
258
|
+
if (prefix.length > 0) {
|
|
259
|
+
const at = [];
|
|
260
|
+
for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i);
|
|
261
|
+
entry = { prefix, at };
|
|
262
|
+
}
|
|
263
|
+
prefixes.set(label, entry);
|
|
264
|
+
}
|
|
265
|
+
if (entry !== null && token.startsWith(entry.prefix)) {
|
|
266
|
+
return entry.at.some((i) => input.startsWith(token, i));
|
|
267
|
+
}
|
|
268
|
+
return input.includes(token);
|
|
269
|
+
};
|
|
270
|
+
}
|
|
214
271
|
function redact(input, options = {}) {
|
|
215
272
|
const detectors = options.detectors ?? defaultDetectors;
|
|
216
273
|
const all = [];
|
|
@@ -223,26 +280,35 @@ function redact(input, options = {}) {
|
|
|
223
280
|
}
|
|
224
281
|
function redactFromDetections(input, detections, options = {}) {
|
|
225
282
|
const placeholder = options.placeholder ?? defaultPlaceholder;
|
|
283
|
+
for (const d of detections) {
|
|
284
|
+
if (!Number.isInteger(d.start) || !Number.isInteger(d.end) || d.start < 0 || d.end > input.length || d.start >= d.end) {
|
|
285
|
+
throw new Error(
|
|
286
|
+
`maskera: detection span out of range for "${d.label}": [${d.start}, ${d.end}) in an input of length ${input.length}`
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
226
290
|
const resolved = resolveOverlaps(detections, input);
|
|
227
291
|
const counters = /* @__PURE__ */ new Map();
|
|
228
292
|
const tokenByKey = /* @__PURE__ */ new Map();
|
|
229
293
|
const map = {};
|
|
230
294
|
const redactions = [];
|
|
295
|
+
const occursInInput = createInputProbe(input, placeholder);
|
|
231
296
|
for (const d of resolved) {
|
|
232
|
-
const key =
|
|
297
|
+
const key = tokenKey(d.label, d.value);
|
|
233
298
|
let token = tokenByKey.get(key);
|
|
234
299
|
if (!token) {
|
|
235
300
|
let next = counters.get(d.label) ?? 0;
|
|
236
301
|
let attempts = 0;
|
|
237
|
-
|
|
302
|
+
for (; ; ) {
|
|
238
303
|
next += 1;
|
|
239
304
|
token = placeholder(d.label, next);
|
|
240
305
|
attempts += 1;
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
306
|
+
if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break;
|
|
307
|
+
if (token.length === 0 || attempts > 8 + input.length / token.length) {
|
|
308
|
+
throw new Error(
|
|
309
|
+
"maskera: placeholder() must return a token that is unique per (label, index) and does not occur in the input"
|
|
310
|
+
);
|
|
311
|
+
}
|
|
246
312
|
}
|
|
247
313
|
counters.set(d.label, next);
|
|
248
314
|
tokenByKey.set(key, token);
|
|
@@ -266,12 +332,47 @@ function redactFromDetections(input, detections, options = {}) {
|
|
|
266
332
|
};
|
|
267
333
|
}
|
|
268
334
|
function restore(text, map) {
|
|
269
|
-
|
|
270
|
-
|
|
335
|
+
const tokens = Object.keys(map).filter((t) => t.length > 0);
|
|
336
|
+
if (tokens.length === 0) return text;
|
|
337
|
+
const root = { next: /* @__PURE__ */ new Map() };
|
|
271
338
|
for (const token of tokens) {
|
|
272
|
-
|
|
339
|
+
let node = root;
|
|
340
|
+
for (let k = 0; k < token.length; k++) {
|
|
341
|
+
const ch = token[k];
|
|
342
|
+
let child = node.next.get(ch);
|
|
343
|
+
if (!child) {
|
|
344
|
+
child = { next: /* @__PURE__ */ new Map() };
|
|
345
|
+
node.next.set(ch, child);
|
|
346
|
+
}
|
|
347
|
+
node = child;
|
|
348
|
+
}
|
|
349
|
+
node.value = map[token];
|
|
350
|
+
}
|
|
351
|
+
let out = "";
|
|
352
|
+
let last = 0;
|
|
353
|
+
let i = 0;
|
|
354
|
+
while (i < text.length) {
|
|
355
|
+
let node = root.next.get(text[i]);
|
|
356
|
+
let matchEnd = -1;
|
|
357
|
+
let matchValue;
|
|
358
|
+
let j = i;
|
|
359
|
+
while (node) {
|
|
360
|
+
j++;
|
|
361
|
+
if (node.value !== void 0) {
|
|
362
|
+
matchEnd = j;
|
|
363
|
+
matchValue = node.value;
|
|
364
|
+
}
|
|
365
|
+
node = j < text.length ? node.next.get(text[j]) : void 0;
|
|
366
|
+
}
|
|
367
|
+
if (matchValue === void 0) {
|
|
368
|
+
i++;
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
out += text.slice(last, i) + matchValue;
|
|
372
|
+
i = matchEnd;
|
|
373
|
+
last = i;
|
|
273
374
|
}
|
|
274
|
-
return out;
|
|
375
|
+
return out + text.slice(last);
|
|
275
376
|
}
|
|
276
377
|
|
|
277
378
|
export { adress, bankgiro, creditCard, defaultDetectors, email, heuristicDetectors, iban, ipAddress, isOrganisationsnummer, isPersonnummer, isSamordningsnummer, lagenhetsnummer, luhnValid, organisationsnummer, personnummer, phone, plusgiro, postnummer, redact, redactFromDetections, regexDetector, regnummer, restore, samordningsnummer, url };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/validators.ts","../src/detectors/index.ts","../src/redact.ts"],"names":["i"],"mappings":";AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IAAK,CAAA;AACL,MAAA,IAAI,CAAA,GAAI,GAAG,CAAA,IAAK,CAAA;AAAA,IAClB;AACA,IAAA,GAAA,IAAO,CAAA;AACP,IAAA,MAAA,GAAS,CAAC,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,MAAM,EAAA,KAAO,CAAA;AACtB;AAOO,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,KAAA,CAAM,6CAA6C,CAAA;AACnE,EAAA,IAAI,CAAC,GAAG,OAAO,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,KAA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A,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.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/** A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain. */\nconst DIGIT_RUN = /\\d[\\d+-]*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span.\n const offsets: number[] = []\n let digits = \"\"\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n digits += text[i]\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * 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, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n\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":["i"],"mappings":";AAIO,SAAS,UAAU,MAAA,EAAyB;AACjD,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAC9B,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,IAAS,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,EAAG,CAAA,IAAK,GAAG,CAAA,EAAA,EAAK;AACzC,IAAA,IAAI,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,GAAI,EAAA;AAC7B,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,CAAA,IAAK,CAAA;AACL,MAAA,IAAI,CAAA,GAAI,GAAG,CAAA,IAAK,CAAA;AAAA,IAClB;AACA,IAAA,GAAA,IAAO,CAAA;AACP,IAAA,MAAA,GAAS,CAAC,MAAA;AAAA,EACZ;AACA,EAAA,OAAO,MAAM,EAAA,KAAO,CAAA;AACtB;AAOO,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,KAAA,CAAM,6CAA6C,CAAA;AACnE,EAAA,IAAI,CAAC,GAAG,OAAO,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,EAAA,IAAI,GAAA,GAAM,CAAA,IAAK,GAAA,GAAM,EAAA,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,CAAI,IAAA,CAAK,CAAC,CAAW,CAAA,GAAI,MAAA;AAAA,IAC9D;AACA,IAAA,IAAI,eAAe,MAAA,EAAW;AAC5B,MAAA,CAAA,EAAA;AACA,MAAA;AAAA,IACF;AACA,IAAA,GAAA,IAAO,IAAA,CAAK,KAAA,CAAM,IAAA,EAAM,CAAC,CAAA,GAAI,UAAA;AAC7B,IAAA,CAAA,GAAI,QAAA;AACJ,IAAA,IAAA,GAAO,CAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC9B","file":"index.js","sourcesContent":["/**\n * Luhn / mod-10 checksum, used by Swedish personnummer, samordningsnummer\n * and organisationsnummer. Operates on the digits only.\n */\nexport function luhnValid(digits: string): boolean {\n const only = digits.replace(/\\D/g, \"\")\n if (only.length === 0) return false\n let sum = 0\n let double = false\n for (let i = only.length - 1; i >= 0; i--) {\n let d = only.charCodeAt(i) - 48\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\n/**\n * Validate a Swedish personnummer.\n * Accepts 10 or 12 digit forms with optional `-`/`+` separator.\n * Checks the date part and the Luhn control digit (on the 10-digit core).\n */\nexport function isPersonnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n // Groups: 1=century? 2=YY 3=MM 4=DD 5=birth+check\n const month = Number(m[3])\n const day = Number(m[4])\n // Day can be 1-31 (personnummer); samordningsnummer adds 60, handled separately.\n if (month < 1 || month > 12) return false\n if (day < 1 || day > 31) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish samordningsnummer: like a personnummer but day has +60. */\nexport function isSamordningsnummer(value: string): boolean {\n const m = value.match(/^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})[-+]?(\\d{4})$/)\n if (!m) return false\n const month = Number(m[3])\n const day = Number(m[4])\n if (month < 1 || month > 12) return false\n if (day < 61 || day > 91) return false\n const core = value.replace(/[-+]/g, \"\").slice(-10)\n return luhnValid(core)\n}\n\n/** Swedish organisationsnummer: 10 digits, third digit >= 2, Luhn valid. */\nexport function isOrganisationsnummer(value: string): boolean {\n const only = value.replace(/\\D/g, \"\")\n const core = only.length === 12 ? only.slice(2) : only\n if (core.length !== 10) return false\n // Third digit of the group number must be >= 2 to distinguish from personnummer.\n if (Number(core[2]) < 2) return false\n return luhnValid(core)\n}\n","import type { Detection, Detector, PiiLabel } from \"../types\"\nimport {\n isOrganisationsnummer,\n isPersonnummer,\n isSamordningsnummer,\n luhnValid,\n} from \"../validators\"\n\ntype RawMatch = Omit<Detection, \"label\">\n\n/**\n * Build a detector from a global regex, with an optional `validate` predicate\n * that can reject false positives (e.g. a number that fails a checksum).\n */\nexport function regexDetector(\n label: PiiLabel,\n regex: RegExp,\n validate?: (value: string) => boolean,\n): Detector {\n if (!regex.global) {\n throw new Error(`Detector \"${label}\" requires a global (\"g\") regex`)\n }\n // Match indices (\"d\") give the capture group's real position. Looking the\n // group text up inside m[0] instead (`m[0].indexOf(value)`) finds its first\n // *occurrence*, which is a different place whenever that text also appears\n // earlier in the match: a custom detector like /kontakt (\\S+) mejl \\1/ then\n // reports a span four characters too far left, and redact() masks the wrong\n // slice and leaves the value itself in the clear. The built-in detectors all\n // capture at an unambiguous position, but this is public API.\n //\n // The flag is added to a copy, which also keeps `lastIndex` off the caller's\n // regex. Engines predating the flag (it needs Chrome 90 / Safari 15 / Node\n // 16) throw on construction, and these detectors are built at module scope,\n // so the fallback is what keeps `import` itself from failing there.\n let scanner = regex\n let hasIndices = regex.flags.includes(\"d\")\n if (!hasIndices) {\n try {\n scanner = new RegExp(regex.source, `${regex.flags}d`)\n hasIndices = true\n } catch {\n scanner = regex\n }\n }\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n for (const m of input.matchAll(scanner)) {\n if (m.index === undefined) continue\n // If the pattern uses a capture group for the actual value, prefer it.\n const group = m[1] !== undefined ? 1 : 0\n const value = m[group] as string\n if (value.length === 0) continue\n const span = hasIndices ? (m as MatchWithIndices).indices?.[group] : undefined\n const start = span ? span[0] : m.index + m[0].indexOf(value)\n if (validate && !validate(value)) continue\n out.push({ start, end: start + value.length, value })\n }\n return out\n },\n }\n}\n\n/** `RegExpMatchArray.indices` is ES2022; the package compiles against ES2021. */\ntype MatchWithIndices = RegExpMatchArray & {\n indices?: Array<[number, number] | undefined>\n}\n\n// --- Swedish structured identifiers --------------------------------------\n\n/**\n * A maximal run of digits, plus the `-`/`+` a Swedish identifier may contain\n * and the horizontal whitespace it is routinely typed with (\"811218 9876\",\n * \"19 811218 9876\" in forms and journal notes). Stopping the run at a space\n * made one space a reliable one-character bypass, the same failure the missing\n * word boundary was fixed for. Newlines are NOT included, so two numbers in a\n * column never merge, and the whitespace run is bounded so the pattern cannot\n * backtrack over a long gap.\n */\nconst DIGIT_RUN = /\\d(?:[\\d+-]|[ \\t\\u00a0]{1,2}(?=\\d))*\\d|\\d/g\n\nconst isDigit = (code: number) => code >= 48 && code <= 57\nconst WS = /\\s/\n\n/**\n * Find checksum-valid identifiers by sliding a window over every digit run,\n * with no word-boundary requirement at all.\n *\n * `\\b` is what a caller uses to slip PII past the filter: appending a single\n * digit to a personnummer took detection from 100% to 0%, reliably, and that is\n * a poor property for the most sensitive identifier Sweden has. The boundary is\n * only load-bearing because a bare digit run is usually an order id, so we let\n * the checksum carry that weight instead. It can, but only where the format is\n * selective enough: personnummer and samordningsnummer also constrain month and\n * day, which rejects ~96% of candidates before Luhn even runs. Measured on\n * 20,000 sentences of number-dense Swedish business text containing no personal\n * identifiers, this costs 0.4 false positives per 100 sentences against 0.1 for\n * the boundary version.\n *\n * Organisationsnummer (only \"third digit >= 2\" plus Luhn) and card numbers (only\n * Luhn) are NOT scanned this way: they fire on ~10% of window positions, which\n * measured at 10 false positives per 100 sentences. They keep their boundaries.\n *\n * A run may contain whitespace (\"811218 9876\"), but a window is only allowed to\n * cross it at the position the separator actually belongs, four digits from the\n * end. Anything else would let two unrelated numbers in a table (\"Belopp 4711\n * 220345\") fuse into a candidate, and it is the cheap check that keeps the\n * widened run from spending the false-positive budget the checksum bought.\n *\n * Widths are tried widest-first and a match consumes its window, so a 12-digit\n * form is never also reported as the 10-digit form hiding inside it.\n */\nfunction checksumWindowDetector(\n label: PiiLabel,\n widths: readonly number[],\n validate: (digits: string) => boolean,\n): Detector {\n return {\n label,\n detect(input: string): RawMatch[] {\n const out: RawMatch[] = []\n DIGIT_RUN.lastIndex = 0\n for (const run of input.matchAll(DIGIT_RUN)) {\n const text = run[0]\n const base = run.index\n if (base === undefined) continue\n // Absolute offset of each digit, so a separator inside the run stays\n // inside the reported span. `spaced[k]` records that whitespace sits\n // between digit k-1 and digit k.\n const offsets: number[] = []\n const spaced: boolean[] = []\n let digits = \"\"\n let gapSpaced = false\n let anySpaced = false\n for (let i = 0; i < text.length; i++) {\n if (isDigit(text.charCodeAt(i))) {\n offsets.push(base + i)\n spaced.push(gapSpaced)\n digits += text[i]\n gapSpaced = false\n } else if (WS.test(text[i] as string)) {\n gapSpaced = true\n anySpaced = true\n }\n }\n let i = 0\n while (i < digits.length) {\n let width = 0\n for (const w of widths) {\n if (i + w > digits.length) continue\n // Whitespace may only sit where the identifier's own separator\n // does: four digits from the end of the window.\n if (anySpaced) {\n let ok = true\n for (let k = i + 1; k < i + w; k++) {\n if (spaced[k] && k !== i + w - 4) {\n ok = false\n break\n }\n }\n if (!ok) continue\n }\n if (!validate(digits.slice(i, i + w))) continue\n width = w\n break\n }\n if (width === 0) {\n i++\n continue\n }\n const start = offsets[i] as number\n const end = (offsets[i + width - 1] as number) + 1\n out.push({ start, end, value: input.slice(start, end) })\n i += width\n }\n }\n return out\n },\n }\n}\n\n/** Personnummer: YYYYMMDD-XXXX / YYMMDD-XXXX, `-` or `+` separator optional. */\nexport const personnummer = checksumWindowDetector(\"PERSONNUMMER\", [12, 10], isPersonnummer)\n\n/** Samordningsnummer: personnummer-shaped but with day + 60. */\nexport const samordningsnummer = checksumWindowDetector(\n \"SAMORDNINGSNUMMER\",\n [12, 10],\n isSamordningsnummer,\n)\n\n/** Organisationsnummer: NNNNNN-NNNN, Luhn-checked, third digit >= 2. */\nexport const organisationsnummer = regexDetector(\n \"ORGANISATIONSNUMMER\",\n /\\b\\d{6}[-]?\\d{4}\\b/g,\n isOrganisationsnummer,\n)\n\n// --- Contact details ------------------------------------------------------\n\n// åäö in both parts: addresses like \"åsa.öberg@example.com\" exist in the wild,\n// and a leading \\b would never match before \"å\" (JS \\b is ASCII-only).\n//\n// The quantifiers are bounded to the RFC 5321 maxima (local part 64 octets,\n// domain 255, DNS label 63) rather than left open. Not for validation: it caps\n// backtracking. `[A-Z0-9._%+-]+@` is quadratic on any long unbroken run of\n// those characters, because every start position consumes the whole run and\n// then backs out one char at a time looking for an `@` that isn't there. A\n// hex digest, a base64url blob or a JWT segment is exactly such a run\n// (base64url's `-` and `_` are both in the class), so a 250 KB paste took ~57 s\n// on the unbounded pattern and ~30 ms bounded. Ordinary prose never noticed,\n// which is precisely why this could sit here unseen.\nexport const email = regexDetector(\n \"EPOST\",\n /[A-ZÅÄÖ0-9._%+-]{1,64}@[A-ZÅÄÖ0-9.-]{1,255}\\.[A-Z]{2,63}\\b/gi,\n)\n\n/**\n * Swedish phone numbers: +46 / 0 prefix, mobile and landline, including the\n * e-mail-signature style \"+46(0)70-174 06 58\" where the trunk zero rides\n * along in parentheses. The consumed left guard (capture group carries the\n * value) stops the match from starting inside a longer digit run like\n * \"kundnummer 100200-3000\".\n */\nexport const phone = regexDetector(\n \"TELEFON\",\n /(?:^|[^\\d])((?:\\+46[\\s-]?(?:\\(0\\)[\\s-]?)?|0)(?:7[02369]|[1-9]\\d?)(?:[\\s-]?\\d){6,8})\\b/g,\n)\n\n/**\n * Postnummer: NNN NN. The spaced form is distinctive enough to match on its\n * own. The compact 5-digit form only matches with context: followed by a\n * capitalized word (\"12345 Staden\") or preceded by an SE- prefix, because\n * a bare digit run is far more often an order id, case number or price than a\n * postal code, and masking those as POSTNUMMER over-redacts everyday text.\n * Swedish postal codes never start with 0.\n */\nexport const postnummer = regexDetector(\n \"POSTNUMMER\",\n /\\b[1-9]\\d{2}\\s\\d{2}\\b|\\b[1-9]\\d{4}\\b(?=\\s+[A-ZÅÄÖ])|(?<=\\bSE-?)[1-9]\\d{2}\\s?\\d{2}\\b/g,\n)\n\n// --- Payment identifiers --------------------------------------------------\n\n/**\n * Bankgiro: NNN-NNNN or NNNN-NNNN, with a mod-10 (Luhn) check digit. The\n * checksum is what separates a real bankgiro from look-alikes such as a year\n * range (\"2019-2024\") or an arbitrary reference id.\n */\nexport const bankgiro = regexDetector(\"BANKGIRO\", /\\b\\d{3,4}-\\d{4}\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/**\n * Plusgiro: 2-7 digits, dash, single check digit, commonly written with\n * space groups (\"92 01 00-5\"). The whole number carries a mod-10 (Luhn)\n * check digit, which filters out look-alikes like list numbering (\"punkt 1-2\").\n * A single-digit body is deliberately NOT matched: ~1 in 9 digit-dash-digit\n * pairs in running text is Luhn-valid by chance (\"3-4\", \"6-7\", match scores,\n * page ranges), which over-masks far more than the vanishingly rare\n * one-digit plusgiro accounts protect.\n */\nexport const plusgiro = regexDetector(\"PLUSGIRO\", /\\b\\d(?:\\s?\\d){1,6}-\\d\\b/g, (v) =>\n luhnValid(v.replace(/\\D/g, \"\")),\n)\n\n/** Swedish IBAN: SE + 22 digits (spaces tolerated). */\nexport const iban = regexDetector(\"IBAN\", /\\bSE\\d{2}(?:\\s?\\d){20}\\b/gi)\n\n// --- Generic / international ----------------------------------------------\n\n// Anchored on a digit at both ends so the captured value can't include a\n// trailing space or dash (the old `(?:\\d[ -]?){13,19}` swallowed the separator).\nexport const creditCard = regexDetector(\"KORTNUMMER\", /\\b\\d(?:[ -]?\\d){12,18}\\b/g, (v) => {\n const digits = v.replace(/\\D/g, \"\")\n return digits.length >= 13 && digits.length <= 19 && luhnValid(digits)\n})\n\nexport const ipAddress = regexDetector(\n \"IP_ADRESS\",\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/g,\n)\n\n// Scheme-less `www.` hosts are matched too: they are everywhere in email\n// signatures (\"www.foretaget.se\") and leak the organisation if left in place.\n// Bare domains without either signal (\"example.com\") are deliberately NOT\n// guessed at: that would over-mask ordinary filenames and abbreviations.\n// The final character class refuses sentence punctuation, so \"se www.x.se.\"\n// keeps its full stop outside the mask (mid-URL dots still match; only a\n// trailing run of `.,;:!?` is backtracked off).\nexport const url = regexDetector(\"URL\", /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\")]*[^\\s<>\").,;:!?]/gi)\n\n// --- Heuristic Swedish detectors (opt-in) ----------------------------------\n//\n// Format-based like `phone` and `postnummer`, but with no checksum to validate\n// against, so they carry a higher false-positive risk than the defaults. They\n// are deliberately NOT part of `defaultDetectors`: add them explicitly via\n// `heuristicDetectors` when free-text addresses and plates matter more than\n// the occasional over-redaction.\n\n/**\n * Swedish street address: \"Påhittsgatan 12B\", \"Maskeravägen 3\". Three case\n * shapes on purpose: chat text writes \"påhittsvägen 21\" and forms write\n * \"PÅHITTSGATAN 12\", and an NER model that only catches the street name would\n * leave the house number exposed. The two-word prefix (\"Sankt\", \"Norra\")\n * requires a capital so it never swallows a preceding \"på\"/\"till\". The\n * consumed left guard replaces \\b, which never matches before Å/Ä/Ö (JS \\b\n * is ASCII-only), so \"Maskeragränd 15\" works too.\n */\nexport const adress = regexDetector(\n \"ADRESS\",\n /(?:^|[^A-Za-zÅÄÖåäö0-9])((?:(?:[A-ZÅÄÖ][a-zåäö]+\\s)?[A-ZÅÄÖa-zåäö][a-zåäö]*(?:gatan|vägen|gränd|gränden|torget|stigen|backen|allén|plan|gata|väg)|[A-ZÅÄÖ]+(?:GATAN|VÄGEN|GRÄND|GRÄNDEN|TORGET|STIGEN|BACKEN|ALLÉN|PLAN|GATA|VÄG))\\s?\\d{1,3}[A-Za-z]?)\\b/g,\n)\n\n/** Apartment number: \"lgh 1203\", \"lägenhet 42\". */\nexport const lagenhetsnummer = regexDetector(\n \"LAGENHETSNUMMER\",\n /\\b(?:lgh|lägenhet)\\.?\\s?\\d{2,4}\\b/gi,\n)\n\n// Amounts like \"SEK 100\" share the plate shape; rejecting currency codes is\n// cheaper than false-positive redactions in every invoice.\nconst CURRENCY_CODES = new Set([\"SEK\", \"USD\", \"EUR\", \"NOK\", \"DKK\", \"GBP\", \"CHF\", \"JPY\", \"ISK\"])\n\n/**\n * Swedish car registration plate: \"ABC 123\", \"ABC12D\". The letter set matches\n * what Transportstyrelsen actually issues (no I, Q, V, Å, Ä, Ö), which also\n * filters out most acronym look-alikes.\n */\nexport const regnummer = regexDetector(\n \"REGNUMMER\",\n /\\b[A-HJ-PR-UW-Z]{3}\\s?\\d{2}[A-HJ-PR-UW-Z0-9]\\b/g,\n (v) => !CURRENCY_CODES.has(v.slice(0, 3)),\n)\n\n/**\n * The opt-in heuristics as one bundle:\n * `redact(text, { detectors: [...defaultDetectors, ...heuristicDetectors] })`.\n */\nexport const heuristicDetectors: Detector[] = [adress, lagenhetsnummer, regnummer]\n\n/**\n * Default detector set, ordered so that the most specific / highest-confidence\n * detectors run first. Overlap resolution keeps the longest, earliest match.\n */\nexport const defaultDetectors: Detector[] = [\n email,\n url,\n personnummer,\n samordningsnummer,\n organisationsnummer,\n iban,\n creditCard,\n bankgiro,\n plusgiro,\n phone,\n postnummer,\n ipAddress,\n]\n","import { defaultDetectors } from \"./detectors\"\nimport type { Detection, PiiLabel, Redaction, RedactOptions, RedactResult } from \"./types\"\n\nfunction defaultPlaceholder(label: PiiLabel, index: number): string {\n return `[${label}_${index}]`\n}\n\n/** A character that can carry meaning on its own, used to trim clipped edges. */\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u\n\n/**\n * Resolve overlapping detections deterministically:\n * keep the earliest start, and among equal starts the longest match.\n * This means e.g. a full IBAN wins over a postnummer hiding inside it.\n *\n * A detection that is *fully* inside a kept one is dropped. One that merely\n * *overlaps* is clipped to the part no earlier detection claimed, rather than\n * dropped: dropping it wholesale leaks the remainder in the clear. Detectors\n * genuinely reach across each other, because `.` and digits belong to the\n * e-mail local part too, so \"4242 4242 4242 4242.anna@example.com\" produces a\n * card span and an e-mail span starting inside it, and the naive rule left the\n * whole address unmasked. Over-masking the clipped remnant is the right side to\n * err on for a redaction tool; `redactWithNer` already clips model spans\n * against rule spans for exactly this reason.\n */\nfunction resolveOverlaps(detections: Detection[], input: string): Detection[] {\n const sorted = [...detections].sort((a, b) => {\n if (a.start !== b.start) return a.start - b.start\n if (b.end - b.start !== a.end - a.start) return b.end - b.start - (a.end - a.start)\n return a.label.localeCompare(b.label)\n })\n const kept: Detection[] = []\n let cursor = -1\n for (const d of sorted) {\n if (d.start >= cursor) {\n kept.push(d)\n cursor = d.end\n continue\n }\n if (d.end <= cursor) continue // wholly inside what we already mask\n // Partial overlap: mask the tail, trimmed to something meaningful. A\n // single leftover character is punctuation or a stray digit, never PII\n // worth a placeholder of its own.\n let start = Math.max(cursor, 0)\n let end = d.end\n while (start < end && !WORD_CHAR.test(input[start] ?? \"\")) start++\n while (end > start && !WORD_CHAR.test(input[end - 1] ?? \"\")) end--\n if (end - start < 2) continue\n kept.push({ ...d, start, end, value: input.slice(start, end) })\n cursor = end\n }\n return kept\n}\n\n/**\n * Key for the stable-placeholder cache. Length-prefixed rather than\n * `${label}::${value}`, which is ambiguous the moment a custom label contains\n * `::`: (\"A::B\", \"c\") and (\"A\", \"B::c\") would share one placeholder, and\n * restore() would then write the first value where the second one stood.\n */\nfunction tokenKey(label: PiiLabel, value: string): string {\n return `${label.length}:${label}:${value}`\n}\n\n/**\n * Answers \"does this generated token already occur in the input?\" without\n * scanning the input once per redacted value.\n *\n * The plain scan is O(values × input): 4k distinct values in a 150 KB log spent\n * 237 ms in this check alone, and both factors grow with the document, so a\n * megabyte-sized log dump (the paste this library exists for) blocks for\n * seconds. The placeholders of one label share a prefix (\"[EPOST_\"), so one\n * scan per label settles all of them: a token carrying that prefix can only\n * occur where the prefix occurs, which is usually nowhere and is a short list\n * even when re-redacting an already redacted document. A token that does not\n * carry the prefix - `placeholder` is an arbitrary caller function, it need not\n * be prefix-stable - still takes the full scan, so the answer stays exact.\n */\nfunction createInputProbe(\n input: string,\n placeholder: (label: PiiLabel, index: number) => string,\n): (label: PiiLabel, token: string) => boolean {\n const prefixes = new Map<PiiLabel, { prefix: string; at: number[] } | null>()\n return (label, token) => {\n let entry = prefixes.get(label)\n if (entry === undefined) {\n const first = placeholder(label, 1)\n const second = placeholder(label, 2)\n let n = 0\n while (n < first.length && n < second.length && first[n] === second[n]) n++\n const prefix = first.slice(0, n)\n entry = null\n if (prefix.length > 0) {\n const at: number[] = []\n for (let i = input.indexOf(prefix); i !== -1; i = input.indexOf(prefix, i + 1)) at.push(i)\n entry = { prefix, at }\n }\n prefixes.set(label, entry)\n }\n if (entry !== null && token.startsWith(entry.prefix)) {\n return entry.at.some((i) => input.startsWith(token, i))\n }\n return input.includes(token)\n }\n}\n\n/**\n * Detect and replace PII in `input`, returning the redacted text plus a\n * restore map. Placeholders are *stable*: the same value always maps to the\n * same token within one call, so an LLM can reason about `[NAMN_1]`\n * consistently and you can map results back afterwards.\n */\nexport function redact(input: string, options: RedactOptions = {}): RedactResult {\n const detectors = options.detectors ?? defaultDetectors\n\n const all: Detection[] = []\n for (const detector of detectors) {\n for (const m of detector.detect(input)) {\n all.push({ ...m, label: detector.label })\n }\n }\n\n return redactFromDetections(input, all, options)\n}\n\n/**\n * Lower-level entry point: turn a pre-computed list of detections into a\n * {@link RedactResult}. Use this when detections come from somewhere async or\n * external (e.g. an NER model in `maskera`) and you want the same stable\n * placeholder + overlap-resolution behaviour as {@link redact}.\n */\nexport function redactFromDetections(\n input: string,\n detections: Detection[],\n options: Pick<RedactOptions, \"placeholder\"> = {},\n): RedactResult {\n const placeholder = options.placeholder ?? defaultPlaceholder\n\n // Spans arrive from callers too (`redactWithNer`, anything model-shaped), and\n // a malformed one does not fail loudly on its own: `resolveOverlaps` sorts a\n // reversed span into place and the rebuild loop below then *duplicates* the\n // text between `last` and `r.start` instead of removing it, which is silent\n // corruption of a document someone is redacting. Reject it instead.\n for (const d of detections) {\n if (\n !Number.isInteger(d.start) ||\n !Number.isInteger(d.end) ||\n d.start < 0 ||\n d.end > input.length ||\n d.start >= d.end\n ) {\n throw new Error(\n `maskera: detection span out of range for \"${d.label}\": [${d.start}, ${d.end}) ` +\n `in an input of length ${input.length}`,\n )\n }\n }\n\n const resolved = resolveOverlaps(detections, input)\n\n // Stable numbering: same value under the same label reuses its placeholder.\n const counters = new Map<PiiLabel, number>()\n const tokenByKey = new Map<string, string>()\n const map: Record<string, string> = {}\n const redactions: Redaction[] = []\n const occursInInput = createInputProbe(input, placeholder)\n\n for (const d of resolved) {\n const key = tokenKey(d.label, d.value)\n let token = tokenByKey.get(key)\n if (!token) {\n // Never hand out a token that already occurs literally in the input\n // (a crafted \"[NAMN_1]\" in the input would collide with a generated\n // placeholder, and restore() would write the real value into positions\n // the author of the input chose), and never a token another value\n // already owns (a custom placeholder() that ignores the index would\n // otherwise silently map two values to one token and corrupt restore).\n let next = counters.get(d.label) ?? 0\n let attempts = 0\n for (;;) {\n next += 1\n token = placeholder(d.label, next)\n attempts += 1\n if (token.length > 0 && !occursInInput(d.label, token) && !(token in map)) break\n // Giving up after a fixed number of tries made a crafted input a denial\n // of service: seeding \"[EPOST_1]\"..\"[EPOST_100]\" was enough to make\n // every later redact() throw. An input can only hold\n // input.length / token.length distinct colliding tokens, so past that\n // bound the placeholder() itself is broken (it ignores the index) and\n // no further index will help.\n if (token.length === 0 || attempts > 8 + input.length / token.length) {\n throw new Error(\n \"maskera: placeholder() must return a token that is unique per (label, index) \" +\n \"and does not occur in the input\",\n )\n }\n }\n counters.set(d.label, next)\n tokenByKey.set(key, token)\n map[token] = d.value\n }\n redactions.push({ ...d, replacement: token })\n }\n\n // Rebuild the string left-to-right.\n let text = \"\"\n let last = 0\n for (const r of redactions) {\n text += input.slice(last, r.start)\n text += r.replacement\n last = r.end\n }\n text += input.slice(last)\n\n return {\n text,\n redactions,\n map,\n restore: (s: string) => restore(s, map),\n }\n}\n\n/**\n * Re-insert original values into a string that contains placeholder tokens.\n * Safe to call on LLM output that echoes the placeholders back.\n */\nexport function restore(text: string, map: Record<string, string>): string {\n const tokens = Object.keys(map).filter((t) => t.length > 0)\n if (tokens.length === 0) return text\n\n // One left-to-right pass over a trie of the tokens, rather than a\n // split/join per token. Two reasons, and the first one is correctness:\n // replacing token by token re-scans text that was already restored, so a\n // value that happens to contain another token (\"Anna [EPOST_1]\" as a NAMN\n // value handed in via redactFromDetections) got substituted a second time\n // and the output was neither the placeholder nor the original. A single pass\n // never revisits what it wrote. The second is cost: split/join is O(tokens ×\n // text), which is the same product that made redaction slow on large logs.\n // Matching the deepest node at each position keeps the old longest-first\n // rule, so `[X_10]` still wins over `[X_1]`.\n const root: TrieNode = { next: new Map() }\n for (const token of tokens) {\n let node = root\n // Indexed by UTF-16 unit, the same way the scan below reads the text: a\n // code-point walk here would key a surrogate pair as one two-unit string\n // and never match.\n for (let k = 0; k < token.length; k++) {\n const ch = token[k] as string\n let child = node.next.get(ch)\n if (!child) {\n child = { next: new Map() }\n node.next.set(ch, child)\n }\n node = child\n }\n node.value = map[token]\n }\n\n let out = \"\"\n let last = 0\n let i = 0\n while (i < text.length) {\n let node = root.next.get(text[i] as string)\n let matchEnd = -1\n let matchValue: string | undefined\n let j = i\n while (node) {\n j++\n if (node.value !== undefined) {\n matchEnd = j\n matchValue = node.value\n }\n node = j < text.length ? node.next.get(text[j] as string) : undefined\n }\n if (matchValue === undefined) {\n i++\n continue\n }\n out += text.slice(last, i) + matchValue\n i = matchEnd\n last = i\n }\n return out + text.slice(last)\n}\n\ntype TrieNode = { value?: string; next: Map<string, TrieNode> }\n"]}
|