@maskera/mcp 0.4.8 → 0.5.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/dist/cli.js CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { readFile, unlink, mkdir, writeFile, stat, access, appendFile, realpath, lstat, readlink, readdir } from 'fs/promises';
3
- import { delimiter, join, dirname, resolve, isAbsolute, relative, sep, posix, extname } from 'path';
2
+ import { readFile, writeFile, unlink, mkdir, stat, access, appendFile, realpath, readdir, lstat, readlink } from 'fs/promises';
3
+ import { extname, basename, join, dirname, delimiter, resolve, sep, relative, isAbsolute, posix } from 'path';
4
4
  import { createInterface } from 'readline';
5
5
  import { format } from 'util';
6
+ import { unzipSync, zipSync } from 'fflate';
7
+ import { PDFDocument, PDFName } from 'pdf-lib';
6
8
  import { constants, existsSync } from 'fs';
7
9
  import { createRequire } from 'module';
8
10
  import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
@@ -12,6 +14,1714 @@ import { homedir } from 'os';
12
14
  import { createServer } from 'http';
13
15
  import * as zlib from 'zlib';
14
16
 
17
+ var MAX_DEFAULT_FILE_BYTES = 25 * 1024 * 1024;
18
+ var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
19
+ var TEXT_MIME_BY_EXT = {
20
+ ".txt": "text/plain",
21
+ ".md": "text/markdown",
22
+ ".markdown": "text/markdown",
23
+ ".csv": "text/csv",
24
+ ".tsv": "text/tab-separated-values",
25
+ ".json": "application/json",
26
+ ".jsonl": "application/x-ndjson",
27
+ ".xml": "application/xml",
28
+ ".yaml": "application/yaml",
29
+ ".yml": "application/yaml",
30
+ ".html": "text/html",
31
+ ".htm": "text/html",
32
+ ".log": "text/plain",
33
+ ".sql": "text/plain",
34
+ ".ts": "text/plain",
35
+ ".tsx": "text/plain",
36
+ ".js": "text/plain",
37
+ ".mjs": "text/plain",
38
+ ".py": "text/plain"
39
+ };
40
+ function extractExtension(fileName) {
41
+ if (!fileName) return "";
42
+ const base = fileName.split(/[\\/]/).pop() ?? "";
43
+ const dot = base.lastIndexOf(".");
44
+ if (dot <= 0) return "";
45
+ return base.slice(dot).toLowerCase();
46
+ }
47
+ function hasPdfHeader(bytes) {
48
+ const limit = Math.min(bytes.byteLength, 1024);
49
+ for (let i = 0; i + 4 < limit; i++) {
50
+ if (bytes[i] === 37 && // %
51
+ bytes[i + 1] === 80 && // P
52
+ bytes[i + 2] === 68 && // D
53
+ bytes[i + 3] === 70 && // F
54
+ bytes[i + 4] === 45) {
55
+ return true;
56
+ }
57
+ }
58
+ return false;
59
+ }
60
+ function hasZipHeader(bytes) {
61
+ if (bytes.byteLength < 4) return false;
62
+ return bytes[0] === 80 && bytes[1] === 75 && (bytes[2] === 3 && bytes[3] === 4 || bytes[2] === 5 && bytes[3] === 6 || bytes[2] === 7 && bytes[3] === 8);
63
+ }
64
+ function detectOfficeZipFormat(bytes) {
65
+ try {
66
+ let isDocx = false;
67
+ let isXlsx = false;
68
+ let entriesSeen = 0;
69
+ unzipSync(bytes, {
70
+ filter(file) {
71
+ entriesSeen += 1;
72
+ if (entriesSeen > 2e3) return false;
73
+ const name = file.name.toLowerCase();
74
+ if (name === "word/document.xml") isDocx = true;
75
+ if (name === "xl/workbook.xml") isXlsx = true;
76
+ return false;
77
+ }
78
+ });
79
+ if (isDocx) return "docx";
80
+ if (isXlsx) return "xlsx";
81
+ return null;
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+ function mimeTypeForFormat(format2, fileName) {
87
+ const ext = extractExtension(fileName);
88
+ return TEXT_MIME_BY_EXT[ext] ?? "text/plain";
89
+ }
90
+ function detectFileFormat(bytes, fileName, mimeType) {
91
+ const ext = extractExtension(fileName);
92
+ const normalizedMime = mimeType?.split(";")[0]?.trim().toLowerCase() ?? "";
93
+ if (hasPdfHeader(bytes)) {
94
+ return { format: "pdf", mimeType: "application/pdf", extension: ".pdf" };
95
+ }
96
+ if (hasZipHeader(bytes)) {
97
+ const office = detectOfficeZipFormat(bytes);
98
+ if (office === "docx") {
99
+ return {
100
+ format: "docx",
101
+ mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
102
+ extension: ".docx"
103
+ };
104
+ }
105
+ if (office === "xlsx") {
106
+ return {
107
+ format: "xlsx",
108
+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
109
+ extension: ".xlsx"
110
+ };
111
+ }
112
+ return {
113
+ format: "binary",
114
+ mimeType: normalizedMime || "application/zip",
115
+ extension: ext || ".zip"
116
+ };
117
+ }
118
+ for (let i = 0; i < bytes.byteLength; i++) {
119
+ if (bytes[i] === 0) {
120
+ return {
121
+ format: "binary",
122
+ mimeType: normalizedMime || "application/octet-stream",
123
+ extension: ext
124
+ };
125
+ }
126
+ }
127
+ try {
128
+ UTF8_DECODER.decode(bytes);
129
+ return {
130
+ format: "text",
131
+ mimeType: normalizedMime && (normalizedMime.startsWith("text/") || normalizedMime.includes("json")) ? normalizedMime : mimeTypeForFormat("text", fileName),
132
+ extension: ext || ".txt"
133
+ };
134
+ } catch {
135
+ return {
136
+ format: "binary",
137
+ mimeType: normalizedMime || "application/octet-stream",
138
+ extension: ext
139
+ };
140
+ }
141
+ }
142
+ var MAX_ZIP_ENTRIES = 2e3;
143
+ var MAX_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
144
+ var UTF8_DECODER2 = new TextDecoder("utf-8", { fatal: false });
145
+ var UTF8_ENCODER = new TextEncoder();
146
+ function decodeUtf8(bytes) {
147
+ return UTF8_DECODER2.decode(bytes);
148
+ }
149
+ function encodeUtf8(text) {
150
+ return UTF8_ENCODER.encode(text);
151
+ }
152
+ function unzipSafely(bytes) {
153
+ let entryCount = 0;
154
+ let totalUncompressed = 0;
155
+ const files = unzipSync(bytes, {
156
+ filter(file) {
157
+ entryCount += 1;
158
+ if (entryCount > MAX_ZIP_ENTRIES) {
159
+ throw new Error(`Archive exceeds max allowed entry count (${MAX_ZIP_ENTRIES}).`);
160
+ }
161
+ totalUncompressed += file.originalSize;
162
+ if (totalUncompressed > MAX_ZIP_UNCOMPRESSED_BYTES) {
163
+ throw new Error(
164
+ `Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
165
+ );
166
+ }
167
+ return true;
168
+ }
169
+ });
170
+ let actualBytes = 0;
171
+ for (const data of Object.values(files)) {
172
+ actualBytes += data.byteLength;
173
+ if (actualBytes > MAX_ZIP_UNCOMPRESSED_BYTES) {
174
+ throw new Error(
175
+ `Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
176
+ );
177
+ }
178
+ }
179
+ return files;
180
+ }
181
+ function zipFiles(files) {
182
+ return zipSync(files, { level: 6 });
183
+ }
184
+ function unescapeXml(value) {
185
+ return value.replace(
186
+ /&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,
187
+ (match, entity) => {
188
+ if (entity === "amp") return "&";
189
+ if (entity === "lt") return "<";
190
+ if (entity === "gt") return ">";
191
+ if (entity === "quot") return '"';
192
+ if (entity === "apos") return "'";
193
+ if (entity.startsWith("#x") || entity.startsWith("#X")) {
194
+ const code = Number.parseInt(entity.slice(2), 16);
195
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
196
+ }
197
+ if (entity.startsWith("#")) {
198
+ const code = Number.parseInt(entity.slice(1), 10);
199
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
200
+ }
201
+ return match;
202
+ }
203
+ );
204
+ }
205
+ function escapeXml(value) {
206
+ let out = "";
207
+ for (let i = 0; i < value.length; i++) {
208
+ const ch = value[i] ?? "";
209
+ const code = value.charCodeAt(i);
210
+ if (code < 32 && code !== 9 && code !== 10 && code !== 13) continue;
211
+ if (ch === "&") out += "&amp;";
212
+ else if (ch === "<") out += "&lt;";
213
+ else if (ch === ">") out += "&gt;";
214
+ else if (ch === '"') out += "&quot;";
215
+ else if (ch === "'") out += "&apos;";
216
+ else out += ch;
217
+ }
218
+ return out;
219
+ }
220
+ function escapeRegexLiteral(value) {
221
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
222
+ }
223
+ function extractXmlTextContainers(xml, containerTag, textTags, options) {
224
+ const escapedContainer = escapeRegexLiteral(containerTag);
225
+ const containerRe = new RegExp(
226
+ `<${escapedContainer}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${escapedContainer}>`,
227
+ "g"
228
+ );
229
+ const sepTags = options?.separatorTags ?? {};
230
+ const sepTagNames = Object.keys(sepTags);
231
+ const allTagAlternation = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
232
+ const tokenRe = new RegExp(
233
+ `<(${allTagAlternation})(?:\\s[^>]*)?\\/>|<(${textTags.map(escapeRegexLiteral).join("|")})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\2>`,
234
+ "g"
235
+ );
236
+ const containers = [];
237
+ let containerMatch = containerRe.exec(xml);
238
+ while (containerMatch !== null) {
239
+ const inner = containerMatch[1] ?? "";
240
+ const openEndOffset = containerMatch.index + containerMatch[0].indexOf(">") + 1;
241
+ const nodes = [];
242
+ let combined = "";
243
+ tokenRe.lastIndex = 0;
244
+ let tok = tokenRe.exec(inner);
245
+ while (tok !== null) {
246
+ const selfClosingName = tok[1];
247
+ if (selfClosingName !== void 0) {
248
+ const sepChar = sepTags[selfClosingName];
249
+ if (sepChar) {
250
+ combined += sepChar;
251
+ }
252
+ tok = tokenRe.exec(inner);
253
+ continue;
254
+ }
255
+ const tagName = tok[2] ?? "";
256
+ const attrs = tok[3] ?? "";
257
+ const rawContent = tok[4] ?? "";
258
+ const openTag = `<${tagName}${attrs}>`;
259
+ const unescaped = unescapeXml(rawContent);
260
+ const tagStart = openEndOffset + tok.index;
261
+ const contentStart = tagStart + openTag.length;
262
+ const contentEnd = contentStart + rawContent.length;
263
+ const combinedStart = combined.length;
264
+ combined += unescaped;
265
+ const combinedEnd = combined.length;
266
+ nodes.push({
267
+ tagStart,
268
+ contentStart,
269
+ contentEnd,
270
+ openTag,
271
+ text: unescaped,
272
+ combinedStart,
273
+ combinedEnd
274
+ });
275
+ tok = tokenRe.exec(inner);
276
+ }
277
+ if (nodes.length > 0) {
278
+ containers.push({ text: combined, nodes });
279
+ }
280
+ containerMatch = containerRe.exec(xml);
281
+ }
282
+ return containers;
283
+ }
284
+ function ensurePreserveSpace(openTag, nextText) {
285
+ if (!nextText) return openTag;
286
+ const needsPreserve = /^\s|\s$/.test(nextText);
287
+ if (!needsPreserve || openTag.includes("xml:space=")) return openTag;
288
+ return `${openTag.slice(0, -1)} xml:space="preserve">`;
289
+ }
290
+ function applyXmlContainerReplacements(xml, containers, replacementsByContainer) {
291
+ const rawPatches = [];
292
+ for (const [containerIndex, spans] of replacementsByContainer.entries()) {
293
+ if (spans.length === 0) continue;
294
+ const container = containers[containerIndex];
295
+ if (!container) continue;
296
+ const sortedSpans = [...spans].sort((a, b) => a.start - b.start);
297
+ const nextNodeTexts = container.nodes.map((node) => node.text);
298
+ for (let s = sortedSpans.length - 1; s >= 0; s--) {
299
+ const span = sortedSpans[s];
300
+ if (!span || span.end <= span.start) continue;
301
+ let placedReplacement = false;
302
+ for (let n = 0; n < container.nodes.length; n++) {
303
+ const node = container.nodes[n];
304
+ if (!node) continue;
305
+ const overlapStart = Math.max(span.start, node.combinedStart);
306
+ const overlapEnd = Math.min(span.end, node.combinedEnd);
307
+ if (overlapEnd <= overlapStart) continue;
308
+ const localStart = overlapStart - node.combinedStart;
309
+ const localEnd = overlapEnd - node.combinedStart;
310
+ const current = nextNodeTexts[n] ?? "";
311
+ const insert = placedReplacement ? "" : span.replacement;
312
+ placedReplacement = true;
313
+ nextNodeTexts[n] = current.slice(0, localStart) + insert + current.slice(localEnd);
314
+ }
315
+ }
316
+ for (let n = 0; n < container.nodes.length; n++) {
317
+ const node = container.nodes[n];
318
+ const nextText = nextNodeTexts[n];
319
+ if (!node || nextText === void 0 || nextText === node.text) continue;
320
+ const nextOpenTag = ensurePreserveSpace(node.openTag, nextText);
321
+ rawPatches.push({
322
+ start: node.tagStart,
323
+ end: node.contentEnd,
324
+ replacement: `${nextOpenTag}${escapeXml(nextText)}`
325
+ });
326
+ }
327
+ }
328
+ if (rawPatches.length === 0) return xml;
329
+ rawPatches.sort((a, b) => b.start - a.start);
330
+ let out = xml;
331
+ for (const patch of rawPatches) {
332
+ out = out.slice(0, patch.start) + patch.replacement + out.slice(patch.end);
333
+ }
334
+ return out;
335
+ }
336
+ function scrubXmlMetadata(xml, tagNames) {
337
+ const found = {};
338
+ const cleared = [];
339
+ let nextXml = xml;
340
+ for (const tag of tagNames) {
341
+ const escaped = escapeRegexLiteral(tag);
342
+ const re = new RegExp(`(<${escaped}(?:\\s[^>]*)?>)([\\s\\S]*?)(<\\/${escaped}>)`, "g");
343
+ nextXml = nextXml.replace(re, (_match, open, inner, close) => {
344
+ const text = unescapeXml(inner).trim();
345
+ if (text.length > 0) {
346
+ found[tag] = text;
347
+ cleared.push(tag);
348
+ }
349
+ return `${open}${close}`;
350
+ });
351
+ }
352
+ return { xml: nextXml, found, cleared };
353
+ }
354
+ var CORE_META_TAGS = [
355
+ "dc:creator",
356
+ "cp:lastModifiedBy",
357
+ "dc:title",
358
+ "dc:subject",
359
+ "dc:description",
360
+ "cp:keywords"
361
+ ];
362
+ var APP_META_TAGS = ["Company", "Manager"];
363
+ var DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
364
+ var XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
365
+ var DOCX_TEXT_PART_RE = /^word\/(?:document|header\d+|footer\d+|footnotes|endnotes|comments)\.xml$/i;
366
+ var XLSX_SHEET_PART_RE = /^xl\/worksheets\/sheet\d+\.xml$/i;
367
+ var XLSX_COMMENT_PART_RE = /^xl\/comments\d*\.xml$/i;
368
+ function countRedactionsByLabel(redactions) {
369
+ const counts = {};
370
+ for (const r of redactions) {
371
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
372
+ }
373
+ return counts;
374
+ }
375
+ function scrubDocxReviewAuthors(xml) {
376
+ const stripped = [];
377
+ const next = xml.replace(
378
+ /(<w:(?:comment|ins|del|moveFrom|moveTo)\b[^>]*?\bw:author=")([^"]*)(")/g,
379
+ (_m, open, val, close) => {
380
+ const cleaned = unescapeXml(val).trim();
381
+ if (cleaned) stripped.push(cleaned);
382
+ return `${open}${close}`;
383
+ }
384
+ );
385
+ return { xml: next, stripped };
386
+ }
387
+ function scrubXlsxCommentAuthors(xml) {
388
+ const stripped = [];
389
+ const next = xml.replace(
390
+ /(<author(?:\s[^>]*)?>)([\s\S]*?)(<\/author>)/g,
391
+ (_m, open, inner, close) => {
392
+ const cleaned = unescapeXml(inner).trim();
393
+ if (cleaned) stripped.push(cleaned);
394
+ return `${open}${close}`;
395
+ }
396
+ );
397
+ return { xml: next, stripped };
398
+ }
399
+ async function redactRelsTargets(archive, redactFn) {
400
+ const cleared = [];
401
+ const originalValues = [];
402
+ for (const [entryName, raw] of Object.entries(archive)) {
403
+ if (!entryName.toLowerCase().endsWith(".rels")) continue;
404
+ const xml = decodeUtf8(raw);
405
+ const relRe = /<Relationship\b[^>]*>/g;
406
+ const patches = [];
407
+ let relMatch = relRe.exec(xml);
408
+ while (relMatch !== null) {
409
+ const tag = relMatch[0];
410
+ const targetMatch = /\bTarget="([^"]*)"/.exec(tag);
411
+ if (targetMatch?.[1]) {
412
+ const rawTarget = unescapeXml(targetMatch[1]);
413
+ const isExternal = /\bTargetMode="External"/i.test(tag) || /^(?:mailto:|tel:|https?:)/i.test(rawTarget);
414
+ if (isExternal) {
415
+ const res = await redactFn(rawTarget);
416
+ if (res.redactions.length > 0) {
417
+ for (const r of res.redactions) originalValues.push(r.value);
418
+ const nextTag = tag.replace(/\bTarget="([^"]*)"/, `Target="${escapeXml(res.text)}"`);
419
+ patches.push({
420
+ start: relMatch.index,
421
+ end: relMatch.index + tag.length,
422
+ replacement: nextTag
423
+ });
424
+ }
425
+ }
426
+ }
427
+ relMatch = relRe.exec(xml);
428
+ }
429
+ if (patches.length > 0) {
430
+ let nextXml = xml;
431
+ for (let i = patches.length - 1; i >= 0; i--) {
432
+ const p = patches[i];
433
+ if (!p) continue;
434
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
435
+ }
436
+ archive[entryName] = encodeUtf8(nextXml);
437
+ cleared.push(`${entryName}:Target`);
438
+ }
439
+ }
440
+ return { cleared, originalValues };
441
+ }
442
+ async function redactDocxInstrText(xml, redactFn) {
443
+ const originalValues = [];
444
+ const instrRe = /(<w:instrText(?:\s[^>]*)?>)([\s\S]*?)(<\/w:instrText>)/g;
445
+ const patches = [];
446
+ let m = instrRe.exec(xml);
447
+ while (m !== null) {
448
+ const open = m[1] ?? "";
449
+ const rawInner = m[2] ?? "";
450
+ const close = m[3] ?? "";
451
+ const text = unescapeXml(rawInner);
452
+ if (text.trim().length > 0) {
453
+ const res = await redactFn(text);
454
+ if (res.redactions.length > 0) {
455
+ for (const r of res.redactions) originalValues.push(r.value);
456
+ patches.push({
457
+ start: m.index,
458
+ end: m.index + m[0].length,
459
+ replacement: `${open}${escapeXml(res.text)}${close}`
460
+ });
461
+ }
462
+ }
463
+ m = instrRe.exec(xml);
464
+ }
465
+ if (patches.length === 0) return { xml, originalValues };
466
+ let out = xml;
467
+ for (let i = patches.length - 1; i >= 0; i--) {
468
+ const p = patches[i];
469
+ if (!p) continue;
470
+ out = out.slice(0, p.start) + p.replacement + out.slice(p.end);
471
+ }
472
+ return { xml: out, originalValues };
473
+ }
474
+ function sanitizeExcelSheetName(raw, usedNames) {
475
+ let cleaned = raw.replace(/[\\/?*[\]:]/g, "").replace(/\s+/g, " ").trim();
476
+ if (!cleaned) cleaned = "Sheet";
477
+ if (cleaned.length > 31) cleaned = cleaned.slice(0, 31).trim();
478
+ let candidate = cleaned;
479
+ let suffix = 2;
480
+ while (usedNames.has(candidate.toLowerCase())) {
481
+ const tag = `_${suffix}`;
482
+ candidate = `${cleaned.slice(0, Math.max(1, 31 - tag.length))}${tag}`;
483
+ suffix += 1;
484
+ }
485
+ usedNames.add(candidate.toLowerCase());
486
+ return candidate;
487
+ }
488
+ async function redactXlsxWorkbookSheetNames(archive, redactFn) {
489
+ const wbKey = Object.keys(archive).find((k) => k.toLowerCase() === "xl/workbook.xml");
490
+ if (!wbKey || !archive[wbKey]) return { cleared: [], originalValues: [] };
491
+ const xml = decodeUtf8(archive[wbKey]);
492
+ const sheetRe = /<sheet\b[^>]*>/g;
493
+ const usedNames = /* @__PURE__ */ new Set();
494
+ const patches = [];
495
+ const originalValues = [];
496
+ let m = sheetRe.exec(xml);
497
+ while (m !== null) {
498
+ const tag = m[0];
499
+ const nameMatch = /\bname="([^"]*)"/.exec(tag);
500
+ if (nameMatch?.[1]) {
501
+ const sheetName = unescapeXml(nameMatch[1]);
502
+ const res = await redactFn(sheetName);
503
+ if (res.redactions.length > 0) {
504
+ for (const r of res.redactions) originalValues.push(r.value);
505
+ const safeName = sanitizeExcelSheetName(res.text, usedNames);
506
+ const nextTag = tag.replace(/\bname="([^"]*)"/, `name="${escapeXml(safeName)}"`);
507
+ patches.push({
508
+ start: m.index,
509
+ end: m.index + tag.length,
510
+ replacement: nextTag
511
+ });
512
+ } else {
513
+ usedNames.add(sheetName.toLowerCase());
514
+ }
515
+ }
516
+ m = sheetRe.exec(xml);
517
+ }
518
+ if (patches.length === 0) return { cleared: [], originalValues: [] };
519
+ let nextXml = xml;
520
+ for (let i = patches.length - 1; i >= 0; i--) {
521
+ const p = patches[i];
522
+ if (!p) continue;
523
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
524
+ }
525
+ archive[wbKey] = encodeUtf8(nextXml);
526
+ return { cleared: [`${wbKey}:sheetName`], originalValues };
527
+ }
528
+ function listDocxTextParts(entryNames) {
529
+ return entryNames.filter((name) => DOCX_TEXT_PART_RE.test(name)).sort((a, b) => {
530
+ if (a.toLowerCase() === "word/document.xml") return -1;
531
+ if (b.toLowerCase() === "word/document.xml") return 1;
532
+ return a.localeCompare(b);
533
+ });
534
+ }
535
+ function listXlsxParts(entryNames) {
536
+ const sharedStrings = entryNames.find((n) => n.toLowerCase() === "xl/sharedstrings.xml");
537
+ const sheets = entryNames.filter((n) => XLSX_SHEET_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
538
+ const comments = entryNames.filter((n) => XLSX_COMMENT_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
539
+ return { sharedStrings, sheets, comments };
540
+ }
541
+ function extractOfficeMetadata(archive) {
542
+ const metadata = {};
543
+ const cleared = [];
544
+ const updatedArchive = { ...archive };
545
+ const coreKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/core.xml");
546
+ if (coreKey && archive[coreKey]) {
547
+ const res = scrubXmlMetadata(decodeUtf8(archive[coreKey]), CORE_META_TAGS);
548
+ Object.assign(metadata, res.found);
549
+ cleared.push(...res.cleared);
550
+ updatedArchive[coreKey] = encodeUtf8(res.xml);
551
+ }
552
+ const appKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/app.xml");
553
+ if (appKey && archive[appKey]) {
554
+ const res = scrubXmlMetadata(decodeUtf8(archive[appKey]), APP_META_TAGS);
555
+ Object.assign(metadata, res.found);
556
+ cleared.push(...res.cleared);
557
+ updatedArchive[appKey] = encodeUtf8(res.xml);
558
+ }
559
+ return { metadata, cleared, updatedArchive };
560
+ }
561
+ function mapRedactionsToPartContainers(parts, redactions) {
562
+ const byPart = /* @__PURE__ */ new Map();
563
+ for (const r of redactions) {
564
+ for (const part of parts) {
565
+ let partMap = byPart.get(part.partPath);
566
+ for (let i = 0; i < part.containerOffsets.length; i++) {
567
+ const range = part.containerOffsets[i];
568
+ if (!range) continue;
569
+ if (r.end <= range.start || r.start >= range.end) continue;
570
+ const localStart = Math.max(0, r.start - range.start);
571
+ const localEnd = Math.min(range.end - range.start, r.end - range.start);
572
+ if (localEnd <= localStart) continue;
573
+ if (!partMap) {
574
+ partMap = /* @__PURE__ */ new Map();
575
+ byPart.set(part.partPath, partMap);
576
+ }
577
+ const list = partMap.get(i) ?? [];
578
+ list.push({ start: localStart, end: localEnd, replacement: r.replacement });
579
+ partMap.set(i, list);
580
+ }
581
+ }
582
+ }
583
+ return byPart;
584
+ }
585
+ function extractDocx(bytes) {
586
+ const archive = unzipSafely(bytes);
587
+ const parts = listDocxTextParts(Object.keys(archive));
588
+ const sections = [];
589
+ for (const partPath of parts) {
590
+ const raw = archive[partPath];
591
+ if (!raw) continue;
592
+ const xml = decodeUtf8(raw);
593
+ const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
594
+ separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
595
+ });
596
+ const partText = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
597
+ if (partText.length > 0) {
598
+ sections.push({
599
+ id: partPath,
600
+ label: partPath.replace(/^word\//i, "").replace(/\.xml$/i, ""),
601
+ text: partText
602
+ });
603
+ }
604
+ }
605
+ const { metadata } = extractOfficeMetadata(archive);
606
+ const fullText = sections.map((s) => s.text).join("\n\n");
607
+ return {
608
+ format: "docx",
609
+ mimeType: DOCX_MIME,
610
+ text: fullText,
611
+ sections,
612
+ metadata,
613
+ warnings: [],
614
+ scannedPages: []
615
+ };
616
+ }
617
+ async function redactDocx(bytes, redactFn) {
618
+ const archive = unzipSafely(bytes);
619
+ const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
620
+ const metadataValues = Object.values(metadata);
621
+ const partPaths = listDocxTextParts(Object.keys(updatedArchive));
622
+ const parts = [];
623
+ const textChunks = [];
624
+ let cursor = 0;
625
+ for (const partPath of partPaths) {
626
+ const raw = updatedArchive[partPath];
627
+ if (!raw) continue;
628
+ const rawXml = decodeUtf8(raw);
629
+ const { xml, stripped } = scrubDocxReviewAuthors(rawXml);
630
+ if (stripped.length > 0) {
631
+ metadataCleared.push(`${partPath}:w:author`);
632
+ metadataValues.push(...stripped);
633
+ }
634
+ const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
635
+ separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
636
+ });
637
+ const containerOffsets = [];
638
+ for (const container of containers) {
639
+ if (container.text.length === 0) {
640
+ containerOffsets.push({ start: cursor, end: cursor });
641
+ continue;
642
+ }
643
+ if (textChunks.length > 0) {
644
+ textChunks.push("\n\n");
645
+ cursor += 2;
646
+ }
647
+ const start = cursor;
648
+ textChunks.push(container.text);
649
+ cursor += container.text.length;
650
+ containerOffsets.push({ start, end: cursor });
651
+ }
652
+ parts.push({ partPath, xml, containers, containerOffsets });
653
+ }
654
+ const combinedText = textChunks.join("");
655
+ const result = await redactFn(combinedText);
656
+ const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
657
+ for (const part of parts) {
658
+ const partMap = replacementsByPart.get(part.partPath);
659
+ let nextXml = partMap ? applyXmlContainerReplacements(part.xml, part.containers, partMap) : part.xml;
660
+ const instr = await redactDocxInstrText(nextXml, redactFn);
661
+ if (instr.originalValues.length > 0) {
662
+ nextXml = instr.xml;
663
+ metadataCleared.push(`${part.partPath}:w:instrText`);
664
+ metadataValues.push(...instr.originalValues);
665
+ }
666
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
667
+ }
668
+ const relsRes = await redactRelsTargets(updatedArchive, redactFn);
669
+ metadataCleared.push(...relsRes.cleared);
670
+ metadataValues.push(...relsRes.originalValues);
671
+ return {
672
+ bytes: zipFiles(updatedArchive),
673
+ extractedText: combinedText,
674
+ redactedText: result.text,
675
+ totalRedactions: result.redactions.length,
676
+ counts: countRedactionsByLabel(result.redactions),
677
+ redactions: result.redactions,
678
+ map: result.map,
679
+ metadataCleared,
680
+ metadataValues,
681
+ warnings: []
682
+ };
683
+ }
684
+ function extractXlsxCachedFormulaStrings(xml) {
685
+ const out = [];
686
+ const cellRe = /<c\b[^>]*\bt="str"[^>]*>([\s\S]*?)<\/c>/g;
687
+ let m = cellRe.exec(xml);
688
+ while (m !== null) {
689
+ const inner = m[1] ?? "";
690
+ const vMatch = /<v(?:\s[^>]*)?>([\s\S]*?)<\/v>/.exec(inner);
691
+ if (vMatch) {
692
+ const openEnd = m.index + m[0].indexOf(">") + 1;
693
+ const vOpenEnd = vMatch.index + vMatch[0].indexOf(">") + 1;
694
+ const rawContent = vMatch[1] ?? "";
695
+ const contentStart = openEnd + vOpenEnd;
696
+ const contentEnd = contentStart + rawContent.length;
697
+ out.push({ contentStart, contentEnd, text: unescapeXml(rawContent) });
698
+ }
699
+ m = cellRe.exec(xml);
700
+ }
701
+ return out;
702
+ }
703
+ function extractXlsx(bytes) {
704
+ const archive = unzipSafely(bytes);
705
+ const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(archive));
706
+ const sections = [];
707
+ if (sharedStrings && archive[sharedStrings]) {
708
+ const xml = decodeUtf8(archive[sharedStrings]);
709
+ const containers = extractXmlTextContainers(xml, "si", ["t"]);
710
+ const text = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
711
+ if (text) {
712
+ sections.push({ id: sharedStrings, label: "sharedStrings", text });
713
+ }
714
+ }
715
+ for (const sheetPath of sheets) {
716
+ const raw = archive[sheetPath];
717
+ if (!raw) continue;
718
+ const xml = decodeUtf8(raw);
719
+ const inlineContainers = extractXmlTextContainers(xml, "is", ["t"]);
720
+ const formulaStrings = extractXlsxCachedFormulaStrings(xml);
721
+ const lines = [
722
+ ...inlineContainers.map((c) => c.text),
723
+ ...formulaStrings.map((f) => f.text)
724
+ ].filter((t) => t.length > 0);
725
+ if (lines.length > 0) {
726
+ sections.push({
727
+ id: sheetPath,
728
+ label: sheetPath.replace(/^xl\/worksheets\//i, "").replace(/\.xml$/i, ""),
729
+ text: lines.join("\n\n")
730
+ });
731
+ }
732
+ }
733
+ for (const commentPath of comments) {
734
+ const raw = archive[commentPath];
735
+ if (!raw) continue;
736
+ const xml = decodeUtf8(raw);
737
+ const commentContainers = extractXmlTextContainers(xml, "text", ["t"]);
738
+ const lines = commentContainers.map((c) => c.text).filter((t) => t.length > 0);
739
+ if (lines.length > 0) {
740
+ sections.push({
741
+ id: commentPath,
742
+ label: commentPath.replace(/^xl\//i, "").replace(/\.xml$/i, ""),
743
+ text: lines.join("\n\n")
744
+ });
745
+ }
746
+ }
747
+ const { metadata } = extractOfficeMetadata(archive);
748
+ return {
749
+ format: "xlsx",
750
+ mimeType: XLSX_MIME,
751
+ text: sections.map((s) => s.text).join("\n\n"),
752
+ sections,
753
+ metadata,
754
+ warnings: [],
755
+ scannedPages: []
756
+ };
757
+ }
758
+ async function redactXlsx(bytes, redactFn) {
759
+ const archive = unzipSafely(bytes);
760
+ const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
761
+ const metadataValues = Object.values(metadata);
762
+ const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(updatedArchive));
763
+ const parts = [];
764
+ const formulaRecords = [];
765
+ const textChunks = [];
766
+ let cursor = 0;
767
+ const addPart = (partPath, xml, containerTag) => {
768
+ const containers = extractXmlTextContainers(xml, containerTag, ["t"]);
769
+ const containerOffsets = [];
770
+ for (const container of containers) {
771
+ if (container.text.length === 0) {
772
+ containerOffsets.push({ start: cursor, end: cursor });
773
+ continue;
774
+ }
775
+ if (textChunks.length > 0) {
776
+ textChunks.push("\n\n");
777
+ cursor += 2;
778
+ }
779
+ const start = cursor;
780
+ textChunks.push(container.text);
781
+ cursor += container.text.length;
782
+ containerOffsets.push({ start, end: cursor });
783
+ }
784
+ parts.push({ partPath, xml, containers, containerOffsets });
785
+ };
786
+ if (sharedStrings && updatedArchive[sharedStrings]) {
787
+ addPart(sharedStrings, decodeUtf8(updatedArchive[sharedStrings]), "si");
788
+ }
789
+ for (const sheetPath of sheets) {
790
+ const raw = updatedArchive[sheetPath];
791
+ if (!raw) continue;
792
+ const xml = decodeUtf8(raw);
793
+ addPart(sheetPath, xml, "is");
794
+ const formulas = extractXlsxCachedFormulaStrings(xml);
795
+ if (formulas.length > 0) {
796
+ const entries = [];
797
+ for (const f of formulas) {
798
+ if (textChunks.length > 0) {
799
+ textChunks.push("\n\n");
800
+ cursor += 2;
801
+ }
802
+ const start = cursor;
803
+ textChunks.push(f.text);
804
+ cursor += f.text.length;
805
+ entries.push({
806
+ contentStart: f.contentStart,
807
+ contentEnd: f.contentEnd,
808
+ start,
809
+ end: cursor
810
+ });
811
+ }
812
+ formulaRecords.push({ partPath: sheetPath, entries });
813
+ }
814
+ }
815
+ for (const commentPath of comments) {
816
+ const raw = updatedArchive[commentPath];
817
+ if (!raw) continue;
818
+ const { xml, stripped } = scrubXlsxCommentAuthors(decodeUtf8(raw));
819
+ if (stripped.length > 0) {
820
+ metadataCleared.push(`${commentPath}:author`);
821
+ metadataValues.push(...stripped);
822
+ }
823
+ addPart(commentPath, xml, "text");
824
+ }
825
+ const combinedText = textChunks.join("");
826
+ const result = await redactFn(combinedText);
827
+ const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
828
+ const formulaByPart = new Map(formulaRecords.map((f) => [f.partPath, f.entries]));
829
+ for (const part of parts) {
830
+ let nextXml = part.xml;
831
+ const formulaEntries = formulaByPart.get(part.partPath);
832
+ if (formulaEntries && formulaEntries.length > 0) {
833
+ const rawPatches = [];
834
+ for (const entry of formulaEntries) {
835
+ const overlapping = result.redactions.filter(
836
+ (r) => r.end > entry.start && r.start < entry.end
837
+ );
838
+ if (overlapping.length === 0) continue;
839
+ let text = combinedText.slice(entry.start, entry.end);
840
+ for (let i = overlapping.length - 1; i >= 0; i--) {
841
+ const r = overlapping[i];
842
+ if (!r) continue;
843
+ const localStart = Math.max(0, r.start - entry.start);
844
+ const localEnd = Math.min(text.length, r.end - entry.start);
845
+ text = text.slice(0, localStart) + r.replacement + text.slice(localEnd);
846
+ }
847
+ rawPatches.push({
848
+ start: entry.contentStart,
849
+ end: entry.contentEnd,
850
+ replacement: escapeXml(text)
851
+ });
852
+ }
853
+ if (rawPatches.length > 0) {
854
+ rawPatches.sort((a, b) => b.start - a.start);
855
+ for (const p of rawPatches) {
856
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
857
+ }
858
+ const partMap2 = replacementsByPart.get(part.partPath);
859
+ if (partMap2 && partMap2.size > 0) {
860
+ const freshContainers = extractXmlTextContainers(nextXml, "is", ["t"]);
861
+ nextXml = applyXmlContainerReplacements(nextXml, freshContainers, partMap2);
862
+ }
863
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
864
+ continue;
865
+ }
866
+ }
867
+ const partMap = replacementsByPart.get(part.partPath);
868
+ if (partMap) {
869
+ nextXml = applyXmlContainerReplacements(nextXml, part.containers, partMap);
870
+ }
871
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
872
+ }
873
+ const wbRes = await redactXlsxWorkbookSheetNames(updatedArchive, redactFn);
874
+ metadataCleared.push(...wbRes.cleared);
875
+ metadataValues.push(...wbRes.originalValues);
876
+ const relsRes = await redactRelsTargets(updatedArchive, redactFn);
877
+ metadataCleared.push(...relsRes.cleared);
878
+ metadataValues.push(...relsRes.originalValues);
879
+ return {
880
+ bytes: zipFiles(updatedArchive),
881
+ extractedText: combinedText,
882
+ redactedText: result.text,
883
+ totalRedactions: result.redactions.length,
884
+ counts: countRedactionsByLabel(result.redactions),
885
+ redactions: result.redactions,
886
+ map: result.map,
887
+ metadataCleared,
888
+ metadataValues,
889
+ warnings: []
890
+ };
891
+ }
892
+ var configuredWorkerSrc;
893
+ var cachedPdfjsPromise = null;
894
+ async function loadPdfjs(workerSrcOverride) {
895
+ if (!cachedPdfjsPromise) {
896
+ cachedPdfjsPromise = import('pdfjs-dist/legacy/build/pdf.mjs');
897
+ }
898
+ const pdfjs = await cachedPdfjsPromise;
899
+ const workerSrc = workerSrcOverride ?? configuredWorkerSrc;
900
+ if (workerSrc && pdfjs.GlobalWorkerOptions.workerSrc !== workerSrc) {
901
+ pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
902
+ }
903
+ return pdfjs;
904
+ }
905
+ function isPdfTextItem(item) {
906
+ if (!item || typeof item !== "object") return false;
907
+ const rec = item;
908
+ return typeof rec.str === "string" && Array.isArray(rec.transform) && rec.transform.length >= 6;
909
+ }
910
+ function computeItemBounds(item) {
911
+ const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = item.transform;
912
+ const scaleX = Math.hypot(a, b);
913
+ const scaleY = Math.hypot(c, d);
914
+ const fontHeight = Math.max(scaleY, scaleX, item.height || 0, 6);
915
+ const width = typeof item.width === "number" && item.width > 0 ? item.width : fontHeight * 0.55 * Math.max(1, item.str.length);
916
+ const isHorizontal = Math.abs(b) < 0.05 && Math.abs(c) < 0.05;
917
+ if (isHorizontal) {
918
+ return {
919
+ x1: e,
920
+ y1: f - fontHeight * 0.3,
921
+ x2: e + width,
922
+ y2: f + fontHeight * 1.08,
923
+ fontHeight,
924
+ isHorizontal: true
925
+ };
926
+ }
927
+ const lenX = scaleX || 1;
928
+ const ux = a / lenX;
929
+ const uy = b / lenX;
930
+ const lenY = scaleY || 1;
931
+ const vx = c / lenY;
932
+ const vy = d / lenY;
933
+ const asc = fontHeight * 1.08;
934
+ const desc = -fontHeight * 0.3;
935
+ const corners = [
936
+ [e + vx * desc, f + vy * desc],
937
+ [e + ux * width + vx * desc, f + uy * width + vy * desc],
938
+ [e + vx * asc, f + vy * asc],
939
+ [e + ux * width + vx * asc, f + uy * width + vy * asc]
940
+ ];
941
+ let x1 = Number.POSITIVE_INFINITY;
942
+ let y1 = Number.POSITIVE_INFINITY;
943
+ let x2 = Number.NEGATIVE_INFINITY;
944
+ let y2 = Number.NEGATIVE_INFINITY;
945
+ for (const [cx, cy] of corners) {
946
+ if (cx < x1) x1 = cx;
947
+ if (cy < y1) y1 = cy;
948
+ if (cx > x2) x2 = cx;
949
+ if (cy > y2) y2 = cy;
950
+ }
951
+ return { x1, y1, x2, y2, fontHeight, isHorizontal: false };
952
+ }
953
+ function buildPageTextAndMap(rawItems, styles) {
954
+ const items = [];
955
+ let text = "";
956
+ let prevBaselineY = null;
957
+ let prevRightX = 0;
958
+ let prevHadEol = false;
959
+ for (const raw of rawItems) {
960
+ if (!isPdfTextItem(raw)) continue;
961
+ if (raw.str.length === 0) {
962
+ if (raw.hasEOL) prevHadEol = true;
963
+ continue;
964
+ }
965
+ const bounds = computeItemBounds(raw);
966
+ const baselineY = raw.transform[5] ?? 0;
967
+ const leftX = raw.transform[4] ?? 0;
968
+ const style = raw.fontName ? styles?.[raw.fontName] : void 0;
969
+ const fontFamily = style?.fontFamily || "sans-serif";
970
+ if (text.length > 0) {
971
+ const lineChanged = prevHadEol || prevBaselineY !== null && Math.abs(baselineY - prevBaselineY) > bounds.fontHeight * 0.6;
972
+ if (lineChanged) {
973
+ if (!text.endsWith("\n")) text += "\n";
974
+ } else {
975
+ const gap = leftX - prevRightX;
976
+ const needsSpace = gap > bounds.fontHeight * 0.16 && !/\s$/.test(text) && !/^\s/.test(raw.str);
977
+ if (needsSpace) text += " ";
978
+ }
979
+ }
980
+ const start = text.length;
981
+ text += raw.str;
982
+ const end = text.length;
983
+ const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = raw.transform;
984
+ const itemWidth = typeof raw.width === "number" && raw.width > 0 ? raw.width : bounds.fontHeight * 0.55 * Math.max(1, raw.str.length);
985
+ items.push({
986
+ str: raw.str,
987
+ start,
988
+ end,
989
+ x1: bounds.x1,
990
+ y1: bounds.y1,
991
+ x2: bounds.x2,
992
+ y2: bounds.y2,
993
+ fontHeight: bounds.fontHeight,
994
+ fontFamily,
995
+ width: itemWidth,
996
+ transform: [a, b, c, d, e, f],
997
+ isHorizontal: bounds.isHorizontal
998
+ });
999
+ prevBaselineY = baselineY;
1000
+ prevRightX = bounds.x2;
1001
+ prevHadEol = raw.hasEOL === true;
1002
+ }
1003
+ return { text, items };
1004
+ }
1005
+ function extractAnnotationTexts(annotations) {
1006
+ const out = [];
1007
+ for (const raw of annotations) {
1008
+ if (!raw || typeof raw !== "object") continue;
1009
+ const rec = raw;
1010
+ const snippets = [];
1011
+ if (typeof rec.url === "string" && rec.url.trim()) {
1012
+ snippets.push(rec.url.trim());
1013
+ }
1014
+ if (typeof rec.fieldValue === "string" && rec.fieldValue.trim()) {
1015
+ snippets.push(rec.fieldValue.trim());
1016
+ } else if (Array.isArray(rec.fieldValue)) {
1017
+ for (const v of rec.fieldValue) {
1018
+ if (typeof v === "string" && v.trim()) snippets.push(v.trim());
1019
+ }
1020
+ }
1021
+ if (rec.contentsObj && typeof rec.contentsObj === "object") {
1022
+ const str = rec.contentsObj.str;
1023
+ if (typeof str === "string" && str.trim()) snippets.push(str.trim());
1024
+ }
1025
+ if (typeof rec.titleObj === "object" && rec.titleObj !== null) {
1026
+ const str = rec.titleObj.str;
1027
+ if (typeof str === "string" && str.trim()) snippets.push(str.trim());
1028
+ }
1029
+ if (typeof rec.alternativeText === "string" && rec.alternativeText.trim()) {
1030
+ snippets.push(rec.alternativeText.trim());
1031
+ }
1032
+ if (snippets.length === 0) continue;
1033
+ let rect;
1034
+ if (Array.isArray(rec.rect) && rec.rect.length === 4 && rec.rect.every((n) => typeof n === "number" && Number.isFinite(n))) {
1035
+ rect = [rec.rect[0], rec.rect[1], rec.rect[2], rec.rect[3]];
1036
+ }
1037
+ out.push({ text: snippets.join(" "), rect });
1038
+ }
1039
+ return out;
1040
+ }
1041
+ function collectPdfMetadataStrings(meta) {
1042
+ const out = {};
1043
+ const sensitiveInfoKeys = [
1044
+ "Title",
1045
+ "Author",
1046
+ "Subject",
1047
+ "Keywords",
1048
+ "Creator",
1049
+ "Producer"
1050
+ ];
1051
+ if (meta.info && typeof meta.info === "object") {
1052
+ const info = meta.info;
1053
+ for (const key of sensitiveInfoKeys) {
1054
+ const value = info[key];
1055
+ if (typeof value === "string" && value.trim()) {
1056
+ out[key] = value.trim();
1057
+ }
1058
+ }
1059
+ }
1060
+ return out;
1061
+ }
1062
+ async function resolveDefaultCanvasProvider() {
1063
+ if (typeof document !== "undefined" && typeof document.createElement === "function") {
1064
+ return {
1065
+ createCanvas(width, height) {
1066
+ const canvas = document.createElement("canvas");
1067
+ canvas.width = width;
1068
+ canvas.height = height;
1069
+ return canvas;
1070
+ },
1071
+ async toPngBytes(canvas) {
1072
+ const htmlCanvas = canvas;
1073
+ const blob = await new Promise((resolve5, reject) => {
1074
+ htmlCanvas.toBlob((b) => {
1075
+ if (b) resolve5(b);
1076
+ else reject(new Error("Failed to encode PDF page canvas to PNG."));
1077
+ }, "image/png");
1078
+ });
1079
+ return new Uint8Array(await blob.arrayBuffer());
1080
+ }
1081
+ };
1082
+ }
1083
+ if (typeof OffscreenCanvas !== "undefined") {
1084
+ return {
1085
+ createCanvas(width, height) {
1086
+ return new OffscreenCanvas(width, height);
1087
+ },
1088
+ async toPngBytes(canvas) {
1089
+ const off = canvas;
1090
+ const blob = await off.convertToBlob({ type: "image/png" });
1091
+ return new Uint8Array(await blob.arrayBuffer());
1092
+ }
1093
+ };
1094
+ }
1095
+ const canvasPkg = "@napi-rs/canvas";
1096
+ const mod = await import(
1097
+ /* @vite-ignore */
1098
+ canvasPkg
1099
+ );
1100
+ return {
1101
+ createCanvas(width, height) {
1102
+ return mod.createCanvas(width, height);
1103
+ },
1104
+ toPngBytes(canvas) {
1105
+ const napiCanvas = canvas;
1106
+ return new Uint8Array(napiCanvas.toBuffer("image/png"));
1107
+ }
1108
+ };
1109
+ }
1110
+ function mergeLineBoxes(boxes) {
1111
+ if (boxes.length <= 1) return [...boxes];
1112
+ const sorted = [...boxes].sort((a, b) => {
1113
+ const cyA = (a.y1 + a.y2) / 2;
1114
+ const cyB = (b.y1 + b.y2) / 2;
1115
+ if (Math.abs(cyA - cyB) > Math.min(a.y2 - a.y1, b.y2 - b.y1) * 0.5) {
1116
+ return cyB - cyA;
1117
+ }
1118
+ return a.x1 - b.x1;
1119
+ });
1120
+ const merged = [];
1121
+ for (const box of sorted) {
1122
+ const prev = merged[merged.length - 1];
1123
+ if (prev && prev.replacement === box.replacement) {
1124
+ const hPrev = prev.y2 - prev.y1;
1125
+ const hCur = box.y2 - box.y1;
1126
+ const yOverlap = Math.min(prev.y2, box.y2) - Math.max(prev.y1, box.y1);
1127
+ const minH = Math.min(hPrev, hCur);
1128
+ const xGap = box.x1 - prev.x2;
1129
+ if (minH > 0 && yOverlap > minH * 0.45 && xGap <= Math.max(hPrev, hCur) * 1.5) {
1130
+ prev.x1 = Math.min(prev.x1, box.x1);
1131
+ prev.y1 = Math.min(prev.y1, box.y1);
1132
+ prev.x2 = Math.max(prev.x2, box.x2);
1133
+ prev.y2 = Math.max(prev.y2, box.y2);
1134
+ continue;
1135
+ }
1136
+ }
1137
+ merged.push({ ...box });
1138
+ }
1139
+ return merged;
1140
+ }
1141
+ function measureSubspanFractions(ctx, str, localStart, localEnd, fontFamily) {
1142
+ const len = Math.max(1, str.length);
1143
+ if (localStart <= 0 && localEnd >= len) {
1144
+ return { startFrac: 0, endFrac: 1 };
1145
+ }
1146
+ const isMonospace = /\bmono/i.test(fontFamily);
1147
+ if (isMonospace || !ctx?.measureText) {
1148
+ return { startFrac: localStart / len, endFrac: localEnd / len };
1149
+ }
1150
+ const prefix = str.slice(0, localStart);
1151
+ const uptoEnd = str.slice(0, localEnd);
1152
+ const families = /* @__PURE__ */ new Set([
1153
+ fontFamily,
1154
+ "Helvetica, Arial, sans-serif",
1155
+ "Times New Roman, Times, serif"
1156
+ ]);
1157
+ let minStart = 1;
1158
+ let maxEnd = 0;
1159
+ let measuredAny = false;
1160
+ ctx.save();
1161
+ for (const family of families) {
1162
+ ctx.font = `100px ${family}`;
1163
+ const fullW = ctx.measureText(str).width;
1164
+ if (!(fullW > 0)) continue;
1165
+ const startW = localStart > 0 ? ctx.measureText(prefix).width : 0;
1166
+ const endW = localEnd < len ? ctx.measureText(uptoEnd).width : fullW;
1167
+ minStart = Math.min(minStart, Math.max(0, startW / fullW));
1168
+ maxEnd = Math.max(maxEnd, Math.min(1, endW / fullW));
1169
+ measuredAny = true;
1170
+ }
1171
+ ctx.restore();
1172
+ if (!measuredAny || maxEnd <= minStart) {
1173
+ return { startFrac: localStart / len, endFrac: localEnd / len };
1174
+ }
1175
+ return { startFrac: minStart, endFrac: maxEnd };
1176
+ }
1177
+ function computePageRedactionBoxes(items, pageRedactions, ctx) {
1178
+ const boxes = [];
1179
+ for (const r of pageRedactions) {
1180
+ const rawForSpan = [];
1181
+ for (const item of items) {
1182
+ if (item.end <= r.start || item.start >= r.end) continue;
1183
+ const len = Math.max(1, item.str.length);
1184
+ const localStart = Math.max(0, r.start - item.start);
1185
+ const localEnd = Math.min(len, r.end - item.start);
1186
+ const padX = Math.max(3, item.fontHeight * 0.25);
1187
+ const padY = Math.max(1.5, item.fontHeight * 0.12);
1188
+ const { startFrac, endFrac } = measureSubspanFractions(
1189
+ ctx,
1190
+ item.str,
1191
+ localStart,
1192
+ localEnd,
1193
+ item.fontFamily
1194
+ );
1195
+ if (item.isHorizontal) {
1196
+ const spanWidth = item.x2 - item.x1;
1197
+ const subX1 = item.x1 + startFrac * spanWidth;
1198
+ const subX2 = item.x1 + endFrac * spanWidth;
1199
+ rawForSpan.push({
1200
+ x1: subX1 - padX,
1201
+ y1: item.y1 - padY,
1202
+ x2: subX2 + padX,
1203
+ y2: item.y2 + padY,
1204
+ replacement: r.replacement
1205
+ });
1206
+ } else {
1207
+ const [a, b, c, d, e, f] = item.transform;
1208
+ const scaleX = Math.hypot(a, b) || 1;
1209
+ const scaleY = Math.hypot(c, d) || 1;
1210
+ const ux = a / scaleX;
1211
+ const uy = b / scaleX;
1212
+ const vx = c / scaleY;
1213
+ const vy = d / scaleY;
1214
+ const d1 = startFrac * item.width;
1215
+ const d2 = endFrac * item.width;
1216
+ const asc = item.fontHeight * 1.12;
1217
+ const desc = -item.fontHeight * 0.34;
1218
+ const corners = [
1219
+ [e + ux * d1 + vx * desc, f + uy * d1 + vy * desc],
1220
+ [e + ux * d2 + vx * desc, f + uy * d2 + vy * desc],
1221
+ [e + ux * d1 + vx * asc, f + uy * d1 + vy * asc],
1222
+ [e + ux * d2 + vx * asc, f + uy * d2 + vy * asc]
1223
+ ];
1224
+ let bx1 = Number.POSITIVE_INFINITY;
1225
+ let by1 = Number.POSITIVE_INFINITY;
1226
+ let bx2 = Number.NEGATIVE_INFINITY;
1227
+ let by2 = Number.NEGATIVE_INFINITY;
1228
+ for (const [cx, cy] of corners) {
1229
+ if (cx < bx1) bx1 = cx;
1230
+ if (cy < by1) by1 = cy;
1231
+ if (cx > bx2) bx2 = cx;
1232
+ if (cy > by2) by2 = cy;
1233
+ }
1234
+ rawForSpan.push({
1235
+ x1: bx1 - padX,
1236
+ y1: by1 - padY,
1237
+ x2: bx2 + padX,
1238
+ y2: by2 + padY,
1239
+ replacement: r.replacement
1240
+ });
1241
+ }
1242
+ }
1243
+ boxes.push(...mergeLineBoxes(rawForSpan));
1244
+ }
1245
+ return boxes;
1246
+ }
1247
+ function drawRedactionOverlay(ctx, viewport, boxes, style) {
1248
+ const fillColor = style.fillColor ?? "#111111";
1249
+ const textColor = style.textColor ?? "#ffffff";
1250
+ const showLabels = style.showLabels !== false;
1251
+ for (const box of boxes) {
1252
+ const corners = [
1253
+ viewport.convertToViewportPoint(box.x1, box.y1),
1254
+ viewport.convertToViewportPoint(box.x2, box.y1),
1255
+ viewport.convertToViewportPoint(box.x1, box.y2),
1256
+ viewport.convertToViewportPoint(box.x2, box.y2)
1257
+ ];
1258
+ let minX = Number.POSITIVE_INFINITY;
1259
+ let minY = Number.POSITIVE_INFINITY;
1260
+ let maxX = Number.NEGATIVE_INFINITY;
1261
+ let maxY = Number.NEGATIVE_INFINITY;
1262
+ for (const pt of corners) {
1263
+ const px = Number(pt[0] ?? 0);
1264
+ const py = Number(pt[1] ?? 0);
1265
+ if (px < minX) minX = px;
1266
+ if (py < minY) minY = py;
1267
+ if (px > maxX) maxX = px;
1268
+ if (py > maxY) maxY = py;
1269
+ }
1270
+ const rx = minX;
1271
+ const ry = minY;
1272
+ const rw = maxX - minX;
1273
+ const rh = maxY - minY;
1274
+ if (rw < 1 || rh < 1) continue;
1275
+ ctx.save();
1276
+ ctx.fillStyle = fillColor;
1277
+ ctx.fillRect(rx, ry, rw, rh);
1278
+ if (showLabels && box.replacement && rw >= 24 && rh >= 10) {
1279
+ const pad = Math.min(4, rw * 0.08);
1280
+ const maxTextWidth = Math.max(4, rw - pad * 2);
1281
+ const fontSize = Math.max(8, Math.min(rh * 0.62, 22));
1282
+ ctx.beginPath();
1283
+ ctx.rect(rx, ry, rw, rh);
1284
+ ctx.clip();
1285
+ ctx.fillStyle = textColor;
1286
+ ctx.font = `600 ${fontSize.toFixed(1)}px sans-serif`;
1287
+ ctx.textAlign = "center";
1288
+ ctx.textBaseline = "middle";
1289
+ ctx.fillText(box.replacement, rx + rw / 2, ry + rh / 2 + fontSize * 0.04, maxTextWidth);
1290
+ }
1291
+ ctx.restore();
1292
+ }
1293
+ }
1294
+ async function inspectPdfDocument(bytes, pdfWorkerSrc) {
1295
+ const pdfjs = await loadPdfjs(pdfWorkerSrc);
1296
+ const loadingTask = pdfjs.getDocument({
1297
+ data: bytes.slice(),
1298
+ useSystemFonts: true,
1299
+ verbosity: 0
1300
+ });
1301
+ const doc = await loadingTask.promise;
1302
+ const meta = await doc.getMetadata().catch(() => ({ info: {}, metadata: null }));
1303
+ const metadata = collectPdfMetadataStrings(meta);
1304
+ const pages = [];
1305
+ const scannedPages = [];
1306
+ const warnings = [];
1307
+ const ops = pdfjs.OPS;
1308
+ const imageOpSet = /* @__PURE__ */ new Set([
1309
+ ops.paintImageXObject,
1310
+ ops.paintInlineImageXObject,
1311
+ ops.paintImageMaskXObject
1312
+ ]);
1313
+ for (let pageNumber = 1; pageNumber <= doc.numPages; pageNumber++) {
1314
+ const page = await doc.getPage(pageNumber);
1315
+ const textContent = await page.getTextContent();
1316
+ const { text, items } = buildPageTextAndMap(
1317
+ textContent.items,
1318
+ textContent.styles
1319
+ );
1320
+ const rawAnnotations = await page.getAnnotations().catch(() => []);
1321
+ const annotations = extractAnnotationTexts(rawAnnotations);
1322
+ let scanned = false;
1323
+ if (text.trim().length < 10) {
1324
+ const opList = await page.getOperatorList().catch(() => null);
1325
+ if (opList?.fnArray.some((fn) => imageOpSet.has(fn))) {
1326
+ scanned = true;
1327
+ scannedPages.push(pageNumber);
1328
+ }
1329
+ }
1330
+ pages.push({ pageNumber, text, items, annotations, scanned });
1331
+ }
1332
+ if (scannedPages.length > 0) {
1333
+ warnings.push(
1334
+ `PDF page(s) ${scannedPages.join(", ")} appear to be scanned images without a text layer and cannot be inspected without OCR.`
1335
+ );
1336
+ }
1337
+ return { pdfjs, loadingTask, doc, pages, metadata, scannedPages, warnings };
1338
+ }
1339
+ async function extractPdf(bytes, options) {
1340
+ const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
1341
+ try {
1342
+ const sections = inspected.pages.map((p) => {
1343
+ const annotText = p.annotations.map((a) => a.text).join("\n");
1344
+ const combined = annotText ? `${p.text}${p.text ? "\n" : ""}${annotText}` : p.text;
1345
+ return {
1346
+ id: `page-${p.pageNumber}`,
1347
+ label: `Sida ${p.pageNumber}`,
1348
+ text: combined,
1349
+ pageIndex: p.pageNumber - 1,
1350
+ scanned: p.scanned
1351
+ };
1352
+ });
1353
+ return {
1354
+ format: "pdf",
1355
+ mimeType: "application/pdf",
1356
+ text: sections.map((s) => s.text).filter((t) => t.length > 0).join("\n\n"),
1357
+ sections,
1358
+ metadata: inspected.metadata,
1359
+ warnings: inspected.warnings,
1360
+ scannedPages: inspected.scannedPages,
1361
+ totalPages: inspected.doc.numPages
1362
+ };
1363
+ } finally {
1364
+ await inspected.loadingTask.destroy();
1365
+ }
1366
+ }
1367
+ function countByLabel(redactions) {
1368
+ const counts = {};
1369
+ for (const r of redactions) {
1370
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
1371
+ }
1372
+ return counts;
1373
+ }
1374
+ async function redactPdf(bytes, redactFn, options) {
1375
+ const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
1376
+ try {
1377
+ const pageOffsets = [];
1378
+ const textChunks = [];
1379
+ let cursor = 0;
1380
+ for (let i = 0; i < inspected.pages.length; i++) {
1381
+ const page = inspected.pages[i];
1382
+ if (!page) continue;
1383
+ const hasAnyContent = page.text.length > 0 || page.annotations.some((a) => a.text.length > 0);
1384
+ if (!hasAnyContent) {
1385
+ pageOffsets.push({ pageIndex: i, textStart: cursor, textEnd: cursor, annotRanges: [] });
1386
+ continue;
1387
+ }
1388
+ if (textChunks.length > 0) {
1389
+ textChunks.push("\n\n");
1390
+ cursor += 2;
1391
+ }
1392
+ const textStart = cursor;
1393
+ if (page.text.length > 0) {
1394
+ textChunks.push(page.text);
1395
+ cursor += page.text.length;
1396
+ }
1397
+ const textEnd = cursor;
1398
+ const annotRanges = [];
1399
+ let wroteInPage = page.text.length > 0;
1400
+ for (const annot of page.annotations) {
1401
+ if (!annot.text) continue;
1402
+ if (wroteInPage) {
1403
+ textChunks.push("\n");
1404
+ cursor += 1;
1405
+ }
1406
+ const start = cursor;
1407
+ textChunks.push(annot.text);
1408
+ cursor += annot.text.length;
1409
+ wroteInPage = true;
1410
+ annotRanges.push({ start, end: cursor, rect: annot.rect });
1411
+ }
1412
+ pageOffsets.push({ pageIndex: i, textStart, textEnd, annotRanges });
1413
+ }
1414
+ const combinedText = textChunks.join("");
1415
+ const result = await redactFn(combinedText);
1416
+ const srcDoc = await PDFDocument.load(bytes, {
1417
+ ignoreEncryption: true,
1418
+ updateMetadata: false
1419
+ });
1420
+ const outDoc = await PDFDocument.create();
1421
+ const style = options?.pdfStyle ?? {};
1422
+ const scale = style.scale ?? 2.5;
1423
+ let canvasProvider = options?.canvasProvider;
1424
+ const redactedPages = [];
1425
+ for (let i = 0; i < inspected.pages.length; i++) {
1426
+ const pageInfo = inspected.pages[i];
1427
+ const offsetInfo = pageOffsets[i];
1428
+ if (!pageInfo || !offsetInfo) continue;
1429
+ const localTextRedactions = [];
1430
+ const annotBoxes = [];
1431
+ let hasAnnotPii = false;
1432
+ for (const r of result.redactions) {
1433
+ if (r.end > offsetInfo.textStart && r.start < offsetInfo.textEnd) {
1434
+ localTextRedactions.push({
1435
+ start: Math.max(0, r.start - offsetInfo.textStart),
1436
+ end: Math.min(offsetInfo.textEnd - offsetInfo.textStart, r.end - offsetInfo.textStart),
1437
+ replacement: r.replacement
1438
+ });
1439
+ }
1440
+ for (const ar of offsetInfo.annotRanges) {
1441
+ if (r.end > ar.start && r.start < ar.end) {
1442
+ hasAnnotPii = true;
1443
+ if (ar.rect) {
1444
+ annotBoxes.push({
1445
+ x1: ar.rect[0],
1446
+ y1: ar.rect[1],
1447
+ x2: ar.rect[2],
1448
+ y2: ar.rect[3],
1449
+ replacement: r.replacement
1450
+ });
1451
+ }
1452
+ }
1453
+ }
1454
+ }
1455
+ const shouldBurn = options?.burnAllPdfPages === true || localTextRedactions.length > 0 || annotBoxes.length > 0 || hasAnnotPii;
1456
+ if (!shouldBurn) {
1457
+ const [copied] = await outDoc.copyPages(srcDoc, [i]);
1458
+ if (copied) {
1459
+ copied.node.delete(PDFName.of("Annots"));
1460
+ outDoc.addPage(copied);
1461
+ }
1462
+ continue;
1463
+ }
1464
+ redactedPages.push(pageInfo.pageNumber);
1465
+ if (!canvasProvider) {
1466
+ canvasProvider = await resolveDefaultCanvasProvider();
1467
+ }
1468
+ const pdfjsPage = await inspected.doc.getPage(pageInfo.pageNumber);
1469
+ const unscaledViewport = pdfjsPage.getViewport({ scale: 1 });
1470
+ const renderViewport = pdfjsPage.getViewport({ scale });
1471
+ const canvas = canvasProvider.createCanvas(
1472
+ Math.max(1, Math.ceil(renderViewport.width)),
1473
+ Math.max(1, Math.ceil(renderViewport.height))
1474
+ );
1475
+ const ctx = canvas.getContext("2d");
1476
+ if (!ctx) {
1477
+ throw new Error("Could not acquire 2D canvas context for PDF redaction.");
1478
+ }
1479
+ await pdfjsPage.render({
1480
+ canvasContext: ctx,
1481
+ viewport: renderViewport,
1482
+ canvas,
1483
+ intent: "print"
1484
+ }).promise;
1485
+ const textBoxes = computePageRedactionBoxes(pageInfo.items, localTextRedactions, ctx);
1486
+ const allBoxes = [...textBoxes, ...annotBoxes];
1487
+ drawRedactionOverlay(ctx, renderViewport, allBoxes, style);
1488
+ const pngBytes = await canvasProvider.toPngBytes(canvas);
1489
+ const pngImage = await outDoc.embedPng(pngBytes);
1490
+ const newPage = outDoc.addPage([unscaledViewport.width, unscaledViewport.height]);
1491
+ newPage.drawImage(pngImage, {
1492
+ x: 0,
1493
+ y: 0,
1494
+ width: unscaledViewport.width,
1495
+ height: unscaledViewport.height
1496
+ });
1497
+ }
1498
+ outDoc.setTitle("");
1499
+ outDoc.setAuthor("");
1500
+ outDoc.setSubject("");
1501
+ outDoc.setKeywords([]);
1502
+ outDoc.setCreator("Maskera");
1503
+ outDoc.setProducer("Maskera");
1504
+ const outBytes = new Uint8Array(await outDoc.save({ useObjectStreams: true }));
1505
+ const metadataCleared = Object.keys(inspected.metadata);
1506
+ const metadataValues = Object.values(inspected.metadata);
1507
+ return {
1508
+ bytes: outBytes,
1509
+ extractedText: combinedText,
1510
+ redactedText: result.text,
1511
+ totalRedactions: result.redactions.length,
1512
+ counts: countByLabel(result.redactions),
1513
+ redactions: result.redactions,
1514
+ map: result.map,
1515
+ metadataCleared,
1516
+ metadataValues,
1517
+ warnings: inspected.warnings,
1518
+ scannedPages: inspected.scannedPages,
1519
+ redactedPages,
1520
+ totalPages: inspected.doc.numPages
1521
+ };
1522
+ } finally {
1523
+ await inspected.loadingTask.destroy();
1524
+ }
1525
+ }
1526
+ function normalizeForLeakCheck(value) {
1527
+ return value.replace(/\s+/g, " ").trim().toLowerCase();
1528
+ }
1529
+ function collectNonTrivialSecrets(secrets) {
1530
+ const seen = /* @__PURE__ */ new Set();
1531
+ const out = [];
1532
+ for (const raw of secrets) {
1533
+ const norm = normalizeForLeakCheck(raw);
1534
+ if (norm.length < 3 || seen.has(norm)) continue;
1535
+ seen.add(norm);
1536
+ out.push(raw.trim());
1537
+ }
1538
+ return out;
1539
+ }
1540
+ async function verifyRedactedFile(bytes, format2, originalSecrets, options) {
1541
+ const candidates = collectNonTrivialSecrets(originalSecrets);
1542
+ if (candidates.length === 0) {
1543
+ return { verified: true, leaks: [] };
1544
+ }
1545
+ let haystack = "";
1546
+ if (format2 === "text") {
1547
+ haystack = normalizeForLeakCheck(decodeUtf8(bytes));
1548
+ } else if (format2 === "docx" || format2 === "xlsx") {
1549
+ const archive = unzipSafely(bytes);
1550
+ const parts = [];
1551
+ for (const [name, data] of Object.entries(archive)) {
1552
+ if (!/\.(?:xml|rels)$/i.test(name)) continue;
1553
+ const xml = decodeUtf8(data);
1554
+ parts.push(unescapeXml(xml));
1555
+ parts.push(unescapeXml(xml.replace(/<[^>]+>/g, "")));
1556
+ }
1557
+ haystack = normalizeForLeakCheck(parts.join("\n"));
1558
+ } else if (format2 === "pdf") {
1559
+ const extracted = await extractPdf(bytes, { pdfWorkerSrc: options?.pdfWorkerSrc });
1560
+ const metaValues = Object.values(extracted.metadata).join("\n");
1561
+ const rawLatin = new TextDecoder("latin1").decode(bytes);
1562
+ haystack = normalizeForLeakCheck(`${extracted.text}
1563
+ ${metaValues}
1564
+ ${rawLatin}`);
1565
+ }
1566
+ const leaks = [];
1567
+ for (const secret of candidates) {
1568
+ if (haystack.includes(normalizeForLeakCheck(secret))) {
1569
+ leaks.push(secret);
1570
+ }
1571
+ }
1572
+ return {
1573
+ verified: leaks.length === 0,
1574
+ leaks
1575
+ };
1576
+ }
1577
+ function assertSizeLimit(bytes, maxBytes, fileName) {
1578
+ if (bytes.byteLength > maxBytes) {
1579
+ const label = fileName ? `"${fileName}"` : "File";
1580
+ throw new Error(`${label} is ${bytes.byteLength} bytes (max ${maxBytes} bytes).`);
1581
+ }
1582
+ }
1583
+ function countByLabel2(redactions) {
1584
+ const counts = {};
1585
+ for (const r of redactions) {
1586
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
1587
+ }
1588
+ return counts;
1589
+ }
1590
+ async function extractFileText(bytes, options = {}) {
1591
+ const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
1592
+ assertSizeLimit(bytes, maxBytes, options.fileName);
1593
+ const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
1594
+ if (detected.format === "binary") {
1595
+ const label = options.fileName ? `"${options.fileName}"` : "File";
1596
+ throw new Error(
1597
+ `${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
1598
+ );
1599
+ }
1600
+ if (detected.format === "text") {
1601
+ const text = decodeUtf8(bytes);
1602
+ return {
1603
+ format: "text",
1604
+ mimeType: detected.mimeType,
1605
+ text,
1606
+ sections: [{ id: "body", label: options.fileName ?? "text", text }],
1607
+ metadata: {},
1608
+ warnings: [],
1609
+ scannedPages: []
1610
+ };
1611
+ }
1612
+ if (detected.format === "docx") {
1613
+ return extractDocx(bytes);
1614
+ }
1615
+ if (detected.format === "xlsx") {
1616
+ return extractXlsx(bytes);
1617
+ }
1618
+ return extractPdf(bytes, { pdfWorkerSrc: options.pdfWorkerSrc });
1619
+ }
1620
+ async function redactFile(bytes, redactFn, options = {}) {
1621
+ const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
1622
+ assertSizeLimit(bytes, maxBytes, options.fileName);
1623
+ const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
1624
+ if (detected.format === "binary") {
1625
+ const label = options.fileName ? `"${options.fileName}"` : "File";
1626
+ throw new Error(
1627
+ `${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
1628
+ );
1629
+ }
1630
+ const shouldVerify = options.verify !== false;
1631
+ if (detected.format === "text") {
1632
+ const extractedText = decodeUtf8(bytes);
1633
+ const result = await redactFn(extractedText);
1634
+ const outBytes = encodeUtf8(result.text);
1635
+ const secrets2 = result.redactions.map((r) => r.value);
1636
+ const verification2 = shouldVerify ? await verifyRedactedFile(outBytes, "text", secrets2) : { verified: true, leaks: [] };
1637
+ return {
1638
+ format: "text",
1639
+ mimeType: detected.mimeType,
1640
+ bytes: outBytes,
1641
+ extractedText,
1642
+ redactedText: result.text,
1643
+ totalRedactions: result.redactions.length,
1644
+ counts: countByLabel2(result.redactions),
1645
+ redactions: result.redactions,
1646
+ map: result.map,
1647
+ metadataCleared: [],
1648
+ warnings: [],
1649
+ scannedPages: [],
1650
+ verified: verification2.verified,
1651
+ verificationLeaks: verification2.leaks
1652
+ };
1653
+ }
1654
+ if (detected.format === "docx") {
1655
+ const doc = await redactDocx(bytes, redactFn);
1656
+ const secrets2 = [...doc.redactions.map((r) => r.value), ...doc.metadataValues];
1657
+ const verification2 = shouldVerify ? await verifyRedactedFile(doc.bytes, "docx", secrets2) : { verified: true, leaks: [] };
1658
+ return {
1659
+ format: "docx",
1660
+ mimeType: detected.mimeType,
1661
+ bytes: doc.bytes,
1662
+ extractedText: doc.extractedText,
1663
+ redactedText: doc.redactedText,
1664
+ totalRedactions: doc.totalRedactions,
1665
+ counts: doc.counts,
1666
+ redactions: doc.redactions,
1667
+ map: doc.map,
1668
+ metadataCleared: doc.metadataCleared,
1669
+ warnings: doc.warnings,
1670
+ scannedPages: [],
1671
+ verified: verification2.verified,
1672
+ verificationLeaks: verification2.leaks
1673
+ };
1674
+ }
1675
+ if (detected.format === "xlsx") {
1676
+ const sheet = await redactXlsx(bytes, redactFn);
1677
+ const secrets2 = [...sheet.redactions.map((r) => r.value), ...sheet.metadataValues];
1678
+ const verification2 = shouldVerify ? await verifyRedactedFile(sheet.bytes, "xlsx", secrets2) : { verified: true, leaks: [] };
1679
+ return {
1680
+ format: "xlsx",
1681
+ mimeType: detected.mimeType,
1682
+ bytes: sheet.bytes,
1683
+ extractedText: sheet.extractedText,
1684
+ redactedText: sheet.redactedText,
1685
+ totalRedactions: sheet.totalRedactions,
1686
+ counts: sheet.counts,
1687
+ redactions: sheet.redactions,
1688
+ map: sheet.map,
1689
+ metadataCleared: sheet.metadataCleared,
1690
+ warnings: sheet.warnings,
1691
+ scannedPages: [],
1692
+ verified: verification2.verified,
1693
+ verificationLeaks: verification2.leaks
1694
+ };
1695
+ }
1696
+ const pdf = await redactPdf(bytes, redactFn, {
1697
+ pdfStyle: options.pdfStyle,
1698
+ canvasProvider: options.canvasProvider,
1699
+ pdfWorkerSrc: options.pdfWorkerSrc,
1700
+ burnAllPdfPages: options.burnAllPdfPages
1701
+ });
1702
+ const secrets = [...pdf.redactions.map((r) => r.value), ...pdf.metadataValues];
1703
+ const verification = shouldVerify ? await verifyRedactedFile(pdf.bytes, "pdf", secrets, {
1704
+ pdfWorkerSrc: options.pdfWorkerSrc
1705
+ }) : { verified: true, leaks: [] };
1706
+ return {
1707
+ format: "pdf",
1708
+ mimeType: detected.mimeType,
1709
+ bytes: pdf.bytes,
1710
+ extractedText: pdf.extractedText,
1711
+ redactedText: pdf.redactedText,
1712
+ totalRedactions: pdf.totalRedactions,
1713
+ counts: pdf.counts,
1714
+ redactions: pdf.redactions,
1715
+ map: pdf.map,
1716
+ metadataCleared: pdf.metadataCleared,
1717
+ warnings: pdf.warnings,
1718
+ scannedPages: pdf.scannedPages,
1719
+ redactedPages: pdf.redactedPages,
1720
+ totalPages: pdf.totalPages,
1721
+ verified: verification.verified,
1722
+ verificationLeaks: verification.leaks
1723
+ };
1724
+ }
15
1725
  var WORD_CHAR = /[\p{L}\p{N}_]/u;
16
1726
  var DEFAULT_MAX_CACHE_ENTRIES = 512;
17
1727
  var MAX_CUSTOM_DETECTOR_CACHE = 64;
@@ -474,6 +2184,7 @@ function createModelProgressLogger(write = (line) => process.stderr.write(`${lin
474
2184
  };
475
2185
  }
476
2186
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
2187
+ var MAX_DOCUMENT_BYTES = MAX_DEFAULT_FILE_BYTES;
477
2188
  var MAX_SYMLINK_HOPS = 40;
478
2189
  var DEFAULT_LIST_MAX_ENTRIES = 200;
479
2190
  var HARD_LIST_MAX_ENTRIES = 1e3;
@@ -482,7 +2193,7 @@ var HARD_LIST_MAX_DEPTH = 12;
482
2193
  var DEFAULT_SEARCH_MAX_MATCHES = 50;
483
2194
  var HARD_SEARCH_MAX_MATCHES = 200;
484
2195
  var DEFAULT_SEARCH_MAX_FILES = 500;
485
- var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
2196
+ var UTF8_DECODER3 = new TextDecoder("utf-8", { fatal: true });
486
2197
  var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "dist-ssr", ".next", ".turbo"]);
487
2198
  function isWithinRoot(root, target) {
488
2199
  const rel = relative(root, target);
@@ -626,84 +2337,144 @@ function createFileGuard(roots = [process.cwd()]) {
626
2337
  await visit(baseDir, 0);
627
2338
  return { files, truncated };
628
2339
  }
2340
+ async function resolveReadableFile(filePath, maxBytes) {
2341
+ const rootsList = await getCanonicalRoots();
2342
+ const candidate = resolveAgainstBase(filePath);
2343
+ const { ancestor, tail } = await resolveExistingAncestor(candidate);
2344
+ const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
2345
+ if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
2346
+ throw new Error(
2347
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2348
+ );
2349
+ }
2350
+ const real = await realpath(candidate).catch(() => {
2351
+ throw new Error(`File not found: "${filePath}".`);
2352
+ });
2353
+ if (!rootsList.some((root) => isWithinRoot(root, real))) {
2354
+ throw new Error(
2355
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2356
+ );
2357
+ }
2358
+ const info = await stat(real);
2359
+ if (!info.isFile()) {
2360
+ throw new Error(`"${filePath}" is not a regular file.`);
2361
+ }
2362
+ if (info.size > maxBytes) {
2363
+ throw new Error(
2364
+ `File "${filePath}" is ${info.size} bytes (max ${maxBytes} bytes for local redaction).`
2365
+ );
2366
+ }
2367
+ const buffer = await readFile(real);
2368
+ return { resolvedPath: real, buffer };
2369
+ }
2370
+ async function writeCheckedBytes(filePath, data, options) {
2371
+ const rootsList = await getCanonicalRoots();
2372
+ const candidate = resolveAgainstBase(filePath);
2373
+ const targetReal = await resolveCanonicalTarget(candidate);
2374
+ if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
2375
+ throw new Error(
2376
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2377
+ );
2378
+ }
2379
+ const bytes = typeof data === "string" ? Buffer.byteLength(data, "utf8") : data.byteLength;
2380
+ if (bytes > options.maxBytes) {
2381
+ throw new Error(`Output exceeds max allowed size (${options.maxBytes} bytes).`);
2382
+ }
2383
+ await mkdir(dirname(targetReal), { recursive: true });
2384
+ const parentReal = await realpath(dirname(targetReal));
2385
+ if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
2386
+ throw new Error(
2387
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2388
+ );
2389
+ }
2390
+ await writeFile(targetReal, data, {
2391
+ ...options.encoding ? { encoding: options.encoding } : {},
2392
+ flag: options.overwrite ? "w" : "wx",
2393
+ mode: 384
2394
+ }).catch((err) => {
2395
+ if (err.code === "EEXIST") {
2396
+ throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
2397
+ }
2398
+ throw err;
2399
+ });
2400
+ return { resolvedPath: targetReal, bytes };
2401
+ }
629
2402
  return {
630
2403
  allowedRoots: rawRoots.map((r) => resolve(r)),
631
2404
  async readText(filePath) {
632
- const rootsList = await getCanonicalRoots();
633
- const candidate = resolveAgainstBase(filePath);
634
- const { ancestor, tail } = await resolveExistingAncestor(candidate);
635
- const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
636
- if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
637
- throw new Error(
638
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
639
- );
640
- }
641
- const real = await realpath(candidate).catch(() => {
642
- throw new Error(`File not found: "${filePath}".`);
643
- });
644
- if (!rootsList.some((root) => isWithinRoot(root, real))) {
645
- throw new Error(
646
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
647
- );
648
- }
649
- const info = await stat(real);
650
- if (!info.isFile()) {
651
- throw new Error(`"${filePath}" is not a regular file.`);
652
- }
653
- if (info.size > MAX_FILE_BYTES) {
654
- throw new Error(
655
- `File "${filePath}" is ${info.size} bytes (max ${MAX_FILE_BYTES} bytes for local redaction).`
656
- );
657
- }
658
- const buffer = await readFile(real);
2405
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_FILE_BYTES);
659
2406
  if (buffer.includes(0)) {
660
2407
  throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
661
2408
  }
662
2409
  let content;
663
2410
  try {
664
- content = UTF8_DECODER.decode(buffer);
2411
+ content = UTF8_DECODER3.decode(buffer);
665
2412
  } catch {
666
2413
  throw new Error(
667
2414
  `"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
668
2415
  );
669
2416
  }
670
2417
  return {
671
- resolvedPath: real,
2418
+ resolvedPath,
672
2419
  content,
673
2420
  bytes: buffer.byteLength
674
2421
  };
675
2422
  },
676
- async writeText(filePath, content, options = {}) {
677
- const rootsList = await getCanonicalRoots();
678
- const candidate = resolveAgainstBase(filePath);
679
- const targetReal = await resolveCanonicalTarget(candidate);
680
- if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
2423
+ async readDocument(filePath) {
2424
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_DOCUMENT_BYTES);
2425
+ const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2426
+ const detected = detectFileFormat(bytes, resolvedPath);
2427
+ if (detected.format === "text" && buffer.byteLength > MAX_FILE_BYTES) {
681
2428
  throw new Error(
682
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2429
+ `File "${filePath}" is ${buffer.byteLength} bytes (max ${MAX_FILE_BYTES} bytes for local text redaction).`
683
2430
  );
684
2431
  }
685
- const bytes = Buffer.byteLength(content, "utf8");
686
- if (bytes > MAX_FILE_BYTES) {
687
- throw new Error(`Output exceeds max allowed size (${MAX_FILE_BYTES} bytes).`);
688
- }
689
- await mkdir(dirname(targetReal), { recursive: true });
690
- const parentReal = await realpath(dirname(targetReal));
691
- if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
2432
+ if (detected.format === "binary") {
2433
+ if (!buffer.includes(0)) {
2434
+ throw new Error(
2435
+ `"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
2436
+ );
2437
+ }
692
2438
  throw new Error(
693
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2439
+ `"${filePath}" appears to be an unsupported binary file (${detected.mimeType}); supported formats are UTF-8 text, PDF, DOCX, and XLSX.`
694
2440
  );
695
2441
  }
696
- await writeFile(targetReal, content, {
697
- encoding: "utf8",
698
- flag: options.overwrite ? "w" : "wx",
699
- mode: 384
700
- }).catch((err) => {
701
- if (err.code === "EEXIST") {
702
- throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
703
- }
704
- throw err;
2442
+ const extracted = await extractFileText(bytes, {
2443
+ fileName: resolvedPath,
2444
+ maxBytes: MAX_DOCUMENT_BYTES
2445
+ });
2446
+ return {
2447
+ resolvedPath,
2448
+ content: extracted.text,
2449
+ bytes: buffer.byteLength,
2450
+ format: extracted.format,
2451
+ mimeType: extracted.mimeType,
2452
+ metadataFields: Object.keys(extracted.metadata),
2453
+ warnings: extracted.warnings,
2454
+ scannedPages: extracted.scannedPages,
2455
+ totalPages: extracted.totalPages
2456
+ };
2457
+ },
2458
+ async readBytes(filePath, options = {}) {
2459
+ const maxBytes = options.maxBytes ?? MAX_DOCUMENT_BYTES;
2460
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, maxBytes);
2461
+ return {
2462
+ resolvedPath,
2463
+ bytes: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
2464
+ };
2465
+ },
2466
+ async writeText(filePath, content, options = {}) {
2467
+ return writeCheckedBytes(filePath, content, {
2468
+ overwrite: options.overwrite,
2469
+ maxBytes: MAX_FILE_BYTES,
2470
+ encoding: "utf8"
2471
+ });
2472
+ },
2473
+ async writeBytes(filePath, bytes, options = {}) {
2474
+ return writeCheckedBytes(filePath, bytes, {
2475
+ overwrite: options.overwrite,
2476
+ maxBytes: options.maxBytes ?? MAX_DOCUMENT_BYTES
705
2477
  });
706
- return { resolvedPath: targetReal, bytes };
707
2478
  },
708
2479
  async listFiles(dirPath, options = {}) {
709
2480
  const { rootsList, baseDir } = await resolveAllowedDirectory(dirPath);
@@ -749,19 +2520,36 @@ function createFileGuard(roots = [process.cwd()]) {
749
2520
  let scannedFiles = 0;
750
2521
  let truncated = walkTruncated;
751
2522
  for (const file of files) {
752
- if (file.bytes > MAX_FILE_BYTES) continue;
2523
+ if (file.bytes > MAX_DOCUMENT_BYTES) continue;
753
2524
  let buffer;
754
2525
  try {
755
2526
  buffer = await readFile(file.realPath);
756
2527
  } catch {
757
2528
  continue;
758
2529
  }
759
- if (buffer.includes(0)) continue;
760
2530
  let text;
761
- try {
762
- text = UTF8_DECODER.decode(buffer);
763
- } catch {
764
- continue;
2531
+ if (!buffer.includes(0)) {
2532
+ if (file.bytes > MAX_FILE_BYTES) continue;
2533
+ try {
2534
+ text = UTF8_DECODER3.decode(buffer);
2535
+ } catch {
2536
+ continue;
2537
+ }
2538
+ } else {
2539
+ const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2540
+ const detected = detectFileFormat(bytes, file.realPath);
2541
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
2542
+ continue;
2543
+ }
2544
+ try {
2545
+ const extracted = await extractFileText(bytes, {
2546
+ fileName: file.realPath,
2547
+ maxBytes: MAX_DOCUMENT_BYTES
2548
+ });
2549
+ text = extracted.text;
2550
+ } catch {
2551
+ continue;
2552
+ }
765
2553
  }
766
2554
  scannedFiles += 1;
767
2555
  const lines = text.split(/\r?\n/);
@@ -1026,11 +2814,13 @@ var SessionVault = class {
1026
2814
  redacted: originalInput,
1027
2815
  counts: {},
1028
2816
  totalRedactions: 0,
1029
- map: {}
2817
+ map: {},
2818
+ redactions: []
1030
2819
  };
1031
2820
  }
1032
2821
  const counts = {};
1033
2822
  const localMap = {};
2823
+ const appliedRedactions = [];
1034
2824
  const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
1035
2825
  let redacted = "";
1036
2826
  let cursor = 0;
@@ -1070,6 +2860,7 @@ var SessionVault = class {
1070
2860
  }
1071
2861
  localMap[token] = r.value;
1072
2862
  counts[r.label] = (counts[r.label] ?? 0) + 1;
2863
+ appliedRedactions.push({ ...r, replacement: token });
1073
2864
  redacted += originalInput.slice(cursor, r.start) + token;
1074
2865
  cursor = r.end;
1075
2866
  }
@@ -1079,7 +2870,8 @@ var SessionVault = class {
1079
2870
  redacted,
1080
2871
  counts,
1081
2872
  totalRedactions: result.redactions.length,
1082
- map: localMap
2873
+ map: localMap,
2874
+ redactions: appliedRedactions
1083
2875
  };
1084
2876
  }
1085
2877
  restore(text, options) {
@@ -1297,9 +3089,9 @@ var TOOLS = [
1297
3089
  },
1298
3090
  {
1299
3091
  name: "maskera_read_file",
1300
- description: "Read a local UTF-8 text file and redact Swedish PII BEFORE returning its contents to the model. Keeps raw PII strictly in local memory under session_id so the cloud LLM never sees real names or personal IDs.",
3092
+ description: "Read a local UTF-8 text, PDF, DOCX, or XLSX file and redact Swedish PII BEFORE returning its contents to the model. Keeps raw PII strictly in local memory under session_id so the cloud LLM never sees real names or personal IDs.",
1301
3093
  annotations: {
1302
- title: "Read local file with PII redaction",
3094
+ title: "Read local file or document with PII redaction",
1303
3095
  readOnlyHint: true,
1304
3096
  destructiveHint: false,
1305
3097
  idempotentHint: false,
@@ -1310,7 +3102,7 @@ var TOOLS = [
1310
3102
  properties: {
1311
3103
  path: {
1312
3104
  type: "string",
1313
- description: "Path to a UTF-8 file inside the allowed workspace roots."
3105
+ description: "Path to a UTF-8 text, PDF, DOCX, or XLSX file inside allowed workspace roots."
1314
3106
  },
1315
3107
  session_id: {
1316
3108
  type: "string",
@@ -1339,15 +3131,102 @@ var TOOLS = [
1339
3131
  properties: {
1340
3132
  path: { type: "string" },
1341
3133
  bytes: { type: "integer" },
3134
+ format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
1342
3135
  redacted: { type: "string" },
1343
3136
  session_id: { type: "string" },
1344
3137
  counts: COUNTS_SCHEMA,
1345
3138
  total_redactions: { type: "integer" },
1346
- mode: { type: "string", enum: ["hybrid", "rules"] }
3139
+ mode: { type: "string", enum: ["hybrid", "rules"] },
3140
+ total_pages: { type: "integer" },
3141
+ scanned_pages: { type: "array", items: { type: "integer" } },
3142
+ metadata_fields: { type: "array", items: { type: "string" } },
3143
+ warnings: { type: "array", items: { type: "string" } }
1347
3144
  },
1348
3145
  required: ["path", "bytes", "redacted", "session_id", "counts", "total_redactions", "mode"]
1349
3146
  }
1350
3147
  },
3148
+ {
3149
+ name: "maskera_redact_file",
3150
+ description: "Redact Swedish PII inside a local PDF, DOCX, XLSX, or UTF-8 text file and write a verified clean file directly to disk without exposing raw PII to the model. For PDFs, affected pages are rasterized and burned so zero raw text survives in the PDF stream; metadata is stripped.",
3151
+ annotations: {
3152
+ title: "Redact local PDF/DOCX/XLSX/text file to disk",
3153
+ readOnlyHint: false,
3154
+ destructiveHint: false,
3155
+ idempotentHint: false,
3156
+ openWorldHint: false
3157
+ },
3158
+ inputSchema: {
3159
+ type: "object",
3160
+ properties: {
3161
+ input_path: {
3162
+ type: "string",
3163
+ description: "Source file path (PDF, DOCX, XLSX, or UTF-8 text) inside allowed roots."
3164
+ },
3165
+ output_path: {
3166
+ type: "string",
3167
+ description: "Destination path for the redacted file inside allowed roots."
3168
+ },
3169
+ session_id: {
3170
+ type: "string",
3171
+ description: "Optional session ID to share placeholder numbering across files."
3172
+ },
3173
+ overwrite: {
3174
+ type: "boolean",
3175
+ description: "Allow overwriting an existing output file. Default false."
3176
+ },
3177
+ show_labels: {
3178
+ type: "boolean",
3179
+ description: "Draw placeholder labels (e.g. [NAMN_1]) inside burned PDF boxes. Default true."
3180
+ },
3181
+ mode: {
3182
+ type: "string",
3183
+ enum: ["auto", "rules"],
3184
+ description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
3185
+ },
3186
+ profile: {
3187
+ type: "string",
3188
+ enum: ["general", "clinical"],
3189
+ description: 'Optional built-in precision profile (default "general").'
3190
+ },
3191
+ custom_terms: {
3192
+ type: "array",
3193
+ items: { type: "string" },
3194
+ description: "Optional extra protected words (client names, project codenames)."
3195
+ }
3196
+ },
3197
+ required: ["input_path", "output_path"]
3198
+ },
3199
+ outputSchema: {
3200
+ type: "object",
3201
+ properties: {
3202
+ input_path: { type: "string" },
3203
+ output_path: { type: "string" },
3204
+ format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
3205
+ bytes: { type: "integer" },
3206
+ session_id: { type: "string" },
3207
+ counts: COUNTS_SCHEMA,
3208
+ total_redactions: { type: "integer" },
3209
+ mode: { type: "string", enum: ["hybrid", "rules"] },
3210
+ verified: { type: "boolean" },
3211
+ metadata_cleared: { type: "array", items: { type: "string" } },
3212
+ redacted_pages: { type: "array", items: { type: "integer" } },
3213
+ total_pages: { type: "integer" },
3214
+ scanned_pages: { type: "array", items: { type: "integer" } },
3215
+ warnings: { type: "array", items: { type: "string" } }
3216
+ },
3217
+ required: [
3218
+ "input_path",
3219
+ "output_path",
3220
+ "format",
3221
+ "bytes",
3222
+ "session_id",
3223
+ "counts",
3224
+ "total_redactions",
3225
+ "mode",
3226
+ "verified"
3227
+ ]
3228
+ }
3229
+ },
1351
3230
  {
1352
3231
  name: "maskera_write_file",
1353
3232
  description: "Restore Maskera placeholders from a local session_id and write the restored text directly to a local file without echoing raw PII back into the LLM context.",
@@ -1642,7 +3521,7 @@ var TOOLS = [
1642
3521
  }
1643
3522
  }
1644
3523
  ];
1645
- var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_clear_session"]);
3524
+ var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_redact_file", "maskera_clear_session"]);
1646
3525
  var CODE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1647
3526
  ".ts",
1648
3527
  ".tsx",
@@ -2151,7 +4030,7 @@ function createMaskeraMcpServer(options = {}) {
2151
4030
  }
2152
4031
  const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
2153
4032
  const resolvedInputPath = resolveInputPath(args.path, owner, requestedSession);
2154
- const file = await files.readText(resolvedInputPath);
4033
+ const file = await files.readDocument(resolvedInputPath);
2155
4034
  const profile = asProfile(args.profile) ?? defaultProfile;
2156
4035
  const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
2157
4036
  const { result, modeUsed } = await engine.redact(file.content, {
@@ -2174,11 +4053,109 @@ function createMaskeraMcpServer(options = {}) {
2174
4053
  toolOk({
2175
4054
  path: safePath,
2176
4055
  bytes: file.bytes,
4056
+ format: file.format,
2177
4057
  redacted: applied.redacted,
2178
4058
  session_id: applied.sessionId,
2179
4059
  counts: applied.counts,
2180
4060
  total_redactions: applied.totalRedactions,
2181
- mode: modeUsed
4061
+ mode: modeUsed,
4062
+ ...file.totalPages !== void 0 ? { total_pages: file.totalPages } : {},
4063
+ ...file.scannedPages.length > 0 ? { scanned_pages: file.scannedPages } : {},
4064
+ ...file.metadataFields.length > 0 ? { metadata_fields: file.metadataFields } : {},
4065
+ ...file.warnings.length > 0 ? { warnings: file.warnings } : {}
4066
+ })
4067
+ );
4068
+ }
4069
+ if (name === "maskera_redact_file") {
4070
+ if (typeof args.input_path !== "string") {
4071
+ return finish(toolError("Missing required string: input_path"));
4072
+ }
4073
+ if (typeof args.output_path !== "string") {
4074
+ return finish(toolError("Missing required string: output_path"));
4075
+ }
4076
+ const requestedMode = asMode(args.mode);
4077
+ if (engine.status().defaultMode === "auto" && requestedMode === "rules") {
4078
+ return finish(
4079
+ toolError(
4080
+ 'Downgrading mode to "rules" is not allowed on maskera_redact_file when the server runs in hybrid "auto" mode.'
4081
+ )
4082
+ );
4083
+ }
4084
+ const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
4085
+ const resolvedInputPath = resolveInputPath(args.input_path, owner, requestedSession);
4086
+ const resolvedOutputPath = resolveInputPath(args.output_path, owner, requestedSession);
4087
+ const source = await files.readBytes(resolvedInputPath);
4088
+ const profile = asProfile(args.profile) ?? defaultProfile;
4089
+ const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
4090
+ let sessionId = requestedSession ?? "";
4091
+ let modeUsed = engine.status().defaultMode === "rules" ? "rules" : "hybrid";
4092
+ const redactedDoc = await redactFile(
4093
+ source.bytes,
4094
+ async (text) => {
4095
+ const eng = await engine.redact(text, {
4096
+ mode: requestedMode,
4097
+ profile,
4098
+ customTerms
4099
+ });
4100
+ modeUsed = eng.modeUsed;
4101
+ const applied = vault.apply(text, eng.result, sessionId || void 0, owner);
4102
+ sessionId = applied.sessionId;
4103
+ return {
4104
+ text: applied.redacted,
4105
+ redactions: applied.redactions,
4106
+ map: applied.map,
4107
+ restore: (t) => vault.restore(t, { sessionId: applied.sessionId, owner }).restored
4108
+ };
4109
+ },
4110
+ {
4111
+ fileName: source.resolvedPath,
4112
+ pdfStyle: { showLabels: args.show_labels !== false },
4113
+ verify: true
4114
+ }
4115
+ );
4116
+ if (!redactedDoc.verified) {
4117
+ return finish(
4118
+ toolError(
4119
+ `Post-redaction verification detected ${redactedDoc.verificationLeaks.length} residual item(s) in the output file; refused to write unverified output.`
4120
+ )
4121
+ );
4122
+ }
4123
+ const written = await files.writeBytes(resolvedOutputPath, redactedDoc.bytes, {
4124
+ overwrite: args.overwrite === true
4125
+ });
4126
+ const safeInputPath = await redactResolvedPath(source.resolvedPath, {
4127
+ owner,
4128
+ sessionId: sessionId || void 0,
4129
+ mode: requestedMode,
4130
+ profile,
4131
+ customTerms
4132
+ });
4133
+ const safeOutputPath = await redactResolvedPath(written.resolvedPath, {
4134
+ owner,
4135
+ sessionId: sessionId || void 0,
4136
+ mode: requestedMode,
4137
+ profile,
4138
+ customTerms
4139
+ });
4140
+ telemetrySessionId = sessionId || void 0;
4141
+ telemetryRedactions = redactedDoc.totalRedactions;
4142
+ telemetryCounts = redactedDoc.counts;
4143
+ return finish(
4144
+ toolOk({
4145
+ input_path: safeInputPath,
4146
+ output_path: safeOutputPath,
4147
+ format: redactedDoc.format,
4148
+ bytes: written.bytes,
4149
+ session_id: sessionId,
4150
+ counts: redactedDoc.counts,
4151
+ total_redactions: redactedDoc.totalRedactions,
4152
+ mode: modeUsed,
4153
+ verified: redactedDoc.verified,
4154
+ metadata_cleared: redactedDoc.metadataCleared,
4155
+ ...redactedDoc.redactedPages ? { redacted_pages: redactedDoc.redactedPages } : {},
4156
+ ...redactedDoc.totalPages !== void 0 ? { total_pages: redactedDoc.totalPages } : {},
4157
+ ...redactedDoc.scannedPages.length > 0 ? { scanned_pages: redactedDoc.scannedPages } : {},
4158
+ ...redactedDoc.warnings.length > 0 ? { warnings: redactedDoc.warnings } : {}
2182
4159
  })
2183
4160
  );
2184
4161
  }
@@ -4737,7 +6714,38 @@ function deriveProxySessionId(headers, body) {
4737
6714
  }
4738
6715
  var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
4739
6716
  var DATA_URI_TEXT_BASE64_RE = /^data:((?:text\/[a-z0-9.+-]+|application\/(?:json|xml|csv|x-ndjson|javascript))[^;,]*);base64,([A-Za-z0-9+/=\s]+)$/i;
4740
- var DATA_URI_ANY_RE = /^data:([^;,]+);base64,/i;
6717
+ var DATA_URI_ANY_RE = /^data:([^;,]+);base64,([A-Za-z0-9+/=\s]+)$/i;
6718
+ async function tryRedactBase64Document(encoded, mediaType, fileName, redactDocument, noteBinary) {
6719
+ if (!redactDocument) {
6720
+ noteBinary(mediaType);
6721
+ return encoded;
6722
+ }
6723
+ try {
6724
+ const rawBuf = Buffer.from(encoded, "base64");
6725
+ if (rawBuf.byteLength === 0 || rawBuf.byteLength > MAX_BODY_BYTES) {
6726
+ noteBinary(mediaType);
6727
+ return encoded;
6728
+ }
6729
+ const bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
6730
+ const detected = detectFileFormat(bytes, fileName, mediaType);
6731
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
6732
+ noteBinary(mediaType);
6733
+ return encoded;
6734
+ }
6735
+ const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
6736
+ if (!res.verified) {
6737
+ noteBinary(`${mediaType} (unverified)`);
6738
+ return encoded;
6739
+ }
6740
+ if (res.scannedPages.length > 0) {
6741
+ noteBinary(`${mediaType} (scanned)`);
6742
+ }
6743
+ return Buffer.from(res.bytes).toString("base64");
6744
+ } catch {
6745
+ noteBinary(mediaType);
6746
+ return encoded;
6747
+ }
6748
+ }
4741
6749
  async function redactBase64Utf8(encoded, redactString, kind) {
4742
6750
  try {
4743
6751
  const rawBuf = Buffer.from(encoded, "base64");
@@ -4800,17 +6808,37 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4800
6808
  await redactContentBlocks(block.output, kind);
4801
6809
  }
4802
6810
  if (typeof block.file_data === "string") {
6811
+ const fileName = typeof block.filename === "string" ? block.filename : void 0;
4803
6812
  const match = DATA_URI_TEXT_BASE64_RE.exec(block.file_data);
4804
6813
  if (match?.[1] && match[2]) {
4805
6814
  const nextB64 = await redactBase64Utf8(match[2], redactString, kind);
4806
6815
  block.file_data = `data:${match[1]};base64,${nextB64}`;
4807
6816
  } else if (block.file_data.startsWith("data:")) {
4808
- const anyMime = DATA_URI_ANY_RE.exec(block.file_data)?.[1] ?? "application/octet-stream";
4809
- noteBinary(anyMime);
6817
+ const anyMatch = DATA_URI_ANY_RE.exec(block.file_data);
6818
+ const anyMime = anyMatch?.[1] ?? "application/octet-stream";
6819
+ const b64Payload = anyMatch?.[2];
6820
+ if (b64Payload) {
6821
+ const nextB64 = await tryRedactBase64Document(
6822
+ b64Payload,
6823
+ anyMime,
6824
+ fileName,
6825
+ options.redactDocument,
6826
+ noteBinary
6827
+ );
6828
+ block.file_data = `data:${anyMime};base64,${nextB64}`;
6829
+ } else {
6830
+ noteBinary(anyMime);
6831
+ }
4810
6832
  } else {
4811
6833
  const rawBuf = Buffer.from(block.file_data, "base64");
4812
6834
  if (rawBuf.includes(0)) {
4813
- noteBinary("application/octet-stream");
6835
+ block.file_data = await tryRedactBase64Document(
6836
+ block.file_data,
6837
+ "application/octet-stream",
6838
+ fileName,
6839
+ options.redactDocument,
6840
+ noteBinary
6841
+ );
4814
6842
  } else {
4815
6843
  block.file_data = await redactBase64Utf8(block.file_data, redactString, kind);
4816
6844
  }
@@ -4821,6 +6849,18 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4821
6849
  block.source.data = await redactString(block.source.data, kind);
4822
6850
  } else if (block.source.type === "base64" && typeof block.source.data === "string" && typeof block.source.media_type === "string" && TEXT_BASE64_MEDIA_RE.test(block.source.media_type)) {
4823
6851
  block.source.data = await redactBase64Utf8(block.source.data, redactString, kind);
6852
+ } else if (block.source.type === "base64" && typeof block.source.data === "string") {
6853
+ const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
6854
+ if (blockType !== "image" && blockType !== "input_image") {
6855
+ const docTitle = typeof block.title === "string" ? block.title : void 0;
6856
+ block.source.data = await tryRedactBase64Document(
6857
+ block.source.data,
6858
+ mediaType,
6859
+ docTitle,
6860
+ options.redactDocument,
6861
+ noteBinary
6862
+ );
6863
+ }
4824
6864
  } else if (block.source.type === "base64") {
4825
6865
  const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
4826
6866
  if (blockType !== "image" && blockType !== "input_image") {
@@ -4901,7 +6941,9 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4901
6941
  for (const batchItem of clone.requests) {
4902
6942
  if (isPlainObject(batchItem) && isPlainObject(batchItem.params)) {
4903
6943
  batchItem.params = await redactLlmRequestBody(batchItem.params, redactString, {
4904
- mutate: true
6944
+ mutate: true,
6945
+ onBinaryAttachment: options.onBinaryAttachment,
6946
+ redactDocument: options.redactDocument
4905
6947
  });
4906
6948
  }
4907
6949
  }
@@ -6508,7 +8550,43 @@ async function startMaskeraProxy(options = {}) {
6508
8550
  mutate: true,
6509
8551
  onBinaryAttachment: (kind) => {
6510
8552
  binaryAttachments.add(kind);
6511
- }
8553
+ },
8554
+ redactDocument: async (bytes, info) => redactFile(
8555
+ bytes,
8556
+ async (text) => {
8557
+ const { result } = await engine.redact(text, {
8558
+ profile: options.profile,
8559
+ customTerms: options.customTerms
8560
+ });
8561
+ const applied = vault.apply(text, result, sessionId, proxyVaultOwner);
8562
+ stats.redactions += applied.totalRedactions;
8563
+ mergeCounts(stats.counts, applied.counts);
8564
+ if (applied.totalRedactions > 0) {
8565
+ if (!messageTokensForSession) {
8566
+ messageTokensForSession = /* @__PURE__ */ new Set();
8567
+ messageTokensBySession.set(sessionId, messageTokensForSession);
8568
+ }
8569
+ for (const tok of Object.keys(applied.map)) {
8570
+ messageTokensForSession.add(tok);
8571
+ }
8572
+ }
8573
+ if (messagePreviews.length < 6 && applied.redacted.trim()) {
8574
+ const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
8575
+ messagePreviews.push(snippet);
8576
+ }
8577
+ return {
8578
+ text: applied.redacted,
8579
+ redactions: applied.redactions,
8580
+ map: applied.map,
8581
+ restore: (t) => vault.restore(t, { sessionId, owner: proxyVaultOwner }).restored
8582
+ };
8583
+ },
8584
+ {
8585
+ fileName: info.fileName,
8586
+ mimeType: info.mimeType,
8587
+ verify: true
8588
+ }
8589
+ )
6512
8590
  }
6513
8591
  );
6514
8592
  redactedPreview.push(...messagePreviews.length > 0 ? messagePreviews : fallbackPreviews);
@@ -7379,7 +9457,7 @@ function isServiceAction(value) {
7379
9457
  function parseArgs(argv) {
7380
9458
  let startIndex = 0;
7381
9459
  let command = "mcp";
7382
- if (argv[0] === "proxy" || argv[0] === "wrap" || argv[0] === "guard" || argv[0] === "mcp" || argv[0] === "install" || argv[0] === "doctor" || argv[0] === "service") {
9460
+ if (argv[0] === "proxy" || argv[0] === "wrap" || argv[0] === "guard" || argv[0] === "redact" || argv[0] === "mcp" || argv[0] === "install" || argv[0] === "doctor" || argv[0] === "service") {
7383
9461
  command = argv[0];
7384
9462
  startIndex = 1;
7385
9463
  }
@@ -7407,6 +9485,9 @@ function parseArgs(argv) {
7407
9485
  let redact2 = false;
7408
9486
  let noProxy = process.env.MASKERA_GUARD_NO_PROXY === "1";
7409
9487
  let file;
9488
+ let outFile;
9489
+ let overwrite = false;
9490
+ let showLabels = true;
7410
9491
  let client;
7411
9492
  let transport = "stdio";
7412
9493
  let mcpUrl;
@@ -7540,6 +9621,14 @@ function parseArgs(argv) {
7540
9621
  const { value, nextIndex } = takeValue(flag, arg, i, true);
7541
9622
  i = nextIndex;
7542
9623
  file = value;
9624
+ } else if (flag === "--out" || flag === "-o") {
9625
+ const { value, nextIndex } = takeValue(flag, arg, i, true);
9626
+ i = nextIndex;
9627
+ outFile = value;
9628
+ } else if (flag === "--overwrite") {
9629
+ overwrite = true;
9630
+ } else if (flag === "--no-labels") {
9631
+ showLabels = false;
7543
9632
  } else if (flag === "--transport") {
7544
9633
  const { value, nextIndex } = takeValue(flag, arg, i);
7545
9634
  i = nextIndex;
@@ -7573,6 +9662,8 @@ function parseArgs(argv) {
7573
9662
  `Unknown client "${arg}". Expected one of: ${SUPPORTED_CLIENTS.join(", ")}, or all.`
7574
9663
  );
7575
9664
  }
9665
+ } else if (command === "redact" && !arg.startsWith("-") && !file) {
9666
+ file = arg;
7576
9667
  } else if (command === "service" && !arg.startsWith("-") && !serviceAction) {
7577
9668
  if (!isServiceAction(arg)) {
7578
9669
  throw new Error(`Unknown service action "${arg}". Expected: install, status, or uninstall.`);
@@ -7612,6 +9703,9 @@ function parseArgs(argv) {
7612
9703
  redact: redact2,
7613
9704
  noProxy,
7614
9705
  file,
9706
+ outFile,
9707
+ overwrite,
9708
+ showLabels,
7615
9709
  client,
7616
9710
  transport,
7617
9711
  mcpUrl,
@@ -7637,16 +9731,18 @@ function printHelp() {
7637
9731
  " maskera-mcp [mcp] [--root <dir>] [--no-raw-restore] [--read-only] [--approval-mode automatic|native] [--rules-only]",
7638
9732
  " maskera-mcp proxy [--port 8787] [--host 127.0.0.1] [--root <dir>] [--open] [--upstream <url>] [--audit-log <file.jsonl>] [--no-raw-restore] [--read-only] [--approval-mode automatic|browser] [--rules-only] [--no-restore] [--block-binary]",
7639
9733
  " maskera-mcp wrap [flags] -- <cmd> [args...]",
7640
- " maskera-mcp guard [--redact] [--file <path>] [--proxy-url <url>] [--no-proxy] [--rules-only]",
9734
+ " maskera-mcp guard [--redact] [--file <path>] [--out <path>] [--overwrite] [--proxy-url <url>] [--no-proxy] [--rules-only]",
9735
+ " maskera-mcp redact <file> [-o|--out <path>] [--overwrite] [--no-labels] [--profile general|clinical] [--rules-only] [--json]",
7641
9736
  ` maskera-mcp install [client|all] [--transport stdio|http] [--url <http://127.0.0.1:8787/mcp>] [--root <dir>] [--apply] [--project] [--with-hook] [--no-raw-restore] [--read-only] [--config <path>] [--receipt <file.json>] [--no-verify] [--dry-run]`,
7642
9737
  " maskera-mcp doctor [--root <dir>] [--proxy-url <url>] [--receipt <file.json>] [--rules-only] [--json]",
7643
9738
  " maskera-mcp service <install|status|uninstall> [--port 8787] [--root <dir>] [--no-raw-restore] [--rules-only] [--dry-run] [--json]",
7644
9739
  "",
7645
9740
  "Subcommands:",
7646
- " mcp (default) Start MCP stdio server (read/write/list/search files, redact, restore, prompts, resources)",
9741
+ " mcp (default) Start MCP stdio server (read/write/redact/list/search UTF-8/PDF/DOCX/XLSX files, restore, prompts, resources)",
7647
9742
  " proxy Start local Anthropic/OpenAI HTTP reverse proxy + Streamable HTTP /mcp + live inspector",
7648
9743
  " wrap One-command launcher: starts ephemeral local proxy, verifies 0 leaks, runs any CLI with proxy env vars, prints session receipt on exit",
7649
- " guard Check stdin/file/hook JSON for PII (exits 2 if PII found, or outputs redacted text with --redact)",
9744
+ " guard Check stdin or UTF-8/PDF/DOCX/XLSX file for PII (exits 2 if PII found, or outputs redacted text/file with --redact)",
9745
+ " redact Redact a local PDF, DOCX, XLSX, or UTF-8 text file to a verified clean output file on disk",
7650
9746
  ` install Auto-detect or configure an MCP client (${SUPPORTED_CLIENTS.join(", ")}, or all) + optional guard hook (--with-hook) + setup receipt`,
7651
9747
  " doctor Verify Node runtime, workspace roots, local Swedish PII roundtrip, and running proxy + /mcp",
7652
9748
  " service Install, inspect, or remove a local launchd (macOS) or systemd --user (Linux) background proxy service",
@@ -7914,22 +10010,161 @@ Verify: ${primary.verifyStep}
7914
10010
  if (receipt && !receipt.ok) process.exit(1);
7915
10011
  return;
7916
10012
  }
10013
+ if (args.command === "redact") {
10014
+ if (!args.file) {
10015
+ throw new Error(
10016
+ "Missing input file. Usage: maskera-mcp redact <file> [-o <out>] [--overwrite]"
10017
+ );
10018
+ }
10019
+ const buf = await readFile(args.file);
10020
+ if (buf.byteLength > MAX_DEFAULT_FILE_BYTES) {
10021
+ throw new Error(
10022
+ `"${args.file}" is ${buf.byteLength} bytes (max ${MAX_DEFAULT_FILE_BYTES} bytes).`
10023
+ );
10024
+ }
10025
+ const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
10026
+ const engine2 = buildEngine(args);
10027
+ let modeUsed = args.defaultMode === "rules" ? "rules" : "hybrid";
10028
+ const res = await redactFile(
10029
+ bytes,
10030
+ async (text) => {
10031
+ const eng = await engine2.redact(text, {
10032
+ mode: args.defaultMode,
10033
+ profile: args.profile,
10034
+ customTerms: args.customTerms.length > 0 ? args.customTerms : void 0
10035
+ });
10036
+ modeUsed = eng.modeUsed;
10037
+ return eng.result;
10038
+ },
10039
+ {
10040
+ fileName: args.file,
10041
+ pdfStyle: { showLabels: args.showLabels },
10042
+ verify: true
10043
+ }
10044
+ );
10045
+ if (!res.verified) {
10046
+ throw new Error(
10047
+ `Post-redaction verification detected ${res.verificationLeaks.length} residual item(s); refused to write output.`
10048
+ );
10049
+ }
10050
+ const ext = extname(args.file);
10051
+ const stem = ext ? basename(args.file, ext) : basename(args.file);
10052
+ const targetPath = args.outFile ?? join(dirname(args.file), `${stem}.masked${ext}`);
10053
+ await writeFile(targetPath, res.bytes, {
10054
+ flag: args.overwrite ? "w" : "wx",
10055
+ mode: 384
10056
+ }).catch((err) => {
10057
+ if (err.code === "EEXIST") {
10058
+ throw new Error(
10059
+ `Output file already exists: "${targetPath}". Pass --overwrite to replace it.`
10060
+ );
10061
+ }
10062
+ throw err;
10063
+ });
10064
+ const summary = {
10065
+ input: args.file,
10066
+ output: targetPath,
10067
+ format: res.format,
10068
+ bytes: res.bytes.byteLength,
10069
+ mode: modeUsed,
10070
+ totalRedactions: res.totalRedactions,
10071
+ counts: res.counts,
10072
+ verified: res.verified,
10073
+ metadataCleared: res.metadataCleared,
10074
+ ...res.redactedPages ? { redactedPages: res.redactedPages } : {},
10075
+ ...res.totalPages !== void 0 ? { totalPages: res.totalPages } : {},
10076
+ ...res.scannedPages.length > 0 ? { scannedPages: res.scannedPages } : {},
10077
+ ...res.warnings.length > 0 ? { warnings: res.warnings } : {}
10078
+ };
10079
+ if (args.json) {
10080
+ process.stdout.write(`${JSON.stringify(summary, null, 2)}
10081
+ `);
10082
+ } else {
10083
+ const countList = Object.entries(res.counts).map(([k, v]) => `${k}=${v}`).join(", ") || "none";
10084
+ process.stdout.write(
10085
+ `Redacted ${args.file} -> ${targetPath} (${res.format}, ${res.totalRedactions} redaction(s): ${countList}, verified=true)
10086
+ `
10087
+ );
10088
+ if (res.metadataCleared.length > 0) {
10089
+ process.stdout.write(`Metadata cleared: ${res.metadataCleared.join(", ")}
10090
+ `);
10091
+ }
10092
+ for (const warning of res.warnings) {
10093
+ process.stderr.write(`[maskera] Warning: ${warning}
10094
+ `);
10095
+ }
10096
+ }
10097
+ return;
10098
+ }
7917
10099
  if (args.command === "guard") {
7918
10100
  let raw;
7919
10101
  if (args.file) {
7920
10102
  const buf = await readFile(args.file);
7921
- if (buf.byteLength > MAX_GUARD_INPUT_BYTES) {
10103
+ const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
10104
+ const detected = detectFileFormat(bytes, args.file);
10105
+ if (detected.format === "binary") {
10106
+ if (!buf.includes(0)) {
10107
+ throw new Error(`"${args.file}" is not valid UTF-8 text; convert it to UTF-8 first.`);
10108
+ }
7922
10109
  throw new Error(
7923
- `"${args.file}" is ${buf.byteLength} bytes (max ${MAX_GUARD_INPUT_BYTES} bytes for guard).`
10110
+ `"${args.file}" appears to be an unsupported binary file (${detected.mimeType}); supported formats are UTF-8 text, PDF, DOCX, and XLSX.`
7924
10111
  );
7925
10112
  }
7926
- if (buf.includes(0)) {
7927
- throw new Error(`"${args.file}" appears to be a binary file; only UTF-8 text is supported.`);
10113
+ if (args.redact && args.outFile) {
10114
+ if (buf.byteLength > MAX_DEFAULT_FILE_BYTES) {
10115
+ throw new Error(
10116
+ `"${args.file}" is ${buf.byteLength} bytes (max ${MAX_DEFAULT_FILE_BYTES} bytes).`
10117
+ );
10118
+ }
10119
+ const engine2 = buildEngine(args);
10120
+ const docRes = await redactFile(
10121
+ bytes,
10122
+ async (text) => {
10123
+ const eng = await engine2.redact(text, {
10124
+ mode: args.defaultMode,
10125
+ profile: args.profile,
10126
+ customTerms: args.customTerms.length > 0 ? args.customTerms : void 0
10127
+ });
10128
+ return eng.result;
10129
+ },
10130
+ {
10131
+ fileName: args.file,
10132
+ pdfStyle: { showLabels: args.showLabels },
10133
+ verify: true
10134
+ }
10135
+ );
10136
+ if (!docRes.verified) {
10137
+ throw new Error(
10138
+ `Post-redaction verification detected ${docRes.verificationLeaks.length} residual item(s); refused to write output.`
10139
+ );
10140
+ }
10141
+ await writeFile(args.outFile, docRes.bytes, {
10142
+ flag: args.overwrite ? "w" : "wx",
10143
+ mode: 384
10144
+ });
10145
+ for (const warning of docRes.warnings) {
10146
+ process.stderr.write(`[maskera-guard] Warning: ${warning}
10147
+ `);
10148
+ }
10149
+ return;
7928
10150
  }
7929
- try {
10151
+ if (detected.format === "text") {
10152
+ if (buf.byteLength > MAX_GUARD_INPUT_BYTES) {
10153
+ throw new Error(
10154
+ `"${args.file}" is ${buf.byteLength} bytes (max ${MAX_GUARD_INPUT_BYTES} bytes for guard).`
10155
+ );
10156
+ }
7930
10157
  raw = new TextDecoder("utf-8", { fatal: true }).decode(buf);
7931
- } catch {
7932
- throw new Error(`"${args.file}" is not valid UTF-8 text; convert it to UTF-8 first.`);
10158
+ } else {
10159
+ const extracted = await extractFileText(bytes, {
10160
+ fileName: args.file,
10161
+ maxBytes: MAX_DEFAULT_FILE_BYTES
10162
+ });
10163
+ for (const warning of extracted.warnings) {
10164
+ process.stderr.write(`[maskera-guard] Warning: ${warning}
10165
+ `);
10166
+ }
10167
+ raw = extracted.text;
7933
10168
  }
7934
10169
  } else {
7935
10170
  raw = await readStdinAll();