privacy-redact 1.1.0 → 1.2.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/README.md +12 -1
- package/package.json +2 -1
- package/scripts/copy-assets.mjs +8 -2
- package/src/detect/locales/checksums.js +62 -0
- package/src/detect/locales/compile.js +177 -0
- package/src/detect/locales/createDetector.js +179 -0
- package/src/detect/locales/englishDefaultRules.js +164 -0
- package/src/detect/locales/packs/en.js +23 -0
- package/src/detect/locales/packs/hi.js +33 -0
- package/src/detect/locales/packs/regions.js +174 -0
- package/src/detect/locales/scope.js +24 -0
- package/src/detect/locales/universal.js +59 -0
- package/src/detect/locales/validate.js +78 -0
- package/src/detect/locales/warnings.js +54 -0
- package/src/detect/ocr.js +58 -5
- package/src/detect/ocrFilter.js +31 -0
- package/src/detect/patterns.js +11 -302
- package/src/detect/textRegions.js +15 -19
- package/src/host/assets.js +29 -2
- package/src/index.js +8 -1
- package/src/prefs/languages.js +75 -0
- package/src/review/controller.js +146 -27
- package/src/review/element.js +25 -0
- package/src/review/react.js +15 -1
- package/src/review/review.css +68 -43
- package/src/review/template.js +12 -14
package/README.md
CHANGED
|
@@ -56,6 +56,17 @@ redactDocument(text, ['email', 'phone']);
|
|
|
56
56
|
console.log(TEXT_TYPES); // every category the default run checks
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
+
For Hindi documents, build a detector that includes the `hi` pack. OCR then loads `eng+hin`, and Devanagari labels and digits are checked:
|
|
60
|
+
|
|
61
|
+
```js
|
|
62
|
+
import { createDetector } from 'privacy-redact';
|
|
63
|
+
|
|
64
|
+
const detector = createDetector({ regions: ['IN'], languages: ['en', 'hi'] });
|
|
65
|
+
const { text, findings, warnings } = detector.redactDocument(hindiFormText);
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
On the review element, set `languages="en hi"` (or the React `languages={['en', 'hi']}` prop). Hindi is opt-in so English-only hosts keep the smaller default OCR load.
|
|
69
|
+
|
|
59
70
|
### Images and PDFs (React)
|
|
60
71
|
|
|
61
72
|
```jsx
|
|
@@ -155,7 +166,7 @@ For images and PDFs, the scan also finds faces, barcodes, and QR codes. More bef
|
|
|
155
166
|
privacy-redact is a safety net, not a guarantee. Review the preview before sharing.
|
|
156
167
|
|
|
157
168
|
- Names, company names, signatures, logos, and license plates are not detected.
|
|
158
|
-
- Detection
|
|
169
|
+
- Detection defaults to English. Address rules cover US, Canada, UK, and India. For Hindi (Devanagari) documents, pass `languages: ['en', 'hi']` to `createDetector` or set `languages="en hi"` on the review element so OCR loads `eng+hin` and Hindi labels are checked.
|
|
159
170
|
- OCR can miss tiny, low-contrast, rotated, or handwritten text. Small or heavily rotated faces can be missed too.
|
|
160
171
|
- HEIC images cannot be decoded in browsers. Convert them to JPG or PNG first.
|
|
161
172
|
- PDFs are limited to 60 pages and are exported as images.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "privacy-redact",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Library for detecting private content, redacting it, and handling document metadata. Browser components cover OCR, faces, barcodes, and PDF pages.",
|
|
6
6
|
"exports": {
|
|
@@ -67,6 +67,7 @@
|
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
69
|
"@tesseract.js-data/eng": "^1.0.0",
|
|
70
|
+
"@tesseract.js-data/hin": "^1.0.0",
|
|
70
71
|
"@vladmandic/face-api": "^1.7.15",
|
|
71
72
|
"@zxing/library": "^0.23.0",
|
|
72
73
|
"exifr": "^7.1.3",
|
package/scripts/copy-assets.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { cpSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
|
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { OCR_CORE_FILES } from '../src/detect/ocrCore.js';
|
|
7
|
+
import { SHIPPED_OCR_CODES } from '../src/detect/locales/scope.js';
|
|
7
8
|
|
|
8
9
|
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
9
10
|
/**
|
|
@@ -30,12 +31,17 @@ function copy(src, dest) {
|
|
|
30
31
|
cpSync(src, dest, { recursive: true });
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
// Tesseract OCR: worker + every LSTM-only WASM core the OCR module can pick +
|
|
34
|
+
// Tesseract OCR: worker + every LSTM-only WASM core the OCR module can pick + shipped language models
|
|
34
35
|
copy(nm('tesseract.js/dist/worker.min.js'), out('tesseract/worker.min.js'));
|
|
35
36
|
for (const f of Object.values(OCR_CORE_FILES)) {
|
|
36
37
|
copy(nm(`tesseract.js-core/${f}`), out(`tesseract/${f}`));
|
|
37
38
|
}
|
|
38
|
-
|
|
39
|
+
for (const code of SHIPPED_OCR_CODES) {
|
|
40
|
+
copy(
|
|
41
|
+
nm(`@tesseract.js-data/${code}/4.0.0_best_int/${code}.traineddata.gz`),
|
|
42
|
+
out(`tesseract/${code}.traineddata.gz`),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
39
45
|
|
|
40
46
|
// Face detection model (SSD MobileNet v1)
|
|
41
47
|
const faceModelDir = nm('@vladmandic/face-api/model');
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checksums and PAN shape helpers shared by region packs and the public patterns API.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/** Luhn checksum – used to tell real card numbers from random digit runs. */
|
|
6
|
+
export function luhn(digits) {
|
|
7
|
+
let sum = 0;
|
|
8
|
+
let alt = false;
|
|
9
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
10
|
+
let n = digits.charCodeAt(i) - 48;
|
|
11
|
+
if (n < 0 || n > 9) return false;
|
|
12
|
+
if (alt) { n *= 2; if (n > 9) n -= 9; }
|
|
13
|
+
sum += n;
|
|
14
|
+
alt = !alt;
|
|
15
|
+
}
|
|
16
|
+
return digits.length > 0 && sum % 10 === 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const VERHOEFF_D = [
|
|
20
|
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
|
|
21
|
+
[3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
|
|
22
|
+
[6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
|
|
23
|
+
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
|
|
24
|
+
];
|
|
25
|
+
const VERHOEFF_P = [
|
|
26
|
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
|
|
27
|
+
[8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
|
|
28
|
+
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
/** Verhoeff checksum - used to tell real Aadhaar numbers from random 12-digit runs. */
|
|
32
|
+
export function verhoeff(digits) {
|
|
33
|
+
let c = 0;
|
|
34
|
+
for (let i = 0; i < digits.length; i++) {
|
|
35
|
+
const n = digits.charCodeAt(digits.length - 1 - i) - 48;
|
|
36
|
+
if (n < 0 || n > 9) return false;
|
|
37
|
+
c = VERHOEFF_D[c][VERHOEFF_P[i % 8][n]];
|
|
38
|
+
}
|
|
39
|
+
return digits.length > 0 && c === 0;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const PAN_DIGIT_TO_LETTER = { 0: 'O', 1: 'I', 2: 'Z', 5: 'S', 6: 'G', 8: 'B' };
|
|
43
|
+
export const PAN_LETTER_TO_DIGIT = { O: '0', D: '0', I: '1', L: '1', Z: '2', S: '5', G: '6', B: '8' };
|
|
44
|
+
export const PAN_TRAILING_NOISE = '|])!/\\';
|
|
45
|
+
export const PAN_HOLDER_TYPES = 'PCHFATBLJG';
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* True if a 10-char value is a PAN once common OCR look-alike swaps are undone.
|
|
49
|
+
* `minExact` is how many characters must already be the right kind without any repair.
|
|
50
|
+
*/
|
|
51
|
+
export function looksLikePan(value, minExact = 0) {
|
|
52
|
+
if (value.length !== 10) return false;
|
|
53
|
+
let exact = 0;
|
|
54
|
+
for (let i = 0; i < 10; i++) {
|
|
55
|
+
const c = value[i];
|
|
56
|
+
const wantLetter = i < 5 || i === 9;
|
|
57
|
+
if (wantLetter ? (c >= 'A' && c <= 'Z') : (c >= '0' && c <= '9')) { exact++; continue; }
|
|
58
|
+
const repaired = wantLetter ? PAN_DIGIT_TO_LETTER[c] : PAN_LETTER_TO_DIGIT[c];
|
|
59
|
+
if (!repaired && !(i === 9 && PAN_TRAILING_NOISE.includes(c))) return false;
|
|
60
|
+
}
|
|
61
|
+
return exact >= minExact;
|
|
62
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiles language and region packs into the regex rule list a detector runs.
|
|
3
|
+
*/
|
|
4
|
+
import { ENGLISH_DEFAULT_RULES } from './englishDefaultRules.js';
|
|
5
|
+
import { UNIVERSAL_RULES } from './universal.js';
|
|
6
|
+
import { escapeRe, labelForms } from './validate.js';
|
|
7
|
+
|
|
8
|
+
const BOUND_START = String.raw`(?<![\p{L}\p{M}\p{N}_])`;
|
|
9
|
+
const SEP = String.raw`\.?\s*[:#;\-=\u2013\u2014]?\s*`;
|
|
10
|
+
|
|
11
|
+
/** Build one alternation from literal labels, including NFC/NFD forms. */
|
|
12
|
+
function altFromLabels(labels) {
|
|
13
|
+
const forms = [];
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
for (const label of labels) {
|
|
16
|
+
for (const form of labelForms(label)) {
|
|
17
|
+
const spaced = escapeRe(form).replace(/\\ /g, String.raw`\s+`).replace(/ /g, String.raw`\s+`);
|
|
18
|
+
if (seen.has(spaced)) continue;
|
|
19
|
+
seen.add(spaced);
|
|
20
|
+
forms.push(spaced);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
forms.sort((a, b) => b.length - a.length);
|
|
24
|
+
return forms.join('|');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Optional suffix group after a label (No, संख्या, …). */
|
|
28
|
+
function suffixGroup(suffixes) {
|
|
29
|
+
if (!suffixes?.length) return '';
|
|
30
|
+
const alt = altFromLabels(suffixes);
|
|
31
|
+
return String.raw`(?:\s+(?:${alt}))*`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Labelled rules: for each category with a value shape in a scoped region,
|
|
36
|
+
* combine every label for that category from scoped languages.
|
|
37
|
+
*/
|
|
38
|
+
export function compileLabelledRules(languages, regions) {
|
|
39
|
+
const rules = [];
|
|
40
|
+
const shapesByType = new Map();
|
|
41
|
+
for (const region of regions) {
|
|
42
|
+
for (const [type, shape] of Object.entries(region.valueShapes || {})) {
|
|
43
|
+
if (!shapesByType.has(type)) shapesByType.set(type, shape);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
for (const [type, shape] of shapesByType) {
|
|
48
|
+
const labels = [];
|
|
49
|
+
for (const lang of languages) {
|
|
50
|
+
const list = lang.labels?.[type];
|
|
51
|
+
if (list) labels.push(...list);
|
|
52
|
+
}
|
|
53
|
+
if (!labels.length) continue;
|
|
54
|
+
|
|
55
|
+
const labelAlt = altFromLabels(labels);
|
|
56
|
+
const suffixes = languages.flatMap((l) => l.labelSuffixes || []);
|
|
57
|
+
const hasLatin = labels.some((l) => /[A-Za-z]/.test(l));
|
|
58
|
+
const flags = hasLatin ? 'giu' : 'gu';
|
|
59
|
+
const source = `${BOUND_START}(?:${labelAlt})${suffixGroup(suffixes)}${SEP}${shape.source}`;
|
|
60
|
+
rules.push({
|
|
61
|
+
type,
|
|
62
|
+
re: new RegExp(source, flags),
|
|
63
|
+
group: shape.group ?? 1,
|
|
64
|
+
confidence: shape.confidence,
|
|
65
|
+
validate: shape.validate,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return rules;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Postal rules: postal labels or place names followed by the region's postal shape. */
|
|
72
|
+
export function compilePostalRules(languages, regions) {
|
|
73
|
+
const rules = [];
|
|
74
|
+
for (const region of regions) {
|
|
75
|
+
if (!region.postal?.source) continue;
|
|
76
|
+
const postalLabels = languages.flatMap((l) => l.postalLabels || []);
|
|
77
|
+
const places = [
|
|
78
|
+
...(region.places || []),
|
|
79
|
+
...languages.flatMap((l) => l.places?.[region.id] || []),
|
|
80
|
+
];
|
|
81
|
+
if (postalLabels.length) {
|
|
82
|
+
const alt = altFromLabels(postalLabels);
|
|
83
|
+
const hasLatin = postalLabels.some((l) => /[A-Za-z]/.test(l));
|
|
84
|
+
rules.push({
|
|
85
|
+
type: 'address',
|
|
86
|
+
re: new RegExp(`${BOUND_START}(?:${alt})${SEP}(${region.postal.source})`, hasLatin ? 'giu' : 'gu'),
|
|
87
|
+
group: 1,
|
|
88
|
+
confidence: region.postal.confidence ?? 0.9,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
if (places.length) {
|
|
92
|
+
const alt = altFromLabels(places);
|
|
93
|
+
const hasLatin = places.some((l) => /[A-Za-z]/.test(l));
|
|
94
|
+
rules.push({
|
|
95
|
+
type: 'address',
|
|
96
|
+
re: new RegExp(`${BOUND_START}(?:${alt})${SEP}(${region.postal.source})`, hasLatin ? 'giu' : 'gu'),
|
|
97
|
+
group: 1,
|
|
98
|
+
confidence: region.postal.confidence ?? 0.9,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return rules;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Extra India unlabelled rules not yet folded into the frozen English list. */
|
|
106
|
+
export function indiaExtraRules(regions) {
|
|
107
|
+
if (!regions.some((r) => r.id === 'IN')) return [];
|
|
108
|
+
return [
|
|
109
|
+
{
|
|
110
|
+
type: 'phone',
|
|
111
|
+
re: /(?<![\d])0\d{2,4}[\s.\-]?\d{6,8}(?!\d)/g,
|
|
112
|
+
validate(m) {
|
|
113
|
+
const n = m.replace(/\D/g, '').length;
|
|
114
|
+
return n === 10 || n === 11 ? 0.85 : 0;
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
type: 'aadhaar',
|
|
119
|
+
re: /(?:[*xX•●·]{4}[ \-]?){2}\d{4}(?!\d)/g,
|
|
120
|
+
confidence: 0.85,
|
|
121
|
+
},
|
|
122
|
+
];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Build the rule list for one resolved scope.
|
|
127
|
+
* When English is on, reuse the frozen default list so current tests stay unchanged.
|
|
128
|
+
*/
|
|
129
|
+
export function compileRules(languages, regions) {
|
|
130
|
+
const hasEn = languages.some((l) => l.id === 'en');
|
|
131
|
+
const otherLangs = languages.filter((l) => l.id !== 'en');
|
|
132
|
+
|
|
133
|
+
if (hasEn) {
|
|
134
|
+
const rules = [
|
|
135
|
+
...ENGLISH_DEFAULT_RULES,
|
|
136
|
+
...indiaExtraRules(regions),
|
|
137
|
+
...compileLabelledRules(otherLangs, regions),
|
|
138
|
+
...compilePostalRules(languages, regions),
|
|
139
|
+
];
|
|
140
|
+
return rules;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const seen = new Set();
|
|
144
|
+
const unlabelled = [];
|
|
145
|
+
for (const region of regions) {
|
|
146
|
+
for (const rule of region.unlabelledRules || []) {
|
|
147
|
+
const key = `${rule.type}:${rule.re}`;
|
|
148
|
+
if (seen.has(key)) continue;
|
|
149
|
+
seen.add(key);
|
|
150
|
+
unlabelled.push(rule);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return [
|
|
154
|
+
...UNIVERSAL_RULES,
|
|
155
|
+
...unlabelled,
|
|
156
|
+
...compileLabelledRules(languages, regions),
|
|
157
|
+
...compilePostalRules(languages, regions),
|
|
158
|
+
];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Merge digit tables from every language in scope. */
|
|
162
|
+
export function mergeDigitMaps(languages) {
|
|
163
|
+
const map = Object.create(null);
|
|
164
|
+
for (const lang of languages) {
|
|
165
|
+
if (!lang.digits) continue;
|
|
166
|
+
Object.assign(map, lang.digits);
|
|
167
|
+
}
|
|
168
|
+
return map;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Map native digits to ASCII one code unit at a time so offsets stay stable. */
|
|
172
|
+
export function applyDigitMap(text, digitMap) {
|
|
173
|
+
if (!digitMap || !Object.keys(digitMap).length) return text;
|
|
174
|
+
let out = '';
|
|
175
|
+
for (const ch of text) out += digitMap[ch] ?? ch;
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds a detector for one region/language scope. Rules are compiled once.
|
|
3
|
+
*/
|
|
4
|
+
import en from './packs/en.js';
|
|
5
|
+
import hi from './packs/hi.js';
|
|
6
|
+
import { REGION_PACKS } from './packs/regions.js';
|
|
7
|
+
import { DEFAULT_SCOPE, normalizeScopeInput } from './scope.js';
|
|
8
|
+
import { validateLanguagePack } from './validate.js';
|
|
9
|
+
import { compileRules, mergeDigitMaps, applyDigitMap } from './compile.js';
|
|
10
|
+
import { scriptWarnings } from './warnings.js';
|
|
11
|
+
|
|
12
|
+
const LANGUAGE_PACKS = { en, hi };
|
|
13
|
+
|
|
14
|
+
export const CATEGORIES = {
|
|
15
|
+
card: { label: 'Credit cards', icon: '💳', regions: [] },
|
|
16
|
+
ssn: { label: 'SSN / national ID', icon: '🪪', regions: ['US', 'CA'] },
|
|
17
|
+
aadhaar: { label: 'Aadhaar numbers', icon: '🆔', regions: ['IN'] },
|
|
18
|
+
pan: { label: 'PAN (India tax ID)', icon: '🧾', regions: ['IN'] },
|
|
19
|
+
email: { label: 'Emails', icon: '✉️', regions: [] },
|
|
20
|
+
phone: { label: 'Phone numbers', icon: '📞', regions: [] },
|
|
21
|
+
address: { label: 'Home addresses', icon: '🏠', regions: [] },
|
|
22
|
+
account: { label: 'Account numbers', icon: '🏦', regions: [] },
|
|
23
|
+
dob: { label: 'Dates of birth', icon: '🎂', regions: [] },
|
|
24
|
+
secret: { label: 'API keys & tokens', icon: '🔑', regions: [] },
|
|
25
|
+
face: { label: 'Faces', icon: '🙂', regions: [] },
|
|
26
|
+
barcode: { label: 'Barcodes & QR', icon: '▦', regions: [] },
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const TEXT_TYPES = ['card', 'ssn', 'aadhaar', 'pan', 'email', 'phone', 'address', 'account', 'dob', 'secret'];
|
|
30
|
+
|
|
31
|
+
/** Resolve a language entry (id or pack object) into a validated pack. */
|
|
32
|
+
function resolveLanguage(entry, i) {
|
|
33
|
+
if (typeof entry === 'string') {
|
|
34
|
+
const pack = LANGUAGE_PACKS[entry];
|
|
35
|
+
if (!pack) throw new TypeError(`createDetector: unknown language "${entry}"`);
|
|
36
|
+
return validateLanguagePack(pack, `languages[${i}]`);
|
|
37
|
+
}
|
|
38
|
+
return validateLanguagePack(entry, `languages[${i}]`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Resolve a region id into a shipped region pack. */
|
|
42
|
+
function resolveRegion(entry, i) {
|
|
43
|
+
if (typeof entry !== 'string') {
|
|
44
|
+
throw new TypeError(`createDetector: regions[${i}] must be a shipped region id`);
|
|
45
|
+
}
|
|
46
|
+
const pack = REGION_PACKS[entry];
|
|
47
|
+
if (!pack) throw new TypeError(`createDetector: unknown region "${entry}"`);
|
|
48
|
+
return pack;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Merge overlapping hits, preferring the higher-confidence / more specific one. */
|
|
52
|
+
function dedupe(hits) {
|
|
53
|
+
hits.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
54
|
+
const res = [];
|
|
55
|
+
for (const h of hits) {
|
|
56
|
+
const last = res[res.length - 1];
|
|
57
|
+
if (last && h.start < last.end) {
|
|
58
|
+
if (h.type === last.type) {
|
|
59
|
+
last.end = Math.max(last.end, h.end);
|
|
60
|
+
last.confidence = Math.max(last.confidence, h.confidence);
|
|
61
|
+
} else if (h.confidence > last.confidence && h.end - h.start >= (last.end - last.start) * 0.6) {
|
|
62
|
+
res[res.length - 1] = h;
|
|
63
|
+
}
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
res.push({ ...h });
|
|
67
|
+
}
|
|
68
|
+
return res;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Run compiled rules on (digit-mapped) text for the enabled categories. */
|
|
72
|
+
function runRules(text, rules, enabled) {
|
|
73
|
+
const on = new Set(enabled);
|
|
74
|
+
const out = [];
|
|
75
|
+
for (const rule of rules) {
|
|
76
|
+
if (!on.has(rule.type)) continue;
|
|
77
|
+
rule.re.lastIndex = 0;
|
|
78
|
+
let m;
|
|
79
|
+
while ((m = rule.re.exec(text)) !== null) {
|
|
80
|
+
if (m[0].length === 0) { rule.re.lastIndex++; continue; }
|
|
81
|
+
const conf = rule.validate ? rule.validate(m[0]) : rule.confidence;
|
|
82
|
+
if (!conf) continue;
|
|
83
|
+
let start = m.index;
|
|
84
|
+
let end = m.index + m[0].length;
|
|
85
|
+
if (rule.group) {
|
|
86
|
+
const g = m[rule.group];
|
|
87
|
+
if (!g) continue;
|
|
88
|
+
start = m.index + m[0].lastIndexOf(g);
|
|
89
|
+
end = start + g.length;
|
|
90
|
+
}
|
|
91
|
+
while (end > start && /[\s.,;:)]/.test(text[end - 1]) && !(text[end - 1] === ')' && text.slice(start, end).includes('('))) end--;
|
|
92
|
+
while (start < end && /\s/.test(text[start])) start++;
|
|
93
|
+
if (end > start) out.push({ type: rule.type, start, end, confidence: conf });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return dedupe(out);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Compile one detector for a scope. Unknown ids throw. Pack objects are allowed for languages.
|
|
101
|
+
* @param {{ regions?: string[], languages?: (string|object)[] }} [scope]
|
|
102
|
+
*/
|
|
103
|
+
export function createDetector(scope) {
|
|
104
|
+
const input = normalizeScopeInput(scope);
|
|
105
|
+
if (!Array.isArray(input.regions) || !Array.isArray(input.languages)) {
|
|
106
|
+
throw new TypeError('createDetector: regions and languages must be arrays');
|
|
107
|
+
}
|
|
108
|
+
const regions = input.regions.map(resolveRegion);
|
|
109
|
+
const languages = input.languages.map(resolveLanguage);
|
|
110
|
+
const ids = { regions: regions.map((r) => r.id), languages: languages.map((l) => l.id) };
|
|
111
|
+
|
|
112
|
+
const rules = compileRules(languages, regions);
|
|
113
|
+
const digitMap = mergeDigitMaps(languages);
|
|
114
|
+
const coveredScripts = languages.flatMap((l) => l.scripts);
|
|
115
|
+
const ocrLanguages = languages.flatMap((l) => l.ocr).join('+') || 'eng';
|
|
116
|
+
const textTypes = TEXT_TYPES.filter((id) => {
|
|
117
|
+
const cat = CATEGORIES[id];
|
|
118
|
+
if (!cat.regions.length) return true;
|
|
119
|
+
return cat.regions.some((r) => ids.regions.includes(r));
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
/** Find sensitive spans; offsets are into the original text. */
|
|
123
|
+
function findSensitive(text, enabled = textTypes) {
|
|
124
|
+
const value = String(text ?? '');
|
|
125
|
+
if (!value) return [];
|
|
126
|
+
const mapped = applyDigitMap(value, digitMap);
|
|
127
|
+
return runRules(mapped, rules, enabled);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Redact plain text with bullets of the same length. */
|
|
131
|
+
function redactPlainText(text, types = textTypes) {
|
|
132
|
+
const value = String(text ?? '');
|
|
133
|
+
if (!value) return '';
|
|
134
|
+
const hits = findSensitive(value, types);
|
|
135
|
+
if (!hits.length) return value;
|
|
136
|
+
let out = '';
|
|
137
|
+
let i = 0;
|
|
138
|
+
for (const h of hits) {
|
|
139
|
+
out += value.slice(i, h.start);
|
|
140
|
+
out += '•'.repeat(h.end - h.start);
|
|
141
|
+
i = h.end;
|
|
142
|
+
}
|
|
143
|
+
return out + value.slice(i);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Redact and return counts per category, plus scope and coverage warnings. */
|
|
147
|
+
function redactDocument(text, types = textTypes) {
|
|
148
|
+
const value = String(text ?? '');
|
|
149
|
+
const hits = value ? findSensitive(value, types) : [];
|
|
150
|
+
const counts = {};
|
|
151
|
+
for (const hit of hits) counts[hit.type] = (counts[hit.type] || 0) + 1;
|
|
152
|
+
// Match the public findings field order (type, label, count).
|
|
153
|
+
return {
|
|
154
|
+
text: redactPlainText(value, types),
|
|
155
|
+
findings: Object.entries(counts).map(([type, count]) => ({
|
|
156
|
+
type,
|
|
157
|
+
label: CATEGORIES[type]?.label || type,
|
|
158
|
+
count,
|
|
159
|
+
})),
|
|
160
|
+
scope: { regions: [...ids.regions], languages: [...ids.languages] },
|
|
161
|
+
warnings: scriptWarnings(value, coveredScripts),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
findSensitive,
|
|
167
|
+
redactDocument,
|
|
168
|
+
redactPlainText,
|
|
169
|
+
textTypes,
|
|
170
|
+
ocrLanguages,
|
|
171
|
+
scope: { regions: [...ids.regions], languages: [...ids.languages] },
|
|
172
|
+
coveredScripts,
|
|
173
|
+
labelStarters: languages.flatMap((l) => Object.values(l.labels || {}).flat()),
|
|
174
|
+
digitMap,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Detector used by the top-level functions when no scope is chosen. */
|
|
179
|
+
export const defaultDetector = createDetector(DEFAULT_SCOPE);
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Today's English-default rule list, kept intact so existing tests stay green.
|
|
3
|
+
* createDetector uses this when 'en' is in scope; other language packs append.
|
|
4
|
+
*/
|
|
5
|
+
import { luhn, verhoeff, looksLikePan, PAN_DIGIT_TO_LETTER, PAN_HOLDER_TYPES } from './checksums.js';
|
|
6
|
+
|
|
7
|
+
const STATES = 'AL|AK|AZ|AR|CA|CO|CT|DE|DC|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY';
|
|
8
|
+
const PROVINCES = 'AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT';
|
|
9
|
+
const STREET_SUFFIX_BASE = 'Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Drive|Dr|Lane|Ln|Court|Ct|Way|Place|Pl|Terrace|Ter|Parkway|Pkwy|Circle|Cir|Highway|Hwy|Trail|Trl|Square|Sq|Loop|Alley|Row';
|
|
10
|
+
const STREET_SUFFIX = `${STREET_SUFFIX_BASE}|${STREET_SUFFIX_BASE.toUpperCase()}`;
|
|
11
|
+
const DATE = String.raw`(?:\d{1,2}[\/.\-]\d{1,2}[\/.\-](?:\d{4}|\d{2})|\d{4}[\/.\-]\d{1,2}[\/.\-]\d{1,2}|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*\.?\s+\d{1,2},?\s+\d{4}|\d{1,2}\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*\.?,?\s+\d{4})`;
|
|
12
|
+
|
|
13
|
+
/** Full rule list matching pre-locale English detection. */
|
|
14
|
+
export const ENGLISH_DEFAULT_RULES = [
|
|
15
|
+
{
|
|
16
|
+
type: 'email',
|
|
17
|
+
re: /[A-Za-z0-9._%+\-]+[@@¢©®¤][A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)*\.[A-Za-z]{2,}/g,
|
|
18
|
+
confidence: 0.98,
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
type: 'card',
|
|
22
|
+
re: /(?<![\d])(?:\d[ \-]?){12,18}\d(?![\d])/g,
|
|
23
|
+
validate(m) {
|
|
24
|
+
const digits = m.replace(/\D/g, '');
|
|
25
|
+
if (digits.length < 13 || digits.length > 19) return 0;
|
|
26
|
+
if (luhn(digits)) return 0.97;
|
|
27
|
+
if (/^\d{4}[ \-]\d{4}[ \-]\d{4}[ \-]\d{4}$/.test(m.trim())) return 0.75;
|
|
28
|
+
if (/^\d{4}[ \-]\d{6}[ \-]\d{5}$/.test(m.trim())) return 0.75;
|
|
29
|
+
return 0;
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
type: 'card',
|
|
34
|
+
re: /(?:[*xX•●·]{4}[ \-]?){1,3}\d{4}\b/g,
|
|
35
|
+
confidence: 0.8,
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
type: 'ssn',
|
|
39
|
+
re: /(?<![\d\-])(?!000|666|9\d\d)\d{3}[\- ](?!00)\d{2}[\- ](?!0000)\d{4}(?![\d\-])/g,
|
|
40
|
+
confidence: 0.95,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
type: 'ssn',
|
|
44
|
+
re: /\b(?:SSN|SS#|Social\s+Security(?:\s+(?:No|Number|#))?\.?|SIN|Tax\s*ID|TIN|EIN)\s*[:#\-]?\s*([\dXx*\- ]{9,12})\b/gi,
|
|
45
|
+
group: 1,
|
|
46
|
+
confidence: 0.9,
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
type: 'aadhaar',
|
|
50
|
+
re: /(?<![\d\-])(?<!\d[ \-])[2-9]\d{3}([ \-]?)\d{4}\1\d{4}(?!\d|[ \-]\d|-)/g,
|
|
51
|
+
validate: (m) => (verhoeff(m.replace(/\D/g, '')) ? 0.95 : 0),
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
type: 'aadhaar',
|
|
55
|
+
re: /\b(?:aa?dha{1,2}r|UID(?:AI)?)(?:\s+(?:Card|No|Number|Num|ID))*\.?\s*[:#\-\u2013\u2014]?\s*(\d{4}[ \-]?\d{4}[ \-]?\d{4})(?!\d)/gi,
|
|
56
|
+
group: 1,
|
|
57
|
+
confidence: 0.9,
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
type: 'pan',
|
|
61
|
+
re: /\b[A-Z0-9]{10}\b/g,
|
|
62
|
+
validate(m) {
|
|
63
|
+
if (!looksLikePan(m, 8)) return 0;
|
|
64
|
+
const fourth = /[A-Z]/.test(m[3]) ? m[3] : PAN_DIGIT_TO_LETTER[m[3]];
|
|
65
|
+
return PAN_HOLDER_TYPES.includes(fourth) ? 0.95 : 0;
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
type: 'pan',
|
|
70
|
+
re: /\b(?:Permanent\s+Account\s+(?:No|Number)|PAN)(?:\s*\(\s*PAN\s*\))?(?:\s+(?:No|Number|Card))?\.?\s*[:;,#=\-\u2013\u2014]?\s*([A-Z0-9]{5} ?[A-Z0-9]{4} ?[A-Z0-9|\])!\/\\])(?![A-Za-z0-9])/gi,
|
|
71
|
+
group: 1,
|
|
72
|
+
validate: (m) => (looksLikePan(m.replace(/\s/g, '').toUpperCase().slice(-10)) ? 0.9 : 0),
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
type: 'phone',
|
|
76
|
+
re: /(?<![\w@.\-\/])(?:\+?1[\s.\-]?)?(?:\(\d{3}\)\s?|\d{3}[\s.\-])\d{3}[\s.\-]\d{4}(?![\d\-])/g,
|
|
77
|
+
confidence: 0.9,
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
type: 'phone',
|
|
81
|
+
re: /(?<![\w@.\-\/])\+\d{1,3}[\s.\-]?(?:\(?\d{1,4}\)?[\s.\-]?){2,5}\d{2,4}(?![\d\-])/g,
|
|
82
|
+
validate(m) {
|
|
83
|
+
const n = m.replace(/\D/g, '').length;
|
|
84
|
+
return n >= 8 && n <= 15 ? 0.85 : 0;
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
type: 'phone',
|
|
89
|
+
re: /\b(?:Mobile|Mob|Phone|Ph|Phn|Tel|Telephone|Cell|Whatsapp|WA|Contact)\s*(?:No|Number|#)?\.?\s*[:#\-]?\s*(\+?\d[\d\s.\-()]{7,16}\d)/gi,
|
|
90
|
+
group: 1,
|
|
91
|
+
validate(m) {
|
|
92
|
+
const n = m.replace(/\D/g, '').length;
|
|
93
|
+
return n >= 10 && n <= 15 ? 0.92 : 0;
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
type: 'phone',
|
|
98
|
+
re: /(?<![\w@/])(?:\+91[\s.\-]?)?[6-9]\d{4}[\s.\-]\d{5}(?!\d)/g,
|
|
99
|
+
confidence: 0.88,
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
type: 'phone',
|
|
103
|
+
re: /(?<![\w@/.\-])[6-9]\d{9}(?![\d\-@/]|\.\d)/g,
|
|
104
|
+
confidence: 0.75,
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
type: 'address',
|
|
108
|
+
re: new RegExp(String.raw`\b\d{1,6}[A-Za-z]?\s+(?:(?:N|S|E|W|NE|NW|SE|SW|North|South|East|West|NORTH|SOUTH|EAST|WEST)\.?\s+)?(?:[A-Z0-9][A-Za-z0-9.'\-]*\s+){0,3}?(?:${STREET_SUFFIX})\b\.?(?:\s+(?:NW|NE|SW|SE|N|S|E|W)\b\.?)?(?:,?\s*(?:Apt|Apartment|Suite|Ste|Unit|Fl|Floor|APT|SUITE|STE|UNIT|#)\.?\s*[\w\-]+)?`, 'g'),
|
|
109
|
+
validate: (m) => (/^\d/.test(m) ? 0.85 : 0),
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
type: 'address',
|
|
113
|
+
re: new RegExp(String.raw`\b[A-Z][A-Za-z.'\-]+(?:\s[A-Z][A-Za-z.'\-]+){0,3},?\s+(?:${STATES})\.?\s+\d{5}(?:-\d{4})?\b`, 'g'),
|
|
114
|
+
confidence: 0.9,
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
type: 'address',
|
|
118
|
+
re: new RegExp(String.raw`\b[A-Z][A-Za-z.'\-]+(?:\s[A-Z][A-Za-z.'\-]+){0,3},?\s+(?:${PROVINCES})\s+[A-Z]\d[A-Z][ \-]?\d[A-Z]\d\b`, 'g'),
|
|
119
|
+
confidence: 0.9,
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
type: 'address',
|
|
123
|
+
re: /\bP\.?\s?O\.?\s+Box\s+\d+\b/gi,
|
|
124
|
+
confidence: 0.9,
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
type: 'address',
|
|
128
|
+
re: /\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b/g,
|
|
129
|
+
confidence: 0.6,
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
type: 'account',
|
|
133
|
+
re: /\b(?:Acct|Account|Routing|ABA|Member|Policy|Patient|MRN|Claim|Customer|License|Licence|Passport|Employee|Driver'?s?\s+Lic(?:ense)?)\.?\s*(?:ID|No|Number|Num|#)?\.?\s*[:#\-]?\s*((?=[A-Z\-]*\d)[A-Z0-9][A-Z0-9\-]{5,})/gi,
|
|
134
|
+
group: 1,
|
|
135
|
+
confidence: 0.85,
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
type: 'account',
|
|
139
|
+
re: /\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){3,7}(?:[ ]?[A-Z0-9]{1,4})?\b/g,
|
|
140
|
+
validate: (m) => (m.replace(/\s/g, '').length >= 15 && /\d/.test(m) ? 0.8 : 0),
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
type: 'dob',
|
|
144
|
+
re: new RegExp(String.raw`\b(?:DOB|D\.O\.B\.?|Date\s+of\s+Birth|Birth\s*date|Birthday|Born)\s*[:\-]?\s*(${DATE})`, 'gi'),
|
|
145
|
+
group: 1,
|
|
146
|
+
confidence: 0.92,
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
type: 'secret',
|
|
150
|
+
re: /\b(?:sk-[A-Za-z0-9_\-]{20,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|xox[baprs]-[A-Za-z0-9\-]{10,}|AIza[0-9A-Za-z_\-]{30,}|eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,})\b/g,
|
|
151
|
+
confidence: 0.97,
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
type: 'secret',
|
|
155
|
+
re: /\b(?:sk|pk|rk)[_\- ](?:live|test)[_\- ][A-Za-z0-9]{16,}/g,
|
|
156
|
+
confidence: 0.9,
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
type: 'secret',
|
|
160
|
+
re: /\b(?:password|passwd|pwd|passcode|secret|token|api[_\- ]?key)\s*[:=]\s*(\S{4,})/gi,
|
|
161
|
+
group: 1,
|
|
162
|
+
confidence: 0.85,
|
|
163
|
+
},
|
|
164
|
+
];
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** English: Latin labels and cue words for the default language pack. */
|
|
2
|
+
export default {
|
|
3
|
+
schema: 1,
|
|
4
|
+
id: 'en',
|
|
5
|
+
scripts: ['Latin'],
|
|
6
|
+
ocr: ['eng'],
|
|
7
|
+
labelSuffixes: ['No', 'Number', 'Num', 'ID', 'Card', '#'],
|
|
8
|
+
labels: {
|
|
9
|
+
aadhaar: ['Aadhaar', 'Aadhar', 'Adhaar', 'Adhar', 'UID', 'UIDAI'],
|
|
10
|
+
pan: ['PAN', 'Permanent Account Number', 'Permanent Account No'],
|
|
11
|
+
ssn: ['SSN', 'SS#', 'Social Security', 'Social Security No', 'Social Security Number', 'SIN', 'Tax ID', 'TIN', 'EIN'],
|
|
12
|
+
phone: ['Mobile', 'Mob', 'Phone', 'Ph', 'Phn', 'Tel', 'Telephone', 'Cell', 'Whatsapp', 'WA', 'Contact'],
|
|
13
|
+
account: [
|
|
14
|
+
'Acct', 'Account', 'Routing', 'ABA', 'Member', 'Policy', 'Patient', 'MRN', 'Claim',
|
|
15
|
+
'Customer', 'License', 'Licence', 'Passport', 'Employee', "Driver's Lic", 'Drivers Lic',
|
|
16
|
+
'Driver License', 'Drivers License',
|
|
17
|
+
],
|
|
18
|
+
dob: ['DOB', 'D.O.B', 'D.O.B.', 'Date of Birth', 'Birth date', 'Birthdate', 'Birthday', 'Born'],
|
|
19
|
+
},
|
|
20
|
+
postalLabels: ['ZIP', 'Zip', 'Postal', 'Postcode', 'PIN', 'Pin'],
|
|
21
|
+
addressCues: ['Apt', 'Apartment', 'Suite', 'Ste', 'Unit', 'Fl', 'Floor'],
|
|
22
|
+
places: {},
|
|
23
|
+
};
|