privacy-redact 1.0.3 → 1.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,282 +1,191 @@
1
- <div align="center">
2
-
3
- <img src="public/favicon.svg" width="84" alt="privacy-redact logo" />
4
-
5
1
  # privacy-redact
6
2
 
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:
3
+ [![Demo](https://img.shields.io/badge/demo-live-3f6212)](https://gitcommitshow.github.io/privacy-redact/) [![npm version](https://img.shields.io/npm/v/privacy-redact)](https://www.npmjs.com/package/privacy-redact)
27
4
 
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.
5
+ Detect and redact private data in text, screenshots, and PDFs. It runs locally, and nothing is uploaded.
31
6
 
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
7
+ ```bash
8
+ npm i privacy-redact
9
+ ```
41
10
 
42
- Three redaction styles, seven document types — all produced by the real app. **[See the full gallery →](docs/EXAMPLES.md)**
11
+ Requires Node.js 24 or later. Browser components need Chrome or Edge 119+, Firefox 121+, or Safari 17.4+.
43
12
 
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> |
13
+ ![Before and after: a fictional pay stub with the SSN, address, email, phone, card, account numbers, face, QR code and barcode blurred](docs/before-after.png)
53
14
 
54
15
  ## Features
55
16
 
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
- | 🆔 **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 |
68
- | 🎂 **Dates of birth** | `DOB: 04/12/1988`, `Date of Birth March 3, 1990` | Only when labelled – ordinary dates are left alone |
69
- | 🔑 **API keys & tokens** | `sk-…`, `AKIA…`, `ghp_…`, `xoxb-…`, JWTs, `password: …` | Vendor prefixes + `key=value` |
70
- | 🙂 **Faces** | Photos, ID pictures, group shots | SSD-MobileNet via TensorFlow.js (tiled scan for small faces) |
71
- | ▦ **Barcodes & QR** | QR, Code 128/39, EAN/UPC, PDF417, Data Matrix, Aztec | Native `BarcodeDetector` if present, else ZXing with multi-scale retry |
72
-
73
- ### 🧼 Strips hidden data
74
-
75
- Before you save, privacy-redact shows exactly what's hiding in your file — and what's about to disappear:
17
+ Supported media types:
76
18
 
77
- - 📍 GPS coordinates & altitude
78
- - 📷 Camera / phone model, 🔢 body & lens **serial numbers**
79
- - 🕒 Original capture & edit dates
80
- - 👤 Owner / author / copyright, 🛠️ editing software
81
- - 📄 PDF title, author, producer, keywords, dates
82
- - XMP / IPTC blocks, embedded thumbnails, ICC profiles
19
+ - **Server side** (`privacy-redact`): text, including OCR output from your own engine
20
+ - **Browser side** (`privacy-redact/ui`, `privacy-redact/react`): PNG, JPG, WebP, GIF, BMP, AVIF, and pasted screenshots, plus PDFs. HEIC is not supported
83
21
 
84
- 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").
22
+ Ways to use it:
85
23
 
86
- ### 🎨 Aesthetic, adjustable redaction
24
+ - **Server only:** call `redactDocument` for text. No browser code is needed.
25
+ - **Server for text, React for the UI:** use `redactDocument` on the server, and mount `PrivacyRedactReview` only where images and PDFs are handled.
26
+ - **Browser only:** the text entry is plain JavaScript and also runs in the page. The review component runs decoding, OCR, face and barcode detection, review, and save in the page, so no server is required.
87
27
 
88
- - **Blur** (default) – soft, pretty, and irreversible (see [How redaction stays irreversible](#-how-redaction-stays-irreversible))
89
- - **Pixelate** – classic mosaic
90
- - **Blackout** – maximum-paranoia solid fill
91
- - **Strength slider**, per-category switches, click-to-toggle on any box, drag-to-add manual boxes
92
- - **Hold to compare** with the original · multi-page PDFs with page navigation
93
-
94
- ### 🔒 Private by design
28
+ ## Quick start
95
29
 
96
- - **Everything runs in your browser tab** — OCR (Tesseract), face detection (TensorFlow.js), barcode decoding (ZXing), PDF rendering (PDF.js).
97
- - Models, WASM and fonts are **bundled** – no CDN calls at runtime. Works fully offline after first load.
98
- - 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.
99
- - The end-to-end test fails if the app makes even one request to another origin.
100
- - No analytics, no cookies, no accounts, no telemetry.
30
+ ### Text
101
31
 
102
- ## Quick start
32
+ `privacy-redact` has no browser dependencies, so it runs in a server, a script, or a worker.
103
33
 
104
- ### Run it locally
34
+ ```js
35
+ import { redactDocument } from 'privacy-redact';
105
36
 
106
- ```bash
107
- npm install # also copies the OCR / face / PDF assets into public/vendor
108
- npm run dev # → http://localhost:5173
109
- ```
37
+ const { text, findings } = redactDocument(
38
+ 'Card 4242 4242 4242 4242, contact jane@example.com',
39
+ );
110
40
 
111
- Production build (static files, host anywhere — S3, Netlify, `python -m http.server`, a USB stick):
41
+ console.log(text);
42
+ // The card number and the email are replaced with bullet characters.
112
43
 
113
- ```bash
114
- npm run build # → dist/
115
- npm run preview # serve dist/ at http://localhost:4173
44
+ console.log(findings);
45
+ // [{ type: 'card', label: 'Credit cards', count: 1 }, { type: 'email', label: 'Emails', count: 1 }]
116
46
  ```
117
47
 
118
- Requires Node 18+ and a modern browser (Chrome/Edge 119+, Firefox 121+, Safari 17.4+).
48
+ `findings` gives a count per category. The matched values are not returned.
119
49
 
120
- ### Desktop app (experimental)
50
+ To check only some categories, pass a list. Leave it out to use every text detector the library ships.
121
51
 
122
- A tiny Electron shell is included. It serves the built app from a loopback-only server and **blocks every non-local network request**.
52
+ ```js
53
+ import { redactDocument, TEXT_TYPES } from 'privacy-redact';
123
54
 
124
- ```bash
125
- npm run desktop # build + launch
126
- npm run desktop:pack # installers via electron-builder (dmg / nsis / AppImage) → release/
55
+ redactDocument(text, ['email', 'phone']);
56
+ console.log(TEXT_TYPES); // every category the default run checks
127
57
  ```
128
58
 
129
- > The desktop wrapper hasn't had the same test coverage as the web app yet — PRs and bug reports welcome.
130
-
131
- ## How it works
132
-
133
- ```mermaid
134
- flowchart LR
135
- A[Drop image / PDF] --> B[Decode to canvas<br/>EXIF-orientation applied<br/>PDF pages rasterised]
136
- B --> C1[OCR<br/>Tesseract.js]
137
- B --> C2[Faces<br/>SSD-MobileNet]
138
- B --> C3[Barcodes / QR<br/>ZXing]
139
- C1 --> D[Pattern engine<br/>regex + Luhn + labels]
140
- D --> E[Word boxes → pixel rects]
141
- C2 --> F[Regions]
142
- C3 --> F
143
- E --> F
144
- F --> G[Live preview<br/>blur / pixelate / blackout]
145
- G --> H[Export from raw pixels<br/>PNG · JPG · flattened PDF]
146
- H --> I[Re-open & verify<br/>0 metadata fields]
59
+ ### Images and PDFs (React)
60
+
61
+ ```jsx
62
+ import { PrivacyRedactReview } from 'privacy-redact/react';
63
+
64
+ export function Attachment({ file, onSave }) {
65
+ return (
66
+ <PrivacyRedactReview
67
+ file={file}
68
+ style="blur"
69
+ strength={0.65}
70
+ onResult={onSave}
71
+ />
72
+ );
73
+ }
147
74
  ```
148
75
 
149
- 1. **Decode.** Images become a canvas (transparency flattened, EXIF orientation baked in). PDFs are rendered page-by-page at 144 dpi.
150
- 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.
151
- 3. **Review.** Every detection is a box you can toggle. Categories can be switched off wholesale.
152
- 4. **Export.** The redacted canvas is re-encoded from scratch and re-checked.
76
+ `file` is optional. Without it, the person drops a file into the review screen. `style` is `blur`, `pixelate`, or `blackout`. `strength` runs from 0 to 1.
77
+
78
+ ```js
79
+ function onSave({ file, filename, findings, clean, truncated, transcript }) {
80
+ // file: Blob of the redacted image or flattened PDF
81
+ // filename: the original name plus "-redacted"
82
+ // findings: counts per category that are still turned on
83
+ // clean: true when the saved file re-opened with no metadata left
84
+ // truncated: true when a PDF had more than 60 pages
85
+ // transcript: the redacted text read from the document
86
+ }
87
+ ```
153
88
 
154
- ## 💥 How redaction stays irreversible
89
+ `onResult` runs only when the person clicks Save. Dropping a file or finishing a scan does not call it, so the host decides when the file leaves the page.
155
90
 
156
- Bad redaction is worse than none, so:
91
+ ### Images and PDFs (plain HTML)
157
92
 
158
- - **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.
159
- - **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.
160
- - **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.)
161
- - **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).
162
- - 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.
93
+ ```html
94
+ <privacy-redact-review redact-style="pixelate" strength="0.8"></privacy-redact-review>
163
95
 
164
- > Want zero doubt for something extremely sensitive? Pick **Blackout** and drag the strength up.
96
+ <script type="module">
97
+ import 'privacy-redact/ui';
165
98
 
166
- ## Limitations — please read
99
+ document.querySelector('privacy-redact-review')
100
+ .addEventListener('result', (event) => console.log(event.detail.filename));
101
+ </script>
102
+ ```
167
103
 
168
- privacy-redact is a safety net, not a guarantee. **Always glance at the preview before sharing.**
104
+ ### Browser setup (Vite)
169
105
 
170
- - **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)).
171
- - **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.
172
- - **English-first.** Address rules are US/Canada/UK oriented; phone rules include international formats; OCR uses the English model.
173
- - **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.
174
- - **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.
175
- - **Not detected by design:** license plates, signatures, logos, company names, free-form medical text.
176
- - **HEIC** photos aren't decodable by browsers – convert to JPG/PNG first.
177
- - **PDFs** are limited to 60 pages and become image-only.
178
- - **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.
179
- - Filenames aren't scrubbed beyond adding `-redacted`. If your filename contains your name, rename it.
106
+ The review screen reads its OCR, face, and PDF files from `/vendor`. The Vite plugin serves them in development and copies them into the build.
180
107
 
181
- ## Project structure
108
+ ```js
109
+ // vite.config.js
110
+ import { defineConfig } from 'vite';
111
+ import { privacyRedact } from 'privacy-redact/vite';
182
112
 
183
- ```
184
- privacy-redact/
185
- ├── index.html # app shell
186
- ├── src/
187
- │ ├── main.js # UI controller (state, scanning pipeline, export)
188
- │ ├── style.css
189
- │ ├── detect/
190
- │ │ ├── patterns.js # 🧠 the rule engine (pure JS, unit-tested)
191
- │ │ ├── textRegions.js # OCR words ↔ character ranges ↔ pixel rects, wrapped-line + neighbour merging (pure, unit-tested)
192
- │ │ ├── ocr.js # Tesseract.js worker wrapper (+ pre-processing)
193
- │ │ ├── faces.js # TensorFlow.js face detection with tiling + NMS
194
- │ │ └── barcodes.js # BarcodeDetector / ZXing multi-scale fallback
195
- │ ├── render/effects.js # blur · pixelate · blackout
196
- │ └── io/
197
- │ ├── loader.js # image + PDF → canvases
198
- │ ├── metadata.js # what's hidden in the file + post-export verification
199
- │ └── exporter.js # PNG / JPG / flattened PDF writers
200
- ├── scripts/
201
- │ ├── copy-assets.mjs # vendors OCR/face/PDF assets into public/vendor (postinstall)
202
- │ ├── make-samples.mjs # generates the fictional sample docs
203
- │ └── make-before-after.mjs # README hero image
204
- ├── public/samples/ # fictional pay stub, chat, ID, medical form, checkout, group photo, GPS JPG, lease PDF
205
- ├── docs/EXAMPLES.md # before/after gallery (docs/examples/*)
206
- ├── test/ # node --test unit tests (*.test.js)
207
- │ └── smoke.e2e.test.js # Playwright end-to-end test incl. OCR-of-output check (npm run test:e2e)
208
- ├── desktop/ # optional Electron wrapper
209
- └── .github/workflows/ # CI + GitHub Pages deploy
113
+ export default defineConfig({
114
+ plugins: [privacyRedact()],
115
+ });
210
116
  ```
211
117
 
212
- ## Testing
118
+ A postinstall step copies those files into the package. Installs that skip install scripts (`npm --ignore-scripts`, or pnpm without an allow-list) leave them out, and scans then fail with "Text reading failed".
213
119
 
214
- ```bash
215
- npm test # unit tests (rules, box mapping, metadata, redaction cell size) — under a second
216
- npm run test:e2e:setup # one-time: download Chromium for Playwright
217
- npm run build && npm run preview & # then:
218
- npm run test:e2e -- http://localhost:4173/ # full pipeline in headless Chromium
219
- npm run test:e2e:ci # all of the above in one go: install Chromium, build, serve, test (used by the manual E2E workflow)
220
- ```
221
-
222
- The e2e test drives the real UI against the **production build** (so the CSP is enforced) and asserts:
120
+ ## API
223
121
 
224
- - every category is detected on the sample pay stub (email, phones, SSN, addresses, card, account/routing, DOB, face, QR + barcode)
225
- - the exported PNG can no longer be OCR'd for any secret, while normal text remains readable
226
- - a JPEG with **GPS + camera model** comes out with no EXIF segment
227
- - a 2-page PDF with a real text layer and author metadata comes out with **no selectable secret text and an empty info dictionary**
228
- - **zero** requests to external origins and zero console errors / CSP violations
122
+ | Import | Use |
123
+ | --- | --- |
124
+ | `privacy-redact` | Text detection and redaction. Node-safe. Exports `redactDocument`, `redactPlainText`, `findSensitive`, `TEXT_TYPES`, and `CATEGORIES`. |
125
+ | `privacy-redact/react` | `PrivacyRedactReview` React component. Needs React 18 or later. |
126
+ | `privacy-redact/ui` | The `privacy-redact-review` custom element, for any framework or none. |
127
+ | `privacy-redact/vite` | `privacyRedact()` Vite plugin that serves the OCR, face, and PDF files. |
229
128
 
230
- 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`.
129
+ ## What it detects
231
130
 
232
- ## Roadmap
131
+ | Category | Examples |
132
+ | --- | --- |
133
+ | Credit cards | `4242 4242 4242 4242` (Luhn checked) |
134
+ | SSN / national ID | `123-45-6789` |
135
+ | Emails | `jane.doe+work@example.co.uk` |
136
+ | Phone numbers | `(415) 555-2671`, `+44 20 7946 0958` |
137
+ | Home addresses | `742 Evergreen Terrace, Apt 4B`, `Springfield, IL 62704` |
138
+ | Account numbers | `Account No: 00123456789`, `Routing # 021000021`, IBANs |
139
+ | Aadhaar and PAN | `2341 2341 2346`, `ABCPE1234F` |
140
+ | Dates of birth | `DOB: 04/12/1988` (labeled dates only) |
141
+ | API keys and tokens | `sk-...`, `AKIA...`, JWTs, `password: ...` |
233
142
 
234
- - [ ] Optional local **name / organisation detection** (small on-device NER model)
235
- - [ ] Batch mode – drop a folder, get a folder
236
- - [ ] Watch-folder / clipboard-monitor mode for the desktop app
237
- - [ ] More locales (EU addresses & national IDs, IBAN validation, non-Latin OCR packs)
238
- - [ ] License-plate & signature detectors
239
- - [ ] "Keep text selectable" PDF mode using true content-stream redaction
240
- - [ ] Browser extension: right-click any image → privacy-redact
241
- - [ ] Installable PWA (a web manifest ships already; offline service worker still to do)
242
- - [ ] Custom rules (bring your own regex / keywords, e.g. an employee-ID format)
143
+ For images and PDFs, the scan also finds faces, barcodes, and QR codes. More before and after examples are in [docs/EXAMPLES.md](docs/EXAMPLES.md).
243
144
 
244
- ## FAQ
145
+ ## How redaction works
245
146
 
246
- **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.
147
+ - Images are decoded, read with OCR (Tesseract.js), and scanned for faces (face-api) and codes (ZXing). The text goes through the same rules as `redactDocument`.
148
+ - Blur and pixelate average pixels into coarse blocks before any smoothing, so the original detail is discarded. Blackout paints a solid fill.
149
+ - The output is a new set of pixels. Nothing is layered under a box.
150
+ - Nothing is copied from the source file, so EXIF, GPS, XMP, IPTC, thumbnails, and PDF info do not carry over. The saved file is re-opened and checked, and the result reports that as `clean`.
151
+ - PDFs are flattened to images, so the text under a box is gone. The trade-off is that the output is not text-selectable.
247
152
 
248
- **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.
153
+ ## Limitations
249
154
 
250
- **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.
155
+ privacy-redact is a safety net, not a guarantee. Review the preview before sharing.
251
156
 
252
- **Can I add my own patterns?** Yes — see [CONTRIBUTING.md](CONTRIBUTING.md#adding-a-detection-rule). It's one object in `patterns.js`.
157
+ - Names, company names, signatures, logos, and license plates are not detected.
158
+ - Detection is English-first. OCR uses the English model, and address rules are US, Canada, and UK oriented.
159
+ - OCR can miss tiny, low-contrast, rotated, or handwritten text. Small or heavily rotated faces can be missed too.
160
+ - HEIC images cannot be decoded in browsers. Convert them to JPG or PNG first.
161
+ - PDFs are limited to 60 pages and are exported as images.
162
+ - The first OCR or face scan loads about 15 MB of models.
253
163
 
254
- **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.
164
+ ## Privacy
255
165
 
256
- ## Security
166
+ - The text API is plain JavaScript and makes no network calls.
167
+ - In the browser, the OCR, face, and PDF files ship with the package and are served from the host's own origin. A scan does not contact another server.
168
+ - The original file stays with the host. The package has no telemetry, analytics, or accounts.
257
169
 
258
- 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.
170
+ ## Roadmap
259
171
 
260
- ## Credits
172
+ - Command-line tool that scans a local file and writes a draft for review
173
+ - MCP wrapper around that command, returning counts rather than file contents
174
+ - Text-only install without the OCR, face, and PDF files, for smaller installs
175
+ - Custom detection rules passed in by the host
176
+ - Optional on-device name and organization detection
177
+ - More locales: EU addresses and national IDs, IBAN validation, non-Latin OCR
178
+ - License plate and signature detectors
179
+ - PDF output that keeps text selectable
261
180
 
262
- 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.
181
+ ## Contributing
263
182
 
264
- This repository runs them through the JavaScript projects listed with each one. Those projects keep their own licenses.
183
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, tests, and how to add a detection rule. To report a way to recover redacted content or leak data, see [SECURITY.md](SECURITY.md). Use a private report, and only share fictional documents.
265
184
 
266
- | Project | What it does here | License |
267
- | --- | --- | --- |
268
- | [Tesseract OCR](https://github.com/tesseract-ocr/tesseract) | Recognizes text. The English traineddata vendored with the page is Tesseract language data. | Apache-2.0 |
269
- | [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 |
270
- | [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 |
271
- | [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 |
272
- | [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 |
273
- | [PDF.js](https://github.com/mozilla/pdf.js) | Reads and rasterizes PDFs. | Apache-2.0 |
274
- | [pdf-lib](https://github.com/Hopding/pdf-lib) | Writes the flattened PDF. | MIT |
275
- | [exifr](https://github.com/MikeKovarik/exifr) | Reads image metadata so the export can be checked. | MIT |
185
+ ## Credits
276
186
 
277
- 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.
187
+ Started from [Hushshot](https://github.com/SYasJ/hushshot) by SYasJ (MIT). Built on [Tesseract.js](https://github.com/naptha/tesseract.js), [face-api](https://github.com/vladmandic/face-api), [ZXing](https://github.com/zxing-js/library), [PDF.js](https://github.com/mozilla/pdf.js), [pdf-lib](https://github.com/Hopding/pdf-lib), and [exifr](https://github.com/MikeKovarik/exifr). Each keeps its own license.
278
188
 
279
189
  ## License
280
190
 
281
- All rights reserved. See [LICENSE](LICENSE). See [CONTRIBUTING.md](CONTRIBUTING.md) to get involved.
282
-
191
+ Apache-2.0. See [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "privacy-redact",
3
- "version": "1.0.3",
3
+ "version": "1.1.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": {
@@ -107,15 +107,57 @@ export function redactTranscript(lines, types = TEXT_TYPES) {
107
107
  return rows.map((row) => (row.text ? maskRanges(row.text, row.hits) : '')).filter(Boolean).join('\n');
108
108
  }
109
109
 
110
+ /**
111
+ * Mask the words of one page that sit under a box. Position only: the text rules are not
112
+ * consulted, so a box drawn by hand, a face, or a barcode hides the words beneath it, and a
113
+ * box that is off lets them show, the same as the image.
114
+ * @param {{words:any[]}[]} lines
115
+ * @param {{x:number,y:number,w:number,h:number}[]} boxes boxes still on, in canvas pixels
116
+ */
117
+ export function redactUnderBoxes(lines, boxes = []) {
118
+ if (!lines?.length) return '';
119
+ const rows = lines.map((line) => {
120
+ const { text, spans } = lineToText(line);
121
+ return text ? maskRanges(text, coveredRanges(text, spans, boxes)) : '';
122
+ });
123
+ return rows.filter(Boolean).join('\n');
124
+ }
125
+
126
+ /**
127
+ * Character ranges of one line whose center sits inside a box. A space between two covered
128
+ * characters is covered too, so a multi-word value reads as one run of bullets.
129
+ */
130
+ function coveredRanges(text, spans, boxes) {
131
+ const covered = new Array(text.length).fill(false);
132
+ for (const { start, end, word } of spans) {
133
+ const b = word.bbox;
134
+ const charW = (b.x1 - b.x0) / (end - start);
135
+ const cy = (b.y0 + b.y1) / 2;
136
+ for (let i = start; i < end; i++) {
137
+ const cx = b.x0 + (i - start + 0.5) * charW;
138
+ covered[i] = boxes.some((r) => cx >= r.x && cx <= r.x + r.w && cy >= r.y && cy <= r.y + r.h);
139
+ }
140
+ }
141
+ for (let i = 1; i + 1 < text.length; i++) {
142
+ if (text[i] === ' ' && covered[i - 1] && covered[i + 1]) covered[i] = true;
143
+ }
144
+ return covered.map((on, i) => (on ? { start: i, end: i + 1 } : null)).filter(Boolean);
145
+ }
146
+
110
147
  /**
111
148
  * Every page in one string. One page is just its lines.
112
149
  * More than one page keeps its page number so a copy still shows where each sheet started.
150
+ * With `redact` and `boxes` (one list per page), the mask follows those boxes. Without `boxes`,
151
+ * the text rules for `types` decide, as before.
113
152
  */
114
- export function documentTranscript(pageLines, { redact = false, types = TEXT_TYPES } = {}) {
153
+ export function documentTranscript(pageLines, { redact = false, types = TEXT_TYPES, boxes = null } = {}) {
115
154
  const pages = pageLines || [];
116
155
  const parts = [];
117
156
  for (let i = 0; i < pages.length; i++) {
118
- const text = redact ? redactTranscript(pages[i], types) : transcriptFromLines(pages[i]);
157
+ let text;
158
+ if (!redact) text = transcriptFromLines(pages[i]);
159
+ else if (boxes) text = redactUnderBoxes(pages[i], boxes[i] || []);
160
+ else text = redactTranscript(pages[i], types);
119
161
  if (!text) continue;
120
162
  parts.push(pages.length > 1 ? `Page ${i + 1}\n${text}` : text);
121
163
  }
@@ -44,10 +44,12 @@ export function privacyRedact() {
44
44
  optimizeDeps: {
45
45
  // The review screen imports these on the first file. Prebundle them so that
46
46
  // discovery does not reload the page and discard the open document.
47
- exclude: ['privacy-redact'],
47
+ // pdfjs-dist is not prebundled. A prebundle would make the host's copy serve every
48
+ // import, while the worker URL comes from the copy that owns loader.js. Two versions
49
+ // then fail with "The API version does not match the Worker version".
50
+ exclude: ['privacy-redact', 'pdfjs-dist'],
48
51
  include: [
49
52
  'exifr',
50
- 'pdfjs-dist',
51
53
  'pdf-lib',
52
54
  'tesseract.js',
53
55
  '@zxing/library',
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Review actions: the release buttons a host can set on the review screen. These are pure rules
3
+ * with no DOM, so the controller and the Node tests share one check.
4
+ */
5
+
6
+ const OUTPUTS = ['file', 'text'];
7
+ const VARIANTS = ['primary', 'secondary', 'ghost'];
8
+ const FORMATS = ['png', 'jpeg'];
9
+ const ID_PATTERN = /^[a-z0-9-]+$/;
10
+ const LABEL_MAX = 40;
11
+
12
+ /** Input for the built-in name "download", which keeps today's Save button. */
13
+ const BUILTIN_DOWNLOAD = {
14
+ id: 'download', label: 'Save sanitized file', outputs: ['file', 'text'], download: true, busyLabel: 'Sanitizing...',
15
+ };
16
+
17
+ /**
18
+ * Check a host action list and fill in the defaults. Throws a TypeError that names the entry and
19
+ * the field, so the caller can keep the list it had before.
20
+ * @param {unknown} list an array of "download" and/or action objects, or null for the default
21
+ * @returns {object[]} normalized actions, in the order given
22
+ */
23
+ export function normalizeActions(list) {
24
+ if (list == null) return [normalizeAction('download', 0)];
25
+ if (!Array.isArray(list)) throw new TypeError('actions must be an array of "download" and/or action objects');
26
+ const seen = new Set();
27
+ let primaries = 0;
28
+ return list.map((entry, i) => {
29
+ const action = normalizeAction(entry, i, seen);
30
+ if (action.variant === 'primary') primaries += 1;
31
+ if (primaries > 1) throw new TypeError(`actions[${i}].variant: only one action can be "primary"`);
32
+ return action;
33
+ });
34
+ }
35
+
36
+ /**
37
+ * Check one entry and return it with defaults filled in.
38
+ * @param {unknown} entry the built-in name "download", or an action object
39
+ * @param {number} i position in the list, used for the default variant and error messages
40
+ * @param {Set<string>} [seen] ids already used in this list
41
+ */
42
+ function normalizeAction(entry, i, seen = new Set()) {
43
+ const at = `actions[${i}]`;
44
+ const builtin = entry === 'download';
45
+ if (typeof entry === 'string' && !builtin) {
46
+ throw new TypeError(`${at}: unknown built-in "${entry}". The only built-in is "download".`);
47
+ }
48
+ if (!builtin && (!entry || typeof entry !== 'object' || Array.isArray(entry))) {
49
+ throw new TypeError(`${at}: expected "download" or an action object`);
50
+ }
51
+ const src = builtin ? BUILTIN_DOWNLOAD : entry;
52
+ if (!builtin && src.id === 'download') {
53
+ throw new TypeError(`${at}.id: "download" is reserved for the built-in. Use the string "download" instead.`);
54
+ }
55
+ if (typeof src.id !== 'string' || !ID_PATTERN.test(src.id)) {
56
+ throw new TypeError(`${at}.id must use lowercase letters, digits, and "-"`);
57
+ }
58
+ if (seen.has(src.id)) throw new TypeError(`${at}.id "${src.id}" is already used by another action`);
59
+ seen.add(src.id);
60
+
61
+ const label = typeof src.label === 'string' ? src.label.trim() : '';
62
+ if (!label || label.length > LABEL_MAX) throw new TypeError(`${at}.label must be 1 to ${LABEL_MAX} characters`);
63
+
64
+ const outputs = src.outputs;
65
+ if (!Array.isArray(outputs) || outputs.some((o) => !OUTPUTS.includes(o)) || new Set(outputs).size !== outputs.length) {
66
+ throw new TypeError(`${at}.outputs must list "file" and/or "text", each at most once`);
67
+ }
68
+
69
+ const choose = src.choose ?? false;
70
+ if (typeof choose !== 'boolean') throw new TypeError(`${at}.choose must be true or false`);
71
+ if (choose && outputs.length !== 2) throw new TypeError(`${at}.choose needs outputs ["file", "text"]`);
72
+
73
+ const variant = src.variant ?? (i === 0 ? 'primary' : 'secondary');
74
+ if (!VARIANTS.includes(variant)) throw new TypeError(`${at}.variant must be "primary", "secondary", or "ghost"`);
75
+
76
+ const format = src.format;
77
+ if (format !== undefined && !FORMATS.includes(format)) throw new TypeError(`${at}.format must be "png" or "jpeg"`);
78
+ if (format !== undefined && !outputs.includes('file')) throw new TypeError(`${at}.format needs "file" in outputs`);
79
+
80
+ const download = src.download ?? false;
81
+ if (typeof download !== 'boolean') throw new TypeError(`${at}.download must be true or false`);
82
+ if (download && !outputs.includes('file')) throw new TypeError(`${at}.download needs "file" in outputs`);
83
+
84
+ const busyLabel = src.busyLabel ?? 'Preparing...';
85
+ if (typeof busyLabel !== 'string' || !busyLabel.trim()) throw new TypeError(`${at}.busyLabel must be text`);
86
+
87
+ return { id: src.id, label, outputs: [...outputs], choose, variant, format, busyLabel, download, builtin };
88
+ }
89
+
90
+ /** The built-in Save action, used when the list leaves it out or the screen needs its defaults. */
91
+ export function downloadAction() {
92
+ return normalizeAction('download', 0);
93
+ }
@@ -5,6 +5,7 @@
5
5
  import { CATEGORIES, TEXT_TYPES } from '../detect/patterns.js';
6
6
  import { regionsFromLines, maskHint, documentTranscript } from '../detect/textRegions.js';
7
7
  import { renderRedactions } from '../render/effects.js';
8
+ import { normalizeActions, downloadAction } from './actions.js';
8
9
  import {
9
10
  SCAN_TYPES, PICTURE_SCAN_TYPES, loadScanPrefs, saveScanPrefs, defaultScanPrefs,
10
11
  normalizeScanPrefs, enabledTextTypes, enabledSteps, emailPhonePrefs, scanScopeText,
@@ -22,7 +23,7 @@ const DROP_TITLE = 'Drop a screenshot, photo, or PDF here';
22
23
  * Bind the review flow to one element. Queries stay in its shadow tree. Page paste
23
24
  * is ignored while the person is typing in the host.
24
25
  * @param {HTMLElement} host
25
- * @param {{ style?: string, strength?: number }} [initial]
26
+ * @param {{ style?: string, strength?: number, actions?: unknown }} [initial]
26
27
  */
27
28
  export function attachController(host, initial = {}) {
28
29
  const root = host.shadowRoot;
@@ -44,13 +45,24 @@ export function attachController(host, initial = {}) {
44
45
  return el;
45
46
  };
46
47
 
47
- const state = { doc: null, page: 0, style: 'blur', strength: 0.65, catOn: {}, scan: loadScanPrefs(), scanning: false, run: 0, transcriptRedacted: true };
48
+ const state = {
49
+ doc: null, page: 0, style: 'blur', strength: 0.65, catOn: {}, scan: loadScanPrefs(), scanning: false, run: 0, transcriptRedacted: true,
50
+ actions: normalizeActions(undefined), sendAs: 'both',
51
+ };
48
52
  let nextId = 1;
49
53
 
50
54
  const isActive = (r) => state.catOn[r.type] !== false && r.on;
51
55
  const cur = () => state.doc.pages[state.page];
52
56
  const activeRegions = (p) => p.regions.filter(isActive);
53
57
  const preview = $('preview');
58
+ /** Safety net: keep the preview inside its column even when the stylesheet did not load. */
59
+ function fitPreviewToColumn(canvas) {
60
+ if (!canvas) return;
61
+ canvas.style.display = 'block';
62
+ canvas.style.maxWidth = '100%';
63
+ canvas.style.height = 'auto';
64
+ }
65
+ fitPreviewToColumn(preview);
54
66
  let rafId = 0;
55
67
  const schedule = () => { cancelAnimationFrame(rafId); rafId = requestAnimationFrame(renderNow); };
56
68
 
@@ -185,9 +197,9 @@ export function attachController(host, initial = {}) {
185
197
  $('transcript-card').classList.toggle('open', open);
186
198
  }
187
199
 
188
- /** Text fields still hidden in the preview. The transcript redaction follows these. */
189
- function activeTranscriptTypes() {
190
- return enabledTextTypes(state.scan).filter((id) => state.catOn[id] !== false);
200
+ /** Boxes still on, one list per page. The transcript mask follows these, so the text matches the image. */
201
+ function activeBoxesByPage() {
202
+ return state.doc.pages.map((p) => activeRegions(p));
191
203
  }
192
204
 
193
205
  /** Keep the Redacted switch in step with the reading that will be copied. */
@@ -215,7 +227,7 @@ export function attachController(host, initial = {}) {
215
227
  const failed = pages.some((p) => p.ocr === 'fail');
216
228
  const text = documentTranscript(
217
229
  pages.map((p) => (p.ocr === 'done' ? p.lines : [])),
218
- { redact: state.transcriptRedacted !== false, types: activeTranscriptTypes() },
230
+ { redact: state.transcriptRedacted !== false, boxes: activeBoxesByPage() },
219
231
  );
220
232
  if (pending && !text) return { text: '', empty: 'Reading the document…', pending: true };
221
233
  if (!text && failed) return { text: '', empty: 'Text reading failed.', pending: false };
@@ -228,10 +240,147 @@ export function attachController(host, initial = {}) {
228
240
  function redactedTranscript() {
229
241
  return documentTranscript(
230
242
  state.doc.pages.map((p) => (p.ocr === 'done' ? p.lines : [])),
231
- { redact: true, types: activeTranscriptTypes() },
243
+ { redact: true, boxes: activeBoxesByPage() },
232
244
  );
233
245
  }
234
246
 
247
+ /** Text is still being read on at least one page, so the transcript cannot be released yet. */
248
+ function textPending() {
249
+ if (!state.doc) return false;
250
+ return enabledSteps(state.scan).includes('ocr') && state.doc.pages.some((p) => !p.ocr);
251
+ }
252
+
253
+ /** Give a release button its look, part names, and label from its action. */
254
+ function styleButton(node, action) {
255
+ node.className = action.variant === 'primary' ? 'btn primary big' : `btn ${action.variant} wide`;
256
+ node.dataset.actionId = action.id;
257
+ node.setAttribute('part', `action action-${action.variant} action-${action.id}`);
258
+ node.textContent = action.label;
259
+ return node;
260
+ }
261
+
262
+ /** A release button for a host action. Its label is plain text, never parsed as HTML. */
263
+ function hostButton(action) {
264
+ const node = document.createElement('button');
265
+ node.type = 'button';
266
+ node.addEventListener('click', () => runAction(action, node));
267
+ return styleButton(node, action);
268
+ }
269
+
270
+ /** Put the release buttons in list order. The Save node stays in the DOM when the list leaves it out, so its listener still works. */
271
+ function renderActions() {
272
+ const save = $('btn-save');
273
+ const nodes = state.actions.map((action) => (action.builtin ? styleButton(save, action) : hostButton(action)));
274
+ const saveListed = nodes.includes(save);
275
+ save.hidden = !saveListed;
276
+ if (!saveListed) nodes.push(save);
277
+ nodes.push($('btn-copy'));
278
+ $('actions').replaceChildren(...nodes);
279
+ const fileActions = state.actions.filter((a) => a.outputs.includes('file'));
280
+ $('fmt-wrap').hidden = fileActions.length > 0 && fileActions.every((a) => a.format);
281
+ $('send-as').hidden = !state.actions.some((a) => a.choose);
282
+ syncActionButtons();
283
+ }
284
+
285
+ /** Apply a host action list. A list that fails the rules throws, and the previous list stays. */
286
+ function setActions(list) {
287
+ state.actions = normalizeActions(list);
288
+ renderActions();
289
+ }
290
+
291
+ /** Outputs an action releases right now. A "choose" action follows the person's Send as pick. */
292
+ function outputsFor(action) {
293
+ let outs = action.outputs;
294
+ if (action.choose) outs = state.sendAs === 'both' ? ['file', 'text'] : [state.sendAs];
295
+ if (outs.includes('text') && textPending()) outs = outs.filter((o) => o !== 'text');
296
+ return (outs.length || !action.choose) ? outs : ['file'];
297
+ }
298
+
299
+ /** True when a button must stay disabled: its outputs are not ready, or no document is open. */
300
+ function actionBlocked(action) {
301
+ if (!action.outputs.length) return false;
302
+ if (!state.doc || state.scanning) return true;
303
+ return !action.choose && action.outputs.includes('text') && textPending();
304
+ }
305
+
306
+ /** Enable or disable the release buttons, Copy, and the Send as choice from the current scan state. */
307
+ function syncActionButtons() {
308
+ for (const action of state.actions) {
309
+ const node = root.querySelector(`[data-action-id="${action.id}"]`);
310
+ if (node) node.disabled = actionBlocked(action);
311
+ }
312
+ $('btn-copy').disabled = !state.doc || state.scanning;
313
+ $('send-as-file').textContent = state.doc?.kind === 'pdf' ? 'PDF' : 'Image';
314
+ const pending = textPending();
315
+ for (const btn of root.querySelectorAll('#send-as [data-send]')) {
316
+ const pick = btn.dataset.send;
317
+ btn.disabled = !state.doc || state.scanning || (pick !== 'file' && pending);
318
+ btn.classList.toggle('on', pick === state.sendAs);
319
+ btn.setAttribute('aria-checked', String(pick === state.sendAs));
320
+ }
321
+ }
322
+
323
+ // Send as: the person picks what a "choose" action releases.
324
+ for (const btn of root.querySelectorAll('#send-as [data-send]')) {
325
+ btn.addEventListener('click', () => {
326
+ state.sendAs = btn.dataset.send;
327
+ syncActionButtons();
328
+ });
329
+ }
330
+
331
+ /** The save note under the export card: the file name, what was hidden, and the metadata re-check. */
332
+ function showSaveNote(name, clean, pagesIn) {
333
+ const note = $('save-note');
334
+ const hidden = pagesIn.reduce((n, p) => n + p.regions.length, 0);
335
+ const stripped = state.doc.meta.fields.length;
336
+ note.className = `save-note ${clean ? '' : 'bad'}`;
337
+ note.textContent = clean
338
+ ? `✓ Saved ${name} · ${hidden} region${hidden === 1 ? '' : 's'} hidden · ${stripped ? stripped + ' metadata field' + (stripped === 1 ? '' : 's') + ' removed · ' : ''}re-checked: 0 metadata fields in the output`
339
+ : `Saved ${name}, but a metadata check still found data. Please report this bug.`;
340
+ note.hidden = false;
341
+ }
342
+
343
+ /** Release what an action names, then fire `result` with exactly that. Runs only from a click on its button. */
344
+ async function runAction(action, btn) {
345
+ if (actionBlocked(action)) return;
346
+ const outputs = outputsFor(action);
347
+ const detail = {
348
+ action: action.id, outputs, findings: state.doc ? activeFindings() : [], truncated: !!state.doc?.truncated,
349
+ };
350
+ // An action that releases nothing only reports the click. No document data leaves.
351
+ if (!outputs.length) {
352
+ emit('result', detail);
353
+ return;
354
+ }
355
+ const idle = action.label;
356
+ btn.disabled = true; btn.textContent = action.busyLabel;
357
+ try {
358
+ const ex = await import('../io/exporter.js');
359
+ const opts = { style: state.style, strength: state.strength };
360
+ const pagesIn = state.doc.pages.map((p) => ({ canvas: p.canvas, regions: activeRegions(p) }));
361
+ if (outputs.includes('file')) {
362
+ const format = action.format || $('format').value;
363
+ const res = state.doc.kind === 'pdf'
364
+ ? await ex.exportPdf(pagesIn, opts)
365
+ : await ex.exportImage(pagesIn[0], { ...opts, format });
366
+ const name = ex.outputName(state.doc.name, res.ext);
367
+ if (action.download) ex.download(res.blob, name);
368
+ Object.assign(detail, { file: res.blob, filename: name, clean: res.clean });
369
+ if (action.download) showSaveNote(name, res.clean, pagesIn);
370
+ }
371
+ if (outputs.includes('text')) detail.transcript = redactedTranscript();
372
+ emit('result', detail);
373
+ if (!action.download) toast(`Released ${outputs.map((o) => (o === 'file' ? 'the file' : 'the text')).join(' and ')}.`);
374
+ } catch (err) {
375
+ console.error(err);
376
+ const note = $('save-note');
377
+ note.className = 'save-note bad'; note.textContent = `Export failed: ${err.message}`; note.hidden = false;
378
+ } finally {
379
+ btn.textContent = idle;
380
+ syncActionButtons();
381
+ }
382
+ }
383
+
235
384
  /** Counts of boxes still turned on, one entry per category that has any. */
236
385
  function activeFindings() {
237
386
  const counts = {};
@@ -274,7 +423,7 @@ export function attachController(host, initial = {}) {
274
423
  $('transcript-count').textContent = bits.join(' · ');
275
424
  }
276
425
 
277
- function refreshAll() { drawOverlay(); drawCategories(); drawTranscript(); schedule(); }
426
+ function refreshAll() { drawOverlay(); drawCategories(); drawTranscript(); syncActionButtons(); schedule(); }
278
427
 
279
428
  const STEPS = [
280
429
  ['ocr', 'Reading text'],
@@ -310,8 +459,6 @@ export function attachController(host, initial = {}) {
310
459
  state.scanning = false;
311
460
  $('scan-card').classList.add('done');
312
461
  $('scanfx').hidden = true;
313
- $('btn-save').disabled = false;
314
- $('btn-copy').disabled = false;
315
462
  refreshAll();
316
463
  setScan('done');
317
464
  }
@@ -327,7 +474,7 @@ export function attachController(host, initial = {}) {
327
474
  $('scan-card').classList.remove('done');
328
475
  $('scan-title').textContent = steps.length ? 'Scanning…' : 'Nothing selected to scan';
329
476
  $('scanfx').hidden = !steps.length;
330
- $('btn-save').disabled = true; $('btn-copy').disabled = true;
477
+ syncActionButtons();
331
478
  initSteps(steps);
332
479
  const scope = scanScopeText(prefs);
333
480
  const scopeEl = $('scan-scope');
@@ -468,6 +615,7 @@ export function attachController(host, initial = {}) {
468
615
  state.run++;
469
616
  state.doc = null;
470
617
  state.scanning = false;
618
+ syncActionButtons();
471
619
  setScan('');
472
620
  setScreen('drop');
473
621
  $('file').value = '';
@@ -730,43 +878,8 @@ export function attachController(host, initial = {}) {
730
878
  overlay.addEventListener('pointerup', endDrag);
731
879
  overlay.addEventListener('pointercancel', endDrag);
732
880
 
733
- $('btn-save').addEventListener('click', async () => {
734
- if (!state.doc || state.scanning) return;
735
- const btn = $('btn-save');
736
- const label = btn.textContent;
737
- btn.disabled = true; btn.textContent = 'Sanitizing…';
738
- const note = $('save-note');
739
- try {
740
- const ex = await import('../io/exporter.js');
741
- const opts = { style: state.style, strength: state.strength };
742
- const pagesIn = state.doc.pages.map((p) => ({ canvas: p.canvas, regions: activeRegions(p) }));
743
- let res;
744
- if (state.doc.kind === 'pdf') res = await ex.exportPdf(pagesIn, opts);
745
- else res = await ex.exportImage(pagesIn[0], { ...opts, format: $('format').value });
746
- const name = ex.outputName(state.doc.name, res.ext);
747
- ex.download(res.blob, name);
748
- const hidden = pagesIn.reduce((n, p) => n + p.regions.length, 0);
749
- const stripped = state.doc.meta.fields.length;
750
- note.className = `save-note ${res.clean ? '' : 'bad'}`;
751
- note.textContent = res.clean
752
- ? `✓ Saved ${name} · ${hidden} region${hidden === 1 ? '' : 's'} hidden · ${stripped ? stripped + ' metadata field' + (stripped === 1 ? '' : 's') + ' removed · ' : ''}re-checked: 0 metadata fields in the output`
753
- : `Saved ${name}, but a metadata check still found data. Please report this bug.`;
754
- note.hidden = false;
755
- emit('result', {
756
- file: res.blob,
757
- filename: name,
758
- findings: activeFindings(),
759
- clean: res.clean,
760
- truncated: !!state.doc.truncated,
761
- transcript: redactedTranscript(),
762
- });
763
- } catch (err) {
764
- console.error(err);
765
- note.className = 'save-note bad'; note.textContent = `Export failed: ${err.message}`; note.hidden = false;
766
- } finally {
767
- btn.disabled = false; btn.textContent = label;
768
- }
769
- });
881
+ // The built-in Save button runs the same release path as a host action.
882
+ $('btn-save').addEventListener('click', () => runAction(state.actions.find((a) => a.builtin) || downloadAction(), $('btn-save')));
770
883
  $('transcript-toggle').addEventListener('click', () => {
771
884
  setTranscriptOpen($('transcript-panel').hidden);
772
885
  });
@@ -814,6 +927,7 @@ export function attachController(host, initial = {}) {
814
927
 
815
928
  if (initial.style) setStyle(initial.style);
816
929
  if (initial.strength != null) setStrength(initial.strength);
930
+ setActions(initial.actions);
817
931
  setScreen('drop');
818
932
 
819
933
  return {
@@ -823,6 +937,8 @@ export function attachController(host, initial = {}) {
823
937
  home,
824
938
  setStyle,
825
939
  setStrength,
940
+ setActions,
941
+ getActions: () => state.actions,
826
942
  getStyle: () => state.style,
827
943
  getStrength: () => state.strength,
828
944
  /** Release page listeners. The element calls this when it leaves the document. */
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { reviewTemplate } from './template.js';
6
6
  import { attachController } from './controller.js';
7
+ import { normalizeActions } from './actions.js';
7
8
  import reviewCss from './review.css?inline';
8
9
 
9
10
  export const REVIEW_TAG = 'privacy-redact-review';
@@ -61,6 +62,18 @@ class PiiRedactReview extends HTMLElement {
61
62
  this._api?.setStrength(this._strength);
62
63
  }
63
64
 
65
+ /** The release buttons, as a list of actions. Set it before or after the file opens. */
66
+ get actions() {
67
+ return this._api?.getActions() ?? this._actions ?? null;
68
+ }
69
+
70
+ /** A list that breaks the rules throws a TypeError, and the screen keeps its previous list. */
71
+ set actions(value) {
72
+ normalizeActions(value);
73
+ this._actions = value;
74
+ this._api?.setActions(value);
75
+ }
76
+
64
77
  /** A file assigned here opens in the review flow. */
65
78
  get file() {
66
79
  return this._pendingFile ?? null;
@@ -82,6 +95,7 @@ class PiiRedactReview extends HTMLElement {
82
95
  this._api = attachController(this, {
83
96
  style: this._redactStyle || this.getAttribute('redact-style') || undefined,
84
97
  strength: this._strength ?? (strengthAttr != null && strengthAttr !== '' ? Number(strengthAttr) : undefined),
98
+ actions: this._actions,
85
99
  });
86
100
  if (this._pendingFile) this._api.open(this._pendingFile);
87
101
  }
@@ -5,8 +5,10 @@ import { createElement, useEffect, useRef } from 'react';
5
5
  import './element.js';
6
6
 
7
7
  /** Drop-in review screen. `onResult` runs when the person saves, and only then. */
8
- export function PrivacyRedactReview({ file, style, strength, onResult }) {
8
+ export function PrivacyRedactReview({ file, style, strength, actions, onResult }) {
9
9
  const ref = useRef(null);
10
+ // Compare the action list by value, so an inline array does not reset the screen on every render.
11
+ const actionsKey = actions ? JSON.stringify(actions) : '';
10
12
 
11
13
  useEffect(() => {
12
14
  const el = ref.current;
@@ -34,5 +36,11 @@ export function PrivacyRedactReview({ file, style, strength, onResult }) {
34
36
  el.open(file);
35
37
  }, [file]);
36
38
 
39
+ useEffect(() => {
40
+ const el = ref.current;
41
+ if (!el || !actions) return;
42
+ el.actions = actions;
43
+ }, [actionsKey]);
44
+
37
45
  return createElement('privacy-redact-review', { ref });
38
46
  }
@@ -498,6 +498,7 @@
498
498
  .meta .empty { color: var(--on-surface-muted); }
499
499
 
500
500
  .export { position: sticky; bottom: 1rem; display: grid; gap: 0.75rem; }
501
+ .actions-list { display: grid; gap: 0.6rem; }
501
502
  .row { display: flex; gap: 0.75rem; }
502
503
  .fmt { display: flex; align-items: center; gap: 0.75rem; color: var(--on-surface-muted); font-size: 15px; font-weight: 400; width: 100%; }
503
504
  .fmt select {
@@ -110,8 +110,15 @@ export const reviewTemplate = `
110
110
  <select id="format"><option value="png">PNG (lossless)</option><option value="jpeg">JPG (smaller)</option></select>
111
111
  </label>
112
112
  </div>
113
- <button id="btn-save" class="btn primary big">Save sanitized file</button>
114
- <button id="btn-copy" class="btn ghost wide">Copy to clipboard</button>
113
+ <div id="send-as" class="seg" role="radiogroup" aria-label="Send as" part="send-as" hidden>
114
+ <button type="button" id="send-as-file" data-send="file" role="radio" aria-checked="false">Image</button>
115
+ <button type="button" data-send="text" role="radio" aria-checked="false">Text</button>
116
+ <button type="button" data-send="both" role="radio" aria-checked="true" class="on">Both</button>
117
+ </div>
118
+ <div id="actions" class="actions-list" part="actions">
119
+ <button id="btn-save" class="btn primary big" data-action-id="download">Save sanitized file</button>
120
+ <button id="btn-copy" class="btn ghost wide">Copy to clipboard</button>
121
+ </div>
115
122
  <div id="save-note" class="save-note" hidden></div>
116
123
  <p class="fine">Auto-detection is good, not perfect. Give the preview a quick look before you share.</p>
117
124
  </div>