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.
@@ -1,11 +1,69 @@
1
- import { DetectionSource } from "../types.js";
1
+ import { DetectionSource, EntityType } from "../types.js";
2
2
  import { MultiPatternMatcher } from "./matchers.js";
3
3
  import { shouldSuppress } from "./suppressors.js";
4
4
  import { detectStructuralDob } from "./structural.js";
5
5
  import { COUNTRY_CONFIGS } from "./countries/index.js";
6
+ /**
7
+ * Heuristic to detect nested quantifiers that cause catastrophic backtracking.
8
+ * After stripping escaped chars and character classes, look for an unbounded
9
+ * quantifier (+/*) closing a group that is itself quantified (+/*).
10
+ */
11
+ const NESTED_QUANTIFIER_RE = /[+*]\)[+*]/;
12
+ function validateCustomPattern(pattern) {
13
+ try {
14
+ new RegExp(pattern, "gu");
15
+ }
16
+ catch (e) {
17
+ throw new Error(`Invalid regex pattern: ${e instanceof Error ? e.message : e}`);
18
+ }
19
+ const stripped = pattern
20
+ .replace(/\\./g, "X")
21
+ .replace(/\[(?:[^\]\\]|\\.)*\]/g, "X");
22
+ if (NESTED_QUANTIFIER_RE.test(stripped)) {
23
+ throw new Error("Pattern contains nested quantifiers (e.g. (a+)+) which can cause " +
24
+ "catastrophic backtracking (ReDoS). Restructure the pattern to " +
25
+ "avoid quantifiers inside quantified groups.");
26
+ }
27
+ }
28
+ /**
29
+ * The country modules use the EU/VAT convention (UK, EL) while the public
30
+ * contract is ISO 3166-1 alpha-2 (GB, GR). Accept both spellings so a caller
31
+ * passing correct ISO codes is not punished for it.
32
+ */
33
+ export const COUNTRY_CODE_ALIASES = {
34
+ GB: "UK",
35
+ GR: "EL",
36
+ UK: "UK",
37
+ EL: "EL",
38
+ };
39
+ /** Map a caller-supplied code to a registered one, or null if unknown. */
40
+ export function resolveCountryCode(countryCode) {
41
+ let code = countryCode.trim().toUpperCase();
42
+ code = COUNTRY_CODE_ALIASES[code] ?? code;
43
+ return code in COUNTRY_CONFIGS && code !== "SHARED" ? code : null;
44
+ }
45
+ const warnedCountries = new Set();
46
+ function warnUnknownCountry(code) {
47
+ if (warnedCountries.has(code))
48
+ return;
49
+ warnedCountries.add(code);
50
+ const available = Object.keys(COUNTRY_CONFIGS).filter(c => c !== "SHARED").sort();
51
+ console.warn(`[euredact] Unknown country code: ${JSON.stringify(code)}. Continuing with ` +
52
+ `shared country-independent patterns only (email, IBAN, international ` +
53
+ `phone, credit card, ...). Available: ${available.join(", ")}`);
54
+ }
6
55
  export class RuleEngine {
7
56
  matcher = new MultiPatternMatcher();
8
57
  loadedCountries = new Set();
58
+ addCustomPattern(name, pattern) {
59
+ validateCustomPattern(pattern);
60
+ const pdef = {
61
+ entityType: name, pattern, validator: null,
62
+ description: "", contextKeywords: [], requiresContext: false,
63
+ };
64
+ this.matcher.addPattern(pdef, "CUSTOM");
65
+ this.matcher.compile();
66
+ }
9
67
  loadCountries(countryCodes) {
10
68
  let configs;
11
69
  if (countryCodes === null) {
@@ -14,11 +72,18 @@ export class RuleEngine {
14
72
  else {
15
73
  configs = [];
16
74
  for (const c of countryCodes) {
17
- const code = c.toUpperCase();
75
+ const code = resolveCountryCode(c);
76
+ if (code === null) {
77
+ // Detection continues with the shared, country-independent
78
+ // patterns. Throwing on an unknown locale invites callers to wrap
79
+ // the call in try/catch and skip redaction — failing open, with
80
+ // unredacted PII in the output.
81
+ warnUnknownCountry(c);
82
+ continue;
83
+ }
18
84
  const config = COUNTRY_CONFIGS[code];
19
85
  if (config)
20
86
  configs.push(config);
21
- // Silently skip unknown country codes (e.g. "INTL")
22
87
  }
23
88
  const shared = COUNTRY_CONFIGS["SHARED"];
24
89
  if (shared)
@@ -37,44 +102,131 @@ export class RuleEngine {
37
102
  }
38
103
  detect(text, countryCodes) {
39
104
  this.loadCountries(countryCodes);
40
- let rawMatches = this.matcher.scan(text);
105
+ // Scope the scan to requested countries for efficiency
106
+ // Resolve through the alias table so `countries: ["GB"]` actually scans
107
+ // the patterns registered under "UK".
108
+ let scanCodes = null;
41
109
  if (countryCodes !== null) {
42
- const codesUpper = new Set(countryCodes.map(c => c.toUpperCase()));
43
- rawMatches = rawMatches.filter(m => codesUpper.has(m.countryCode) || m.countryCode === "SHARED");
110
+ scanCodes = new Set();
111
+ for (const c of countryCodes) {
112
+ const code = resolveCountryCode(c);
113
+ if (code !== null)
114
+ scanCodes.add(code);
115
+ }
116
+ scanCodes.add("SHARED");
117
+ scanCodes.add("CUSTOM");
44
118
  }
45
- const validated = rawMatches.filter(m => this.matcher.validate(m));
46
- const detections = [];
47
- for (const match of validated) {
119
+ let rawMatches = this.matcher.scan(text, scanCodes);
120
+ // Matches that have a validator but fail it create suppression zones:
121
+ // the span is recognisably a specific entity (e.g. IBAN-shaped) so
122
+ // overlapping regex-only matches (license plate, phone) are false
123
+ // positives and must be suppressed.
124
+ const validated = [];
125
+ const rawZones = [];
126
+ for (const m of rawMatches) {
127
+ const isValid = this.matcher.validate(m);
128
+ if (isValid) {
129
+ validated.push({ match: m, hasValidValidator: m.patternDef.validator !== null });
130
+ }
131
+ else if (m.patternDef.validator !== null && !m.patternDef.requiresContext) {
132
+ rawZones.push([m.start, m.end]);
133
+ }
134
+ }
135
+ // Merge overlapping suppression zones for O(log n) containment checks
136
+ let zoneStarts = [];
137
+ let zoneEnds = [];
138
+ if (rawZones.length > 0) {
139
+ rawZones.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
140
+ let [ms, me] = rawZones[0];
141
+ for (let i = 1; i < rawZones.length; i++) {
142
+ const [zs, ze] = rawZones[i];
143
+ if (zs <= me) {
144
+ me = Math.max(me, ze);
145
+ }
146
+ else {
147
+ zoneStarts.push(ms);
148
+ zoneEnds.push(me);
149
+ ms = zs;
150
+ me = ze;
151
+ }
152
+ }
153
+ zoneStarts.push(ms);
154
+ zoneEnds.push(me);
155
+ }
156
+ // Build candidates with priority: validated (3) > custom (2) > regex-only (1)
157
+ const candidates = [];
158
+ for (const { match, hasValidValidator } of validated) {
48
159
  if (shouldSuppress(text, match))
49
160
  continue;
50
- detections.push({
51
- entityType: match.patternDef.entityType,
52
- start: match.start,
53
- end: match.end,
54
- text: match.text,
55
- source: DetectionSource.RULES,
56
- country: match.countryCode !== "SHARED" ? match.countryCode : null,
57
- confidence: "high",
161
+ // O(log n) binary-search containment check on merged zones
162
+ if (match.patternDef.validator === null && zoneStarts.length > 0) {
163
+ let lo = 0, hi = zoneStarts.length;
164
+ while (lo < hi) {
165
+ const mid = (lo + hi) >>> 1;
166
+ if (zoneStarts[mid] <= match.start)
167
+ lo = mid + 1;
168
+ else
169
+ hi = mid;
170
+ }
171
+ const idx = lo - 1;
172
+ if (idx >= 0 && zoneEnds[idx] >= match.end)
173
+ continue;
174
+ }
175
+ // A bare digit run is the weakest evidence in the engine and must never
176
+ // re-cut a span a structured detector claims (PHONE, SSN, NATIONAL_ID,
177
+ // BANK_ACCOUNT, VAT...). Postal codes take unclaimed spans only,
178
+ // whatever the span lengths.
179
+ const priority = hasValidValidator
180
+ ? 3
181
+ : match.countryCode === "CUSTOM"
182
+ ? 2
183
+ : match.patternDef.entityType === EntityType.POSTAL_CODE
184
+ ? 0
185
+ : 1;
186
+ const spanLength = match.end - match.start;
187
+ const score = priority * 1_000_000 + spanLength;
188
+ candidates.push({
189
+ det: {
190
+ entityType: match.patternDef.entityType,
191
+ start: match.start,
192
+ end: match.end,
193
+ text: match.text,
194
+ source: DetectionSource.RULES,
195
+ country: (match.countryCode !== "SHARED" && match.countryCode !== "CUSTOM") ? match.countryCode : null,
196
+ confidence: "high",
197
+ },
198
+ score,
58
199
  });
59
200
  }
60
- detections.push(...detectStructuralDob(text));
61
- return this.deduplicate(detections);
201
+ for (const d of detectStructuralDob(text)) {
202
+ candidates.push({ det: d, score: 1_000_000 + (d.end - d.start) });
203
+ }
204
+ return this.deduplicate(candidates);
62
205
  }
63
- deduplicate(detections) {
64
- if (detections.length === 0)
65
- return detections;
66
- const sorted = [...detections].sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start));
206
+ /**
207
+ * Remove overlapping detections with priority-aware resolution.
208
+ * Priority: validated (3) > custom (2) > regex-only (1).
209
+ * Within the same tier, longer span wins.
210
+ */
211
+ deduplicate(candidates) {
212
+ if (candidates.length === 0)
213
+ return [];
214
+ const sorted = [...candidates].sort((a, b) => b.score - a.score);
67
215
  const result = [];
68
- for (const det of sorted) {
216
+ const occupied = new Set();
217
+ for (const { det } of sorted) {
69
218
  let overlaps = false;
70
- for (const kept of result) {
71
- if (det.start < kept.end && det.end > kept.start) {
219
+ for (let p = det.start; p < det.end; p++) {
220
+ if (occupied.has(p)) {
72
221
  overlaps = true;
73
222
  break;
74
223
  }
75
224
  }
76
- if (!overlaps)
225
+ if (!overlaps) {
226
+ for (let p = det.start; p < det.end; p++)
227
+ occupied.add(p);
77
228
  result.push(det);
229
+ }
78
230
  }
79
231
  return result;
80
232
  }
@@ -1,11 +1,12 @@
1
- import type { CountryConfig } from "../types.js";
1
+ import type { CountryConfig, PatternDef } from "../types.js";
2
2
  import type { RawMatch } from "./suppressors.js";
3
3
  export type { RawMatch };
4
4
  export declare class MultiPatternMatcher {
5
5
  private patterns;
6
6
  private compiled;
7
+ addPattern(patternDef: PatternDef, countryCode: string): void;
7
8
  addCountry(config: CountryConfig): void;
8
9
  compile(): void;
9
- scan(text: string): RawMatch[];
10
+ scan(text: string, countryCodes?: Set<string> | null): RawMatch[];
10
11
  validate(match: RawMatch): boolean;
11
12
  }
@@ -2,6 +2,11 @@ import { VALIDATORS } from "./validators.js";
2
2
  export class MultiPatternMatcher {
3
3
  patterns = [];
4
4
  compiled = false;
5
+ addPattern(patternDef, countryCode) {
6
+ const regex = new RegExp(patternDef.pattern, "gu");
7
+ this.patterns.push({ regex, patternDef, countryCode });
8
+ this.compiled = false;
9
+ }
5
10
  addCountry(config) {
6
11
  for (const pdef of config.patterns) {
7
12
  // Convert Python-style \b word boundaries — JS handles them natively
@@ -14,11 +19,13 @@ export class MultiPatternMatcher {
14
19
  compile() {
15
20
  this.compiled = true;
16
21
  }
17
- scan(text) {
22
+ scan(text, countryCodes = null) {
18
23
  if (!this.compiled)
19
24
  this.compile();
20
25
  const matches = [];
21
26
  for (const { regex, patternDef, countryCode } of this.patterns) {
27
+ if (countryCodes !== null && !countryCodes.has(countryCode))
28
+ continue;
22
29
  regex.lastIndex = 0;
23
30
  let m;
24
31
  while ((m = regex.exec(text)) !== null) {
@@ -1,4 +1,5 @@
1
1
  import { EntityType } from "../types.js";
2
+ import { isRegisteredBic } from "./bicRegistry.js";
2
3
  const CONTEXT_CHARS = 150;
3
4
  function getContext(text, start, end) {
4
5
  const ctxStart = Math.max(0, start - CONTEXT_CHARS);
@@ -18,12 +19,14 @@ const REFERENCE_BEFORE = /(?:dossier|ref\.?|referentie|reference|référence|fac
18
19
  const LEGAL_BEFORE = /(?:Art(?:ikel|icle|\.)|§|Artikel|Section|Sectie|Afdeling|paragraaf|Absatz|alinéa|punt|point|Punkt|lid)\s*$/i;
19
20
  const MATH_BEFORE = /[=+\-×÷*/]\s*$/;
20
21
  const MATH_AFTER = /^\s*[=+\-×÷*/]/;
22
+ // "A-1010", "B-2000", "L-1234", "CH-8000", "D-10115": a country prefix on a
23
+ // postal code, not a minus sign.
24
+ const COUNTRY_PREFIX_HYPHEN = /(?:^|[^A-Za-z0-9])[A-Z]{1,2}-\s*$/;
21
25
  const SEQUENTIAL_PATTERNS = /^(?:0{6,}|1234567890?|0123456789|9876543210?|1111111111?|000000000|123456789)$/;
22
- const YEAR_PATTERN = /^(?:19[4-9]\d|20[0-3]\d)$/;
23
- 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;
26
+ // YEAR_PATTERN kept for reference but replaced by RECENT_YEAR in suppressYearAsPostal
24
27
  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;
25
28
  const SERVICE_NUMBER = /^0800[\-\s]/;
26
- const DATE_PATTERN_FULL = /^\d{2}[-/.]\d{2}[-/.]\d{4}$/;
29
+ const DATE_PATTERN_FULL = /^\d{2}[-/.]\d{2}[-/.]\d{4}$|^\d{4}[-/.]\d{2}[-/.]\d{2}$/;
27
30
  const PASSPORT_CONTEXT_BEFORE = /(?:Reisepass|passport|passeport|paspoort|Bisheriger\s+Reisepass)\s*(?:Nr\.?|Nummer|nummer|number|n[°o])?\s*[:.]?\s*$/i;
28
31
  const SE_ORG_CONTEXT_BEFORE = /(?:org\.?\s*nr\.?|organisationsnummer|organisationsnr|Bolagsverket|företag)\s*[:.]?\s*$/i;
29
32
  const NUMERIC_TYPES = new Set([EntityType.PHONE, EntityType.NATIONAL_ID, EntityType.SSN, EntityType.TAX_ID, EntityType.POSTAL_CODE]);
@@ -63,23 +66,40 @@ function suppressMath(text, match) {
63
66
  if (!NUMERIC_TYPES.has(match.patternDef.entityType))
64
67
  return false;
65
68
  const [before, after] = getContext(text, match.start, match.end);
69
+ // A country-prefixed postal code is an address, not a subtraction:
70
+ // "A-1010 Wien", "B-2000 Antwerpen", "D-10115 Berlin".
71
+ if (match.patternDef.entityType === EntityType.POSTAL_CODE && COUNTRY_PREFIX_HYPHEN.test(before)) {
72
+ return false;
73
+ }
66
74
  return MATH_BEFORE.test(before) || MATH_AFTER.test(after);
67
75
  }
68
76
  function suppressSequential(_text, match) {
69
77
  const clean = match.text.replace(/[\s.\-]/g, "");
70
78
  return SEQUENTIAL_PATTERNS.test(clean);
71
79
  }
80
+ const RECENT_YEAR = /^(?:19[5-9]\d|20[0-3]\d)$/;
81
+ 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;
82
+ 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;
72
83
  function suppressYearAsPostal(text, match) {
73
84
  if (match.patternDef.entityType !== EntityType.POSTAL_CODE)
74
85
  return false;
75
86
  const clean = match.text.trim();
76
- if (!YEAR_PATTERN.test(clean))
87
+ if (!RECENT_YEAR.test(clean))
88
+ return false;
89
+ const [before, after] = getContext(text, match.start, match.end);
90
+ const context = before + after;
91
+ // Keep as postal code if postal/address context nearby
92
+ if (POSTAL_CONTEXT_NEAR.test(context))
77
93
  return false;
94
+ // Keep if preceded by comma+space (address pattern: "Amsterdam, 2026")
78
95
  const immediateBefore = text.slice(Math.max(0, match.start - 3), match.start);
79
- if (immediateBefore.endsWith(", ") || immediateBefore.endsWith(",\n"))
96
+ if (/,\s*$/.test(immediateBefore))
80
97
  return false;
81
- const [before, after] = getContext(text, match.start, match.end);
82
- return DATE_KEYWORD_NEAR.test(before + after);
98
+ // Suppress if date keyword nearby (birth date, employment date, etc.)
99
+ if (DATE_KEYWORD_NEAR.test(context))
100
+ return true;
101
+ // Suppress: recent years without postal context are almost never postal codes
102
+ return true;
83
103
  }
84
104
  function suppressPhoneAfterIdLabel(text, match) {
85
105
  if (match.patternDef.entityType !== EntityType.PHONE)
@@ -101,9 +121,13 @@ const NOT_CITY_CODES = new Set([
101
121
  "ID", "NR", "NO", "ST", "DR", "MR", "MS", "HR", "FR", "IM", "IN", "OR", "IF", "IS", "IT", "AT", "AD", "AG", "AV",
102
122
  "BE", "DE", "EU", "NL", "LU", "WS", "SS", "IP",
103
123
  ]);
124
+ const CURRENCY_PLATE = /^(?:EUR|USD|GBP|CHF|SEK|NOK|DKK|ISK|CZK|PLN|HUF|RON|BGN|HRK)\s/i;
104
125
  function suppressPlateInCompound(text, match) {
105
126
  if (match.patternDef.entityType !== EntityType.LICENSE_PLATE)
106
127
  return false;
128
+ // Suppress currency + number misread as plate (e.g. "EUR 2")
129
+ if (CURRENCY_PLATE.test(match.text))
130
+ return true;
107
131
  if (match.start >= 3) {
108
132
  const before = text.slice(Math.max(0, match.start - 10), match.start);
109
133
  if (/[A-Za-zÄÖÜäöüß]{2,}-$/.test(before))
@@ -175,6 +199,218 @@ function suppressPostalAsHouseNumber(text, match) {
175
199
  }
176
200
  return false;
177
201
  }
202
+ // ── BIC: banking-context cues and heading shapes ────────────────────────
203
+ // \bSWIFT\b also covers SWIFT-Code / SWIFT-BIC / Code SWIFT, and \bBIC\b
204
+ // covers BIC-code / BIC/SWIFT.
205
+ const BIC_KEYWORD = /\b(?:BIC|SWIFT)\b/i;
206
+ 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;
207
+ // A line that is nothing but a BIC/SWIFT label, as used in table and column
208
+ // layouts where the code sits on the following line.
209
+ 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;
210
+ // An IBAN in the same structural unit: CC + 2 check digits + 2 or more groups.
211
+ const IBAN_SHAPE = /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,}/;
212
+ // Largest paragraph still treated as one structural unit. Beyond this the unit
213
+ // falls back to the enclosing line, so a run-on document body cannot lend
214
+ // banking context to a token 2,000 characters away.
215
+ const MAX_UNIT_CHARS = 600;
216
+ function enclosingLine(text, start, end) {
217
+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;
218
+ let lineEnd = text.indexOf("\n", end);
219
+ if (lineEnd === -1)
220
+ lineEnd = text.length;
221
+ return [lineStart, lineEnd];
222
+ }
223
+ /**
224
+ * Return the enclosing line / record / paragraph around a match.
225
+ *
226
+ * The context window for BIC is scoped structurally, not by character count.
227
+ * A tight character window measured on the corpus rejects 97.3% of dictionary
228
+ * false positives but wrongly discards ~316 real-looking codes, because the
229
+ * banking cue often sits further away in the same record — e.g. a CSV row
230
+ * carrying the IBAN in one field and the BIC several fields later.
231
+ */
232
+ function structuralUnit(text, start, end) {
233
+ const [lineStart, lineEnd] = enclosingLine(text, start, end);
234
+ let paraStart = lineStart;
235
+ while (paraStart > 0) {
236
+ const prevEnd = paraStart - 1;
237
+ const prevStart = text.lastIndexOf("\n", prevEnd - 1) + 1;
238
+ if (text.slice(prevStart, prevEnd).trim() === "")
239
+ break;
240
+ paraStart = prevStart;
241
+ }
242
+ let paraEnd = lineEnd;
243
+ while (paraEnd < text.length) {
244
+ const nextStart = paraEnd + 1;
245
+ let nextEnd = text.indexOf("\n", nextStart);
246
+ if (nextEnd === -1)
247
+ nextEnd = text.length;
248
+ if (text.slice(nextStart, nextEnd).trim() === "")
249
+ break;
250
+ paraEnd = nextEnd;
251
+ }
252
+ if (paraEnd - paraStart <= MAX_UNIT_CHARS)
253
+ return text.slice(paraStart, paraEnd);
254
+ return text.slice(lineStart, lineEnd);
255
+ }
256
+ function previousNonblankLine(text, lineStart) {
257
+ let pos = lineStart;
258
+ while (pos > 0) {
259
+ const prevEnd = pos - 1;
260
+ const prevStart = text.lastIndexOf("\n", prevEnd - 1) + 1;
261
+ const line = text.slice(prevStart, prevEnd);
262
+ if (line.trim() !== "")
263
+ return line;
264
+ pos = prevStart;
265
+ }
266
+ return "";
267
+ }
268
+ function escapeRe(s) {
269
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
270
+ }
271
+ /**
272
+ * Does `token` also occur as an ordinary lowercase word in this document?
273
+ *
274
+ * `hospital`/`HOSPITAL`, `gegevens`/`GEGEVENS` — a token that appears in
275
+ * ordinary case elsewhere in the same document is a word, not a bank code.
276
+ * Email and domain contexts are excluded, so `ing.nl` does not vouch for a
277
+ * heading. Measured on the corpus this alone identifies ~78% of the BIC false
278
+ * positives with no dictionaries and no labelled data.
279
+ */
280
+ function occursAsLowercaseWord(text, token) {
281
+ if (!/^[A-Za-z]+$/.test(token))
282
+ return false;
283
+ const lower = token.toLowerCase();
284
+ const capitalised = lower[0].toUpperCase() + lower.slice(1);
285
+ for (const form of [lower, capitalised]) {
286
+ // Cheap pre-check: a plain substring test almost always answers "no".
287
+ if (!text.includes(form))
288
+ continue;
289
+ const re = new RegExp(`\\b${escapeRe(form)}\\b`, "g");
290
+ let m;
291
+ while ((m = re.exec(text)) !== null) {
292
+ const before = m.index > 0 ? text[m.index - 1] : "";
293
+ const after = text.slice(m.index + form.length, m.index + form.length + 8);
294
+ if (before === "@" || (before === "." && m.index >= 2 && /[A-Za-z0-9]/.test(text[m.index - 2])))
295
+ continue;
296
+ if (after.startsWith("@") || /^\.[a-zA-Z]{2,6}\b/.test(after))
297
+ continue;
298
+ return true;
299
+ }
300
+ }
301
+ return false;
302
+ }
303
+ /**
304
+ * Is the candidate positioned as a section heading rather than a value?
305
+ * Headings and shouted words are never bank codes. Lines carrying an explicit
306
+ * BIC/SWIFT keyword are exempt from the all-caps rule, so a genuine
307
+ * `BIC: GEBABEBB` line is not mistaken for a heading.
308
+ */
309
+ function isHeadingShape(text, start, end, token) {
310
+ const [lineStart, lineEnd] = enclosingLine(text, start, end);
311
+ const line = text.slice(lineStart, lineEnd);
312
+ // The token is the entire line — unless the line above is a bare BIC/SWIFT
313
+ // label, which makes this a labelled value in a table layout, not a heading.
314
+ if (line.trim() === token) {
315
+ return !BIC_LABEL_LINE.test(previousNonblankLine(text, lineStart));
316
+ }
317
+ // The token starts its line and is immediately followed by a colon
318
+ if (text.slice(lineStart, start).trim() === "" && text.slice(end, lineEnd).trimStart().startsWith(":")) {
319
+ return true;
320
+ }
321
+ // A shouted line: no lowercase, no digits, and no banking keyword
322
+ if (!/[a-z]/.test(line) && !/\d/.test(line) && !BIC_KEYWORD.test(line))
323
+ return true;
324
+ return false;
325
+ }
326
+ /**
327
+ * Emit a BIC only on registry membership or banking context.
328
+ *
329
+ * 0. the token also occurs as an ordinary lowercase word here -> reject;
330
+ * 1. registry hit (deployment-supplied, then bundled seed prefixes) -> emit;
331
+ * 2. heading / shouted-word shape -> reject;
332
+ * 3. BIC/SWIFT keyword, IBAN or bank block in the structural unit -> emit;
333
+ *
334
+ * and a bare shape match reaching the end with none of the above is never
335
+ * emitted. Gate 0 outranks every tier below it — no genuine BIC is also an
336
+ * ordinary lowercase word — so it is applied on both emitting paths. It scans
337
+ * the whole document, so it runs only on the paths that would otherwise emit.
338
+ */
339
+ function suppressBicWithoutEvidence(text, match) {
340
+ if (match.patternDef.entityType !== EntityType.BIC)
341
+ return false;
342
+ const token = match.text.trim();
343
+ if (isRegisteredBic(token))
344
+ return occursAsLowercaseWord(text, token);
345
+ if (isHeadingShape(text, match.start, match.end, token))
346
+ return true;
347
+ // The token itself is blanked out so it cannot vouch for itself.
348
+ const unit = structuralUnit(text, match.start, match.end).split(token).join(" ".repeat(token.length));
349
+ if (BIC_KEYWORD.test(unit) || IBAN_SHAPE.test(unit) || BANK_BLOCK.test(unit)) {
350
+ return occursAsLowercaseWord(text, token);
351
+ }
352
+ return true;
353
+ }
354
+ // ── Postal code: digits belonging to a longer identifier ────────────────
355
+ // An identifier label immediately before the digits. A postal code is never
356
+ // introduced this way; an SVNr, policy number or service number always is.
357
+ 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;
358
+ // An international dialling prefix earlier on the same line, with nothing but
359
+ // number punctuation in between: these digits belong to the phone detector.
360
+ const DIALLING_PREFIX_BEFORE = /\+\d{1,3}[\d\s\-().]*$/;
361
+ // A country prefix on a postal code — "A-1010 Wien", "B-2000", "L-1234".
362
+ const COUNTRY_PREFIXED = /(?:^|[^A-Za-z0-9])[A-Z]{1,2}$/;
363
+ /**
364
+ * Suppress bare digit runs that belong to a longer number, not an address.
365
+ *
366
+ * A bare 4- or 5-digit run is the weakest shape in the engine, and when it
367
+ * cuts into a longer identifier the damage is worse than a plain false
368
+ * positive: `SV-Nummer: [POSTAL_CODE] 040390` leaves half an Austrian social
369
+ * security number exposed with no way to label the remainder.
370
+ *
371
+ * Applies only to digits-only matches, so structured forms keep their own
372
+ * behaviour — NL `1234 AB`, PT `1234-567`, LU `L-1234`.
373
+ */
374
+ function suppressPostalInLongerIdentifier(text, match) {
375
+ if (match.patternDef.entityType !== EntityType.POSTAL_CODE)
376
+ return false;
377
+ const clean = match.text.trim();
378
+ if (!/^\d+$/.test(clean))
379
+ return false;
380
+ const beforeChar = match.start > 0 ? text[match.start - 1] : "";
381
+ const afterChar = match.end < text.length ? text[match.end] : "";
382
+ const prevPrev = match.start >= 2 ? text[match.start - 2] : "";
383
+ const nextNext = match.end + 1 < text.length ? text[match.end + 1] : "";
384
+ // Directly glued to more digits
385
+ if (/\d/.test(beforeChar) || /\d/.test(afterChar))
386
+ return true;
387
+ // Joined by identifier punctuation: "0456.2398.71-02", "4471/2025".
388
+ // The punctuation only counts when it actually *joins two digit groups* — a
389
+ // trailing period is ordinary sentence punctuation, and treating it as a
390
+ // separator discards every postal code that ends a sentence
391
+ // ("Domicilio: Palma, 13867. Pagos a ...").
392
+ if ("._/".includes(beforeChar) && /\d/.test(prevPrev))
393
+ return true;
394
+ if ("._/".includes(afterChar) && /\d/.test(nextNext))
395
+ return true;
396
+ if (afterChar === "-" && /\d/.test(nextNext))
397
+ return true;
398
+ if (beforeChar === "-" && !COUNTRY_PREFIXED.test(text.slice(0, match.start - 1)))
399
+ return true;
400
+ // A further digit group on the same line: "1268 040390", "1234 5678 925",
401
+ // "+43 664 8213 907". Horizontal whitespace only — a digit on the *next*
402
+ // line is a separate field, not a continuation.
403
+ if (/^[ \t]+\d/.test(text.slice(match.end, match.end + 4)))
404
+ return true;
405
+ // An identifier label introduces the digits: "DiNr. 4471", "Policen-Nr."
406
+ if (ID_CUE_BEFORE.test(text.slice(Math.max(0, match.start - 40), match.start)))
407
+ return true;
408
+ // Digits after an international dialling prefix belong to PHONE
409
+ const [lineStart] = enclosingLine(text, match.start, match.end);
410
+ if (DIALLING_PREFIX_BEFORE.test(text.slice(lineStart, match.start)))
411
+ return true;
412
+ return false;
413
+ }
178
414
  function suppressRequiresContext(text, match) {
179
415
  if (!match.patternDef.requiresContext || match.patternDef.contextKeywords.length === 0)
180
416
  return false;
@@ -187,8 +423,9 @@ const TYPE_SUPPRESSORS = {
187
423
  [EntityType.NATIONAL_ID]: [suppressCurrency, suppressUnits, suppressReference, suppressLegal, suppressMath, suppressNatidAsPassport, suppressSeNatidAsOrg],
188
424
  [EntityType.SSN]: [suppressCurrency, suppressUnits, suppressReference, suppressMath],
189
425
  [EntityType.TAX_ID]: [suppressCurrency, suppressUnits, suppressReference, suppressMath],
190
- [EntityType.POSTAL_CODE]: [suppressCurrency, suppressUnits, suppressMath, suppressLegal, suppressYearAsPostal, suppressPostalInsideIban, suppressPostalAsHouseNumber],
191
- [EntityType.IBAN]: [suppressReference],
426
+ [EntityType.POSTAL_CODE]: [suppressCurrency, suppressUnits, suppressMath, suppressLegal, suppressYearAsPostal, suppressPostalInsideIban, suppressPostalAsHouseNumber, suppressPostalInLongerIdentifier],
427
+ [EntityType.BIC]: [suppressBicWithoutEvidence],
428
+ [EntityType.BANK_ACCOUNT]: [suppressReference],
192
429
  [EntityType.LICENSE_PLATE]: [suppressPlateInCompound],
193
430
  [EntityType.CHAMBER_OF_COMMERCE]: [suppressReference],
194
431
  };
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Total IBAN length per country (ISO 13616 registry). Also used to build the
3
+ * country-independent IBAN pattern in rules/countries, so an IBAN is detected
4
+ * on its own structure rather than on the caller's `countries` setting.
5
+ */
6
+ export declare const IBAN_LENGTHS: Record<string, number>;
7
+ /** ISO 3166-1 alpha-2 codes, plus XK (Kosovo, user-assigned but in banking use). */
8
+ export declare const ISO_3166_ALPHA2: ReadonlySet<string>;
1
9
  export declare function validateIban(candidate: string): boolean;
2
10
  export declare function validateBsn(candidate: string): boolean;
3
11
  export declare function validateBelgianNn(candidate: string): boolean;
@@ -10,7 +18,24 @@ export declare function validateVatLu(candidate: string): boolean;
10
18
  export declare function validateGermanTaxId(candidate: string): boolean;
11
19
  export declare function validateFrenchNir(candidate: string): boolean;
12
20
  export declare function validateVin(candidate: string): boolean;
21
+ /**
22
+ * BIC/SWIFT structural validation (ISO 9362): BBBB CC LL (PPP).
23
+ *
24
+ * Necessary but **not sufficient** — BIC has no check digit, and characters
25
+ * 5-6 of ordinary uppercase words are frequently valid country codes
26
+ * (`DRINGEND` -> `GE`, `HOSPITAL` -> `IT`). Emission additionally requires a
27
+ * registry hit or banking context; see `suppressBicWithoutEvidence`.
28
+ */
13
29
  export declare function validateBic(candidate: string): boolean;
30
+ /**
31
+ * International phone number in E.164 form: `+` then 8-15 digits.
32
+ *
33
+ * A `+` prefix makes a phone number self-identifying, so this backs a
34
+ * country-independent pattern: the per-country patterns each hard-code one
35
+ * grouping and miss the others (`+43 664 8213 907` was invisible because the
36
+ * Austrian pattern expects an unbroken subscriber number).
37
+ */
38
+ export declare function validateE164(candidate: string): boolean;
14
39
  export declare function validateKvk(candidate: string): boolean;
15
40
  export declare function validateSwedishPnr(candidate: string): boolean;
16
41
  export declare function validateNorwegianFnr(candidate: string): boolean;