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.
@@ -98,7 +98,7 @@ const RULES = [
98
98
  {
99
99
  // "Mobile No.98765-43210" — the dot is glued on, so a bare number pattern never sees a word boundary.
100
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,
101
+ re: /\b(?:Mobile|Mob|Phone|Ph|Phn|Tel|Telephone|Cell|Whatsapp|WA|Contact)\s*(?:No|Number|#)?\.?\s*[:#\-]?\s*(\+?\d[\d\s.\-()]{7,16}\d)/gi,
102
102
  group: 1,
103
103
  validate(m) {
104
104
  const n = m.replace(/\D/g, '').length;
@@ -111,6 +111,12 @@ const RULES = [
111
111
  re: /(?<![\w@/])(?:\+91[\s.\-]?)?[6-9]\d{4}[\s.\-]\d{5}(?!\d)/g,
112
112
  confidence: 0.88,
113
113
  },
114
+ {
115
+ // Unlabelled bare Indian mobile: 9977343444 (10 digits, starts 6-9, not part of a longer number/decimal/ID).
116
+ type: 'phone',
117
+ re: /(?<![\w@/.\-])[6-9]\d{9}(?![\d\-@/]|\.\d)/g,
118
+ confidence: 0.75,
119
+ },
114
120
  {
115
121
  // 123 Main Street, Apt 4B
116
122
  type: 'address',
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Turns pattern matches on OCR lines into pixel rectangles.
3
+ * Pure – no DOM – so it is unit-tested in Node.
4
+ *
5
+ * A line is { words: [{ text, bbox:{x0,y0,x1,y1} }] }.
6
+ */
7
+ import { CATEGORIES, findSensitive, TEXT_TYPES } from './patterns.js';
8
+
9
+ export function lineToText(line) {
10
+ let text = '';
11
+ const spans = [];
12
+ for (const w of line.words) {
13
+ if (!w.text || !w.text.trim()) continue;
14
+ if (text) text += ' ';
15
+ const start = text.length;
16
+ text += w.text;
17
+ spans.push({ start, end: text.length, word: w });
18
+ }
19
+ return { text, spans };
20
+ }
21
+
22
+ /** The words the scanner kept, one recognized row per line. */
23
+ export function transcriptFromLines(lines) {
24
+ if (!lines?.length) return '';
25
+ return lines.map((line) => lineToText(line).text).filter(Boolean).join('\n');
26
+ }
27
+
28
+ /**
29
+ * Replace sensitive spans in a plain string with bullets of the same length.
30
+ * OCR lines use redactTranscript, which also joins values split across stacked rows.
31
+ */
32
+ export function redactPlainText(text, types = TEXT_TYPES) {
33
+ const value = String(text ?? '');
34
+ if (!value) return '';
35
+ return maskRanges(value, findSensitive(value, types));
36
+ }
37
+
38
+ /**
39
+ * Redact plain text with the library's current text detectors.
40
+ * Omit `types` so a caller picks up new detectors without changing its own code.
41
+ * Returns the redacted string and a count per detector. The matched secrets are not included.
42
+ */
43
+ export function redactDocument(text, types = TEXT_TYPES) {
44
+ const value = String(text ?? '');
45
+ const hits = value ? findSensitive(value, types) : [];
46
+ const counts = {};
47
+ for (const hit of hits) counts[hit.type] = (counts[hit.type] || 0) + 1;
48
+ return {
49
+ text: redactPlainText(value, types),
50
+ findings: Object.entries(counts).map(([type, count]) => ({
51
+ type,
52
+ label: CATEGORIES[type]?.label || type,
53
+ count,
54
+ })),
55
+ };
56
+ }
57
+
58
+ /** Cover [start, end) ranges with bullets, merging overlaps first. */
59
+ function maskRanges(text, hits) {
60
+ const merged = [];
61
+ const ordered = hits
62
+ .map((h) => ({ start: Math.max(0, h.start), end: Math.min(text.length, h.end) }))
63
+ .filter((h) => h.end > h.start)
64
+ .sort((a, b) => a.start - b.start || b.end - a.end);
65
+ for (const h of ordered) {
66
+ const last = merged[merged.length - 1];
67
+ if (last && h.start <= last.end) last.end = Math.max(last.end, h.end);
68
+ else merged.push({ ...h });
69
+ }
70
+ let out = '';
71
+ let cursor = 0;
72
+ for (const h of merged) {
73
+ out += text.slice(cursor, h.start) + '•'.repeat(h.end - h.start);
74
+ cursor = h.end;
75
+ }
76
+ return out + text.slice(cursor);
77
+ }
78
+
79
+ /**
80
+ * The same reading as transcriptFromLines, with sensitive spans replaced by bullets.
81
+ * Includes a value that continues on the next stacked line, matching the boxes.
82
+ */
83
+ export function redactTranscript(lines, types = TEXT_TYPES) {
84
+ if (!lines?.length) return '';
85
+ const rows = lines.map((line) => {
86
+ const { text, spans } = lineToText(line);
87
+ return { text, box: text ? lineBox(spans) : null, hits: text ? findSensitive(text, types) : [] };
88
+ });
89
+ const wrapTypes = types.filter((t) => WRAPPABLE.includes(t));
90
+ if (wrapTypes.length) {
91
+ for (let i = 0; i + 1 < rows.length; i++) {
92
+ const a = rows[i], b = rows[i + 1];
93
+ if (!a.text || !b.text || !a.box || !b.box) continue;
94
+ const lineH = Math.min(a.box.y1 - a.box.y0, b.box.y1 - b.box.y0);
95
+ const gap = b.box.y0 - a.box.y1;
96
+ const stacked = gap < lineH && gap > -lineH * 0.6 && b.box.x0 < a.box.x1 && a.box.x0 < b.box.x1;
97
+ if (!stacked) continue;
98
+ const boundary = a.text.length;
99
+ for (const hit of findSensitive(`${a.text} ${b.text}`, wrapTypes)) {
100
+ if (!(hit.start < boundary - 1 && hit.end > boundary + 2)) continue;
101
+ a.hits.push({ start: hit.start, end: boundary });
102
+ const bEnd = hit.end - boundary - 1;
103
+ if (bEnd > 0) b.hits.push({ start: Math.max(0, hit.start - boundary - 1), end: bEnd });
104
+ }
105
+ }
106
+ }
107
+ return rows.map((row) => (row.text ? maskRanges(row.text, row.hits) : '')).filter(Boolean).join('\n');
108
+ }
109
+
110
+ /**
111
+ * Every page in one string. One page is just its lines.
112
+ * More than one page keeps its page number so a copy still shows where each sheet started.
113
+ */
114
+ export function documentTranscript(pageLines, { redact = false, types = TEXT_TYPES } = {}) {
115
+ const pages = pageLines || [];
116
+ const parts = [];
117
+ for (let i = 0; i < pages.length; i++) {
118
+ const text = redact ? redactTranscript(pages[i], types) : transcriptFromLines(pages[i]);
119
+ if (!text) continue;
120
+ parts.push(pages.length > 1 ? `Page ${i + 1}\n${text}` : text);
121
+ }
122
+ return parts.join('\n\n');
123
+ }
124
+
125
+ /** Bounding box of [start,end) inside a line, trimming partially-covered words proportionally. */
126
+ export function rectForRange(spans, start, end) {
127
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
128
+ for (const s of spans) {
129
+ if (s.end <= start || s.start >= end) continue;
130
+ const b = s.word.bbox;
131
+ const len = s.end - s.start;
132
+ let from = Math.max(start, s.start) - s.start;
133
+ let to = Math.min(end, s.end) - s.start;
134
+ const w = b.x1 - b.x0;
135
+ const charW = w / len;
136
+ const token = s.word.text;
137
+ // Trailing/leading punctuation isn't worth leaving a sliver for ("NW," → cover the comma too).
138
+ if (to < len && /^[.,;:!?)\]"'”’]+$/.test(token.slice(to))) to = len;
139
+ if (from > 0 && /^[("'“‘\[]+$/.test(token.slice(0, from))) from = 0;
140
+ // Character positions are estimated proportionally; cut a little generously on the *sensitive* side.
141
+ let bx0 = b.x0 + w * from / len - (from > 0 ? charW * 0.35 : 0);
142
+ let bx1 = b.x0 + w * to / len + (to < len ? charW * 0.35 : 0);
143
+ bx0 = Math.max(b.x0, bx0); bx1 = Math.min(b.x1, bx1);
144
+ x0 = Math.min(x0, bx0); x1 = Math.max(x1, bx1);
145
+ y0 = Math.min(y0, b.y0); y1 = Math.max(y1, b.y1);
146
+ }
147
+ if (!isFinite(x0)) return null;
148
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
149
+ }
150
+
151
+ const WRAPPABLE = ['phone', 'address', 'card'];
152
+
153
+ function lineBox(spans) {
154
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
155
+ for (const { word: { bbox: b } } of spans) { x0 = Math.min(x0, b.x0); y0 = Math.min(y0, b.y0); x1 = Math.max(x1, b.x1); y1 = Math.max(y1, b.y1); }
156
+ return { x0, y0, x1, y1 };
157
+ }
158
+
159
+ const overlapRatio = (a, b) => {
160
+ const w = Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x));
161
+ const h = Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y));
162
+ return (w * h) / Math.min(a.w * a.h, b.w * b.h);
163
+ };
164
+
165
+ /**
166
+ * @param {{words:any[]}[]} lines
167
+ * @param {string[]} types
168
+ * @returns {{type:string,x:number,y:number,w:number,h:number,confidence:number,text:string}[]}
169
+ */
170
+ export function regionsFromLines(lines, types) {
171
+ const regions = [];
172
+ const infos = [];
173
+ for (const line of lines) {
174
+ const { text, spans } = lineToText(line);
175
+ infos.push({ text, spans, box: text ? lineBox(spans) : null });
176
+ if (!text) continue;
177
+ for (const hit of findSensitive(text, types)) {
178
+ const r = rectForRange(spans, hit.start, hit.end);
179
+ if (r && r.w > 0 && r.h > 0) {
180
+ regions.push({ type: hit.type, ...r, confidence: hit.confidence, text: text.slice(hit.start, hit.end) });
181
+ }
182
+ }
183
+ }
184
+
185
+ // Second pass: things that wrap onto the next line ("+1 303 555⏎0166", "742 Evergreen⏎Terrace, Apt 4B").
186
+ const wrapTypes = types.filter((t) => WRAPPABLE.includes(t));
187
+ if (wrapTypes.length) {
188
+ for (let i = 0; i + 1 < infos.length; i++) {
189
+ const a = infos[i], b = infos[i + 1];
190
+ if (!a.text || !b.text) continue;
191
+ const lineH = Math.min(a.box.y1 - a.box.y0, b.box.y1 - b.box.y0);
192
+ const gap = b.box.y0 - a.box.y1;
193
+ const stacked = gap < lineH * 1.0 && gap > -lineH * 0.6 && b.box.x0 < a.box.x1 && a.box.x0 < b.box.x1;
194
+ if (!stacked) continue;
195
+ const boundary = a.text.length;
196
+ for (const hit of findSensitive(`${a.text} ${b.text}`, wrapTypes)) {
197
+ if (!(hit.start < boundary - 1 && hit.end > boundary + 2)) continue; // must genuinely cross the line break
198
+ const r1 = rectForRange(a.spans, hit.start, boundary);
199
+ const r2 = rectForRange(b.spans, 0, hit.end - boundary - 1);
200
+ const text = `${a.text} ${b.text}`.slice(hit.start, hit.end);
201
+ for (const r of [r1, r2]) {
202
+ if (!r || r.w <= 0 || r.h <= 0) continue;
203
+ if (regions.some((x) => x.type === hit.type && overlapRatio(x, r) > 0.6)) continue;
204
+ regions.push({ type: hit.type, ...r, confidence: hit.confidence * 0.9, text });
205
+ }
206
+ }
207
+ }
208
+ }
209
+ return mergeAdjacent(regions);
210
+ }
211
+
212
+ /**
213
+ * Same-type hits that sit next to each other on one line (e.g. "1600 Pennsylvania Ave NW," + "Washington, DC 20500")
214
+ * become one box – otherwise the rounded corners of two neighbours can leave a sliver of text visible between them.
215
+ */
216
+ export function mergeAdjacent(regions) {
217
+ const out = [];
218
+ for (const r of regions.slice().sort((a, b) => a.y - b.y || a.x - b.x)) {
219
+ const prev = out.find((o) => {
220
+ if (o.type !== r.type) return false;
221
+ const vOverlap = Math.min(o.y + o.h, r.y + r.h) - Math.max(o.y, r.y);
222
+ if (vOverlap < 0.6 * Math.min(o.h, r.h)) return false;
223
+ const gap = r.x - (o.x + o.w);
224
+ return gap > -4 && gap < 0.9 * Math.min(o.h, r.h);
225
+ });
226
+ if (prev) {
227
+ const x1 = Math.max(prev.x + prev.w, r.x + r.w), y1 = Math.max(prev.y + prev.h, r.y + r.h);
228
+ prev.x = Math.min(prev.x, r.x); prev.y = Math.min(prev.y, r.y);
229
+ prev.w = x1 - prev.x; prev.h = y1 - prev.y;
230
+ prev.text = `${prev.text} ${r.text}`;
231
+ } else out.push({ ...r });
232
+ }
233
+ return out;
234
+ }
235
+
236
+ /** Mask a matched string for display: keep at most the first character. */
237
+ export function maskHint(s) {
238
+ if (!s) return '';
239
+ const t = s.trim();
240
+ return t[0] + '•'.repeat(Math.min(8, Math.max(2, t.length - 1)));
241
+ }
Binary file
@@ -0,0 +1,93 @@
1
+ Copyright 2018 The Crimson Pro Project Authors (https://github.com/Fonthausen/CrimsonPro) CrimsonPro-Italic[wght].ttf: Copyright 2018 The Crimson Pro Project Authors (https://github.com/Fonthausen/CrimsonPro)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Google Inc.
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Serves the package's OCR, face, and PDF files on the host's own origin.
3
+ * The review element loads them from `/vendor` and does not take a model URL.
4
+ */
5
+ import { createReadStream, existsSync, statSync, cpSync } from 'node:fs';
6
+ import { join, normalize, extname, sep } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const packageRoot = fileURLToPath(new URL('../..', import.meta.url));
10
+ const vendorDir = fileURLToPath(new URL('../../public/vendor/', import.meta.url));
11
+
12
+ const types = {
13
+ '.js': 'text/javascript; charset=utf-8',
14
+ '.mjs': 'text/javascript; charset=utf-8',
15
+ '.json': 'application/json',
16
+ '.wasm': 'application/wasm',
17
+ '.gz': 'application/gzip',
18
+ '.ttf': 'font/ttf',
19
+ };
20
+
21
+ /** URL prefix for the vendored files, including the Vite `base`. */
22
+ function vendorPrefix(base) {
23
+ const normalized = !base || base === './' ? '/' : (base.startsWith('/') ? base : `/${base}`);
24
+ const withSlash = normalized.endsWith('/') ? normalized : `${normalized}/`;
25
+ return `${withSlash}vendor`;
26
+ }
27
+
28
+ /** True when `file` is a real file inside the vendored directory. */
29
+ function vendorFile(rel) {
30
+ const clean = normalize(rel).replace(/^[/\\]+/, '');
31
+ if (!clean || clean.startsWith('..') || clean.includes(`..${sep}`)) return null;
32
+ const file = join(vendorDir, clean);
33
+ const root = vendorDir.endsWith(sep) ? vendorDir : vendorDir + sep;
34
+ if (!file.startsWith(root) || !existsSync(file) || !statSync(file).isFile()) return null;
35
+ return file;
36
+ }
37
+
38
+ /** Vite plugin. Copy is for production builds. Dev requests are read from the package. */
39
+ export function privacyRedact() {
40
+ return {
41
+ name: 'privacy-redact-assets',
42
+ config() {
43
+ return {
44
+ optimizeDeps: {
45
+ // The review screen imports these on the first file. Prebundle them so that
46
+ // discovery does not reload the page and discard the open document.
47
+ exclude: ['privacy-redact'],
48
+ include: [
49
+ 'exifr',
50
+ 'pdfjs-dist',
51
+ 'pdf-lib',
52
+ 'tesseract.js',
53
+ '@zxing/library',
54
+ '@vladmandic/face-api/dist/face-api.esm.js',
55
+ ],
56
+ },
57
+ server: { fs: { allow: [packageRoot] } },
58
+ };
59
+ },
60
+ configResolved() {
61
+ if (!existsSync(vendorDir)) {
62
+ console.warn('[privacy-redact] public/vendor is missing. Run npm install in the privacy-redact package.');
63
+ }
64
+ },
65
+ configureServer(server) {
66
+ const prefix = vendorPrefix(server.config.base);
67
+ server.middlewares.use((req, res, next) => {
68
+ const url = decodeURIComponent((req.url || '').split('?')[0]);
69
+ if (url !== prefix && !url.startsWith(`${prefix}/`)) return next();
70
+ const file = vendorFile(url.slice(prefix.length));
71
+ if (!file) return next();
72
+ res.setHeader('Content-Type', types[extname(file)] || 'application/octet-stream');
73
+ createReadStream(file).on('error', next).pipe(res);
74
+ });
75
+ },
76
+ writeBundle(options) {
77
+ if (!options.dir || !existsSync(vendorDir)) return;
78
+ cpSync(vendorDir, join(options.dir, 'vendor'), { recursive: true });
79
+ },
80
+ };
81
+ }
package/src/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Node-safe library: find private text, redact it, and summarize document metadata.
3
+ * OCR, faces, barcodes, PDF rendering, and canvas export stay in their own modules
4
+ * so a server does not load a browser.
5
+ */
6
+ export { findSensitive, luhn, CATEGORIES, TEXT_TYPES } from './detect/patterns.js';
7
+ export {
8
+ redactDocument, redactPlainText, redactTranscript, documentTranscript, transcriptFromLines, regionsFromLines,
9
+ } from './detect/textRegions.js';
10
+ export {
11
+ SCAN_TYPES, defaultScanPrefs, normalizeScanPrefs, enabledTextTypes, enabledSteps,
12
+ } from './prefs/scan.js';
13
+ export { summarizeTags } from './io/metadata.js';
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Export = re-encode from raw pixels. Nothing from the source file (EXIF, XMP, IPTC, ICC, PDF info, embedded
3
+ * text layers, thumbnails…) can be carried over because we never copy bytes – we only write fresh pixels.
4
+ */
5
+ import { PDFDocument } from 'pdf-lib';
6
+ import { renderRedactions } from '../render/effects.js';
7
+ import { PDF_SCALE } from './loader.js';
8
+ import { verifyImageClean } from './metadata.js';
9
+
10
+ const toBlob = (canvas, type, quality) =>
11
+ new Promise((res, rej) => canvas.toBlob((b) => (b ? res(b) : rej(new Error('Encoding failed'))), type, quality));
12
+
13
+ function flatten(source, regions, style, strength) {
14
+ const c = document.createElement('canvas');
15
+ renderRedactions(c, source, regions, style, strength);
16
+ return c;
17
+ }
18
+
19
+ export function outputName(name, ext) {
20
+ const base = name.replace(/\.[^.]+$/, '') || 'document';
21
+ return `${base}-redacted.${ext}`;
22
+ }
23
+
24
+ /** @param pages {{canvas:HTMLCanvasElement, regions:any[]}[]} */
25
+ export async function exportImage(page, { style, strength, format }) {
26
+ const out = flatten(page.canvas, page.regions, style, strength);
27
+ const mime = format === 'jpeg' ? 'image/jpeg' : 'image/png';
28
+ const blob = await toBlob(out, mime, 0.93);
29
+ const clean = await verifyImageClean(blob);
30
+ return { blob, ext: format === 'jpeg' ? 'jpg' : 'png', clean };
31
+ }
32
+
33
+ export async function exportPdf(pages, { style, strength }) {
34
+ const doc = await PDFDocument.create({ updateMetadata: false }); // no default Producer / dates
35
+ for (const p of pages) {
36
+ const out = flatten(p.canvas, p.regions, style, strength);
37
+ const jpg = await toBlob(out, 'image/jpeg', 0.92);
38
+ const img = await doc.embedJpg(new Uint8Array(await jpg.arrayBuffer()));
39
+ const page = doc.addPage([out.width / PDF_SCALE, out.height / PDF_SCALE]);
40
+ page.drawImage(img, { x: 0, y: 0, width: out.width / PDF_SCALE, height: out.height / PDF_SCALE });
41
+ }
42
+ const bytes = await doc.save({ useObjectStreams: false });
43
+ const blob = new Blob([bytes], { type: 'application/pdf' });
44
+
45
+ // Verify: reopen and make sure the info dictionary is empty.
46
+ const check = await PDFDocument.load(bytes, { updateMetadata: false });
47
+ const clean = ![check.getAuthor(), check.getTitle(), check.getCreator(), check.getProducer(), check.getSubject(), check.getKeywords(), check.getCreationDate(), check.getModificationDate()]
48
+ .some((v) => v !== undefined && v !== null && v !== '');
49
+ return { blob, ext: 'pdf', clean };
50
+ }
51
+
52
+ export function download(blob, filename) {
53
+ const url = URL.createObjectURL(blob);
54
+ const a = document.createElement('a');
55
+ a.href = url; a.download = filename;
56
+ document.body.appendChild(a); a.click(); a.remove();
57
+ setTimeout(() => URL.revokeObjectURL(url), 10_000);
58
+ }
59
+
60
+ export async function copyImage(blob) {
61
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
62
+ }