privacy-redact 0.1.0 → 1.0.2

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.
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Turns a dropped File into page canvases. Images are decoded honouring EXIF orientation
3
+ * (so the exported result is upright even though we drop the orientation tag).
4
+ * PDFs are rasterised page-by-page – which is also what makes PDF redaction *real*: the text under a
5
+ * redaction box no longer exists in the output.
6
+ */
7
+ import * as pdfjs from 'pdfjs-dist';
8
+ import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
9
+ import { readImageMetadata, readPdfMetadata } from './metadata.js';
10
+
11
+ pdfjs.GlobalWorkerOptions.workerSrc = pdfWorkerUrl;
12
+
13
+ export const PDF_SCALE = 2; // 144 dpi – crisp text, reasonable memory
14
+ export const MAX_PDF_PAGES = 60;
15
+ const MAX_SIDE = 9000;
16
+
17
+ const IMAGE_TYPES = /^image\/(png|jpe?g|webp|gif|bmp|avif)$/i;
18
+ const IMAGE_EXT = /\.(png|jpe?g|webp|gif|bmp|avif)$/i;
19
+
20
+ export function classify(file) {
21
+ if (file.type === 'application/pdf' || /\.pdf$/i.test(file.name)) return 'pdf';
22
+ if (IMAGE_TYPES.test(file.type) || IMAGE_EXT.test(file.name)) return 'image';
23
+ if (/heic|heif/i.test(file.type) || /\.(heic|heif)$/i.test(file.name)) return 'heic';
24
+ return null;
25
+ }
26
+
27
+ async function imageToCanvas(file) {
28
+ let bmp;
29
+ try {
30
+ bmp = await createImageBitmap(file, { imageOrientation: 'from-image' });
31
+ } catch {
32
+ bmp = await createImageBitmap(file);
33
+ }
34
+ let { width: w, height: h } = bmp;
35
+ const k = Math.min(1, MAX_SIDE / Math.max(w, h));
36
+ w = Math.round(w * k); h = Math.round(h * k);
37
+ const canvas = document.createElement('canvas');
38
+ canvas.width = w; canvas.height = h;
39
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
40
+ ctx.fillStyle = '#fff'; // flatten transparency so exports never show through
41
+ ctx.fillRect(0, 0, w, h);
42
+ ctx.drawImage(bmp, 0, 0, w, h);
43
+ bmp.close?.();
44
+ return canvas;
45
+ }
46
+
47
+ /**
48
+ * @param {File} file
49
+ * @param {(msg:string)=>void} [onStatus]
50
+ * @returns {Promise<{kind:'image'|'pdf', name:string, pages:HTMLCanvasElement[], meta:{fields:any[],rawCount:number}, truncated:boolean}>}
51
+ */
52
+ export async function loadFile(file, onStatus) {
53
+ const kind = classify(file);
54
+ if (kind === 'heic') throw new Error('HEIC photos aren’t supported by browsers yet. Convert to JPG/PNG first (on iPhone: Settings → Camera → Formats → Most Compatible).');
55
+ if (!kind) throw new Error('Unsupported file type. Drop a PNG, JPG, WebP, GIF, BMP, AVIF or PDF.');
56
+
57
+ const name = file.name || 'pasted-image.png';
58
+ if (kind === 'image') {
59
+ const [canvas, meta] = await Promise.all([imageToCanvas(file), readImageMetadata(file)]);
60
+ return { kind, name, pages: [canvas], meta, truncated: false };
61
+ }
62
+
63
+ const data = new Uint8Array(await file.arrayBuffer());
64
+ const base = new URL(import.meta.env.BASE_URL + 'vendor/pdfjs/', window.location.href).href;
65
+ // In pdf.js 6 only the loading task can be destroyed (PDFDocumentProxy has no destroy()).
66
+ const loadingTask = pdfjs.getDocument({
67
+ data,
68
+ standardFontDataUrl: base + 'standard_fonts/',
69
+ cMapUrl: base + 'cmaps/',
70
+ cMapPacked: true,
71
+ wasmUrl: base + 'wasm/',
72
+ iccUrl: base + 'iccs/',
73
+ isEvalSupported: false,
74
+ });
75
+ try {
76
+ const pdf = await loadingTask.promise;
77
+ const meta = await readPdfMetadata(pdf);
78
+ const numPages = pdf.numPages;
79
+ const count = Math.min(numPages, MAX_PDF_PAGES);
80
+ const pages = [];
81
+ for (let i = 1; i <= count; i++) {
82
+ onStatus?.(`Rendering page ${i} of ${count}…`);
83
+ const page = await pdf.getPage(i);
84
+ const viewport = page.getViewport({ scale: PDF_SCALE });
85
+ const canvas = document.createElement('canvas');
86
+ canvas.width = Math.floor(viewport.width);
87
+ canvas.height = Math.floor(viewport.height);
88
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
89
+ ctx.fillStyle = '#fff';
90
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
91
+ await page.render({ canvasContext: ctx, viewport }).promise;
92
+ pages.push(canvas);
93
+ page.cleanup();
94
+ }
95
+ return { kind, name, pages, meta, truncated: numPages > MAX_PDF_PAGES };
96
+ } finally {
97
+ // Always release the worker, even if parsing or rendering failed.
98
+ await loadingTask.destroy().catch(() => {});
99
+ }
100
+ }
@@ -0,0 +1,75 @@
1
+ /** Reads (for display only) the hidden metadata that will NOT survive export. */
2
+ import exifr from 'exifr';
3
+
4
+ const fmtDate = (d) => {
5
+ if (!d) return '';
6
+ const dt = d instanceof Date ? d : new Date(d);
7
+ return isNaN(dt) ? String(d) : dt.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
8
+ };
9
+
10
+ /**
11
+ * Turns raw EXIF/XMP tags into a short human list. Pure function (unit-tested).
12
+ * @returns {{icon:string,label:string,value:string,risk:'high'|'med'|'low'}[]}
13
+ */
14
+ export function summarizeTags(t) {
15
+ if (!t) return [];
16
+ const out = [];
17
+ const add = (icon, label, value, risk = 'low') => { if (value !== undefined && value !== null && String(value).trim() !== '') out.push({ icon, label, value: String(value), risk }); };
18
+
19
+ if (typeof t.latitude === 'number' && typeof t.longitude === 'number') {
20
+ add('📍', 'GPS location', `${t.latitude.toFixed(4)}, ${t.longitude.toFixed(4)}`, 'high');
21
+ }
22
+ if (typeof t.GPSAltitude === 'number') add('⛰️', 'GPS altitude', `${Math.round(t.GPSAltitude)} m`, 'med');
23
+ const cam = [t.Make, t.Model].filter(Boolean).join(' ').trim();
24
+ add('📷', 'Camera / device', cam, 'med');
25
+ add('🔢', 'Camera serial number', t.BodySerialNumber || t.SerialNumber || t.CameraSerialNumber, 'high');
26
+ add('🔭', 'Lens serial number', t.LensSerialNumber, 'med');
27
+ add('👤', 'Owner / author', t.OwnerName || t.Artist || t.Creator || t.Author, 'high');
28
+ add('©️', 'Copyright', t.Copyright || t.Rights, 'low');
29
+ add('🕒', 'Original capture date', fmtDate(t.DateTimeOriginal || t.CreateDate), 'med');
30
+ add('🛠️', 'Edited with', t.Software || t.CreatorTool, 'low');
31
+ add('💬', 'Description / comments', t.ImageDescription || t.UserComment || t.Description, 'med');
32
+ add('🧭', 'Image unique ID', t.ImageUniqueID, 'med');
33
+ return out;
34
+ }
35
+
36
+ export async function readImageMetadata(file) {
37
+ try {
38
+ const tags = await exifr.parse(file, {
39
+ tiff: true, exif: true, gps: true, xmp: true, iptc: true, icc: false, jfif: false, ihdr: false,
40
+ mergeOutput: true, translateValues: true, reviveValues: true, sanitize: false,
41
+ });
42
+ return { fields: summarizeTags(tags), rawCount: tags ? Object.keys(tags).length : 0 };
43
+ } catch {
44
+ return { fields: [], rawCount: 0 };
45
+ }
46
+ }
47
+
48
+ export async function readPdfMetadata(pdf) {
49
+ try {
50
+ const { info } = await pdf.getMetadata();
51
+ const fields = [];
52
+ const add = (icon, label, v, risk = 'low') => { if (v && String(v).trim()) fields.push({ icon, label, value: String(v), risk }); };
53
+ add('👤', 'Author', info.Author, 'high');
54
+ add('📄', 'Title', info.Title, 'med');
55
+ add('🛠️', 'Created with', info.Creator, 'low');
56
+ add('⚙️', 'PDF producer', info.Producer, 'low');
57
+ add('🏷️', 'Keywords / subject', [info.Subject, info.Keywords].filter(Boolean).join(' · '), 'med');
58
+ const pdate = (s) => { const m = /D:(\d{4})(\d\d)(\d\d)/.exec(s || ''); return m ? `${m[1]}-${m[2]}-${m[3]}` : ''; };
59
+ add('🕒', 'Created', pdate(info.CreationDate), 'med');
60
+ add('✏️', 'Modified', pdate(info.ModDate), 'low');
61
+ return { fields, rawCount: Object.keys(info || {}).length };
62
+ } catch {
63
+ return { fields: [], rawCount: 0 };
64
+ }
65
+ }
66
+
67
+ /** Re-open an exported image and confirm no metadata segment is left. */
68
+ export async function verifyImageClean(blob) {
69
+ try {
70
+ const tags = await exifr.parse(blob, { tiff: true, exif: true, gps: true, xmp: true, iptc: true, icc: false, jfif: false, ihdr: false, mergeOutput: true });
71
+ return !tags || Object.keys(tags).length === 0;
72
+ } catch {
73
+ return true; // exifr throws when there is no metadata container at all
74
+ }
75
+ }
package/src/main.js ADDED
@@ -0,0 +1,37 @@
1
+ import './style.css';
2
+ import './review/element.js';
3
+
4
+ const BASE = import.meta.env.BASE_URL;
5
+ const review = document.querySelector('privacy-redact-review');
6
+ const marketing = document.querySelectorAll('#landing > .landing-copy');
7
+
8
+ /** Show or hide the harness chrome around the review element. */
9
+ function applyMode(detail) {
10
+ document.getElementById('btn-reset').hidden = !detail.hasDoc;
11
+ document.getElementById('btn-settings').setAttribute('aria-pressed', String(detail.screen === 'settings'));
12
+ for (const block of marketing) block.hidden = detail.screen !== 'drop';
13
+ }
14
+
15
+ document.getElementById('btn-settings').addEventListener('click', () => review.toggleSettings());
16
+ document.getElementById('btn-reset').addEventListener('click', () => review.reset());
17
+ document.getElementById('brand').addEventListener('click', (e) => {
18
+ e.preventDefault();
19
+ review.home();
20
+ });
21
+
22
+ review.addEventListener('mode', (e) => applyMode(e.detail));
23
+
24
+ document.getElementById('samples').addEventListener('click', async (e) => {
25
+ const name = e.target.closest('[data-sample]')?.dataset.sample;
26
+ if (!name) return;
27
+ try {
28
+ const res = await fetch(`${BASE}samples/${name}`);
29
+ if (!res.ok) throw new Error(res.statusText);
30
+ const blob = await res.blob();
31
+ review.open(new File([blob], name, { type: blob.type }));
32
+ } catch {
33
+ const error = review.shadowRoot.querySelector('#landing-error');
34
+ error.textContent = 'Could not load the sample.';
35
+ error.hidden = false;
36
+ }
37
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Which fields a scan should look for. Pure: no DOM. The page stores the
3
+ * result in localStorage; tests pass a fake storage object.
4
+ */
5
+ import { CATEGORIES, TEXT_TYPES } from '../detect/patterns.js';
6
+
7
+ const STORAGE_KEY = 'privacy-redact.scan';
8
+
9
+ /** Picture detectors. Each one is its own pass, unlike the text fields. */
10
+ export const PICTURE_SCAN_TYPES = ['face', 'barcode'];
11
+
12
+ /** Every field the settings page can turn on or off, in display order. */
13
+ export const SCAN_TYPES = [...TEXT_TYPES, ...PICTURE_SCAN_TYPES];
14
+
15
+ /** All fields on. A new detector stays on until the user turns it off. */
16
+ export function defaultScanPrefs() {
17
+ return Object.fromEntries(SCAN_TYPES.map((id) => [id, true]));
18
+ }
19
+
20
+ /**
21
+ * Keep only known fields. A non-boolean value is ignored so a bad save
22
+ * cannot quietly leave a field out of the scan.
23
+ */
24
+ export function normalizeScanPrefs(raw) {
25
+ const prefs = defaultScanPrefs();
26
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return prefs;
27
+ for (const id of SCAN_TYPES) {
28
+ if (typeof raw[id] === 'boolean') prefs[id] = raw[id];
29
+ }
30
+ return prefs;
31
+ }
32
+
33
+ /** Read saved fields. Missing or unreadable storage means scan everything. */
34
+ export function loadScanPrefs(storage) {
35
+ const store = storage ?? globalThis.localStorage;
36
+ try {
37
+ const raw = store?.getItem(STORAGE_KEY);
38
+ if (!raw) return defaultScanPrefs();
39
+ return normalizeScanPrefs(JSON.parse(raw));
40
+ } catch {
41
+ return defaultScanPrefs();
42
+ }
43
+ }
44
+
45
+ /** Persist fields. Returns the normalized set even if the write fails. */
46
+ export function saveScanPrefs(prefs, storage) {
47
+ const clean = normalizeScanPrefs(prefs);
48
+ const store = storage ?? globalThis.localStorage;
49
+ try {
50
+ store?.setItem(STORAGE_KEY, JSON.stringify(clean));
51
+ } catch {
52
+ // Private mode or a full quota. The in-memory set still applies this session.
53
+ }
54
+ return clean;
55
+ }
56
+
57
+ /** Text fields still selected. Empty means the text pass can be skipped. */
58
+ export function enabledTextTypes(prefs) {
59
+ const on = normalizeScanPrefs(prefs);
60
+ return TEXT_TYPES.filter((id) => on[id]);
61
+ }
62
+
63
+ /** Detector passes to run: one text pass, then barcodes, then faces. */
64
+ export function enabledSteps(prefs) {
65
+ const on = normalizeScanPrefs(prefs);
66
+ const steps = [];
67
+ if (TEXT_TYPES.some((id) => on[id])) steps.push('ocr');
68
+ if (on.barcode) steps.push('barcode');
69
+ if (on.face) steps.push('face');
70
+ return steps;
71
+ }
72
+
73
+ /** Fields for the common "only emails and phone numbers" choice. */
74
+ export function emailPhonePrefs() {
75
+ const prefs = defaultScanPrefs();
76
+ for (const id of SCAN_TYPES) prefs[id] = id === 'email' || id === 'phone';
77
+ return prefs;
78
+ }
79
+
80
+ /** One line for the scan card. Empty when every field is still on. */
81
+ export function scanScopeText(prefs) {
82
+ const on = normalizeScanPrefs(prefs);
83
+ const ids = SCAN_TYPES.filter((id) => on[id]);
84
+ if (ids.length === SCAN_TYPES.length) return '';
85
+ if (!ids.length) return 'No fields selected. You can still draw boxes by hand.';
86
+ const labels = ids.map((id) => CATEGORIES[id].label.toLowerCase());
87
+ if (labels.length === 1) return `Looking for ${labels[0]} only.`;
88
+ const last = labels.pop();
89
+ return `Looking for ${labels.join(', ')} and ${last} only.`;
90
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Redaction rendering. Every effect destroys information (block-averaging) *before* any smoothing,
3
+ * so blurred regions cannot be "un-blurred" – the original pixels are never kept in the output.
4
+ */
5
+
6
+ export const STYLES = {
7
+ blur: { label: 'Blur' },
8
+ pixelate: { label: 'Pixelate' },
9
+ blackout: { label: 'Blackout' },
10
+ };
11
+
12
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
13
+
14
+ /** Rectangle actually covered for a region (adds breathing room, more for faces). */
15
+ export function coverRect(r, W, H) {
16
+ const isFace = r.type === 'face';
17
+ const padX = isFace ? r.w * 0.18 : Math.max(3, r.h * 0.18);
18
+ const padY = isFace ? r.h * 0.28 : Math.max(2, r.h * 0.14);
19
+ const x0 = clamp(Math.floor(r.x - padX), 0, W);
20
+ const y0 = clamp(Math.floor(r.y - padY), 0, H);
21
+ const x1 = clamp(Math.ceil(r.x + r.w + padX), 0, W);
22
+ const y1 = clamp(Math.ceil(r.y + r.h + padY), 0, H);
23
+ return { x: x0, y: y0, w: Math.max(1, x1 - x0), h: Math.max(1, y1 - y0) };
24
+ }
25
+
26
+ /** Size (px) of one mosaic cell. strength 0..1 (higher = coarser). */
27
+ export function cellSize(rect, type, strength) {
28
+ const shorter = Math.min(rect.w, rect.h);
29
+ // Text gets very coarse cells (≈1–2.4 across a line's height): fine mosaics of known fonts can be brute-forced back
30
+ // into text (see "Depix"/"Unredacter"), so a text cell must span most of a glyph.
31
+ const cells = type === 'face' || type === 'barcode' ? 11 - 6 * strength : 2.4 - 1.4 * strength; // cells across the short side
32
+ return Math.max(3, Math.round(shorter / cells));
33
+ }
34
+
35
+ function shapePath(ctx, rect, type) {
36
+ ctx.beginPath();
37
+ if (type === 'face') {
38
+ ctx.ellipse(rect.x + rect.w / 2, rect.y + rect.h / 2, rect.w / 2, rect.h / 2, 0, 0, Math.PI * 2);
39
+ } else {
40
+ const rad = Math.min(rect.h / 4, 6);
41
+ const { x, y, w, h } = rect;
42
+ ctx.moveTo(x + rad, y);
43
+ ctx.arcTo(x + w, y, x + w, y + h, rad);
44
+ ctx.arcTo(x + w, y + h, x, y + h, rad);
45
+ ctx.arcTo(x, y + h, x, y, rad);
46
+ ctx.arcTo(x, y, x + w, y, rad);
47
+ ctx.closePath();
48
+ }
49
+ }
50
+
51
+ /** Average colour of each `cell`×`cell` block → tiny canvas (1px per block). */
52
+ function averageBlocks(source, rect, cell, noise = 0) {
53
+ const sctx = source.getContext('2d', { willReadFrequently: true });
54
+ const { data } = sctx.getImageData(rect.x, rect.y, rect.w, rect.h);
55
+ const bw = Math.ceil(rect.w / cell);
56
+ const bh = Math.ceil(rect.h / cell);
57
+ const small = document.createElement('canvas');
58
+ small.width = bw; small.height = bh;
59
+ const out = small.getContext('2d');
60
+ const img = out.createImageData(bw, bh);
61
+ for (let by = 0; by < bh; by++) {
62
+ for (let bx = 0; bx < bw; bx++) {
63
+ let r = 0, g = 0, b = 0, n = 0;
64
+ const y1 = Math.min(rect.h, (by + 1) * cell);
65
+ const x1 = Math.min(rect.w, (bx + 1) * cell);
66
+ for (let y = by * cell; y < y1; y++) {
67
+ let i = (y * rect.w + bx * cell) * 4;
68
+ for (let x = bx * cell; x < x1; x++, i += 4) { r += data[i]; g += data[i + 1]; b += data[i + 2]; n++; }
69
+ }
70
+ const o = (by * bw + bx) * 4;
71
+ // Random jitter per block defeats attacks that re-pixelate candidate text and look for an exact colour match.
72
+ const j = noise ? (Math.random() * 2 - 1) * noise : 0;
73
+ img.data[o] = r / n + j; img.data[o + 1] = g / n + j; img.data[o + 2] = b / n + j; img.data[o + 3] = 255;
74
+ }
75
+ }
76
+ out.putImageData(img, 0, 0);
77
+ return { small, bw, bh };
78
+ }
79
+
80
+ const FILTER_OK = typeof CanvasRenderingContext2D !== 'undefined' && 'filter' in CanvasRenderingContext2D.prototype;
81
+
82
+ function applyOne(ctx, source, region, style, strength) {
83
+ const W = source.width, H = source.height;
84
+ const rect = coverRect(region, W, H);
85
+ ctx.save();
86
+ shapePath(ctx, rect, region.type);
87
+ ctx.clip();
88
+
89
+ if (style === 'blackout') {
90
+ ctx.fillStyle = '#0a0a0f';
91
+ ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
92
+ } else {
93
+ const cell = cellSize(rect, region.type, strength);
94
+ // Blur samples a slightly larger area so the soft edge blends with the surroundings.
95
+ const grow = style === 'blur' ? cell : 0;
96
+ const area = {
97
+ x: clamp(rect.x - grow, 0, W), y: clamp(rect.y - grow, 0, H),
98
+ w: 0, h: 0,
99
+ };
100
+ area.w = clamp(rect.x + rect.w + grow, 0, W) - area.x;
101
+ area.h = clamp(rect.y + rect.h + grow, 0, H) - area.y;
102
+ const { small, bw, bh } = averageBlocks(source, area, cell, region.type === 'face' ? 0 : 10);
103
+ if (style === 'pixelate') {
104
+ ctx.imageSmoothingEnabled = false;
105
+ ctx.drawImage(small, 0, 0, bw, bh, area.x, area.y, bw * cell, bh * cell);
106
+ } else {
107
+ ctx.imageSmoothingEnabled = true;
108
+ ctx.imageSmoothingQuality = 'high';
109
+ if (FILTER_OK) ctx.filter = `blur(${(cell * 0.55).toFixed(1)}px)`;
110
+ ctx.drawImage(small, 0, 0, bw, bh, area.x, area.y, bw * cell, bh * cell);
111
+ ctx.filter = 'none';
112
+ }
113
+ }
114
+ ctx.restore();
115
+ }
116
+
117
+ /**
118
+ * Draws `source` onto `target` with all given regions redacted.
119
+ * @param {HTMLCanvasElement} target
120
+ * @param {HTMLCanvasElement} source original page (never modified)
121
+ * @param {{type:string,x:number,y:number,w:number,h:number}[]} regions already filtered to the enabled ones
122
+ */
123
+ export function renderRedactions(target, source, regions, style = 'blur', strength = 0.6) {
124
+ if (target.width !== source.width) target.width = source.width;
125
+ if (target.height !== source.height) target.height = source.height;
126
+ const ctx = target.getContext('2d');
127
+ ctx.drawImage(source, 0, 0);
128
+ for (const r of regions) applyOne(ctx, source, r, style, strength);
129
+ }