privacy-redact 1.0.2 β†’ 1.0.3

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 CHANGED
@@ -63,6 +63,8 @@ Three redaction styles, seven document types β€” all produced by the real app. *
63
63
  | πŸ“ž **Phone numbers** | `(415) 555-2671`, `+1 415 555 2671`, `+44 20 7946 0958` | US + international patterns |
64
64
  | 🏠 **Home addresses** | `742 Evergreen Terrace, Apt 4B`, `Springfield, IL 62704`, `PO Box 12`, Canadian & UK postcodes | Street/suffix, City-State-ZIP, PO box rules |
65
65
  | 🏦 **Account numbers** | `Account No: 00123456789`, `Routing # 021000021`, `MRN`, `Policy`, IBANs | Label-aware: redacts the *value*, not the label |
66
+ | πŸ†” **Aadhaar numbers** | `2341 2341 2346`, `Aadhaar No: 2341-2341-2346` | 12 digits, first digit 2-9, Verhoeff checksum when unlabelled |
67
+ | 🧾 **PAN (India tax ID)** | `ABCPE1234F`, `PAN: ABCPE1234F` | `AAAAA9999A` shape with a valid holder-type letter; labelled values tolerate OCR look-alike swaps |
66
68
  | πŸŽ‚ **Dates of birth** | `DOB: 04/12/1988`, `Date of Birth March 3, 1990` | Only when labelled – ordinary dates are left alone |
67
69
  | πŸ”‘ **API keys & tokens** | `sk-…`, `AKIA…`, `ghp_…`, `xoxb-…`, JWTs, `password: …` | Vendor prefixes + `key=value` |
68
70
  | πŸ™‚ **Faces** | Photos, ID pictures, group shots | SSD-MobileNet via TensorFlow.js (tiled scan for small faces) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "privacy-redact",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
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": {
@@ -3,6 +3,7 @@
3
3
  import { cpSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { OCR_CORE_FILES } from '../src/detect/ocrCore.js';
6
7
 
7
8
  const root = join(dirname(fileURLToPath(import.meta.url)), '..');
8
9
  /**
@@ -29,9 +30,9 @@ function copy(src, dest) {
29
30
  cpSync(src, dest, { recursive: true });
30
31
  }
31
32
 
32
- // Tesseract OCR: worker + LSTM-only WASM cores (plain + SIMD) + English model
33
+ // Tesseract OCR: worker + every LSTM-only WASM core the OCR module can pick + English model
33
34
  copy(nm('tesseract.js/dist/worker.min.js'), out('tesseract/worker.min.js'));
34
- for (const f of ['tesseract-core-lstm.wasm.js', 'tesseract-core-simd-lstm.wasm.js']) {
35
+ for (const f of Object.values(OCR_CORE_FILES)) {
35
36
  copy(nm(`tesseract.js-core/${f}`), out(`tesseract/${f}`));
36
37
  }
37
38
  copy(nm('@tesseract.js-data/eng/4.0.0_best_int/eng.traineddata.gz'), out('tesseract/eng.traineddata.gz'));
package/src/detect/ocr.js CHANGED
@@ -3,24 +3,70 @@
3
3
  * Returns lines of words in the *original* canvas' pixel coordinates.
4
4
  */
5
5
  import { createWorker } from 'tesseract.js';
6
+ import { coreCandidates, OCR_CORE_PREFERENCES } from './ocrCore.js';
6
7
 
7
8
  let workerPromise = null;
8
9
  let progressCb = null;
10
+ let corePreference = 'stable';
9
11
 
10
12
  const abs = (p) => new URL(import.meta.env.BASE_URL + p, window.location.href).href;
11
13
 
14
+ /** True if this browser accepts the given WASM probe module. */
15
+ function wasmSupports(bytes) {
16
+ try {
17
+ return WebAssembly.validate(new Uint8Array(bytes));
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ // Probe modules from wasm-feature-detect. A wrong probe only means a slower core is picked.
24
+ const SIMD_PROBE = [0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11];
25
+ const RELAXED_SIMD_PROBE = [0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 15, 1, 13, 0, 65, 1, 253, 15, 65, 2, 253, 15, 253, 128, 2, 11];
26
+
27
+ /**
28
+ * Choose 'stable' (default, same OCR output on every CPU) or 'fast' (relaxed SIMD when available).
29
+ * Takes effect for the next worker, so call it before the first scan or after disposeOcr().
30
+ */
31
+ export function setOcrCorePreference(preference) {
32
+ if (!OCR_CORE_PREFERENCES.includes(preference)) {
33
+ throw new Error(`Unknown OCR core preference "${preference}". Use one of: ${OCR_CORE_PREFERENCES.join(', ')}.`);
34
+ }
35
+ corePreference = preference;
36
+ }
37
+
38
+ /**
39
+ * Start a worker on the first core that loads. We pick the core file ourselves instead of handing
40
+ * tesseract.js a directory, so a tesseract.js upgrade that asks for a new file name cannot break OCR.
41
+ */
42
+ async function startWorker() {
43
+ const files = coreCandidates(corePreference, { simd: wasmSupports(SIMD_PROBE), relaxedSimd: wasmSupports(RELAXED_SIMD_PROBE) });
44
+ let lastError;
45
+ for (const file of files) {
46
+ try {
47
+ const worker = await createWorker('eng', 1, {
48
+ workerPath: abs('vendor/tesseract/worker.min.js'),
49
+ corePath: abs(`vendor/tesseract/${file}`),
50
+ langPath: abs('vendor/tesseract'),
51
+ gzip: true,
52
+ cacheMethod: 'none',
53
+ logger: (m) => { if (m.status === 'recognizing text' && progressCb) progressCb(m.progress); },
54
+ });
55
+ await worker.setParameters({ user_defined_dpi: '300' });
56
+ return worker;
57
+ } catch (err) {
58
+ lastError = err;
59
+ console.warn(`[privacy-redact] OCR core ${file} did not load, trying the next one`, err);
60
+ }
61
+ }
62
+ throw lastError;
63
+ }
64
+
12
65
  function getWorker() {
13
66
  if (!workerPromise) {
14
- workerPromise = createWorker('eng', 1, {
15
- workerPath: abs('vendor/tesseract/worker.min.js'),
16
- corePath: abs('vendor/tesseract'),
17
- langPath: abs('vendor/tesseract'),
18
- gzip: true,
19
- cacheMethod: 'none',
20
- logger: (m) => { if (m.status === 'recognizing text' && progressCb) progressCb(m.progress); },
21
- }).then(async (w) => {
22
- await w.setParameters({ user_defined_dpi: '300' });
23
- return w;
67
+ workerPromise = startWorker().catch((err) => {
68
+ workerPromise = null;
69
+ throw err;
24
70
  });
25
71
  }
26
72
  return workerPromise;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Which Tesseract WASM core to load. Pure: no DOM, no tesseract.js - runs in Node for tests.
3
+ * The same file list drives scripts/copy-assets.mjs, so what we vendor and what we load cannot drift apart.
4
+ */
5
+
6
+ /** Vendored LSTM-only cores, fastest first. */
7
+ export const OCR_CORE_FILES = {
8
+ relaxedSimd: 'tesseract-core-relaxedsimd-lstm.wasm.js',
9
+ simd: 'tesseract-core-simd-lstm.wasm.js',
10
+ baseline: 'tesseract-core-lstm.wasm.js',
11
+ };
12
+
13
+ /**
14
+ * 'stable' never uses relaxed SIMD, whose results are allowed to differ between CPUs.
15
+ * 'fast' tries relaxed SIMD first when the browser supports it.
16
+ */
17
+ export const OCR_CORE_PREFERENCES = ['stable', 'fast'];
18
+
19
+ /** Core files to try in order. Always ends with the baseline core, which every WASM browser can run. */
20
+ export function coreCandidates(preference, { simd = false, relaxedSimd = false } = {}) {
21
+ if (!OCR_CORE_PREFERENCES.includes(preference)) {
22
+ throw new Error(`Unknown OCR core preference "${preference}". Use one of: ${OCR_CORE_PREFERENCES.join(', ')}.`);
23
+ }
24
+ const files = [];
25
+ if (preference === 'fast' && relaxedSimd) files.push(OCR_CORE_FILES.relaxedSimd);
26
+ if (simd) files.push(OCR_CORE_FILES.simd);
27
+ files.push(OCR_CORE_FILES.baseline);
28
+ return files;
29
+ }
@@ -8,6 +8,8 @@
8
8
  export const CATEGORIES = {
9
9
  card: { label: 'Credit cards', icon: 'πŸ’³' },
10
10
  ssn: { label: 'SSN / national ID', icon: 'πŸͺͺ' },
11
+ aadhaar: { label: 'Aadhaar numbers', icon: 'πŸ†”' },
12
+ pan: { label: 'PAN (India tax ID)', icon: '🧾' },
11
13
  email: { label: 'Emails', icon: 'βœ‰οΈ' },
12
14
  phone: { label: 'Phone numbers', icon: 'πŸ“ž' },
13
15
  address: { label: 'Home addresses', icon: '🏠' },
@@ -18,7 +20,7 @@ export const CATEGORIES = {
18
20
  barcode: { label: 'Barcodes & QR', icon: 'β–¦' },
19
21
  };
20
22
 
21
- export const TEXT_TYPES = ['card', 'ssn', 'email', 'phone', 'address', 'account', 'dob', 'secret'];
23
+ export const TEXT_TYPES = ['card', 'ssn', 'aadhaar', 'pan', 'email', 'phone', 'address', 'account', 'dob', 'secret'];
22
24
 
23
25
  /** Luhn checksum – used to tell real card numbers from random digit runs. */
24
26
  export function luhn(digits) {
@@ -34,6 +36,55 @@ export function luhn(digits) {
34
36
  return digits.length > 0 && sum % 10 === 0;
35
37
  }
36
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
+
37
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';
38
89
  const PROVINCES = 'AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT';
39
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';
@@ -81,6 +132,38 @@ const RULES = [
81
132
  group: 1,
82
133
  confidence: 0.9,
83
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
+ },
84
167
  {
85
168
  type: 'phone',
86
169
  re: /(?<![\w@.\-\/])(?:\+?1[\s.\-]?)?(?:\(\d{3}\)\s?|\d{3}[\s.\-])\d{3}[\s.\-]\d{4}(?![\d\-])/g,
package/src/index.js CHANGED
@@ -3,7 +3,7 @@
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 { findSensitive, luhn, CATEGORIES, TEXT_TYPES } from './detect/patterns.js';
6
+ export { findSensitive, luhn, verhoeff, CATEGORIES, TEXT_TYPES } from './detect/patterns.js';
7
7
  export {
8
8
  redactDocument, redactPlainText, redactTranscript, documentTranscript, transcriptFromLines, regionsFromLines,
9
9
  } from './detect/textRegions.js';
@@ -11,7 +11,7 @@ import {
11
11
  } from '../prefs/scan.js';
12
12
 
13
13
  const TAGS = {
14
- card: 'Credit card', ssn: 'SSN / ID', email: 'Email', phone: 'Phone', address: 'Address', account: 'Account no.',
14
+ card: 'Credit card', ssn: 'SSN / ID', aadhaar: 'Aadhaar', pan: 'PAN', email: 'Email', phone: 'Phone', address: 'Address', account: 'Account no.',
15
15
  dob: 'Birth date', secret: 'Secret / key', face: 'Face', barcode: 'Barcode / QR', manual: 'Manual',
16
16
  };
17
17
  const CAT_ORDER = [...SCAN_TYPES, 'manual'];