privacy-redact 0.0.0-stage → 0.1.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 CHANGED
@@ -1,3 +1,280 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
+
3
+ <img src="public/favicon.svg" width="84" alt="privacy-redact logo" />
4
+
5
+ # privacy-redact
6
+
7
+ ### One-click privacy shield for screenshots & documents
8
+
9
+ **Drop an image or PDF → sensitive info is auto-blurred → click Save.**
10
+
11
+ Cards, emails, phones, addresses, faces, barcodes — gone. Hidden metadata — gone. Nothing ever leaves your device.
12
+
13
+ ![Runs offline](https://img.shields.io/badge/network-none-34d399)
14
+ ![No uploads](https://img.shields.io/badge/uploads-0-22d3ee)
15
+
16
+ <img src="docs/before-after.png" alt="Before and after: a fictional pay stub with the SSN, address, email, phone, card, account numbers, face, QR code and barcode blurred" width="100%" />
17
+
18
+ </div>
19
+
20
+ ---
21
+
22
+ ## Why
23
+
24
+ We paste screenshots into **ChatGPT, Claude, Slack, Discord, GitHub issues and social media** all day. Every one of them can quietly contain a home address, a card number, a face that isn't yours, or a QR code that logs someone in. And the "fix" — drawing black boxes by hand in Paint or Photoshop — is tedious, easy to get wrong, and usually leaves the **EXIF/GPS/camera-serial metadata** untouched.
25
+
26
+ privacy-redact makes the safe thing the *easy* thing:
27
+
28
+ 1. **Drop** any image or PDF (or paste a screenshot with <kbd>Ctrl</kbd>/<kbd>⌘</kbd>+<kbd>V</kbd>).
29
+ 2. **Auto-blur** — sensitive items are found and hidden for you. Click any box to un-hide it, drag to hide something we missed.
30
+ 3. **Save** (or **Copy to clipboard**) — a clean file with zero metadata, verified before you share it.
31
+
32
+ > This repository is the library: detection, redaction, and document handling, plus browser components for OCR, faces, barcodes, and PDFs. The page in this repo is a harness for those components, not a brand. A small host that shows each call is in [examples/](examples/README.md).
33
+
34
+ ## Screenshots
35
+
36
+ | Landing | Workspace |
37
+ | --- | --- |
38
+ | <img src="docs/landing.png" alt="privacy-redact landing page with drop zone" /> | <img src="docs/screenshot-app.png" alt="privacy-redact workspace showing detected items with per-category toggles" /> |
39
+
40
+ ## Before & after gallery
41
+
42
+ Three redaction styles, seven document types — all produced by the real app. **[See the full gallery →](docs/EXAMPLES.md)**
43
+
44
+ | Document | Blur · Pixelate · Blackout |
45
+ | --- | --- |
46
+ | 🧾 Pay stub (photo, QR, barcode) | <a href="docs/EXAMPLES.md#1--pay-stub--image-with-photo-qr-code-and-barcode"><img src="docs/examples/paystub-comparison.png" width="420" alt="Pay stub before/after"></a> |
47
+ | 💬 Dark-mode Slack chat (keys, password) | <a href="docs/EXAMPLES.md#2--dark-mode-slack-chat--screenshot-with-secrets"><img src="docs/examples/chat-dark-mode-comparison.png" width="420" alt="Chat before/after"></a> |
48
+ | 🪪 Driver's license | <a href="docs/EXAMPLES.md#3--drivers-license--id-card-with-photo-and-barcode"><img src="docs/examples/id-card-comparison.png" width="420" alt="ID card before/after"></a> |
49
+ | 🏥 Medical intake form | <a href="docs/EXAMPLES.md#4--medical-intake-form--labelled-fields-wrapped-lines"><img src="docs/examples/medical-form-comparison.png" width="420" alt="Medical form before/after"></a> |
50
+ | 💳 Checkout page | <a href="docs/EXAMPLES.md#5--checkout-page--card-billing-details-qr"><img src="docs/examples/checkout-comparison.png" width="420" alt="Checkout before/after"></a> |
51
+ | 👨‍👩‍👧 Group photo (faces) | <a href="docs/EXAMPLES.md#6--group-photo--faces-only"><img src="docs/examples/group-photo-comparison.png" width="420" alt="Group photo before/after"></a> |
52
+ | 📄 Lease PDF | <a href="docs/EXAMPLES.md#7--lease-pdf-page-2--pdf-with-a-real-text-layer"><img src="docs/examples/lease-pdf-page2-comparison.png" width="420" alt="Lease PDF before/after"></a> |
53
+
54
+ ## Features
55
+
56
+ ### 🔍 Detects
57
+
58
+ | Category | Examples | How |
59
+ | --- | --- | --- |
60
+ | 💳 **Credit cards** | `4242 4242 4242 4242`, Amex `3782 822463 10005`, masked `**** 4242` | Regex + **Luhn checksum** (tolerates OCR slips on well-formed 4-4-4-4 groups) |
61
+ | 🪪 **SSN / national ID** | `123-45-6789`, `SSN: 123456789`, `TIN`, `EIN` | Pattern + invalid-range filtering (`000`, `666`, `9xx`) |
62
+ | ✉️ **Emails** | `jane.doe+work@example.co.uk` | RFC-ish regex |
63
+ | 📞 **Phone numbers** | `(415) 555-2671`, `+1 415 555 2671`, `+44 20 7946 0958` | US + international patterns |
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
+ | 🏦 **Account numbers** | `Account No: 00123456789`, `Routing # 021000021`, `MRN`, `Policy`, IBANs | Label-aware: redacts the *value*, not the label |
66
+ | 🎂 **Dates of birth** | `DOB: 04/12/1988`, `Date of Birth March 3, 1990` | Only when labelled – ordinary dates are left alone |
67
+ | 🔑 **API keys & tokens** | `sk-…`, `AKIA…`, `ghp_…`, `xoxb-…`, JWTs, `password: …` | Vendor prefixes + `key=value` |
68
+ | 🙂 **Faces** | Photos, ID pictures, group shots | SSD-MobileNet via TensorFlow.js (tiled scan for small faces) |
69
+ | ▦ **Barcodes & QR** | QR, Code 128/39, EAN/UPC, PDF417, Data Matrix, Aztec | Native `BarcodeDetector` if present, else ZXing with multi-scale retry |
70
+
71
+ ### 🧼 Strips hidden data
72
+
73
+ Before you save, privacy-redact shows exactly what's hiding in your file — and what's about to disappear:
74
+
75
+ - 📍 GPS coordinates & altitude
76
+ - 📷 Camera / phone model, 🔢 body & lens **serial numbers**
77
+ - 🕒 Original capture & edit dates
78
+ - 👤 Owner / author / copyright, 🛠️ editing software
79
+ - 📄 PDF title, author, producer, keywords, dates
80
+ - XMP / IPTC blocks, embedded thumbnails, ICC profiles
81
+
82
+ After export it **re-opens the file it just wrote** and checks that no metadata is left ("re-checked: 0 metadata fields in the output").
83
+
84
+ ### 🎨 Aesthetic, adjustable redaction
85
+
86
+ - **Blur** (default) – soft, pretty, and irreversible (see [How redaction stays irreversible](#-how-redaction-stays-irreversible))
87
+ - **Pixelate** – classic mosaic
88
+ - **Blackout** – maximum-paranoia solid fill
89
+ - **Strength slider**, per-category switches, click-to-toggle on any box, drag-to-add manual boxes
90
+ - **Hold to compare** with the original · multi-page PDFs with page navigation
91
+
92
+ ### 🔒 Private by design
93
+
94
+ - **Everything runs in your browser tab** — OCR (Tesseract), face detection (TensorFlow.js), barcode decoding (ZXing), PDF rendering (PDF.js).
95
+ - Models, WASM and fonts are **bundled** – no CDN calls at runtime. Works fully offline after first load.
96
+ - Production builds ship a strict **Content-Security-Policy** (`connect-src 'self'`, `form-action 'none'`, `object-src 'none'`) so the page is *technically unable* to send your file anywhere.
97
+ - The end-to-end test fails if the app makes even one request to another origin.
98
+ - No analytics, no cookies, no accounts, no telemetry.
99
+
100
+ ## Quick start
101
+
102
+ ### Run it locally
103
+
104
+ ```bash
105
+ npm install # also copies the OCR / face / PDF assets into public/vendor
106
+ npm run dev # → http://localhost:5173
107
+ ```
108
+
109
+ Production build (static files, host anywhere — S3, Netlify, `python -m http.server`, a USB stick):
110
+
111
+ ```bash
112
+ npm run build # → dist/
113
+ npm run preview # serve dist/ at http://localhost:4173
114
+ ```
115
+
116
+ Requires Node 18+ and a modern browser (Chrome/Edge 119+, Firefox 121+, Safari 17.4+).
117
+
118
+ ### Desktop app (experimental)
119
+
120
+ A tiny Electron shell is included. It serves the built app from a loopback-only server and **blocks every non-local network request**.
121
+
122
+ ```bash
123
+ npm run desktop # build + launch
124
+ npm run desktop:pack # installers via electron-builder (dmg / nsis / AppImage) → release/
125
+ ```
126
+
127
+ > The desktop wrapper hasn't had the same test coverage as the web app yet — PRs and bug reports welcome.
128
+
129
+ ## How it works
130
+
131
+ ```mermaid
132
+ flowchart LR
133
+ A[Drop image / PDF] --> B[Decode to canvas<br/>EXIF-orientation applied<br/>PDF pages rasterised]
134
+ B --> C1[OCR<br/>Tesseract.js]
135
+ B --> C2[Faces<br/>SSD-MobileNet]
136
+ B --> C3[Barcodes / QR<br/>ZXing]
137
+ C1 --> D[Pattern engine<br/>regex + Luhn + labels]
138
+ D --> E[Word boxes → pixel rects]
139
+ C2 --> F[Regions]
140
+ C3 --> F
141
+ E --> F
142
+ F --> G[Live preview<br/>blur / pixelate / blackout]
143
+ G --> H[Export from raw pixels<br/>PNG · JPG · flattened PDF]
144
+ H --> I[Re-open & verify<br/>0 metadata fields]
145
+ ```
146
+
147
+ 1. **Decode.** Images become a canvas (transparency flattened, EXIF orientation baked in). PDFs are rendered page-by-page at 144 dpi.
148
+ 2. **Detect.** OCR yields words with bounding boxes. Screenshots are upscaled and dark themes inverted first to help the OCR. Each line is scanned with the rule set in [`src/detect/patterns.js`](src/detect/patterns.js); matches are mapped back to pixels — even partial words like `Email:jane@x.com` are trimmed to just the address.
149
+ 3. **Review.** Every detection is a box you can toggle. Categories can be switched off wholesale.
150
+ 4. **Export.** The redacted canvas is re-encoded from scratch and re-checked.
151
+
152
+ ## 💥 How redaction stays irreversible
153
+
154
+ Bad redaction is worse than none, so:
155
+
156
+ - **Blur and pixelate average pixels into blocks first** (only ~1–2.4 cells across a line of text, ~5–11 across a face), add random per-block noise, and only *then* smooth. The original detail is discarded, not merely obscured — there is nothing to "un-blur". Text cells are deliberately coarser than a glyph because fine mosaics of a known font can be brute-forced back into text ([Depix](https://github.com/spipm/Depix)-style attacks); the jitter stops exact colour matching.
157
+ - **Nothing is layered.** The output image is a new set of pixels. There is no hidden original underneath a box, unlike PDF "highlight" annotations that can be deleted.
158
+ - **PDFs are flattened.** Each page is rasterised, redacted and re-embedded as an image, so the text layer beneath a redaction no longer exists. (The trade-off: exported PDFs aren't text-selectable.)
159
+ - **Nothing is copied byte-for-byte from your source file**, so EXIF, XMP, IPTC, thumbnails and PDF info dictionaries can't tag along. PDFs are written with metadata auto-stamping disabled (no `Producer`, no dates).
160
+ - The e2e suite **OCRs the exported file** and asserts that the SSN, email, phone, card, address and account numbers of the sample document are no longer readable.
161
+
162
+ > Want zero doubt for something extremely sensitive? Pick **Blackout** and drag the strength up.
163
+
164
+ ## Limitations — please read
165
+
166
+ privacy-redact is a safety net, not a guarantee. **Always glance at the preview before sharing.**
167
+
168
+ - **Names aren't detected.** Names are context-dependent and would cause a lot of false positives with regex-only detection. Use the drag-to-hide tool (a local NER model is on the [roadmap](#roadmap)).
169
+ - **OCR isn't perfect.** Tiny fonts, low contrast, unusual fonts, handwriting, rotated or curved text can be missed. A digit misread by OCR can still leave a card *pattern* undetected if it's badly broken up.
170
+ - **English-first.** Address rules are US/Canada/UK oriented; phone rules include international formats; OCR uses the English model.
171
+ - **Faces:** heavily rotated, occluded or tiny faces can be missed; non-faces occasionally trigger. Wide images are scanned in overlapping tiles so small faces are found, at the cost of speed. Toggle boxes to correct.
172
+ - **Barcodes:** without the native `BarcodeDetector` API (Chrome on Windows/Linux, Firefox), 1D codes are located via scan-line heuristics and a structure check that rejects text mistaken for bars. Damaged or very small codes can be missed.
173
+ - **Not detected by design:** license plates, signatures, logos, company names, free-form medical text.
174
+ - **HEIC** photos aren't decodable by browsers – convert to JPG/PNG first.
175
+ - **PDFs** are limited to 60 pages and become image-only.
176
+ - **Performance:** first scan loads ~15 MB of models. Face detection uses WebGL when available; on machines without GPU acceleration it falls back to CPU and can take a while on big images.
177
+ - Filenames aren't scrubbed beyond adding `-redacted`. If your filename contains your name, rename it.
178
+
179
+ ## Project structure
180
+
181
+ ```
182
+ privacy-redact/
183
+ ├── index.html # app shell
184
+ ├── src/
185
+ │ ├── main.js # UI controller (state, scanning pipeline, export)
186
+ │ ├── style.css
187
+ │ ├── detect/
188
+ │ │ ├── patterns.js # 🧠 the rule engine (pure JS, unit-tested)
189
+ │ │ ├── textRegions.js # OCR words ↔ character ranges ↔ pixel rects, wrapped-line + neighbour merging (pure, unit-tested)
190
+ │ │ ├── ocr.js # Tesseract.js worker wrapper (+ pre-processing)
191
+ │ │ ├── faces.js # TensorFlow.js face detection with tiling + NMS
192
+ │ │ └── barcodes.js # BarcodeDetector / ZXing multi-scale fallback
193
+ │ ├── render/effects.js # blur · pixelate · blackout
194
+ │ └── io/
195
+ │ ├── loader.js # image + PDF → canvases
196
+ │ ├── metadata.js # what's hidden in the file + post-export verification
197
+ │ └── exporter.js # PNG / JPG / flattened PDF writers
198
+ ├── scripts/
199
+ │ ├── copy-assets.mjs # vendors OCR/face/PDF assets into public/vendor (postinstall)
200
+ │ ├── make-samples.mjs # generates the fictional sample docs
201
+ │ └── make-before-after.mjs # README hero image
202
+ ├── public/samples/ # fictional pay stub, chat, ID, medical form, checkout, group photo, GPS JPG, lease PDF
203
+ ├── docs/EXAMPLES.md # before/after gallery (docs/examples/*)
204
+ ├── test/ # node --test unit tests (*.test.js)
205
+ │ └── smoke.e2e.test.js # Playwright end-to-end test incl. OCR-of-output check (npm run test:e2e)
206
+ ├── desktop/ # optional Electron wrapper
207
+ └── .github/workflows/ # CI + GitHub Pages deploy
208
+ ```
209
+
210
+ ## Testing
211
+
212
+ ```bash
213
+ npm test # unit tests (rules, box mapping, metadata, redaction cell size) — under a second
214
+ npm run test:e2e:setup # one-time: download Chromium for Playwright
215
+ npm run build && npm run preview & # then:
216
+ npm run test:e2e -- http://localhost:4173/ # full pipeline in headless Chromium
217
+ npm run test:e2e:ci # all of the above in one go: install Chromium, build, serve, test (used by the manual E2E workflow)
218
+ ```
219
+
220
+ The e2e test drives the real UI against the **production build** (so the CSP is enforced) and asserts:
221
+
222
+ - every category is detected on the sample pay stub (email, phones, SSN, addresses, card, account/routing, DOB, face, QR + barcode)
223
+ - the exported PNG can no longer be OCR'd for any secret, while normal text remains readable
224
+ - a JPEG with **GPS + camera model** comes out with no EXIF segment
225
+ - a 2-page PDF with a real text layer and author metadata comes out with **no selectable secret text and an empty info dictionary**
226
+ - **zero** requests to external origins and zero console errors / CSP violations
227
+
228
+ All sample data is fictional (`4242 4242 4242 4242` is a public test card number; the portrait is AI-generated). Regenerate with `npm run samples`.
229
+
230
+ ## Roadmap
231
+
232
+ - [ ] Optional local **name / organisation detection** (small on-device NER model)
233
+ - [ ] Batch mode – drop a folder, get a folder
234
+ - [ ] Watch-folder / clipboard-monitor mode for the desktop app
235
+ - [ ] More locales (EU addresses & national IDs, IBAN validation, non-Latin OCR packs)
236
+ - [ ] License-plate & signature detectors
237
+ - [ ] "Keep text selectable" PDF mode using true content-stream redaction
238
+ - [ ] Browser extension: right-click any image → privacy-redact
239
+ - [ ] Installable PWA (a web manifest ships already; offline service worker still to do)
240
+ - [ ] Custom rules (bring your own regex / keywords, e.g. an employee-ID format)
241
+
242
+ ## FAQ
243
+
244
+ **Does anything get uploaded?** No. There is no backend. Open your browser's Network tab and see for yourself — after the page loads, dropping a file causes zero requests.
245
+
246
+ **Why not just blur it in Preview / Paint?** You can, but you have to spot every item yourself, get the boxes right, and remember that the file's EXIF/GPS data is still there. privacy-redact does the spotting and the scrubbing.
247
+
248
+ **Is PNG/JPG export lossless / does it change my image?** PNG is lossless. JPG is re-encoded at quality 93. Colour profiles are dropped (part of metadata stripping), which may shift colours very slightly on wide-gamut photos.
249
+
250
+ **Can I add my own patterns?** Yes — see [CONTRIBUTING.md](CONTRIBUTING.md#adding-a-detection-rule). It's one object in `patterns.js`.
251
+
252
+ **Why is the first scan slow?** The OCR engine and face model load on first use, then get reused for the rest of the session.
253
+
254
+ ## Security
255
+
256
+ Found a way to recover redacted content or leak data? Please see [SECURITY.md](SECURITY.md) — use a private report, and only ever share fictional documents.
257
+
258
+ ## Credits
259
+
260
+ This repository started from [Hushshot](https://github.com/SYasJ/hushshot) by [SYasJ](https://github.com/SYasJ). That project is the offline browser tool that finds private content in a screenshot or PDF, redacts it, and strips metadata. Its license is MIT. This repository borrowed that first approach and aligned it as a library a host can call, including before a document goes to an AI.
261
+
262
+ This repository runs them through the JavaScript projects listed with each one. Those projects keep their own licenses.
263
+
264
+ | Project | What it does here | License |
265
+ | --- | --- | --- |
266
+ | [Tesseract OCR](https://github.com/tesseract-ocr/tesseract) | Recognizes text. The English traineddata vendored with the page is Tesseract language data. | Apache-2.0 |
267
+ | [Tesseract.js](https://github.com/naptha/tesseract.js) and [tesseract.js-core](https://github.com/naptha/tesseract.js-core) | Runs that engine in the browser and in Node, from the vendored worker and WASM. | Apache-2.0 |
268
+ | [TensorFlow](https://github.com/tensorflow/tensorflow) and [TensorFlow.js](https://github.com/tensorflow/tfjs) | Runs the face model. TensorFlow.js is bundled inside face-api and is not loaded from the network. | Apache-2.0 |
269
+ | [face-api.js](https://github.com/justadudewhohacks/face-api.js), continued as [@vladmandic/face-api](https://github.com/vladmandic/face-api) | Finds faces with the SSD MobileNet v1 model shipped in that package. | MIT |
270
+ | [ZXing](https://github.com/zxing/zxing) and [@zxing/library](https://github.com/zxing-js/library) | Decodes barcodes and QR codes when the browser has no `BarcodeDetector`. | Apache-2.0, MIT for the JavaScript port |
271
+ | [PDF.js](https://github.com/mozilla/pdf.js) | Reads and rasterizes PDFs. | Apache-2.0 |
272
+ | [pdf-lib](https://github.com/Hopding/pdf-lib) | Writes the flattened PDF. | MIT |
273
+ | [exifr](https://github.com/MikeKovarik/exifr) | Reads image metadata so the export can be checked. | MIT |
274
+
275
+ The page is built with [Vite](https://vitejs.dev/) (MIT). End-to-end tests use [Playwright](https://playwright.dev/) (Apache-2.0). [Crimson Pro](https://github.com/Fonthausen/CrimsonPro) and [IBM Plex Sans](https://github.com/IBM/plex) are used under the SIL Open Font License.
276
+
277
+ ## License
278
+
279
+ All rights reserved. See [LICENSE](LICENSE). See [CONTRIBUTING.md](CONTRIBUTING.md) to get involved.
2
280
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
package/package.json CHANGED
@@ -1,6 +1,85 @@
1
1
  {
2
2
  "name": "privacy-redact",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Library for detecting private content, redacting it, and handling document metadata. Browser components cover OCR, faces, barcodes, and PDF pages.",
6
+ "exports": {
7
+ ".": "./src/index.js",
8
+ "./ui": "./src/review/element.js",
9
+ "./react": "./src/review/react.js",
10
+ "./vite": "./src/host/assets.js",
11
+ "./detect/ocr": "./src/detect/ocr.js",
12
+ "./detect/faces": "./src/detect/faces.js",
13
+ "./detect/barcodes": "./src/detect/barcodes.js",
14
+ "./render/effects": "./src/render/effects.js",
15
+ "./io/loader": "./src/io/loader.js",
16
+ "./io/exporter": "./src/io/exporter.js",
17
+ "./io/metadata": "./src/io/metadata.js"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "files": [
21
+ "src",
22
+ "scripts/copy-assets.mjs",
23
+ "README.md"
24
+ ],
25
+ "peerDependencies": {
26
+ "react": ">=18",
27
+ "react-dom": ">=18"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "react": { "optional": true },
31
+ "react-dom": { "optional": true }
32
+ },
33
+ "scripts": {
34
+ "postinstall": "node scripts/copy-assets.mjs",
35
+ "dev": "vite",
36
+ "playground": "npm run dev --prefix examples/playground",
37
+ "build": "node scripts/copy-assets.mjs && vite build",
38
+ "preview": "vite preview",
39
+ "test": "node --test \"test/!(*.e2e).test.js\"",
40
+ "test:e2e": "node test/smoke.e2e.test.js",
41
+ "test:e2e:setup": "playwright install chromium",
42
+ "test:e2e:ci": "node scripts/run-e2e.mjs",
43
+ "samples": "node scripts/make-samples.mjs",
44
+ "desktop": "npm run build && npx electron desktop/main.cjs",
45
+ "desktop:pack": "npm run build && npx electron-builder --config desktop/electron-builder.yml",
46
+ "examples": "node scripts/make-examples.mjs",
47
+ "examples:inputs": "node scripts/make-example-inputs.mjs"
48
+ },
49
+ "devDependencies": {
50
+ "jsbarcode": "^3.12.3",
51
+ "playwright": "^1.63.0",
52
+ "qrcode": "^1.5.4",
53
+ "vite": "^6.4.3",
54
+ "wait-on": "^9.4.0"
55
+ },
56
+ "dependencies": {
57
+ "@tesseract.js-data/eng": "^1.0.0",
58
+ "@vladmandic/face-api": "^1.7.15",
59
+ "@zxing/library": "^0.21.3",
60
+ "exifr": "^7.1.3",
61
+ "pdf-lib": "^1.17.1",
62
+ "pdfjs-dist": "^4.10.38",
63
+ "tesseract.js": "^5.1.1"
64
+ },
65
+ "keywords": [
66
+ "privacy",
67
+ "redaction",
68
+ "redact",
69
+ "screenshot",
70
+ "pdf",
71
+ "ocr",
72
+ "pii",
73
+ "exif",
74
+ "gps",
75
+ "metadata",
76
+ "blur",
77
+ "face-blur",
78
+ "anonymize",
79
+ "local-first",
80
+ "offline"
81
+ ],
82
+ "engines": {
83
+ "node": ">=24"
84
+ }
85
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Pure text pattern detection. No DOM, no dependencies – runs in Node for tests.
3
+ *
4
+ * `findSensitive(text, enabledTypes)` returns [{ type, start, end, confidence }]
5
+ * where start/end are character offsets into `text` (end exclusive).
6
+ */
7
+
8
+ export const CATEGORIES = {
9
+ card: { label: 'Credit cards', icon: '💳' },
10
+ ssn: { label: 'SSN / national ID', icon: '🪪' },
11
+ email: { label: 'Emails', icon: '✉️' },
12
+ phone: { label: 'Phone numbers', icon: '📞' },
13
+ address: { label: 'Home addresses', icon: '🏠' },
14
+ account: { label: 'Account numbers', icon: '🏦' },
15
+ dob: { label: 'Dates of birth', icon: '🎂' },
16
+ secret: { label: 'API keys & tokens', icon: '🔑' },
17
+ face: { label: 'Faces', icon: '🙂' },
18
+ barcode: { label: 'Barcodes & QR', icon: '▦' },
19
+ };
20
+
21
+ export const TEXT_TYPES = ['card', 'ssn', 'email', 'phone', 'address', 'account', 'dob', 'secret'];
22
+
23
+ /** Luhn checksum – used to tell real card numbers from random digit runs. */
24
+ export function luhn(digits) {
25
+ let sum = 0;
26
+ let alt = false;
27
+ for (let i = digits.length - 1; i >= 0; i--) {
28
+ let n = digits.charCodeAt(i) - 48;
29
+ if (n < 0 || n > 9) return false;
30
+ if (alt) { n *= 2; if (n > 9) n -= 9; }
31
+ sum += n;
32
+ alt = !alt;
33
+ }
34
+ return digits.length > 0 && sum % 10 === 0;
35
+ }
36
+
37
+ 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
+ const PROVINCES = 'AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT';
39
+ 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';
40
+ // Capitalised ("Street") or ALL CAPS ("STREET") – never lowercase, which avoids matching prose like "3 items to the way".
41
+ const STREET_SUFFIX = `${STREET_SUFFIX_BASE}|${STREET_SUFFIX_BASE.toUpperCase()}`;
42
+
43
+ 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})`;
44
+
45
+ /** Each rule: regex with /g, optional `group` (capture group to redact), optional `validate`. */
46
+ const RULES = [
47
+ {
48
+ // @ plus marks OCR prints in its place: fullwidth @, cent ¢, © ® ¤.
49
+ type: 'email',
50
+ re: /[A-Za-z0-9._%+\-]+[@@¢©®¤][A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)*\.[A-Za-z]{2,}/g,
51
+ confidence: 0.98,
52
+ },
53
+ {
54
+ type: 'card',
55
+ re: /(?<![\d])(?:\d[ \-]?){12,18}\d(?![\d])/g,
56
+ validate(m) {
57
+ const digits = m.replace(/\D/g, '');
58
+ if (digits.length < 13 || digits.length > 19) return 0;
59
+ if (luhn(digits)) return 0.97;
60
+ // OCR often misreads a digit; keep well-formed 4-4-4-4 / Amex 4-6-5 groupings.
61
+ if (/^\d{4}[ \-]\d{4}[ \-]\d{4}[ \-]\d{4}$/.test(m.trim())) return 0.75;
62
+ if (/^\d{4}[ \-]\d{6}[ \-]\d{5}$/.test(m.trim())) return 0.75;
63
+ return 0;
64
+ },
65
+ },
66
+ {
67
+ // Masked cards: "**** **** **** 1234", "XXXX-XXXX-XXXX-1234", "•••• 1234"
68
+ type: 'card',
69
+ re: /(?:[*xX•●·]{4}[ \-]?){1,3}\d{4}\b/g,
70
+ confidence: 0.8,
71
+ },
72
+ {
73
+ type: 'ssn',
74
+ re: /(?<![\d\-])(?!000|666|9\d\d)\d{3}[\- ](?!00)\d{2}[\- ](?!0000)\d{4}(?![\d\-])/g,
75
+ confidence: 0.95,
76
+ },
77
+ {
78
+ // "SSN: 123456789" / "Social Security No. 123 45 6789"
79
+ type: 'ssn',
80
+ re: /\b(?:SSN|SS#|Social\s+Security(?:\s+(?:No|Number|#))?\.?|SIN|Tax\s*ID|TIN|EIN)\s*[:#\-]?\s*([\dXx*\- ]{9,12})\b/gi,
81
+ group: 1,
82
+ confidence: 0.9,
83
+ },
84
+ {
85
+ type: 'phone',
86
+ re: /(?<![\w@.\-\/])(?:\+?1[\s.\-]?)?(?:\(\d{3}\)\s?|\d{3}[\s.\-])\d{3}[\s.\-]\d{4}(?![\d\-])/g,
87
+ confidence: 0.9,
88
+ },
89
+ {
90
+ // International: +44 20 7946 0958, +33 1 23 45 67 89
91
+ type: 'phone',
92
+ re: /(?<![\w@.\-\/])\+\d{1,3}[\s.\-]?(?:\(?\d{1,4}\)?[\s.\-]?){2,5}\d{2,4}(?![\d\-])/g,
93
+ validate(m) {
94
+ const n = m.replace(/\D/g, '').length;
95
+ return n >= 8 && n <= 15 ? 0.85 : 0;
96
+ },
97
+ },
98
+ {
99
+ // "Mobile No.98765-43210" — the dot is glued on, so a bare number pattern never sees a word boundary.
100
+ type: 'phone',
101
+ re: /\b(?:Mobile|Mob|Phone|Tel|Telephone|Cell|Contact)\s*(?:No|Number|#)?\.?\s*[:#\-]?\s*(\+?\d[\d\s.\-()]{7,16}\d)/gi,
102
+ group: 1,
103
+ validate(m) {
104
+ const n = m.replace(/\D/g, '').length;
105
+ return n >= 10 && n <= 15 ? 0.92 : 0;
106
+ },
107
+ },
108
+ {
109
+ // India writes a 10-digit mobile as 5-5: 98765-43210, +91 98765 43210.
110
+ type: 'phone',
111
+ re: /(?<![\w@/])(?:\+91[\s.\-]?)?[6-9]\d{4}[\s.\-]\d{5}(?!\d)/g,
112
+ confidence: 0.88,
113
+ },
114
+ {
115
+ // 123 Main Street, Apt 4B
116
+ type: 'address',
117
+ 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'),
118
+ validate: (m) => (/^\d/.test(m) ? 0.85 : 0),
119
+ },
120
+ {
121
+ // Springfield, IL 62704 | Toronto ON M5V 2T6
122
+ type: 'address',
123
+ 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'),
124
+ confidence: 0.9,
125
+ },
126
+ {
127
+ type: 'address',
128
+ 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'),
129
+ confidence: 0.9,
130
+ },
131
+ {
132
+ type: 'address',
133
+ re: /\bP\.?\s?O\.?\s+Box\s+\d+\b/gi,
134
+ confidence: 0.9,
135
+ },
136
+ {
137
+ // UK postcode: SW1A 1AA
138
+ type: 'address',
139
+ re: /\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b/g,
140
+ confidence: 0.6,
141
+ },
142
+ {
143
+ // Labelled values: "Account No: 00123456", "Routing # 021000021", "IBAN GB29 NWBK ..."
144
+ type: 'account',
145
+ 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,
146
+ group: 1,
147
+ confidence: 0.85,
148
+ },
149
+ {
150
+ type: 'account',
151
+ re: /\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){3,7}(?:[ ]?[A-Z0-9]{1,4})?\b/g,
152
+ validate: (m) => (m.replace(/\s/g, '').length >= 15 && /\d/.test(m) ? 0.8 : 0),
153
+ },
154
+ {
155
+ type: 'dob',
156
+ re: new RegExp(String.raw`\b(?:DOB|D\.O\.B\.?|Date\s+of\s+Birth|Birth\s*date|Birthday|Born)\s*[:\-]?\s*(${DATE})`, 'gi'),
157
+ group: 1,
158
+ confidence: 0.92,
159
+ },
160
+ {
161
+ type: 'secret',
162
+ 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,
163
+ confidence: 0.97,
164
+ },
165
+ {
166
+ // Stripe-style keys after OCR turned the underscores into spaces: "sk live 4eC39Hq…"
167
+ type: 'secret',
168
+ re: /\b(?:sk|pk|rk)[_\- ](?:live|test)[_\- ][A-Za-z0-9]{16,}/g,
169
+ confidence: 0.9,
170
+ },
171
+ {
172
+ type: 'secret',
173
+ re: /\b(?:password|passwd|pwd|passcode|secret|token|api[_\- ]?key)\s*[:=]\s*(\S{4,})/gi,
174
+ group: 1,
175
+ confidence: 0.85,
176
+ },
177
+ ];
178
+
179
+ /**
180
+ * @param {string} text
181
+ * @param {Iterable<string>} [enabled] category ids to look for (default: all text types)
182
+ * @returns {{type:string,start:number,end:number,confidence:number}[]}
183
+ */
184
+ export function findSensitive(text, enabled = TEXT_TYPES) {
185
+ const on = new Set(enabled);
186
+ const out = [];
187
+ for (const rule of RULES) {
188
+ if (!on.has(rule.type)) continue;
189
+ rule.re.lastIndex = 0;
190
+ let m;
191
+ while ((m = rule.re.exec(text)) !== null) {
192
+ if (m[0].length === 0) { rule.re.lastIndex++; continue; }
193
+ const conf = rule.validate ? rule.validate(m[0]) : rule.confidence;
194
+ if (!conf) continue;
195
+ let start = m.index;
196
+ let end = m.index + m[0].length;
197
+ if (rule.group) {
198
+ const g = m[rule.group];
199
+ if (!g) continue;
200
+ start = m.index + m[0].lastIndexOf(g);
201
+ end = start + g.length;
202
+ }
203
+ // trim trailing punctuation / whitespace
204
+ while (end > start && /[\s.,;:)]/.test(text[end - 1]) && !(text[end - 1] === ')' && text.slice(start, end).includes('('))) end--;
205
+ while (start < end && /\s/.test(text[start])) start++;
206
+ if (end > start) out.push({ type: rule.type, start, end, confidence: conf });
207
+ }
208
+ }
209
+ return dedupe(out);
210
+ }
211
+
212
+ /** Merge overlapping hits, preferring the higher-confidence / more specific one. */
213
+ function dedupe(hits) {
214
+ hits.sort((a, b) => a.start - b.start || b.end - a.end);
215
+ const res = [];
216
+ for (const h of hits) {
217
+ const last = res[res.length - 1];
218
+ if (last && h.start < last.end) {
219
+ // overlap: keep the union if same type, else keep the better one
220
+ if (h.type === last.type) { last.end = Math.max(last.end, h.end); last.confidence = Math.max(last.confidence, h.confidence); }
221
+ else if (h.confidence > last.confidence && h.end - h.start >= (last.end - last.start) * 0.6) res[res.length - 1] = h;
222
+ continue;
223
+ }
224
+ res.push({ ...h });
225
+ }
226
+ return res;
227
+ }