privacy-redact 1.0.3 โ 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 +137 -217
- 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 +57 -19
- package/src/host/assets.js +33 -4
- package/src/index.js +8 -1
- package/src/prefs/languages.js +75 -0
- package/src/review/actions.js +93 -0
- package/src/review/controller.js +308 -73
- package/src/review/element.js +39 -0
- package/src/review/react.js +23 -1
- package/src/review/review.css +69 -43
- package/src/review/template.js +21 -16
package/src/detect/patterns.js
CHANGED
|
@@ -3,314 +3,23 @@
|
|
|
3
3
|
*
|
|
4
4
|
* `findSensitive(text, enabledTypes)` returns [{ type, start, end, confidence }]
|
|
5
5
|
* where start/end are character offsets into `text` (end exclusive).
|
|
6
|
+
*
|
|
7
|
+
* Locale packs and scopes live under `./locales/`. The top-level functions use
|
|
8
|
+
* the default scope (English + US/CA/GB/IN). Hosts that need Hindi call createDetector.
|
|
6
9
|
*/
|
|
10
|
+
export { luhn, verhoeff } from './locales/checksums.js';
|
|
11
|
+
export {
|
|
12
|
+
CATEGORIES, TEXT_TYPES, createDetector, defaultDetector,
|
|
13
|
+
} from './locales/createDetector.js';
|
|
14
|
+
export { DEFAULT_SCOPE, SHIPPED_OCR_CODES } from './locales/scope.js';
|
|
7
15
|
|
|
8
|
-
|
|
9
|
-
card: { label: 'Credit cards', icon: '๐ณ' },
|
|
10
|
-
ssn: { label: 'SSN / national ID', icon: '๐ชช' },
|
|
11
|
-
aadhaar: { label: 'Aadhaar numbers', icon: '๐' },
|
|
12
|
-
pan: { label: 'PAN (India tax ID)', icon: '๐งพ' },
|
|
13
|
-
email: { label: 'Emails', icon: 'โ๏ธ' },
|
|
14
|
-
phone: { label: 'Phone numbers', icon: '๐' },
|
|
15
|
-
address: { label: 'Home addresses', icon: '๐ ' },
|
|
16
|
-
account: { label: 'Account numbers', icon: '๐ฆ' },
|
|
17
|
-
dob: { label: 'Dates of birth', icon: '๐' },
|
|
18
|
-
secret: { label: 'API keys & tokens', icon: '๐' },
|
|
19
|
-
face: { label: 'Faces', icon: '๐' },
|
|
20
|
-
barcode: { label: 'Barcodes & QR', icon: 'โฆ' },
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
export const TEXT_TYPES = ['card', 'ssn', 'aadhaar', 'pan', 'email', 'phone', 'address', 'account', 'dob', 'secret'];
|
|
24
|
-
|
|
25
|
-
/** Luhn checksum โ used to tell real card numbers from random digit runs. */
|
|
26
|
-
export function luhn(digits) {
|
|
27
|
-
let sum = 0;
|
|
28
|
-
let alt = false;
|
|
29
|
-
for (let i = digits.length - 1; i >= 0; i--) {
|
|
30
|
-
let n = digits.charCodeAt(i) - 48;
|
|
31
|
-
if (n < 0 || n > 9) return false;
|
|
32
|
-
if (alt) { n *= 2; if (n > 9) n -= 9; }
|
|
33
|
-
sum += n;
|
|
34
|
-
alt = !alt;
|
|
35
|
-
}
|
|
36
|
-
return digits.length > 0 && sum % 10 === 0;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Verhoeff tables (multiplication and permutation) used by the Aadhaar checksum.
|
|
40
|
-
const VERHOEFF_D = [
|
|
41
|
-
[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],
|
|
42
|
-
[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],
|
|
43
|
-
[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],
|
|
44
|
-
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
|
|
45
|
-
];
|
|
46
|
-
const VERHOEFF_P = [
|
|
47
|
-
[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],
|
|
48
|
-
[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],
|
|
49
|
-
[2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
|
|
50
|
-
];
|
|
51
|
-
|
|
52
|
-
/** Verhoeff checksum - used to tell real Aadhaar numbers from random 12-digit runs. */
|
|
53
|
-
export function verhoeff(digits) {
|
|
54
|
-
let c = 0;
|
|
55
|
-
for (let i = 0; i < digits.length; i++) {
|
|
56
|
-
const n = digits.charCodeAt(digits.length - 1 - i) - 48;
|
|
57
|
-
if (n < 0 || n > 9) return false;
|
|
58
|
-
c = VERHOEFF_D[c][VERHOEFF_P[i % 8][n]];
|
|
59
|
-
}
|
|
60
|
-
return digits.length > 0 && c === 0;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// PAN is 5 letters, 4 digits, 1 letter. OCR swaps look-alike characters, so these maps repair a labelled value.
|
|
64
|
-
const PAN_DIGIT_TO_LETTER = { 0: 'O', 1: 'I', 2: 'Z', 5: 'S', 6: 'G', 8: 'B' };
|
|
65
|
-
const PAN_LETTER_TO_DIGIT = { O: '0', D: '0', I: '1', L: '1', Z: '2', S: '5', G: '6', B: '8' };
|
|
66
|
-
|
|
67
|
-
// A table border or bracket right after the last character is often read as part of it ("ANQPS5958J|").
|
|
68
|
-
const PAN_TRAILING_NOISE = '|])!/\\';
|
|
69
|
-
const PAN_HOLDER_TYPES = 'PCHFATBLJG';
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* True if a 10-char value is a PAN once common OCR look-alike swaps are undone.
|
|
73
|
-
* `minExact` is how many characters must already be the right kind without any repair.
|
|
74
|
-
*/
|
|
75
|
-
function looksLikePan(value, minExact = 0) {
|
|
76
|
-
if (value.length !== 10) return false;
|
|
77
|
-
let exact = 0;
|
|
78
|
-
for (let i = 0; i < 10; i++) {
|
|
79
|
-
const c = value[i];
|
|
80
|
-
const wantLetter = i < 5 || i === 9;
|
|
81
|
-
if (wantLetter ? (c >= 'A' && c <= 'Z') : (c >= '0' && c <= '9')) { exact++; continue; }
|
|
82
|
-
const repaired = wantLetter ? PAN_DIGIT_TO_LETTER[c] : PAN_LETTER_TO_DIGIT[c];
|
|
83
|
-
if (!repaired && !(i === 9 && PAN_TRAILING_NOISE.includes(c))) return false;
|
|
84
|
-
}
|
|
85
|
-
return exact >= minExact;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
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';
|
|
89
|
-
const PROVINCES = 'AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT';
|
|
90
|
-
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';
|
|
91
|
-
// Capitalised ("Street") or ALL CAPS ("STREET") โ never lowercase, which avoids matching prose like "3 items to the way".
|
|
92
|
-
const STREET_SUFFIX = `${STREET_SUFFIX_BASE}|${STREET_SUFFIX_BASE.toUpperCase()}`;
|
|
93
|
-
|
|
94
|
-
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})`;
|
|
95
|
-
|
|
96
|
-
/** Each rule: regex with /g, optional `group` (capture group to redact), optional `validate`. */
|
|
97
|
-
const RULES = [
|
|
98
|
-
{
|
|
99
|
-
// @ plus marks OCR prints in its place: fullwidth ๏ผ , cent ยข, ยฉ ยฎ ยค.
|
|
100
|
-
type: 'email',
|
|
101
|
-
re: /[A-Za-z0-9._%+\-]+[@๏ผ ยขยฉยฎยค][A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)*\.[A-Za-z]{2,}/g,
|
|
102
|
-
confidence: 0.98,
|
|
103
|
-
},
|
|
104
|
-
{
|
|
105
|
-
type: 'card',
|
|
106
|
-
re: /(?<![\d])(?:\d[ \-]?){12,18}\d(?![\d])/g,
|
|
107
|
-
validate(m) {
|
|
108
|
-
const digits = m.replace(/\D/g, '');
|
|
109
|
-
if (digits.length < 13 || digits.length > 19) return 0;
|
|
110
|
-
if (luhn(digits)) return 0.97;
|
|
111
|
-
// OCR often misreads a digit; keep well-formed 4-4-4-4 / Amex 4-6-5 groupings.
|
|
112
|
-
if (/^\d{4}[ \-]\d{4}[ \-]\d{4}[ \-]\d{4}$/.test(m.trim())) return 0.75;
|
|
113
|
-
if (/^\d{4}[ \-]\d{6}[ \-]\d{5}$/.test(m.trim())) return 0.75;
|
|
114
|
-
return 0;
|
|
115
|
-
},
|
|
116
|
-
},
|
|
117
|
-
{
|
|
118
|
-
// Masked cards: "**** **** **** 1234", "XXXX-XXXX-XXXX-1234", "โขโขโขโข 1234"
|
|
119
|
-
type: 'card',
|
|
120
|
-
re: /(?:[*xXโขโยท]{4}[ \-]?){1,3}\d{4}\b/g,
|
|
121
|
-
confidence: 0.8,
|
|
122
|
-
},
|
|
123
|
-
{
|
|
124
|
-
type: 'ssn',
|
|
125
|
-
re: /(?<![\d\-])(?!000|666|9\d\d)\d{3}[\- ](?!00)\d{2}[\- ](?!0000)\d{4}(?![\d\-])/g,
|
|
126
|
-
confidence: 0.95,
|
|
127
|
-
},
|
|
128
|
-
{
|
|
129
|
-
// "SSN: 123456789" / "Social Security No. 123 45 6789"
|
|
130
|
-
type: 'ssn',
|
|
131
|
-
re: /\b(?:SSN|SS#|Social\s+Security(?:\s+(?:No|Number|#))?\.?|SIN|Tax\s*ID|TIN|EIN)\s*[:#\-]?\s*([\dXx*\- ]{9,12})\b/gi,
|
|
132
|
-
group: 1,
|
|
133
|
-
confidence: 0.9,
|
|
134
|
-
},
|
|
135
|
-
{
|
|
136
|
-
// Aadhaar, unlabelled: 12 digits (optionally grouped 4-4-4), first digit 2-9, must pass the Verhoeff checksum.
|
|
137
|
-
type: 'aadhaar',
|
|
138
|
-
re: /(?<![\d\-])(?<!\d[ \-])[2-9]\d{3}([ \-]?)\d{4}\1\d{4}(?!\d|[ \-]\d|-)/g,
|
|
139
|
-
validate: (m) => (verhoeff(m.replace(/\D/g, '')) ? 0.95 : 0),
|
|
140
|
-
},
|
|
141
|
-
{
|
|
142
|
-
// Aadhaar, labelled ("Aadhaar No: 2341 2341 2346", "UID 234123412346"). No checksum, so OCR digit slips still match.
|
|
143
|
-
type: 'aadhaar',
|
|
144
|
-
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,
|
|
145
|
-
group: 1,
|
|
146
|
-
confidence: 0.9,
|
|
147
|
-
},
|
|
148
|
-
{
|
|
149
|
-
// PAN, unlabelled: AAAAA9999A. The 4th letter is the holder type (P person, C company, H HUF, F firm, ...).
|
|
150
|
-
// Up to two characters may be OCR look-alike swaps (S for 5, O for 0), but the rest must already fit.
|
|
151
|
-
type: 'pan',
|
|
152
|
-
re: /\b[A-Z0-9]{10}\b/g,
|
|
153
|
-
validate(m) {
|
|
154
|
-
if (!looksLikePan(m, 8)) return 0;
|
|
155
|
-
const fourth = /[A-Z]/.test(m[3]) ? m[3] : PAN_DIGIT_TO_LETTER[m[3]];
|
|
156
|
-
return PAN_HOLDER_TYPES.includes(fourth) ? 0.95 : 0;
|
|
157
|
-
},
|
|
158
|
-
},
|
|
159
|
-
{
|
|
160
|
-
// PAN, labelled ("PAN: ABCDE1234F", "Permanent Account Number (PAN) ABCDE1234F"). The label makes it safe to accept
|
|
161
|
-
// a value split by a space, with look-alike swaps, or with a table border glued to the last character.
|
|
162
|
-
type: 'pan',
|
|
163
|
-
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,
|
|
164
|
-
group: 1,
|
|
165
|
-
validate: (m) => (looksLikePan(m.replace(/\s/g, '').toUpperCase().slice(-10)) ? 0.9 : 0),
|
|
166
|
-
},
|
|
167
|
-
{
|
|
168
|
-
type: 'phone',
|
|
169
|
-
re: /(?<![\w@.\-\/])(?:\+?1[\s.\-]?)?(?:\(\d{3}\)\s?|\d{3}[\s.\-])\d{3}[\s.\-]\d{4}(?![\d\-])/g,
|
|
170
|
-
confidence: 0.9,
|
|
171
|
-
},
|
|
172
|
-
{
|
|
173
|
-
// International: +44 20 7946 0958, +33 1 23 45 67 89
|
|
174
|
-
type: 'phone',
|
|
175
|
-
re: /(?<![\w@.\-\/])\+\d{1,3}[\s.\-]?(?:\(?\d{1,4}\)?[\s.\-]?){2,5}\d{2,4}(?![\d\-])/g,
|
|
176
|
-
validate(m) {
|
|
177
|
-
const n = m.replace(/\D/g, '').length;
|
|
178
|
-
return n >= 8 && n <= 15 ? 0.85 : 0;
|
|
179
|
-
},
|
|
180
|
-
},
|
|
181
|
-
{
|
|
182
|
-
// "Mobile No.98765-43210" โ the dot is glued on, so a bare number pattern never sees a word boundary.
|
|
183
|
-
type: 'phone',
|
|
184
|
-
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,
|
|
185
|
-
group: 1,
|
|
186
|
-
validate(m) {
|
|
187
|
-
const n = m.replace(/\D/g, '').length;
|
|
188
|
-
return n >= 10 && n <= 15 ? 0.92 : 0;
|
|
189
|
-
},
|
|
190
|
-
},
|
|
191
|
-
{
|
|
192
|
-
// India writes a 10-digit mobile as 5-5: 98765-43210, +91 98765 43210.
|
|
193
|
-
type: 'phone',
|
|
194
|
-
re: /(?<![\w@/])(?:\+91[\s.\-]?)?[6-9]\d{4}[\s.\-]\d{5}(?!\d)/g,
|
|
195
|
-
confidence: 0.88,
|
|
196
|
-
},
|
|
197
|
-
{
|
|
198
|
-
// Unlabelled bare Indian mobile: 9977343444 (10 digits, starts 6-9, not part of a longer number/decimal/ID).
|
|
199
|
-
type: 'phone',
|
|
200
|
-
re: /(?<![\w@/.\-])[6-9]\d{9}(?![\d\-@/]|\.\d)/g,
|
|
201
|
-
confidence: 0.75,
|
|
202
|
-
},
|
|
203
|
-
{
|
|
204
|
-
// 123 Main Street, Apt 4B
|
|
205
|
-
type: 'address',
|
|
206
|
-
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'),
|
|
207
|
-
validate: (m) => (/^\d/.test(m) ? 0.85 : 0),
|
|
208
|
-
},
|
|
209
|
-
{
|
|
210
|
-
// Springfield, IL 62704 | Toronto ON M5V 2T6
|
|
211
|
-
type: 'address',
|
|
212
|
-
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'),
|
|
213
|
-
confidence: 0.9,
|
|
214
|
-
},
|
|
215
|
-
{
|
|
216
|
-
type: 'address',
|
|
217
|
-
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'),
|
|
218
|
-
confidence: 0.9,
|
|
219
|
-
},
|
|
220
|
-
{
|
|
221
|
-
type: 'address',
|
|
222
|
-
re: /\bP\.?\s?O\.?\s+Box\s+\d+\b/gi,
|
|
223
|
-
confidence: 0.9,
|
|
224
|
-
},
|
|
225
|
-
{
|
|
226
|
-
// UK postcode: SW1A 1AA
|
|
227
|
-
type: 'address',
|
|
228
|
-
re: /\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b/g,
|
|
229
|
-
confidence: 0.6,
|
|
230
|
-
},
|
|
231
|
-
{
|
|
232
|
-
// Labelled values: "Account No: 00123456", "Routing # 021000021", "IBAN GB29 NWBK ..."
|
|
233
|
-
type: 'account',
|
|
234
|
-
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,
|
|
235
|
-
group: 1,
|
|
236
|
-
confidence: 0.85,
|
|
237
|
-
},
|
|
238
|
-
{
|
|
239
|
-
type: 'account',
|
|
240
|
-
re: /\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){3,7}(?:[ ]?[A-Z0-9]{1,4})?\b/g,
|
|
241
|
-
validate: (m) => (m.replace(/\s/g, '').length >= 15 && /\d/.test(m) ? 0.8 : 0),
|
|
242
|
-
},
|
|
243
|
-
{
|
|
244
|
-
type: 'dob',
|
|
245
|
-
re: new RegExp(String.raw`\b(?:DOB|D\.O\.B\.?|Date\s+of\s+Birth|Birth\s*date|Birthday|Born)\s*[:\-]?\s*(${DATE})`, 'gi'),
|
|
246
|
-
group: 1,
|
|
247
|
-
confidence: 0.92,
|
|
248
|
-
},
|
|
249
|
-
{
|
|
250
|
-
type: 'secret',
|
|
251
|
-
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,
|
|
252
|
-
confidence: 0.97,
|
|
253
|
-
},
|
|
254
|
-
{
|
|
255
|
-
// Stripe-style keys after OCR turned the underscores into spaces: "sk live 4eC39Hqโฆ"
|
|
256
|
-
type: 'secret',
|
|
257
|
-
re: /\b(?:sk|pk|rk)[_\- ](?:live|test)[_\- ][A-Za-z0-9]{16,}/g,
|
|
258
|
-
confidence: 0.9,
|
|
259
|
-
},
|
|
260
|
-
{
|
|
261
|
-
type: 'secret',
|
|
262
|
-
re: /\b(?:password|passwd|pwd|passcode|secret|token|api[_\- ]?key)\s*[:=]\s*(\S{4,})/gi,
|
|
263
|
-
group: 1,
|
|
264
|
-
confidence: 0.85,
|
|
265
|
-
},
|
|
266
|
-
];
|
|
16
|
+
import { defaultDetector } from './locales/createDetector.js';
|
|
267
17
|
|
|
268
18
|
/**
|
|
269
19
|
* @param {string} text
|
|
270
20
|
* @param {Iterable<string>} [enabled] category ids to look for (default: all text types)
|
|
271
21
|
* @returns {{type:string,start:number,end:number,confidence:number}[]}
|
|
272
22
|
*/
|
|
273
|
-
export function findSensitive(text, enabled
|
|
274
|
-
|
|
275
|
-
const out = [];
|
|
276
|
-
for (const rule of RULES) {
|
|
277
|
-
if (!on.has(rule.type)) continue;
|
|
278
|
-
rule.re.lastIndex = 0;
|
|
279
|
-
let m;
|
|
280
|
-
while ((m = rule.re.exec(text)) !== null) {
|
|
281
|
-
if (m[0].length === 0) { rule.re.lastIndex++; continue; }
|
|
282
|
-
const conf = rule.validate ? rule.validate(m[0]) : rule.confidence;
|
|
283
|
-
if (!conf) continue;
|
|
284
|
-
let start = m.index;
|
|
285
|
-
let end = m.index + m[0].length;
|
|
286
|
-
if (rule.group) {
|
|
287
|
-
const g = m[rule.group];
|
|
288
|
-
if (!g) continue;
|
|
289
|
-
start = m.index + m[0].lastIndexOf(g);
|
|
290
|
-
end = start + g.length;
|
|
291
|
-
}
|
|
292
|
-
// trim trailing punctuation / whitespace
|
|
293
|
-
while (end > start && /[\s.,;:)]/.test(text[end - 1]) && !(text[end - 1] === ')' && text.slice(start, end).includes('('))) end--;
|
|
294
|
-
while (start < end && /\s/.test(text[start])) start++;
|
|
295
|
-
if (end > start) out.push({ type: rule.type, start, end, confidence: conf });
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
return dedupe(out);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/** Merge overlapping hits, preferring the higher-confidence / more specific one. */
|
|
302
|
-
function dedupe(hits) {
|
|
303
|
-
hits.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
304
|
-
const res = [];
|
|
305
|
-
for (const h of hits) {
|
|
306
|
-
const last = res[res.length - 1];
|
|
307
|
-
if (last && h.start < last.end) {
|
|
308
|
-
// overlap: keep the union if same type, else keep the better one
|
|
309
|
-
if (h.type === last.type) { last.end = Math.max(last.end, h.end); last.confidence = Math.max(last.confidence, h.confidence); }
|
|
310
|
-
else if (h.confidence > last.confidence && h.end - h.start >= (last.end - last.start) * 0.6) res[res.length - 1] = h;
|
|
311
|
-
continue;
|
|
312
|
-
}
|
|
313
|
-
res.push({ ...h });
|
|
314
|
-
}
|
|
315
|
-
return res;
|
|
23
|
+
export function findSensitive(text, enabled) {
|
|
24
|
+
return defaultDetector.findSensitive(text, enabled);
|
|
316
25
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* A line is { words: [{ text, bbox:{x0,y0,x1,y1} }] }.
|
|
6
6
|
*/
|
|
7
|
-
import { CATEGORIES, findSensitive, TEXT_TYPES } from './patterns.js';
|
|
7
|
+
import { CATEGORIES, findSensitive, TEXT_TYPES, defaultDetector } from './patterns.js';
|
|
8
8
|
|
|
9
9
|
export function lineToText(line) {
|
|
10
10
|
let text = '';
|
|
@@ -41,17 +41,12 @@ export function redactPlainText(text, types = TEXT_TYPES) {
|
|
|
41
41
|
* Returns the redacted string and a count per detector. The matched secrets are not included.
|
|
42
42
|
*/
|
|
43
43
|
export function redactDocument(text, types = TEXT_TYPES) {
|
|
44
|
-
const
|
|
45
|
-
const hits = value ? findSensitive(value, types) : [];
|
|
46
|
-
const counts = {};
|
|
47
|
-
for (const hit of hits) counts[hit.type] = (counts[hit.type] || 0) + 1;
|
|
44
|
+
const result = defaultDetector.redactDocument(text, types);
|
|
48
45
|
return {
|
|
49
|
-
text:
|
|
50
|
-
findings:
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
count,
|
|
54
|
-
})),
|
|
46
|
+
text: result.text,
|
|
47
|
+
findings: result.findings,
|
|
48
|
+
scope: result.scope,
|
|
49
|
+
warnings: result.warnings,
|
|
55
50
|
};
|
|
56
51
|
}
|
|
57
52
|
|
|
@@ -80,11 +75,11 @@ function maskRanges(text, hits) {
|
|
|
80
75
|
* The same reading as transcriptFromLines, with sensitive spans replaced by bullets.
|
|
81
76
|
* Includes a value that continues on the next stacked line, matching the boxes.
|
|
82
77
|
*/
|
|
83
|
-
export function redactTranscript(lines, types = TEXT_TYPES) {
|
|
78
|
+
export function redactTranscript(lines, types = TEXT_TYPES, find = findSensitive) {
|
|
84
79
|
if (!lines?.length) return '';
|
|
85
80
|
const rows = lines.map((line) => {
|
|
86
81
|
const { text, spans } = lineToText(line);
|
|
87
|
-
return { text, box: text ? lineBox(spans) : null, hits: text ?
|
|
82
|
+
return { text, box: text ? lineBox(spans) : null, hits: text ? find(text, types) : [] };
|
|
88
83
|
});
|
|
89
84
|
const wrapTypes = types.filter((t) => WRAPPABLE.includes(t));
|
|
90
85
|
if (wrapTypes.length) {
|
|
@@ -96,7 +91,7 @@ export function redactTranscript(lines, types = TEXT_TYPES) {
|
|
|
96
91
|
const stacked = gap < lineH && gap > -lineH * 0.6 && b.box.x0 < a.box.x1 && a.box.x0 < b.box.x1;
|
|
97
92
|
if (!stacked) continue;
|
|
98
93
|
const boundary = a.text.length;
|
|
99
|
-
for (const hit of
|
|
94
|
+
for (const hit of find(`${a.text} ${b.text}`, wrapTypes)) {
|
|
100
95
|
if (!(hit.start < boundary - 1 && hit.end > boundary + 2)) continue;
|
|
101
96
|
a.hits.push({ start: hit.start, end: boundary });
|
|
102
97
|
const bEnd = hit.end - boundary - 1;
|
|
@@ -107,15 +102,57 @@ export function redactTranscript(lines, types = TEXT_TYPES) {
|
|
|
107
102
|
return rows.map((row) => (row.text ? maskRanges(row.text, row.hits) : '')).filter(Boolean).join('\n');
|
|
108
103
|
}
|
|
109
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Mask the words of one page that sit under a box. Position only: the text rules are not
|
|
107
|
+
* consulted, so a box drawn by hand, a face, or a barcode hides the words beneath it, and a
|
|
108
|
+
* box that is off lets them show, the same as the image.
|
|
109
|
+
* @param {{words:any[]}[]} lines
|
|
110
|
+
* @param {{x:number,y:number,w:number,h:number}[]} boxes boxes still on, in canvas pixels
|
|
111
|
+
*/
|
|
112
|
+
export function redactUnderBoxes(lines, boxes = []) {
|
|
113
|
+
if (!lines?.length) return '';
|
|
114
|
+
const rows = lines.map((line) => {
|
|
115
|
+
const { text, spans } = lineToText(line);
|
|
116
|
+
return text ? maskRanges(text, coveredRanges(text, spans, boxes)) : '';
|
|
117
|
+
});
|
|
118
|
+
return rows.filter(Boolean).join('\n');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Character ranges of one line whose center sits inside a box. A space between two covered
|
|
123
|
+
* characters is covered too, so a multi-word value reads as one run of bullets.
|
|
124
|
+
*/
|
|
125
|
+
function coveredRanges(text, spans, boxes) {
|
|
126
|
+
const covered = new Array(text.length).fill(false);
|
|
127
|
+
for (const { start, end, word } of spans) {
|
|
128
|
+
const b = word.bbox;
|
|
129
|
+
const charW = (b.x1 - b.x0) / (end - start);
|
|
130
|
+
const cy = (b.y0 + b.y1) / 2;
|
|
131
|
+
for (let i = start; i < end; i++) {
|
|
132
|
+
const cx = b.x0 + (i - start + 0.5) * charW;
|
|
133
|
+
covered[i] = boxes.some((r) => cx >= r.x && cx <= r.x + r.w && cy >= r.y && cy <= r.y + r.h);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
for (let i = 1; i + 1 < text.length; i++) {
|
|
137
|
+
if (text[i] === ' ' && covered[i - 1] && covered[i + 1]) covered[i] = true;
|
|
138
|
+
}
|
|
139
|
+
return covered.map((on, i) => (on ? { start: i, end: i + 1 } : null)).filter(Boolean);
|
|
140
|
+
}
|
|
141
|
+
|
|
110
142
|
/**
|
|
111
143
|
* Every page in one string. One page is just its lines.
|
|
112
144
|
* More than one page keeps its page number so a copy still shows where each sheet started.
|
|
145
|
+
* With `redact` and `boxes` (one list per page), the mask follows those boxes. Without `boxes`,
|
|
146
|
+
* the text rules for `types` decide, as before.
|
|
113
147
|
*/
|
|
114
|
-
export function documentTranscript(pageLines, { redact = false, types = TEXT_TYPES } = {}) {
|
|
148
|
+
export function documentTranscript(pageLines, { redact = false, types = TEXT_TYPES, boxes = null, find = findSensitive } = {}) {
|
|
115
149
|
const pages = pageLines || [];
|
|
116
150
|
const parts = [];
|
|
117
151
|
for (let i = 0; i < pages.length; i++) {
|
|
118
|
-
|
|
152
|
+
let text;
|
|
153
|
+
if (!redact) text = transcriptFromLines(pages[i]);
|
|
154
|
+
else if (boxes) text = redactUnderBoxes(pages[i], boxes[i] || []);
|
|
155
|
+
else text = redactTranscript(pages[i], types, find);
|
|
119
156
|
if (!text) continue;
|
|
120
157
|
parts.push(pages.length > 1 ? `Page ${i + 1}\n${text}` : text);
|
|
121
158
|
}
|
|
@@ -165,16 +202,17 @@ const overlapRatio = (a, b) => {
|
|
|
165
202
|
/**
|
|
166
203
|
* @param {{words:any[]}[]} lines
|
|
167
204
|
* @param {string[]} types
|
|
205
|
+
* @param {(text:string, types?:string[]) => {type:string,start:number,end:number,confidence:number}[]} [find]
|
|
168
206
|
* @returns {{type:string,x:number,y:number,w:number,h:number,confidence:number,text:string}[]}
|
|
169
207
|
*/
|
|
170
|
-
export function regionsFromLines(lines, types) {
|
|
208
|
+
export function regionsFromLines(lines, types, find = findSensitive) {
|
|
171
209
|
const regions = [];
|
|
172
210
|
const infos = [];
|
|
173
211
|
for (const line of lines) {
|
|
174
212
|
const { text, spans } = lineToText(line);
|
|
175
213
|
infos.push({ text, spans, box: text ? lineBox(spans) : null });
|
|
176
214
|
if (!text) continue;
|
|
177
|
-
for (const hit of
|
|
215
|
+
for (const hit of find(text, types)) {
|
|
178
216
|
const r = rectForRange(spans, hit.start, hit.end);
|
|
179
217
|
if (r && r.w > 0 && r.h > 0) {
|
|
180
218
|
regions.push({ type: hit.type, ...r, confidence: hit.confidence, text: text.slice(hit.start, hit.end) });
|
|
@@ -193,7 +231,7 @@ export function regionsFromLines(lines, types) {
|
|
|
193
231
|
const stacked = gap < lineH * 1.0 && gap > -lineH * 0.6 && b.box.x0 < a.box.x1 && a.box.x0 < b.box.x1;
|
|
194
232
|
if (!stacked) continue;
|
|
195
233
|
const boundary = a.text.length;
|
|
196
|
-
for (const hit of
|
|
234
|
+
for (const hit of find(`${a.text} ${b.text}`, wrapTypes)) {
|
|
197
235
|
if (!(hit.start < boundary - 1 && hit.end > boundary + 2)) continue; // must genuinely cross the line break
|
|
198
236
|
const r1 = rectForRange(a.spans, hit.start, boundary);
|
|
199
237
|
const r2 = rectForRange(b.spans, 0, hit.end - boundary - 1);
|
package/src/host/assets.js
CHANGED
|
@@ -35,8 +35,33 @@ function vendorFile(rel) {
|
|
|
35
35
|
return file;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
/**
|
|
39
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Vite plugin. Copy is for production builds. Dev requests are read from the package.
|
|
40
|
+
* @param {{ languages?: string[] }} [opts] Extra Tesseract codes to copy from
|
|
41
|
+
* `@tesseract.js-data/<code>` beyond the package's shipped set (eng, hin).
|
|
42
|
+
*/
|
|
43
|
+
export function privacyRedact(opts = {}) {
|
|
44
|
+
const extraLangs = Array.isArray(opts.languages) ? opts.languages : [];
|
|
45
|
+
|
|
46
|
+
/** Copy host-installed OCR language data into the package vendor dir when missing. */
|
|
47
|
+
function copyExtraLanguages() {
|
|
48
|
+
for (const code of extraLangs) {
|
|
49
|
+
if (typeof code !== 'string' || !code) continue;
|
|
50
|
+
const dest = join(vendorDir, 'tesseract', `${code}.traineddata.gz`);
|
|
51
|
+
if (existsSync(dest)) continue;
|
|
52
|
+
const src = join(packageRoot, 'node_modules', `@tesseract.js-data/${code}/4.0.0_best_int/${code}.traineddata.gz`);
|
|
53
|
+
const hoisted = join(packageRoot, '..', '..', `@tesseract.js-data/${code}/4.0.0_best_int/${code}.traineddata.gz`);
|
|
54
|
+
// Host node_modules when privacy-redact is nested under the app.
|
|
55
|
+
const hostNm = join(process.cwd(), 'node_modules', `@tesseract.js-data/${code}/4.0.0_best_int/${code}.traineddata.gz`);
|
|
56
|
+
const from = [src, hoisted, hostNm].find((p) => existsSync(p));
|
|
57
|
+
if (!from) {
|
|
58
|
+
console.warn(`[privacy-redact] missing OCR data for "${code}". Install @tesseract.js-data/${code}.`);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
cpSync(from, dest);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
40
65
|
return {
|
|
41
66
|
name: 'privacy-redact-assets',
|
|
42
67
|
config() {
|
|
@@ -44,10 +69,12 @@ export function privacyRedact() {
|
|
|
44
69
|
optimizeDeps: {
|
|
45
70
|
// The review screen imports these on the first file. Prebundle them so that
|
|
46
71
|
// discovery does not reload the page and discard the open document.
|
|
47
|
-
|
|
72
|
+
// pdfjs-dist is not prebundled. A prebundle would make the host's copy serve every
|
|
73
|
+
// import, while the worker URL comes from the copy that owns loader.js. Two versions
|
|
74
|
+
// then fail with "The API version does not match the Worker version".
|
|
75
|
+
exclude: ['privacy-redact', 'pdfjs-dist'],
|
|
48
76
|
include: [
|
|
49
77
|
'exifr',
|
|
50
|
-
'pdfjs-dist',
|
|
51
78
|
'pdf-lib',
|
|
52
79
|
'tesseract.js',
|
|
53
80
|
'@zxing/library',
|
|
@@ -61,6 +88,7 @@ export function privacyRedact() {
|
|
|
61
88
|
if (!existsSync(vendorDir)) {
|
|
62
89
|
console.warn('[privacy-redact] public/vendor is missing. Run npm install in the privacy-redact package.');
|
|
63
90
|
}
|
|
91
|
+
copyExtraLanguages();
|
|
64
92
|
},
|
|
65
93
|
configureServer(server) {
|
|
66
94
|
const prefix = vendorPrefix(server.config.base);
|
|
@@ -74,6 +102,7 @@ export function privacyRedact() {
|
|
|
74
102
|
});
|
|
75
103
|
},
|
|
76
104
|
writeBundle(options) {
|
|
105
|
+
copyExtraLanguages();
|
|
77
106
|
if (!options.dir || !existsSync(vendorDir)) return;
|
|
78
107
|
cpSync(vendorDir, join(options.dir, 'vendor'), { recursive: true });
|
|
79
108
|
},
|
package/src/index.js
CHANGED
|
@@ -3,11 +3,18 @@
|
|
|
3
3
|
* OCR, faces, barcodes, PDF rendering, and canvas export stay in their own modules
|
|
4
4
|
* so a server does not load a browser.
|
|
5
5
|
*/
|
|
6
|
-
export {
|
|
6
|
+
export {
|
|
7
|
+
findSensitive, luhn, verhoeff, CATEGORIES, TEXT_TYPES,
|
|
8
|
+
createDetector, DEFAULT_SCOPE, SHIPPED_OCR_CODES,
|
|
9
|
+
} from './detect/patterns.js';
|
|
7
10
|
export {
|
|
8
11
|
redactDocument, redactPlainText, redactTranscript, documentTranscript, transcriptFromLines, regionsFromLines,
|
|
9
12
|
} from './detect/textRegions.js';
|
|
10
13
|
export {
|
|
11
14
|
SCAN_TYPES, defaultScanPrefs, normalizeScanPrefs, enabledTextTypes, enabledSteps,
|
|
12
15
|
} from './prefs/scan.js';
|
|
16
|
+
export {
|
|
17
|
+
OPTIONAL_LANGUAGES, defaultLanguagePrefs, normalizeLanguagePrefs,
|
|
18
|
+
languagesFromPrefs, prefsFromLanguages,
|
|
19
|
+
} from './prefs/languages.js';
|
|
13
20
|
export { summarizeTags } from './io/metadata.js';
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which OCR/detection languages the person has on. English stays on;
|
|
3
|
+
* optional packs such as Hindi are toggled in Settings and stored locally.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const STORAGE_KEY = 'privacy-redact.languages';
|
|
7
|
+
|
|
8
|
+
/** Optional language packs the settings screen can turn on. English is always included. */
|
|
9
|
+
export const OPTIONAL_LANGUAGES = [
|
|
10
|
+
{
|
|
11
|
+
id: 'hi',
|
|
12
|
+
label: 'Hindi',
|
|
13
|
+
detail: 'Devanagari text and labels. Loads an extra OCR model on the next scan.',
|
|
14
|
+
},
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
/** Default: English only. Hindi is opt-in. */
|
|
18
|
+
export function defaultLanguagePrefs() {
|
|
19
|
+
return { en: true, hi: false };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Keep known flags only. English cannot be turned off. */
|
|
23
|
+
export function normalizeLanguagePrefs(raw) {
|
|
24
|
+
const prefs = defaultLanguagePrefs();
|
|
25
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return prefs;
|
|
26
|
+
for (const { id } of OPTIONAL_LANGUAGES) {
|
|
27
|
+
if (typeof raw[id] === 'boolean') prefs[id] = raw[id];
|
|
28
|
+
}
|
|
29
|
+
prefs.en = true;
|
|
30
|
+
return prefs;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Read saved language flags. Missing storage means English only. */
|
|
34
|
+
export function loadLanguagePrefs(storage) {
|
|
35
|
+
const store = storage ?? globalThis.localStorage;
|
|
36
|
+
try {
|
|
37
|
+
const raw = store?.getItem(STORAGE_KEY);
|
|
38
|
+
if (!raw) return defaultLanguagePrefs();
|
|
39
|
+
return normalizeLanguagePrefs(JSON.parse(raw));
|
|
40
|
+
} catch {
|
|
41
|
+
return defaultLanguagePrefs();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Persist language flags. Returns the normalized set even if the write fails. */
|
|
46
|
+
export function saveLanguagePrefs(prefs, storage) {
|
|
47
|
+
const clean = normalizeLanguagePrefs(prefs);
|
|
48
|
+
const store = storage ?? globalThis.localStorage;
|
|
49
|
+
try {
|
|
50
|
+
store?.setItem(STORAGE_KEY, JSON.stringify(clean));
|
|
51
|
+
} catch {
|
|
52
|
+
// Private mode or a full quota. The in-memory set still applies this session.
|
|
53
|
+
}
|
|
54
|
+
return clean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Pack ids for createDetector, always starting with English. */
|
|
58
|
+
export function languagesFromPrefs(prefs) {
|
|
59
|
+
const on = normalizeLanguagePrefs(prefs);
|
|
60
|
+
const ids = ['en'];
|
|
61
|
+
for (const { id } of OPTIONAL_LANGUAGES) {
|
|
62
|
+
if (on[id]) ids.push(id);
|
|
63
|
+
}
|
|
64
|
+
return ids;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Build prefs from a host languages list such as ['en', 'hi']. */
|
|
68
|
+
export function prefsFromLanguages(list) {
|
|
69
|
+
const prefs = defaultLanguagePrefs();
|
|
70
|
+
if (!Array.isArray(list)) return prefs;
|
|
71
|
+
const ids = new Set(list.map((entry) => (typeof entry === 'string' ? entry : entry?.id)).filter(Boolean));
|
|
72
|
+
for (const { id } of OPTIONAL_LANGUAGES) prefs[id] = ids.has(id);
|
|
73
|
+
prefs.en = true;
|
|
74
|
+
return prefs;
|
|
75
|
+
}
|