euredact 0.1.0 → 0.3.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.
@@ -5,6 +5,11 @@ const validators_js_1 = require("./validators.js");
5
5
  class MultiPatternMatcher {
6
6
  patterns = [];
7
7
  compiled = false;
8
+ addPattern(patternDef, countryCode) {
9
+ const regex = new RegExp(patternDef.pattern, "gu");
10
+ this.patterns.push({ regex, patternDef, countryCode });
11
+ this.compiled = false;
12
+ }
8
13
  addCountry(config) {
9
14
  for (const pdef of config.patterns) {
10
15
  // Convert Python-style \b word boundaries — JS handles them natively
@@ -17,11 +22,13 @@ class MultiPatternMatcher {
17
22
  compile() {
18
23
  this.compiled = true;
19
24
  }
20
- scan(text) {
25
+ scan(text, countryCodes = null) {
21
26
  if (!this.compiled)
22
27
  this.compile();
23
28
  const matches = [];
24
29
  for (const { regex, patternDef, countryCode } of this.patterns) {
30
+ if (countryCodes !== null && !countryCodes.has(countryCode))
31
+ continue;
25
32
  regex.lastIndex = 0;
26
33
  let m;
27
34
  while ((m = regex.exec(text)) !== null) {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.shouldSuppress = shouldSuppress;
4
4
  const types_js_1 = require("../types.js");
5
+ const bicRegistry_js_1 = require("./bicRegistry.js");
5
6
  const CONTEXT_CHARS = 150;
6
7
  function getContext(text, start, end) {
7
8
  const ctxStart = Math.max(0, start - CONTEXT_CHARS);
@@ -21,12 +22,14 @@ const REFERENCE_BEFORE = /(?:dossier|ref\.?|referentie|reference|référence|fac
21
22
  const LEGAL_BEFORE = /(?:Art(?:ikel|icle|\.)|§|Artikel|Section|Sectie|Afdeling|paragraaf|Absatz|alinéa|punt|point|Punkt|lid)\s*$/i;
22
23
  const MATH_BEFORE = /[=+\-×÷*/]\s*$/;
23
24
  const MATH_AFTER = /^\s*[=+\-×÷*/]/;
25
+ // "A-1010", "B-2000", "L-1234", "CH-8000", "D-10115": a country prefix on a
26
+ // postal code, not a minus sign.
27
+ const COUNTRY_PREFIX_HYPHEN = /(?:^|[^A-Za-z0-9])[A-Z]{1,2}-\s*$/;
24
28
  const SEQUENTIAL_PATTERNS = /^(?:0{6,}|1234567890?|0123456789|9876543210?|1111111111?|000000000|123456789)$/;
25
- const YEAR_PATTERN = /^(?:19[4-9]\d|20[0-3]\d)$/;
26
- const DATE_KEYWORD_NEAR = /(?:jaar|year|année|Jahr|datum|date|Datum|in\s+\d{4}|since|sinds|depuis|seit|født|fødselsdato|fødsel|Fødselsdato|född|födelsedatum|födelsedag|syntynyt|syntymäaika|fæddur|fæðingardagur|\d{2}\.\d{2}\.|(?:januar|februar|marts|april|maj|juni|juli|august|september|oktober|november|december|januari|februari|mars|april|mei|juin|juillet|août|Tiltr[æa]delsesdato|Tiltredelsesdato))/i;
29
+ // YEAR_PATTERN kept for reference but replaced by RECENT_YEAR in suppressYearAsPostal
27
30
  const ID_LABEL_BEFORE = /(?:BSN|RR|NN|NIR|INSZ|NISS|NIS|Steuer-?ID|TIN|NIF|NIE|SSN|rijksregisternummer|numéro\s*national|national\s*number|matricule|Ausweisnummer|Personalausweis|Versichertennummer|KVNR|KV-Nr|Steuernummer|St\.\-Nr|StNr|Finanzamt\s+ist|Ondernemingen\s+onder\s+nummer|ondernemingsnummer|numéro\s*d'entreprise|enterprise\s*number|Kruispuntbank)\s*[:.]?\s*$/i;
28
31
  const SERVICE_NUMBER = /^0800[\-\s]/;
29
- const DATE_PATTERN_FULL = /^\d{2}[-/.]\d{2}[-/.]\d{4}$/;
32
+ const DATE_PATTERN_FULL = /^\d{2}[-/.]\d{2}[-/.]\d{4}$|^\d{4}[-/.]\d{2}[-/.]\d{2}$/;
30
33
  const PASSPORT_CONTEXT_BEFORE = /(?:Reisepass|passport|passeport|paspoort|Bisheriger\s+Reisepass)\s*(?:Nr\.?|Nummer|nummer|number|n[°o])?\s*[:.]?\s*$/i;
31
34
  const SE_ORG_CONTEXT_BEFORE = /(?:org\.?\s*nr\.?|organisationsnummer|organisationsnr|Bolagsverket|företag)\s*[:.]?\s*$/i;
32
35
  const NUMERIC_TYPES = new Set([types_js_1.EntityType.PHONE, types_js_1.EntityType.NATIONAL_ID, types_js_1.EntityType.SSN, types_js_1.EntityType.TAX_ID, types_js_1.EntityType.POSTAL_CODE]);
@@ -66,23 +69,40 @@ function suppressMath(text, match) {
66
69
  if (!NUMERIC_TYPES.has(match.patternDef.entityType))
67
70
  return false;
68
71
  const [before, after] = getContext(text, match.start, match.end);
72
+ // A country-prefixed postal code is an address, not a subtraction:
73
+ // "A-1010 Wien", "B-2000 Antwerpen", "D-10115 Berlin".
74
+ if (match.patternDef.entityType === types_js_1.EntityType.POSTAL_CODE && COUNTRY_PREFIX_HYPHEN.test(before)) {
75
+ return false;
76
+ }
69
77
  return MATH_BEFORE.test(before) || MATH_AFTER.test(after);
70
78
  }
71
79
  function suppressSequential(_text, match) {
72
80
  const clean = match.text.replace(/[\s.\-]/g, "");
73
81
  return SEQUENTIAL_PATTERNS.test(clean);
74
82
  }
83
+ const RECENT_YEAR = /^(?:19[5-9]\d|20[0-3]\d)$/;
84
+ const POSTAL_CONTEXT_NEAR = /(?:postcode|postal|code\s*postal|PLZ|Postleitzahl|postnummer|postinumero|póstnúmer|zip|straat|straße|strasse|rue\s|via\s|calle\s|rua\s|ulica|utca|street|avenue|laan\s|weg\s|plein|adres|adresse|address|woonplaats|wonende|woonachtig|gevestigd|domicili|demeurant|résidant|residant|bosatt|bopæl|wohnhaft|ansässig|stad\b|ville\b|city\b|Stadt|città|ciudad|cidade|miasto|město|város)/i;
85
+ const DATE_KEYWORD_NEAR = /(?:født|fødselsdato|fødsel|Fødselsdato|född|födelsedatum|födelsedag|syntynyt|syntymäaika|fæddur|fæðingardagur|geboren|geboortedatum|Geburtsdatum|nascido|nacido|data di nascita|nato il|nata il|Tiltr[æa]delsesdato|Tiltredelsesdato|datum|date\b|Datum|jaar|year|année|Jahr|since|sinds|depuis|seit|\d{2}\.\d{2}\.|(?:januar|februar|marts|april|maj|juni|juli|august|september|oktober|november|december|januari|februari|mars|mei|juin|juillet|août))/i;
75
86
  function suppressYearAsPostal(text, match) {
76
87
  if (match.patternDef.entityType !== types_js_1.EntityType.POSTAL_CODE)
77
88
  return false;
78
89
  const clean = match.text.trim();
79
- if (!YEAR_PATTERN.test(clean))
90
+ if (!RECENT_YEAR.test(clean))
91
+ return false;
92
+ const [before, after] = getContext(text, match.start, match.end);
93
+ const context = before + after;
94
+ // Keep as postal code if postal/address context nearby
95
+ if (POSTAL_CONTEXT_NEAR.test(context))
80
96
  return false;
97
+ // Keep if preceded by comma+space (address pattern: "Amsterdam, 2026")
81
98
  const immediateBefore = text.slice(Math.max(0, match.start - 3), match.start);
82
- if (immediateBefore.endsWith(", ") || immediateBefore.endsWith(",\n"))
99
+ if (/,\s*$/.test(immediateBefore))
83
100
  return false;
84
- const [before, after] = getContext(text, match.start, match.end);
85
- return DATE_KEYWORD_NEAR.test(before + after);
101
+ // Suppress if date keyword nearby (birth date, employment date, etc.)
102
+ if (DATE_KEYWORD_NEAR.test(context))
103
+ return true;
104
+ // Suppress: recent years without postal context are almost never postal codes
105
+ return true;
86
106
  }
87
107
  function suppressPhoneAfterIdLabel(text, match) {
88
108
  if (match.patternDef.entityType !== types_js_1.EntityType.PHONE)
@@ -104,9 +124,13 @@ const NOT_CITY_CODES = new Set([
104
124
  "ID", "NR", "NO", "ST", "DR", "MR", "MS", "HR", "FR", "IM", "IN", "OR", "IF", "IS", "IT", "AT", "AD", "AG", "AV",
105
125
  "BE", "DE", "EU", "NL", "LU", "WS", "SS", "IP",
106
126
  ]);
127
+ const CURRENCY_PLATE = /^(?:EUR|USD|GBP|CHF|SEK|NOK|DKK|ISK|CZK|PLN|HUF|RON|BGN|HRK)\s/i;
107
128
  function suppressPlateInCompound(text, match) {
108
129
  if (match.patternDef.entityType !== types_js_1.EntityType.LICENSE_PLATE)
109
130
  return false;
131
+ // Suppress currency + number misread as plate (e.g. "EUR 2")
132
+ if (CURRENCY_PLATE.test(match.text))
133
+ return true;
110
134
  if (match.start >= 3) {
111
135
  const before = text.slice(Math.max(0, match.start - 10), match.start);
112
136
  if (/[A-Za-zÄÖÜäöüß]{2,}-$/.test(before))
@@ -178,6 +202,218 @@ function suppressPostalAsHouseNumber(text, match) {
178
202
  }
179
203
  return false;
180
204
  }
205
+ // ── BIC: banking-context cues and heading shapes ────────────────────────
206
+ // \bSWIFT\b also covers SWIFT-Code / SWIFT-BIC / Code SWIFT, and \bBIC\b
207
+ // covers BIC-code / BIC/SWIFT.
208
+ const BIC_KEYWORD = /\b(?:BIC|SWIFT)\b/i;
209
+ const BANK_BLOCK = /\b(?:IBAN|Bankverbindung|Bankgegevens|Bankrekening|Rekening(?:nummer)?|Kontonummer|Konto|Kontoinhaber|Compte|Coordonn[ée]es\s+bancaires|Banque|Account\s+(?:number|holder)|Bankleitzahl|BLZ|Betaalgegevens|Zahlungsdaten)\b/i;
210
+ // A line that is nothing but a BIC/SWIFT label, as used in table and column
211
+ // layouts where the code sits on the following line.
212
+ const BIC_LABEL_LINE = /^\s*(?:BIC|SWIFT|SWIFT[-\s]?BIC|BIC\s?\/\s?SWIFT|SWIFT[-\s]?Code|BIC[-\s]?code|Code\s+SWIFT)\s*:?\s*$/i;
213
+ // An IBAN in the same structural unit: CC + 2 check digits + 2 or more groups.
214
+ const IBAN_SHAPE = /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,}/;
215
+ // Largest paragraph still treated as one structural unit. Beyond this the unit
216
+ // falls back to the enclosing line, so a run-on document body cannot lend
217
+ // banking context to a token 2,000 characters away.
218
+ const MAX_UNIT_CHARS = 600;
219
+ function enclosingLine(text, start, end) {
220
+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;
221
+ let lineEnd = text.indexOf("\n", end);
222
+ if (lineEnd === -1)
223
+ lineEnd = text.length;
224
+ return [lineStart, lineEnd];
225
+ }
226
+ /**
227
+ * Return the enclosing line / record / paragraph around a match.
228
+ *
229
+ * The context window for BIC is scoped structurally, not by character count.
230
+ * A tight character window measured on the corpus rejects 97.3% of dictionary
231
+ * false positives but wrongly discards ~316 real-looking codes, because the
232
+ * banking cue often sits further away in the same record — e.g. a CSV row
233
+ * carrying the IBAN in one field and the BIC several fields later.
234
+ */
235
+ function structuralUnit(text, start, end) {
236
+ const [lineStart, lineEnd] = enclosingLine(text, start, end);
237
+ let paraStart = lineStart;
238
+ while (paraStart > 0) {
239
+ const prevEnd = paraStart - 1;
240
+ const prevStart = text.lastIndexOf("\n", prevEnd - 1) + 1;
241
+ if (text.slice(prevStart, prevEnd).trim() === "")
242
+ break;
243
+ paraStart = prevStart;
244
+ }
245
+ let paraEnd = lineEnd;
246
+ while (paraEnd < text.length) {
247
+ const nextStart = paraEnd + 1;
248
+ let nextEnd = text.indexOf("\n", nextStart);
249
+ if (nextEnd === -1)
250
+ nextEnd = text.length;
251
+ if (text.slice(nextStart, nextEnd).trim() === "")
252
+ break;
253
+ paraEnd = nextEnd;
254
+ }
255
+ if (paraEnd - paraStart <= MAX_UNIT_CHARS)
256
+ return text.slice(paraStart, paraEnd);
257
+ return text.slice(lineStart, lineEnd);
258
+ }
259
+ function previousNonblankLine(text, lineStart) {
260
+ let pos = lineStart;
261
+ while (pos > 0) {
262
+ const prevEnd = pos - 1;
263
+ const prevStart = text.lastIndexOf("\n", prevEnd - 1) + 1;
264
+ const line = text.slice(prevStart, prevEnd);
265
+ if (line.trim() !== "")
266
+ return line;
267
+ pos = prevStart;
268
+ }
269
+ return "";
270
+ }
271
+ function escapeRe(s) {
272
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
273
+ }
274
+ /**
275
+ * Does `token` also occur as an ordinary lowercase word in this document?
276
+ *
277
+ * `hospital`/`HOSPITAL`, `gegevens`/`GEGEVENS` — a token that appears in
278
+ * ordinary case elsewhere in the same document is a word, not a bank code.
279
+ * Email and domain contexts are excluded, so `ing.nl` does not vouch for a
280
+ * heading. Measured on the corpus this alone identifies ~78% of the BIC false
281
+ * positives with no dictionaries and no labelled data.
282
+ */
283
+ function occursAsLowercaseWord(text, token) {
284
+ if (!/^[A-Za-z]+$/.test(token))
285
+ return false;
286
+ const lower = token.toLowerCase();
287
+ const capitalised = lower[0].toUpperCase() + lower.slice(1);
288
+ for (const form of [lower, capitalised]) {
289
+ // Cheap pre-check: a plain substring test almost always answers "no".
290
+ if (!text.includes(form))
291
+ continue;
292
+ const re = new RegExp(`\\b${escapeRe(form)}\\b`, "g");
293
+ let m;
294
+ while ((m = re.exec(text)) !== null) {
295
+ const before = m.index > 0 ? text[m.index - 1] : "";
296
+ const after = text.slice(m.index + form.length, m.index + form.length + 8);
297
+ if (before === "@" || (before === "." && m.index >= 2 && /[A-Za-z0-9]/.test(text[m.index - 2])))
298
+ continue;
299
+ if (after.startsWith("@") || /^\.[a-zA-Z]{2,6}\b/.test(after))
300
+ continue;
301
+ return true;
302
+ }
303
+ }
304
+ return false;
305
+ }
306
+ /**
307
+ * Is the candidate positioned as a section heading rather than a value?
308
+ * Headings and shouted words are never bank codes. Lines carrying an explicit
309
+ * BIC/SWIFT keyword are exempt from the all-caps rule, so a genuine
310
+ * `BIC: GEBABEBB` line is not mistaken for a heading.
311
+ */
312
+ function isHeadingShape(text, start, end, token) {
313
+ const [lineStart, lineEnd] = enclosingLine(text, start, end);
314
+ const line = text.slice(lineStart, lineEnd);
315
+ // The token is the entire line — unless the line above is a bare BIC/SWIFT
316
+ // label, which makes this a labelled value in a table layout, not a heading.
317
+ if (line.trim() === token) {
318
+ return !BIC_LABEL_LINE.test(previousNonblankLine(text, lineStart));
319
+ }
320
+ // The token starts its line and is immediately followed by a colon
321
+ if (text.slice(lineStart, start).trim() === "" && text.slice(end, lineEnd).trimStart().startsWith(":")) {
322
+ return true;
323
+ }
324
+ // A shouted line: no lowercase, no digits, and no banking keyword
325
+ if (!/[a-z]/.test(line) && !/\d/.test(line) && !BIC_KEYWORD.test(line))
326
+ return true;
327
+ return false;
328
+ }
329
+ /**
330
+ * Emit a BIC only on registry membership or banking context.
331
+ *
332
+ * 0. the token also occurs as an ordinary lowercase word here -> reject;
333
+ * 1. registry hit (deployment-supplied, then bundled seed prefixes) -> emit;
334
+ * 2. heading / shouted-word shape -> reject;
335
+ * 3. BIC/SWIFT keyword, IBAN or bank block in the structural unit -> emit;
336
+ *
337
+ * and a bare shape match reaching the end with none of the above is never
338
+ * emitted. Gate 0 outranks every tier below it — no genuine BIC is also an
339
+ * ordinary lowercase word — so it is applied on both emitting paths. It scans
340
+ * the whole document, so it runs only on the paths that would otherwise emit.
341
+ */
342
+ function suppressBicWithoutEvidence(text, match) {
343
+ if (match.patternDef.entityType !== types_js_1.EntityType.BIC)
344
+ return false;
345
+ const token = match.text.trim();
346
+ if ((0, bicRegistry_js_1.isRegisteredBic)(token))
347
+ return occursAsLowercaseWord(text, token);
348
+ if (isHeadingShape(text, match.start, match.end, token))
349
+ return true;
350
+ // The token itself is blanked out so it cannot vouch for itself.
351
+ const unit = structuralUnit(text, match.start, match.end).split(token).join(" ".repeat(token.length));
352
+ if (BIC_KEYWORD.test(unit) || IBAN_SHAPE.test(unit) || BANK_BLOCK.test(unit)) {
353
+ return occursAsLowercaseWord(text, token);
354
+ }
355
+ return true;
356
+ }
357
+ // ── Postal code: digits belonging to a longer identifier ────────────────
358
+ // An identifier label immediately before the digits. A postal code is never
359
+ // introduced this way; an SVNr, policy number or service number always is.
360
+ const ID_CUE_BEFORE = /(?:[\w\-]*Nr|[\w\-]*N[°ºo]|[\w\-]*Nummer|[\w\-]*Numero|[\w\-]*Numéro|No|number|num|Kennzahl|Aktenzeichen|Az|e-?card|Polizze|Police|Policen)\.?\s*:?\s*$/i;
361
+ // An international dialling prefix earlier on the same line, with nothing but
362
+ // number punctuation in between: these digits belong to the phone detector.
363
+ const DIALLING_PREFIX_BEFORE = /\+\d{1,3}[\d\s\-().]*$/;
364
+ // A country prefix on a postal code — "A-1010 Wien", "B-2000", "L-1234".
365
+ const COUNTRY_PREFIXED = /(?:^|[^A-Za-z0-9])[A-Z]{1,2}$/;
366
+ /**
367
+ * Suppress bare digit runs that belong to a longer number, not an address.
368
+ *
369
+ * A bare 4- or 5-digit run is the weakest shape in the engine, and when it
370
+ * cuts into a longer identifier the damage is worse than a plain false
371
+ * positive: `SV-Nummer: [POSTAL_CODE] 040390` leaves half an Austrian social
372
+ * security number exposed with no way to label the remainder.
373
+ *
374
+ * Applies only to digits-only matches, so structured forms keep their own
375
+ * behaviour — NL `1234 AB`, PT `1234-567`, LU `L-1234`.
376
+ */
377
+ function suppressPostalInLongerIdentifier(text, match) {
378
+ if (match.patternDef.entityType !== types_js_1.EntityType.POSTAL_CODE)
379
+ return false;
380
+ const clean = match.text.trim();
381
+ if (!/^\d+$/.test(clean))
382
+ return false;
383
+ const beforeChar = match.start > 0 ? text[match.start - 1] : "";
384
+ const afterChar = match.end < text.length ? text[match.end] : "";
385
+ const prevPrev = match.start >= 2 ? text[match.start - 2] : "";
386
+ const nextNext = match.end + 1 < text.length ? text[match.end + 1] : "";
387
+ // Directly glued to more digits
388
+ if (/\d/.test(beforeChar) || /\d/.test(afterChar))
389
+ return true;
390
+ // Joined by identifier punctuation: "0456.2398.71-02", "4471/2025".
391
+ // The punctuation only counts when it actually *joins two digit groups* — a
392
+ // trailing period is ordinary sentence punctuation, and treating it as a
393
+ // separator discards every postal code that ends a sentence
394
+ // ("Domicilio: Palma, 13867. Pagos a ...").
395
+ if ("._/".includes(beforeChar) && /\d/.test(prevPrev))
396
+ return true;
397
+ if ("._/".includes(afterChar) && /\d/.test(nextNext))
398
+ return true;
399
+ if (afterChar === "-" && /\d/.test(nextNext))
400
+ return true;
401
+ if (beforeChar === "-" && !COUNTRY_PREFIXED.test(text.slice(0, match.start - 1)))
402
+ return true;
403
+ // A further digit group on the same line: "1268 040390", "1234 5678 925",
404
+ // "+43 664 8213 907". Horizontal whitespace only — a digit on the *next*
405
+ // line is a separate field, not a continuation.
406
+ if (/^[ \t]+\d/.test(text.slice(match.end, match.end + 4)))
407
+ return true;
408
+ // An identifier label introduces the digits: "DiNr. 4471", "Policen-Nr."
409
+ if (ID_CUE_BEFORE.test(text.slice(Math.max(0, match.start - 40), match.start)))
410
+ return true;
411
+ // Digits after an international dialling prefix belong to PHONE
412
+ const [lineStart] = enclosingLine(text, match.start, match.end);
413
+ if (DIALLING_PREFIX_BEFORE.test(text.slice(lineStart, match.start)))
414
+ return true;
415
+ return false;
416
+ }
181
417
  function suppressRequiresContext(text, match) {
182
418
  if (!match.patternDef.requiresContext || match.patternDef.contextKeywords.length === 0)
183
419
  return false;
@@ -190,8 +426,9 @@ const TYPE_SUPPRESSORS = {
190
426
  [types_js_1.EntityType.NATIONAL_ID]: [suppressCurrency, suppressUnits, suppressReference, suppressLegal, suppressMath, suppressNatidAsPassport, suppressSeNatidAsOrg],
191
427
  [types_js_1.EntityType.SSN]: [suppressCurrency, suppressUnits, suppressReference, suppressMath],
192
428
  [types_js_1.EntityType.TAX_ID]: [suppressCurrency, suppressUnits, suppressReference, suppressMath],
193
- [types_js_1.EntityType.POSTAL_CODE]: [suppressCurrency, suppressUnits, suppressMath, suppressLegal, suppressYearAsPostal, suppressPostalInsideIban, suppressPostalAsHouseNumber],
194
- [types_js_1.EntityType.IBAN]: [suppressReference],
429
+ [types_js_1.EntityType.POSTAL_CODE]: [suppressCurrency, suppressUnits, suppressMath, suppressLegal, suppressYearAsPostal, suppressPostalInsideIban, suppressPostalAsHouseNumber, suppressPostalInLongerIdentifier],
430
+ [types_js_1.EntityType.BIC]: [suppressBicWithoutEvidence],
431
+ [types_js_1.EntityType.BANK_ACCOUNT]: [suppressReference],
195
432
  [types_js_1.EntityType.LICENSE_PLATE]: [suppressPlateInCompound],
196
433
  [types_js_1.EntityType.CHAMBER_OF_COMMERCE]: [suppressReference],
197
434
  };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VALIDATORS = void 0;
3
+ exports.VALIDATORS = exports.ISO_3166_ALPHA2 = exports.IBAN_LENGTHS = void 0;
4
4
  exports.validateIban = validateIban;
5
5
  exports.validateBsn = validateBsn;
6
6
  exports.validateBelgianNn = validateBelgianNn;
@@ -14,6 +14,7 @@ exports.validateGermanTaxId = validateGermanTaxId;
14
14
  exports.validateFrenchNir = validateFrenchNir;
15
15
  exports.validateVin = validateVin;
16
16
  exports.validateBic = validateBic;
17
+ exports.validateE164 = validateE164;
17
18
  exports.validateKvk = validateKvk;
18
19
  exports.validateSwedishPnr = validateSwedishPnr;
19
20
  exports.validateNorwegianFnr = validateNorwegianFnr;
@@ -46,21 +47,45 @@ exports.validateGreekAmka = validateGreekAmka;
46
47
  function clean(candidate, chars = /[\s.\-]/g) {
47
48
  return candidate.replace(chars, "");
48
49
  }
50
+ /**
51
+ * Total IBAN length per country (ISO 13616 registry). Also used to build the
52
+ * country-independent IBAN pattern in rules/countries, so an IBAN is detected
53
+ * on its own structure rather than on the caller's `countries` setting.
54
+ */
55
+ exports.IBAN_LENGTHS = {
56
+ AL: 28, AD: 24, AT: 20, AZ: 28, BH: 22, BY: 28, BE: 16, BA: 20, BR: 29, BG: 22, CR: 22, HR: 21,
57
+ CY: 28, CZ: 24, DK: 18, DO: 28, TL: 23, EE: 20, FO: 18, FI: 18, FR: 27, GE: 22, DE: 22, GI: 23,
58
+ GR: 27, GL: 18, GT: 28, HU: 28, IS: 26, IQ: 23, IE: 22, IL: 23, IT: 27, JO: 30, KZ: 20, XK: 20,
59
+ KW: 30, LV: 21, LB: 28, LI: 21, LT: 20, LU: 20, MT: 31, MR: 27, MU: 30, MC: 27, MD: 24, ME: 22,
60
+ NL: 18, MK: 19, NO: 15, PK: 24, PS: 29, PL: 28, PT: 25, QA: 29, RO: 24, LC: 32, SM: 27, SA: 24,
61
+ RS: 22, SC: 31, SK: 24, SI: 19, ES: 24, SE: 24, CH: 21, TN: 24, TR: 26, UA: 29, AE: 23, GB: 22,
62
+ VA: 22, VG: 24,
63
+ };
64
+ /** ISO 3166-1 alpha-2 codes, plus XK (Kosovo, user-assigned but in banking use). */
65
+ exports.ISO_3166_ALPHA2 = new Set([
66
+ "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ",
67
+ "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS",
68
+ "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN",
69
+ "CO", "CR", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE",
70
+ "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF",
71
+ "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM",
72
+ "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM",
73
+ "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC",
74
+ "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK",
75
+ "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA",
76
+ "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG",
77
+ "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW",
78
+ "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS",
79
+ "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO",
80
+ "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI",
81
+ "VN", "VU", "WF", "WS", "XK", "YE", "YT", "ZA", "ZM", "ZW",
82
+ ]);
49
83
  function validateIban(candidate) {
50
84
  const c = candidate.replace(/[\s\-]/g, "").toUpperCase();
51
85
  if (c.length < 5 || !/^[A-Z]{2}/.test(c) || !/^\d{2}$/.test(c.slice(2, 4)))
52
86
  return false;
53
- const ibanLengths = {
54
- AL: 28, AD: 24, AT: 20, AZ: 28, BH: 22, BY: 28, BE: 16, BA: 20, BR: 29, BG: 22, CR: 22, HR: 21,
55
- CY: 28, CZ: 24, DK: 18, DO: 28, TL: 23, EE: 20, FO: 18, FI: 18, FR: 27, GE: 22, DE: 22, GI: 23,
56
- GR: 27, GL: 18, GT: 28, HU: 28, IS: 26, IQ: 23, IE: 22, IL: 23, IT: 27, JO: 30, KZ: 20, XK: 20,
57
- KW: 30, LV: 21, LB: 28, LI: 21, LT: 20, LU: 20, MT: 31, MR: 27, MU: 30, MC: 27, MD: 24, ME: 22,
58
- NL: 18, MK: 19, NO: 15, PK: 24, PS: 29, PL: 28, PT: 25, QA: 29, RO: 24, LC: 32, SM: 27, SA: 24,
59
- RS: 22, SC: 31, SK: 24, SI: 19, ES: 24, SE: 24, CH: 21, TN: 24, TR: 26, UA: 29, AE: 23, GB: 22,
60
- VA: 22, VG: 24,
61
- };
62
87
  const country = c.slice(0, 2);
63
- const expected = ibanLengths[country];
88
+ const expected = exports.IBAN_LENGTHS[country];
64
89
  if (expected !== undefined && c.length !== expected)
65
90
  return false;
66
91
  const rearranged = c.slice(4) + c.slice(0, 4);
@@ -206,13 +231,22 @@ function validateVin(candidate) {
206
231
  return false;
207
232
  return !/[IOQ]/.test(c);
208
233
  }
234
+ /**
235
+ * BIC/SWIFT structural validation (ISO 9362): BBBB CC LL (PPP).
236
+ *
237
+ * Necessary but **not sufficient** — BIC has no check digit, and characters
238
+ * 5-6 of ordinary uppercase words are frequently valid country codes
239
+ * (`DRINGEND` -> `GE`, `HOSPITAL` -> `IT`). Emission additionally requires a
240
+ * registry hit or banking context; see `suppressBicWithoutEvidence`.
241
+ */
209
242
  function validateBic(candidate) {
210
243
  const c = candidate.replace(/ /g, "").toUpperCase();
211
244
  if (c.length !== 8 && c.length !== 11)
212
245
  return false;
213
246
  if (!/^[A-Z]{4}/.test(c))
214
247
  return false;
215
- if (!/^[A-Z]{2}$/.test(c.slice(4, 6)))
248
+ // Country code must be a real ISO 3166-1 alpha-2 code
249
+ if (!exports.ISO_3166_ALPHA2.has(c.slice(4, 6)))
216
250
  return false;
217
251
  if (!/^[A-Z0-9]{2}$/.test(c.slice(6, 8)))
218
252
  return false;
@@ -220,6 +254,21 @@ function validateBic(candidate) {
220
254
  return false;
221
255
  return true;
222
256
  }
257
+ /**
258
+ * International phone number in E.164 form: `+` then 8-15 digits.
259
+ *
260
+ * A `+` prefix makes a phone number self-identifying, so this backs a
261
+ * country-independent pattern: the per-country patterns each hard-code one
262
+ * grouping and miss the others (`+43 664 8213 907` was invisible because the
263
+ * Austrian pattern expects an unbroken subscriber number).
264
+ */
265
+ function validateE164(candidate) {
266
+ if (!candidate.trimStart().startsWith("+"))
267
+ return false;
268
+ // A trunk prefix written as "(0)" is not part of the E.164 digit count.
269
+ const digits = candidate.replace(/\(\s*0\s*\)/g, "").replace(/\D/g, "");
270
+ return digits.length >= 8 && digits.length <= 15;
271
+ }
223
272
  function validateKvk(candidate) {
224
273
  const c = clean(candidate);
225
274
  return c.length === 8 && /^\d{8}$/.test(c);
@@ -623,6 +672,35 @@ function validateGreekAmka(candidate) {
623
672
  }
624
673
  return total % 10 === 0;
625
674
  }
675
+ function validateHighEntropy(candidate) {
676
+ const clean = candidate.trim();
677
+ if (clean.length < 8)
678
+ return false;
679
+ // Short passwords (< 24 chars): require at least 1 letter, 1 digit, 1 special char
680
+ if (clean.length < 24) {
681
+ const hasLetter = /[a-zA-Z]/.test(clean);
682
+ const hasDigit = /\d/.test(clean);
683
+ const hasSpecial = /[^a-zA-Z0-9]/.test(clean);
684
+ if (hasLetter && hasDigit && hasSpecial)
685
+ return true;
686
+ // For short tokens without special chars, require entropy check
687
+ if (!hasSpecial && clean.length < 16)
688
+ return false;
689
+ }
690
+ const freq = new Map();
691
+ for (const ch of clean)
692
+ freq.set(ch, (freq.get(ch) ?? 0) + 1);
693
+ const len = clean.length;
694
+ let entropy = 0;
695
+ for (const c of freq.values()) {
696
+ const p = c / len;
697
+ entropy -= p * Math.log2(p);
698
+ }
699
+ // Hex-only strings have max ~4.0 bits entropy, use lower threshold
700
+ const isHex = /^[a-fA-F0-9]+$/.test(clean);
701
+ const threshold = isHex ? 3.0 : clean.length < 24 ? 3.0 : 3.5;
702
+ return entropy >= threshold;
703
+ }
626
704
  exports.VALIDATORS = {
627
705
  iban: validateIban,
628
706
  bsn: validateBsn,
@@ -637,6 +715,7 @@ exports.VALIDATORS = {
637
715
  french_nir: validateFrenchNir,
638
716
  vin: validateVin,
639
717
  bic: validateBic,
718
+ e164: validateE164,
640
719
  kvk: validateKvk,
641
720
  swedish_pnr: validateSwedishPnr,
642
721
  norwegian_fnr: validateNorwegianFnr,
@@ -666,4 +745,5 @@ exports.VALIDATORS = {
666
745
  uk_nhs: validateUkNhs,
667
746
  greek_afm: validateGreekAfm,
668
747
  greek_amka: validateGreekAmka,
748
+ high_entropy: validateHighEntropy,
669
749
  };
package/dist/cjs/sdk.js CHANGED
@@ -6,10 +6,10 @@ const normalizer_js_1 = require("./normalizer.js");
6
6
  const engine_js_1 = require("./rules/engine.js");
7
7
  const types_js_1 = require("./types.js");
8
8
  const DATE_TYPES = new Set([types_js_1.EntityType.DOB, types_js_1.EntityType.DATE_OF_DEATH]);
9
- class PseudonymMapper {
9
+ class ReferentialMapper {
10
10
  counters = new Map();
11
11
  mapping = new Map();
12
- getPseudonym(text, entityType) {
12
+ getLabel(text, entityType) {
13
13
  if (!this.mapping.has(text)) {
14
14
  const count = (this.counters.get(entityType) ?? 0) + 1;
15
15
  this.counters.set(entityType, count);
@@ -17,13 +17,37 @@ class PseudonymMapper {
17
17
  }
18
18
  return this.mapping.get(text);
19
19
  }
20
+ clear() {
21
+ this.counters.clear();
22
+ this.mapping.clear();
23
+ }
20
24
  }
25
+ const DEFAULT_MAX_INPUT_LENGTH = 10_485_760; // ~10 MB of text
21
26
  class EuRedact {
22
27
  engine = new engine_js_1.RuleEngine();
23
28
  cache = new cache_js_1.ResultCache();
24
- pseudonymMapper = new PseudonymMapper();
29
+ referentialMapper = new ReferentialMapper();
30
+ maxInputLength;
31
+ constructor(options) {
32
+ this.maxInputLength = options?.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH;
33
+ }
34
+ addCustomPattern(name, pattern) {
35
+ this.engine.addCustomPattern(name, pattern);
36
+ this.cache.clear();
37
+ }
38
+ /** Clear the result cache and referential integrity mappings.
39
+ * Call this in long-running processes to free PII from memory. */
40
+ clear() {
41
+ this.cache.clear();
42
+ this.referentialMapper.clear();
43
+ }
25
44
  redact(text, options = {}) {
26
- const { countries = null, mode = "rules", pseudonymize = false, detectDates = false, cache = true, } = options;
45
+ if (text.length > this.maxInputLength) {
46
+ throw new Error(`Input text length (${text.length.toLocaleString()} chars) exceeds the maximum ` +
47
+ `(${this.maxInputLength.toLocaleString()} chars). Split the input or ` +
48
+ `increase maxInputLength when constructing EuRedact.`);
49
+ }
50
+ const { countries = null, mode = "rules", referentialIntegrity = false, detectDates = false, cache = true, } = options;
27
51
  const [normalizedText, offsetMapping] = (0, normalizer_js_1.normalize)(text);
28
52
  const countriesTuple = countries
29
53
  ? countries.map(c => c.toUpperCase()).sort()
@@ -51,8 +75,8 @@ class EuRedact {
51
75
  let redacted = text;
52
76
  for (let i = detections.length - 1; i >= 0; i--) {
53
77
  const det = detections[i];
54
- const replacement = pseudonymize
55
- ? this.pseudonymMapper.getPseudonym(det.text, det.entityType)
78
+ const replacement = referentialIntegrity
79
+ ? this.referentialMapper.getLabel(det.text, det.entityType)
56
80
  : `[${det.entityType}]`;
57
81
  redacted = redacted.slice(0, det.start) + replacement + redacted.slice(det.end);
58
82
  }
package/dist/cjs/types.js CHANGED
@@ -1,11 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DetectionSource = exports.EntityType = void 0;
3
+ exports.DetectionSource = exports.LEGACY_TYPE_ALIASES = exports.EntityType = void 0;
4
4
  var EntityType;
5
5
  (function (EntityType) {
6
6
  EntityType["NAME"] = "NAME";
7
7
  EntityType["ADDRESS"] = "ADDRESS";
8
- EntityType["IBAN"] = "IBAN";
8
+ /**
9
+ * Canonical name for a bank account identifier. `IBAN` is kept below as a
10
+ * legacy alias with the same value, so `EntityType.IBAN === EntityType.BANK_ACCOUNT`
11
+ * and existing code keeps working — but the emitted value, and therefore the
12
+ * `[BANK_ACCOUNT]` placeholder written into redacted text, is canonical.
13
+ */
14
+ EntityType["BANK_ACCOUNT"] = "BANK_ACCOUNT";
15
+ /** @deprecated legacy alias of {@link EntityType.BANK_ACCOUNT} */
16
+ EntityType["IBAN"] = "BANK_ACCOUNT";
9
17
  EntityType["BIC"] = "BIC";
10
18
  EntityType["CREDIT_CARD"] = "CREDIT_CARD";
11
19
  EntityType["PHONE"] = "PHONE";
@@ -32,8 +40,17 @@ var EntityType;
32
40
  EntityType["GPS_COORDINATES"] = "GPS_COORDINATES";
33
41
  EntityType["UUID"] = "UUID";
34
42
  EntityType["SOCIAL_HANDLE"] = "SOCIAL_HANDLE";
43
+ EntityType["SECRET"] = "SECRET";
35
44
  EntityType["OTHER"] = "OTHER";
36
45
  })(EntityType || (exports.EntityType = EntityType = {}));
46
+ /**
47
+ * Legacy type names accepted on input and mapped to their canonical form.
48
+ * Kept in sync with the pipeline canon (config/entity_types.json →
49
+ * legacy_aliases). The engine never *emits* these names.
50
+ */
51
+ exports.LEGACY_TYPE_ALIASES = {
52
+ IBAN: "BANK_ACCOUNT",
53
+ };
37
54
  var DetectionSource;
38
55
  (function (DetectionSource) {
39
56
  DetectionSource["RULES"] = "rules";
package/dist/esm/cache.js CHANGED
@@ -18,10 +18,10 @@ export class ResultCache {
18
18
  key(text, countries, mode) {
19
19
  const sorted = [...countries].sort();
20
20
  const raw = `${text}|${sorted.join("|")}|${mode}`;
21
- // Use multiple FNV-1a hashes on different slices for reduced collisions
21
+ // Include raw length to reduce collision risk alongside dual FNV-1a hashes
22
22
  const h1 = fnv1aHash(raw);
23
23
  const h2 = fnv1aHash(raw.slice(Math.floor(raw.length / 2)) + raw.slice(0, Math.floor(raw.length / 2)));
24
- return h1 + h2;
24
+ return `${raw.length}:${h1}${h2}`;
25
25
  }
26
26
  get(key) {
27
27
  if (!this.enabled)
@@ -1,9 +1,12 @@
1
- export { EntityType, DetectionSource } from "./types.js";
1
+ export { EntityType, DetectionSource, LEGACY_TYPE_ALIASES } from "./types.js";
2
2
  export type { Detection, RedactResult, PatternDef, CountryConfig } from "./types.js";
3
3
  export { EuRedact, type RedactOptions } from "./sdk.js";
4
4
  export { COUNTRY_CONFIGS } from "./rules/countries/index.js";
5
+ export { setBicRegistry, getBicRegistry, SEED_BIC6_PREFIXES, type BicRegistryProvider } from "./rules/bicRegistry.js";
5
6
  import { type RedactOptions } from "./sdk.js";
6
7
  import type { RedactResult } from "./types.js";
7
8
  export declare function availableCountries(): string[];
8
9
  export declare function redact(text: string, options?: RedactOptions): RedactResult;
10
+ export declare function addCustomPattern(name: string, pattern: string): void;
11
+ export declare function clear(): void;
9
12
  export declare function redactBatch(texts: string[], options?: RedactOptions): RedactResult[];