@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/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { randomUUID, createHash } from 'crypto';
2
2
  import { existsSync, constants } from 'fs';
3
- import { readFile, mkdir, realpath, writeFile, stat, access, appendFile, unlink, readdir, lstat, readlink } from 'fs/promises';
4
- import { join, dirname, resolve, isAbsolute, relative, sep, delimiter, extname, posix } from 'path';
3
+ import { readFile, stat, access, mkdir, writeFile, appendFile, unlink, realpath, readdir, lstat, readlink } from 'fs/promises';
4
+ import { join, resolve, dirname, relative, sep, delimiter, isAbsolute, extname, posix } from 'path';
5
5
  import { createRequire } from 'module';
6
+ import { unzipSync, zipSync } from 'fflate';
7
+ import { PDFDocument, PDFName } from 'pdf-lib';
6
8
  import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
7
9
  import { spawn, spawnSync } from 'child_process';
8
10
  import { homedir } from 'os';
@@ -171,6 +173,1714 @@ var ApprovalBroker = class {
171
173
  this.notify();
172
174
  }
173
175
  };
176
+ var MAX_DEFAULT_FILE_BYTES = 25 * 1024 * 1024;
177
+ var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
178
+ var TEXT_MIME_BY_EXT = {
179
+ ".txt": "text/plain",
180
+ ".md": "text/markdown",
181
+ ".markdown": "text/markdown",
182
+ ".csv": "text/csv",
183
+ ".tsv": "text/tab-separated-values",
184
+ ".json": "application/json",
185
+ ".jsonl": "application/x-ndjson",
186
+ ".xml": "application/xml",
187
+ ".yaml": "application/yaml",
188
+ ".yml": "application/yaml",
189
+ ".html": "text/html",
190
+ ".htm": "text/html",
191
+ ".log": "text/plain",
192
+ ".sql": "text/plain",
193
+ ".ts": "text/plain",
194
+ ".tsx": "text/plain",
195
+ ".js": "text/plain",
196
+ ".mjs": "text/plain",
197
+ ".py": "text/plain"
198
+ };
199
+ function extractExtension(fileName) {
200
+ if (!fileName) return "";
201
+ const base = fileName.split(/[\\/]/).pop() ?? "";
202
+ const dot = base.lastIndexOf(".");
203
+ if (dot <= 0) return "";
204
+ return base.slice(dot).toLowerCase();
205
+ }
206
+ function hasPdfHeader(bytes) {
207
+ const limit = Math.min(bytes.byteLength, 1024);
208
+ for (let i = 0; i + 4 < limit; i++) {
209
+ if (bytes[i] === 37 && // %
210
+ bytes[i + 1] === 80 && // P
211
+ bytes[i + 2] === 68 && // D
212
+ bytes[i + 3] === 70 && // F
213
+ bytes[i + 4] === 45) {
214
+ return true;
215
+ }
216
+ }
217
+ return false;
218
+ }
219
+ function hasZipHeader(bytes) {
220
+ if (bytes.byteLength < 4) return false;
221
+ 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);
222
+ }
223
+ function detectOfficeZipFormat(bytes) {
224
+ try {
225
+ let isDocx = false;
226
+ let isXlsx = false;
227
+ let entriesSeen = 0;
228
+ unzipSync(bytes, {
229
+ filter(file) {
230
+ entriesSeen += 1;
231
+ if (entriesSeen > 2e3) return false;
232
+ const name = file.name.toLowerCase();
233
+ if (name === "word/document.xml") isDocx = true;
234
+ if (name === "xl/workbook.xml") isXlsx = true;
235
+ return false;
236
+ }
237
+ });
238
+ if (isDocx) return "docx";
239
+ if (isXlsx) return "xlsx";
240
+ return null;
241
+ } catch {
242
+ return null;
243
+ }
244
+ }
245
+ function mimeTypeForFormat(format, fileName) {
246
+ const ext = extractExtension(fileName);
247
+ return TEXT_MIME_BY_EXT[ext] ?? "text/plain";
248
+ }
249
+ function detectFileFormat(bytes, fileName, mimeType) {
250
+ const ext = extractExtension(fileName);
251
+ const normalizedMime = mimeType?.split(";")[0]?.trim().toLowerCase() ?? "";
252
+ if (hasPdfHeader(bytes)) {
253
+ return { format: "pdf", mimeType: "application/pdf", extension: ".pdf" };
254
+ }
255
+ if (hasZipHeader(bytes)) {
256
+ const office = detectOfficeZipFormat(bytes);
257
+ if (office === "docx") {
258
+ return {
259
+ format: "docx",
260
+ mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
261
+ extension: ".docx"
262
+ };
263
+ }
264
+ if (office === "xlsx") {
265
+ return {
266
+ format: "xlsx",
267
+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
268
+ extension: ".xlsx"
269
+ };
270
+ }
271
+ return {
272
+ format: "binary",
273
+ mimeType: normalizedMime || "application/zip",
274
+ extension: ext || ".zip"
275
+ };
276
+ }
277
+ for (let i = 0; i < bytes.byteLength; i++) {
278
+ if (bytes[i] === 0) {
279
+ return {
280
+ format: "binary",
281
+ mimeType: normalizedMime || "application/octet-stream",
282
+ extension: ext
283
+ };
284
+ }
285
+ }
286
+ try {
287
+ UTF8_DECODER.decode(bytes);
288
+ return {
289
+ format: "text",
290
+ mimeType: normalizedMime && (normalizedMime.startsWith("text/") || normalizedMime.includes("json")) ? normalizedMime : mimeTypeForFormat("text", fileName),
291
+ extension: ext || ".txt"
292
+ };
293
+ } catch {
294
+ return {
295
+ format: "binary",
296
+ mimeType: normalizedMime || "application/octet-stream",
297
+ extension: ext
298
+ };
299
+ }
300
+ }
301
+ var MAX_ZIP_ENTRIES = 2e3;
302
+ var MAX_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
303
+ var UTF8_DECODER2 = new TextDecoder("utf-8", { fatal: false });
304
+ var UTF8_ENCODER = new TextEncoder();
305
+ function decodeUtf8(bytes) {
306
+ return UTF8_DECODER2.decode(bytes);
307
+ }
308
+ function encodeUtf8(text) {
309
+ return UTF8_ENCODER.encode(text);
310
+ }
311
+ function unzipSafely(bytes) {
312
+ let entryCount = 0;
313
+ let totalUncompressed = 0;
314
+ const files = unzipSync(bytes, {
315
+ filter(file) {
316
+ entryCount += 1;
317
+ if (entryCount > MAX_ZIP_ENTRIES) {
318
+ throw new Error(`Archive exceeds max allowed entry count (${MAX_ZIP_ENTRIES}).`);
319
+ }
320
+ totalUncompressed += file.originalSize;
321
+ if (totalUncompressed > MAX_ZIP_UNCOMPRESSED_BYTES) {
322
+ throw new Error(
323
+ `Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
324
+ );
325
+ }
326
+ return true;
327
+ }
328
+ });
329
+ let actualBytes = 0;
330
+ for (const data of Object.values(files)) {
331
+ actualBytes += data.byteLength;
332
+ if (actualBytes > MAX_ZIP_UNCOMPRESSED_BYTES) {
333
+ throw new Error(
334
+ `Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
335
+ );
336
+ }
337
+ }
338
+ return files;
339
+ }
340
+ function zipFiles(files) {
341
+ return zipSync(files, { level: 6 });
342
+ }
343
+ function unescapeXml(value) {
344
+ return value.replace(
345
+ /&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,
346
+ (match, entity) => {
347
+ if (entity === "amp") return "&";
348
+ if (entity === "lt") return "<";
349
+ if (entity === "gt") return ">";
350
+ if (entity === "quot") return '"';
351
+ if (entity === "apos") return "'";
352
+ if (entity.startsWith("#x") || entity.startsWith("#X")) {
353
+ const code = Number.parseInt(entity.slice(2), 16);
354
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
355
+ }
356
+ if (entity.startsWith("#")) {
357
+ const code = Number.parseInt(entity.slice(1), 10);
358
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
359
+ }
360
+ return match;
361
+ }
362
+ );
363
+ }
364
+ function escapeXml(value) {
365
+ let out = "";
366
+ for (let i = 0; i < value.length; i++) {
367
+ const ch = value[i] ?? "";
368
+ const code = value.charCodeAt(i);
369
+ if (code < 32 && code !== 9 && code !== 10 && code !== 13) continue;
370
+ if (ch === "&") out += "&amp;";
371
+ else if (ch === "<") out += "&lt;";
372
+ else if (ch === ">") out += "&gt;";
373
+ else if (ch === '"') out += "&quot;";
374
+ else if (ch === "'") out += "&apos;";
375
+ else out += ch;
376
+ }
377
+ return out;
378
+ }
379
+ function escapeRegexLiteral(value) {
380
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
381
+ }
382
+ function extractXmlTextContainers(xml, containerTag, textTags, options) {
383
+ const escapedContainer = escapeRegexLiteral(containerTag);
384
+ const containerRe = new RegExp(
385
+ `<${escapedContainer}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${escapedContainer}>`,
386
+ "g"
387
+ );
388
+ const sepTags = options?.separatorTags ?? {};
389
+ const sepTagNames = Object.keys(sepTags);
390
+ const allTagAlternation = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
391
+ const tokenRe = new RegExp(
392
+ `<(${allTagAlternation})(?:\\s[^>]*)?\\/>|<(${textTags.map(escapeRegexLiteral).join("|")})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\2>`,
393
+ "g"
394
+ );
395
+ const containers = [];
396
+ let containerMatch = containerRe.exec(xml);
397
+ while (containerMatch !== null) {
398
+ const inner = containerMatch[1] ?? "";
399
+ const openEndOffset = containerMatch.index + containerMatch[0].indexOf(">") + 1;
400
+ const nodes = [];
401
+ let combined = "";
402
+ tokenRe.lastIndex = 0;
403
+ let tok = tokenRe.exec(inner);
404
+ while (tok !== null) {
405
+ const selfClosingName = tok[1];
406
+ if (selfClosingName !== void 0) {
407
+ const sepChar = sepTags[selfClosingName];
408
+ if (sepChar) {
409
+ combined += sepChar;
410
+ }
411
+ tok = tokenRe.exec(inner);
412
+ continue;
413
+ }
414
+ const tagName = tok[2] ?? "";
415
+ const attrs = tok[3] ?? "";
416
+ const rawContent = tok[4] ?? "";
417
+ const openTag = `<${tagName}${attrs}>`;
418
+ const unescaped = unescapeXml(rawContent);
419
+ const tagStart = openEndOffset + tok.index;
420
+ const contentStart = tagStart + openTag.length;
421
+ const contentEnd = contentStart + rawContent.length;
422
+ const combinedStart = combined.length;
423
+ combined += unescaped;
424
+ const combinedEnd = combined.length;
425
+ nodes.push({
426
+ tagStart,
427
+ contentStart,
428
+ contentEnd,
429
+ openTag,
430
+ text: unescaped,
431
+ combinedStart,
432
+ combinedEnd
433
+ });
434
+ tok = tokenRe.exec(inner);
435
+ }
436
+ if (nodes.length > 0) {
437
+ containers.push({ text: combined, nodes });
438
+ }
439
+ containerMatch = containerRe.exec(xml);
440
+ }
441
+ return containers;
442
+ }
443
+ function ensurePreserveSpace(openTag, nextText) {
444
+ if (!nextText) return openTag;
445
+ const needsPreserve = /^\s|\s$/.test(nextText);
446
+ if (!needsPreserve || openTag.includes("xml:space=")) return openTag;
447
+ return `${openTag.slice(0, -1)} xml:space="preserve">`;
448
+ }
449
+ function applyXmlContainerReplacements(xml, containers, replacementsByContainer) {
450
+ const rawPatches = [];
451
+ for (const [containerIndex, spans] of replacementsByContainer.entries()) {
452
+ if (spans.length === 0) continue;
453
+ const container = containers[containerIndex];
454
+ if (!container) continue;
455
+ const sortedSpans = [...spans].sort((a, b) => a.start - b.start);
456
+ const nextNodeTexts = container.nodes.map((node) => node.text);
457
+ for (let s = sortedSpans.length - 1; s >= 0; s--) {
458
+ const span = sortedSpans[s];
459
+ if (!span || span.end <= span.start) continue;
460
+ let placedReplacement = false;
461
+ for (let n = 0; n < container.nodes.length; n++) {
462
+ const node = container.nodes[n];
463
+ if (!node) continue;
464
+ const overlapStart = Math.max(span.start, node.combinedStart);
465
+ const overlapEnd = Math.min(span.end, node.combinedEnd);
466
+ if (overlapEnd <= overlapStart) continue;
467
+ const localStart = overlapStart - node.combinedStart;
468
+ const localEnd = overlapEnd - node.combinedStart;
469
+ const current = nextNodeTexts[n] ?? "";
470
+ const insert = placedReplacement ? "" : span.replacement;
471
+ placedReplacement = true;
472
+ nextNodeTexts[n] = current.slice(0, localStart) + insert + current.slice(localEnd);
473
+ }
474
+ }
475
+ for (let n = 0; n < container.nodes.length; n++) {
476
+ const node = container.nodes[n];
477
+ const nextText = nextNodeTexts[n];
478
+ if (!node || nextText === void 0 || nextText === node.text) continue;
479
+ const nextOpenTag = ensurePreserveSpace(node.openTag, nextText);
480
+ rawPatches.push({
481
+ start: node.tagStart,
482
+ end: node.contentEnd,
483
+ replacement: `${nextOpenTag}${escapeXml(nextText)}`
484
+ });
485
+ }
486
+ }
487
+ if (rawPatches.length === 0) return xml;
488
+ rawPatches.sort((a, b) => b.start - a.start);
489
+ let out = xml;
490
+ for (const patch of rawPatches) {
491
+ out = out.slice(0, patch.start) + patch.replacement + out.slice(patch.end);
492
+ }
493
+ return out;
494
+ }
495
+ function scrubXmlMetadata(xml, tagNames) {
496
+ const found = {};
497
+ const cleared = [];
498
+ let nextXml = xml;
499
+ for (const tag of tagNames) {
500
+ const escaped = escapeRegexLiteral(tag);
501
+ const re = new RegExp(`(<${escaped}(?:\\s[^>]*)?>)([\\s\\S]*?)(<\\/${escaped}>)`, "g");
502
+ nextXml = nextXml.replace(re, (_match, open, inner, close) => {
503
+ const text = unescapeXml(inner).trim();
504
+ if (text.length > 0) {
505
+ found[tag] = text;
506
+ cleared.push(tag);
507
+ }
508
+ return `${open}${close}`;
509
+ });
510
+ }
511
+ return { xml: nextXml, found, cleared };
512
+ }
513
+ var CORE_META_TAGS = [
514
+ "dc:creator",
515
+ "cp:lastModifiedBy",
516
+ "dc:title",
517
+ "dc:subject",
518
+ "dc:description",
519
+ "cp:keywords"
520
+ ];
521
+ var APP_META_TAGS = ["Company", "Manager"];
522
+ var DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
523
+ var XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
524
+ var DOCX_TEXT_PART_RE = /^word\/(?:document|header\d+|footer\d+|footnotes|endnotes|comments)\.xml$/i;
525
+ var XLSX_SHEET_PART_RE = /^xl\/worksheets\/sheet\d+\.xml$/i;
526
+ var XLSX_COMMENT_PART_RE = /^xl\/comments\d*\.xml$/i;
527
+ function countRedactionsByLabel(redactions) {
528
+ const counts = {};
529
+ for (const r of redactions) {
530
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
531
+ }
532
+ return counts;
533
+ }
534
+ function scrubDocxReviewAuthors(xml) {
535
+ const stripped = [];
536
+ const next = xml.replace(
537
+ /(<w:(?:comment|ins|del|moveFrom|moveTo)\b[^>]*?\bw:author=")([^"]*)(")/g,
538
+ (_m, open, val, close) => {
539
+ const cleaned = unescapeXml(val).trim();
540
+ if (cleaned) stripped.push(cleaned);
541
+ return `${open}${close}`;
542
+ }
543
+ );
544
+ return { xml: next, stripped };
545
+ }
546
+ function scrubXlsxCommentAuthors(xml) {
547
+ const stripped = [];
548
+ const next = xml.replace(
549
+ /(<author(?:\s[^>]*)?>)([\s\S]*?)(<\/author>)/g,
550
+ (_m, open, inner, close) => {
551
+ const cleaned = unescapeXml(inner).trim();
552
+ if (cleaned) stripped.push(cleaned);
553
+ return `${open}${close}`;
554
+ }
555
+ );
556
+ return { xml: next, stripped };
557
+ }
558
+ async function redactRelsTargets(archive, redactFn) {
559
+ const cleared = [];
560
+ const originalValues = [];
561
+ for (const [entryName, raw] of Object.entries(archive)) {
562
+ if (!entryName.toLowerCase().endsWith(".rels")) continue;
563
+ const xml = decodeUtf8(raw);
564
+ const relRe = /<Relationship\b[^>]*>/g;
565
+ const patches = [];
566
+ let relMatch = relRe.exec(xml);
567
+ while (relMatch !== null) {
568
+ const tag = relMatch[0];
569
+ const targetMatch = /\bTarget="([^"]*)"/.exec(tag);
570
+ if (targetMatch?.[1]) {
571
+ const rawTarget = unescapeXml(targetMatch[1]);
572
+ const isExternal = /\bTargetMode="External"/i.test(tag) || /^(?:mailto:|tel:|https?:)/i.test(rawTarget);
573
+ if (isExternal) {
574
+ const res = await redactFn(rawTarget);
575
+ if (res.redactions.length > 0) {
576
+ for (const r of res.redactions) originalValues.push(r.value);
577
+ const nextTag = tag.replace(/\bTarget="([^"]*)"/, `Target="${escapeXml(res.text)}"`);
578
+ patches.push({
579
+ start: relMatch.index,
580
+ end: relMatch.index + tag.length,
581
+ replacement: nextTag
582
+ });
583
+ }
584
+ }
585
+ }
586
+ relMatch = relRe.exec(xml);
587
+ }
588
+ if (patches.length > 0) {
589
+ let nextXml = xml;
590
+ for (let i = patches.length - 1; i >= 0; i--) {
591
+ const p = patches[i];
592
+ if (!p) continue;
593
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
594
+ }
595
+ archive[entryName] = encodeUtf8(nextXml);
596
+ cleared.push(`${entryName}:Target`);
597
+ }
598
+ }
599
+ return { cleared, originalValues };
600
+ }
601
+ async function redactDocxInstrText(xml, redactFn) {
602
+ const originalValues = [];
603
+ const instrRe = /(<w:instrText(?:\s[^>]*)?>)([\s\S]*?)(<\/w:instrText>)/g;
604
+ const patches = [];
605
+ let m = instrRe.exec(xml);
606
+ while (m !== null) {
607
+ const open = m[1] ?? "";
608
+ const rawInner = m[2] ?? "";
609
+ const close = m[3] ?? "";
610
+ const text = unescapeXml(rawInner);
611
+ if (text.trim().length > 0) {
612
+ const res = await redactFn(text);
613
+ if (res.redactions.length > 0) {
614
+ for (const r of res.redactions) originalValues.push(r.value);
615
+ patches.push({
616
+ start: m.index,
617
+ end: m.index + m[0].length,
618
+ replacement: `${open}${escapeXml(res.text)}${close}`
619
+ });
620
+ }
621
+ }
622
+ m = instrRe.exec(xml);
623
+ }
624
+ if (patches.length === 0) return { xml, originalValues };
625
+ let out = xml;
626
+ for (let i = patches.length - 1; i >= 0; i--) {
627
+ const p = patches[i];
628
+ if (!p) continue;
629
+ out = out.slice(0, p.start) + p.replacement + out.slice(p.end);
630
+ }
631
+ return { xml: out, originalValues };
632
+ }
633
+ function sanitizeExcelSheetName(raw, usedNames) {
634
+ let cleaned = raw.replace(/[\\/?*[\]:]/g, "").replace(/\s+/g, " ").trim();
635
+ if (!cleaned) cleaned = "Sheet";
636
+ if (cleaned.length > 31) cleaned = cleaned.slice(0, 31).trim();
637
+ let candidate = cleaned;
638
+ let suffix = 2;
639
+ while (usedNames.has(candidate.toLowerCase())) {
640
+ const tag = `_${suffix}`;
641
+ candidate = `${cleaned.slice(0, Math.max(1, 31 - tag.length))}${tag}`;
642
+ suffix += 1;
643
+ }
644
+ usedNames.add(candidate.toLowerCase());
645
+ return candidate;
646
+ }
647
+ async function redactXlsxWorkbookSheetNames(archive, redactFn) {
648
+ const wbKey = Object.keys(archive).find((k) => k.toLowerCase() === "xl/workbook.xml");
649
+ if (!wbKey || !archive[wbKey]) return { cleared: [], originalValues: [] };
650
+ const xml = decodeUtf8(archive[wbKey]);
651
+ const sheetRe = /<sheet\b[^>]*>/g;
652
+ const usedNames = /* @__PURE__ */ new Set();
653
+ const patches = [];
654
+ const originalValues = [];
655
+ let m = sheetRe.exec(xml);
656
+ while (m !== null) {
657
+ const tag = m[0];
658
+ const nameMatch = /\bname="([^"]*)"/.exec(tag);
659
+ if (nameMatch?.[1]) {
660
+ const sheetName = unescapeXml(nameMatch[1]);
661
+ const res = await redactFn(sheetName);
662
+ if (res.redactions.length > 0) {
663
+ for (const r of res.redactions) originalValues.push(r.value);
664
+ const safeName = sanitizeExcelSheetName(res.text, usedNames);
665
+ const nextTag = tag.replace(/\bname="([^"]*)"/, `name="${escapeXml(safeName)}"`);
666
+ patches.push({
667
+ start: m.index,
668
+ end: m.index + tag.length,
669
+ replacement: nextTag
670
+ });
671
+ } else {
672
+ usedNames.add(sheetName.toLowerCase());
673
+ }
674
+ }
675
+ m = sheetRe.exec(xml);
676
+ }
677
+ if (patches.length === 0) return { cleared: [], originalValues: [] };
678
+ let nextXml = xml;
679
+ for (let i = patches.length - 1; i >= 0; i--) {
680
+ const p = patches[i];
681
+ if (!p) continue;
682
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
683
+ }
684
+ archive[wbKey] = encodeUtf8(nextXml);
685
+ return { cleared: [`${wbKey}:sheetName`], originalValues };
686
+ }
687
+ function listDocxTextParts(entryNames) {
688
+ return entryNames.filter((name) => DOCX_TEXT_PART_RE.test(name)).sort((a, b) => {
689
+ if (a.toLowerCase() === "word/document.xml") return -1;
690
+ if (b.toLowerCase() === "word/document.xml") return 1;
691
+ return a.localeCompare(b);
692
+ });
693
+ }
694
+ function listXlsxParts(entryNames) {
695
+ const sharedStrings = entryNames.find((n) => n.toLowerCase() === "xl/sharedstrings.xml");
696
+ const sheets = entryNames.filter((n) => XLSX_SHEET_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
697
+ const comments = entryNames.filter((n) => XLSX_COMMENT_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
698
+ return { sharedStrings, sheets, comments };
699
+ }
700
+ function extractOfficeMetadata(archive) {
701
+ const metadata = {};
702
+ const cleared = [];
703
+ const updatedArchive = { ...archive };
704
+ const coreKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/core.xml");
705
+ if (coreKey && archive[coreKey]) {
706
+ const res = scrubXmlMetadata(decodeUtf8(archive[coreKey]), CORE_META_TAGS);
707
+ Object.assign(metadata, res.found);
708
+ cleared.push(...res.cleared);
709
+ updatedArchive[coreKey] = encodeUtf8(res.xml);
710
+ }
711
+ const appKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/app.xml");
712
+ if (appKey && archive[appKey]) {
713
+ const res = scrubXmlMetadata(decodeUtf8(archive[appKey]), APP_META_TAGS);
714
+ Object.assign(metadata, res.found);
715
+ cleared.push(...res.cleared);
716
+ updatedArchive[appKey] = encodeUtf8(res.xml);
717
+ }
718
+ return { metadata, cleared, updatedArchive };
719
+ }
720
+ function mapRedactionsToPartContainers(parts, redactions) {
721
+ const byPart = /* @__PURE__ */ new Map();
722
+ for (const r of redactions) {
723
+ for (const part of parts) {
724
+ let partMap = byPart.get(part.partPath);
725
+ for (let i = 0; i < part.containerOffsets.length; i++) {
726
+ const range = part.containerOffsets[i];
727
+ if (!range) continue;
728
+ if (r.end <= range.start || r.start >= range.end) continue;
729
+ const localStart = Math.max(0, r.start - range.start);
730
+ const localEnd = Math.min(range.end - range.start, r.end - range.start);
731
+ if (localEnd <= localStart) continue;
732
+ if (!partMap) {
733
+ partMap = /* @__PURE__ */ new Map();
734
+ byPart.set(part.partPath, partMap);
735
+ }
736
+ const list = partMap.get(i) ?? [];
737
+ list.push({ start: localStart, end: localEnd, replacement: r.replacement });
738
+ partMap.set(i, list);
739
+ }
740
+ }
741
+ }
742
+ return byPart;
743
+ }
744
+ function extractDocx(bytes) {
745
+ const archive = unzipSafely(bytes);
746
+ const parts = listDocxTextParts(Object.keys(archive));
747
+ const sections = [];
748
+ for (const partPath of parts) {
749
+ const raw = archive[partPath];
750
+ if (!raw) continue;
751
+ const xml = decodeUtf8(raw);
752
+ const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
753
+ separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
754
+ });
755
+ const partText = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
756
+ if (partText.length > 0) {
757
+ sections.push({
758
+ id: partPath,
759
+ label: partPath.replace(/^word\//i, "").replace(/\.xml$/i, ""),
760
+ text: partText
761
+ });
762
+ }
763
+ }
764
+ const { metadata } = extractOfficeMetadata(archive);
765
+ const fullText = sections.map((s) => s.text).join("\n\n");
766
+ return {
767
+ format: "docx",
768
+ mimeType: DOCX_MIME,
769
+ text: fullText,
770
+ sections,
771
+ metadata,
772
+ warnings: [],
773
+ scannedPages: []
774
+ };
775
+ }
776
+ async function redactDocx(bytes, redactFn) {
777
+ const archive = unzipSafely(bytes);
778
+ const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
779
+ const metadataValues = Object.values(metadata);
780
+ const partPaths = listDocxTextParts(Object.keys(updatedArchive));
781
+ const parts = [];
782
+ const textChunks = [];
783
+ let cursor = 0;
784
+ for (const partPath of partPaths) {
785
+ const raw = updatedArchive[partPath];
786
+ if (!raw) continue;
787
+ const rawXml = decodeUtf8(raw);
788
+ const { xml, stripped } = scrubDocxReviewAuthors(rawXml);
789
+ if (stripped.length > 0) {
790
+ metadataCleared.push(`${partPath}:w:author`);
791
+ metadataValues.push(...stripped);
792
+ }
793
+ const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
794
+ separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
795
+ });
796
+ const containerOffsets = [];
797
+ for (const container of containers) {
798
+ if (container.text.length === 0) {
799
+ containerOffsets.push({ start: cursor, end: cursor });
800
+ continue;
801
+ }
802
+ if (textChunks.length > 0) {
803
+ textChunks.push("\n\n");
804
+ cursor += 2;
805
+ }
806
+ const start = cursor;
807
+ textChunks.push(container.text);
808
+ cursor += container.text.length;
809
+ containerOffsets.push({ start, end: cursor });
810
+ }
811
+ parts.push({ partPath, xml, containers, containerOffsets });
812
+ }
813
+ const combinedText = textChunks.join("");
814
+ const result = await redactFn(combinedText);
815
+ const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
816
+ for (const part of parts) {
817
+ const partMap = replacementsByPart.get(part.partPath);
818
+ let nextXml = partMap ? applyXmlContainerReplacements(part.xml, part.containers, partMap) : part.xml;
819
+ const instr = await redactDocxInstrText(nextXml, redactFn);
820
+ if (instr.originalValues.length > 0) {
821
+ nextXml = instr.xml;
822
+ metadataCleared.push(`${part.partPath}:w:instrText`);
823
+ metadataValues.push(...instr.originalValues);
824
+ }
825
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
826
+ }
827
+ const relsRes = await redactRelsTargets(updatedArchive, redactFn);
828
+ metadataCleared.push(...relsRes.cleared);
829
+ metadataValues.push(...relsRes.originalValues);
830
+ return {
831
+ bytes: zipFiles(updatedArchive),
832
+ extractedText: combinedText,
833
+ redactedText: result.text,
834
+ totalRedactions: result.redactions.length,
835
+ counts: countRedactionsByLabel(result.redactions),
836
+ redactions: result.redactions,
837
+ map: result.map,
838
+ metadataCleared,
839
+ metadataValues,
840
+ warnings: []
841
+ };
842
+ }
843
+ function extractXlsxCachedFormulaStrings(xml) {
844
+ const out = [];
845
+ const cellRe = /<c\b[^>]*\bt="str"[^>]*>([\s\S]*?)<\/c>/g;
846
+ let m = cellRe.exec(xml);
847
+ while (m !== null) {
848
+ const inner = m[1] ?? "";
849
+ const vMatch = /<v(?:\s[^>]*)?>([\s\S]*?)<\/v>/.exec(inner);
850
+ if (vMatch) {
851
+ const openEnd = m.index + m[0].indexOf(">") + 1;
852
+ const vOpenEnd = vMatch.index + vMatch[0].indexOf(">") + 1;
853
+ const rawContent = vMatch[1] ?? "";
854
+ const contentStart = openEnd + vOpenEnd;
855
+ const contentEnd = contentStart + rawContent.length;
856
+ out.push({ contentStart, contentEnd, text: unescapeXml(rawContent) });
857
+ }
858
+ m = cellRe.exec(xml);
859
+ }
860
+ return out;
861
+ }
862
+ function extractXlsx(bytes) {
863
+ const archive = unzipSafely(bytes);
864
+ const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(archive));
865
+ const sections = [];
866
+ if (sharedStrings && archive[sharedStrings]) {
867
+ const xml = decodeUtf8(archive[sharedStrings]);
868
+ const containers = extractXmlTextContainers(xml, "si", ["t"]);
869
+ const text = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
870
+ if (text) {
871
+ sections.push({ id: sharedStrings, label: "sharedStrings", text });
872
+ }
873
+ }
874
+ for (const sheetPath of sheets) {
875
+ const raw = archive[sheetPath];
876
+ if (!raw) continue;
877
+ const xml = decodeUtf8(raw);
878
+ const inlineContainers = extractXmlTextContainers(xml, "is", ["t"]);
879
+ const formulaStrings = extractXlsxCachedFormulaStrings(xml);
880
+ const lines = [
881
+ ...inlineContainers.map((c) => c.text),
882
+ ...formulaStrings.map((f) => f.text)
883
+ ].filter((t) => t.length > 0);
884
+ if (lines.length > 0) {
885
+ sections.push({
886
+ id: sheetPath,
887
+ label: sheetPath.replace(/^xl\/worksheets\//i, "").replace(/\.xml$/i, ""),
888
+ text: lines.join("\n\n")
889
+ });
890
+ }
891
+ }
892
+ for (const commentPath of comments) {
893
+ const raw = archive[commentPath];
894
+ if (!raw) continue;
895
+ const xml = decodeUtf8(raw);
896
+ const commentContainers = extractXmlTextContainers(xml, "text", ["t"]);
897
+ const lines = commentContainers.map((c) => c.text).filter((t) => t.length > 0);
898
+ if (lines.length > 0) {
899
+ sections.push({
900
+ id: commentPath,
901
+ label: commentPath.replace(/^xl\//i, "").replace(/\.xml$/i, ""),
902
+ text: lines.join("\n\n")
903
+ });
904
+ }
905
+ }
906
+ const { metadata } = extractOfficeMetadata(archive);
907
+ return {
908
+ format: "xlsx",
909
+ mimeType: XLSX_MIME,
910
+ text: sections.map((s) => s.text).join("\n\n"),
911
+ sections,
912
+ metadata,
913
+ warnings: [],
914
+ scannedPages: []
915
+ };
916
+ }
917
+ async function redactXlsx(bytes, redactFn) {
918
+ const archive = unzipSafely(bytes);
919
+ const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
920
+ const metadataValues = Object.values(metadata);
921
+ const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(updatedArchive));
922
+ const parts = [];
923
+ const formulaRecords = [];
924
+ const textChunks = [];
925
+ let cursor = 0;
926
+ const addPart = (partPath, xml, containerTag) => {
927
+ const containers = extractXmlTextContainers(xml, containerTag, ["t"]);
928
+ const containerOffsets = [];
929
+ for (const container of containers) {
930
+ if (container.text.length === 0) {
931
+ containerOffsets.push({ start: cursor, end: cursor });
932
+ continue;
933
+ }
934
+ if (textChunks.length > 0) {
935
+ textChunks.push("\n\n");
936
+ cursor += 2;
937
+ }
938
+ const start = cursor;
939
+ textChunks.push(container.text);
940
+ cursor += container.text.length;
941
+ containerOffsets.push({ start, end: cursor });
942
+ }
943
+ parts.push({ partPath, xml, containers, containerOffsets });
944
+ };
945
+ if (sharedStrings && updatedArchive[sharedStrings]) {
946
+ addPart(sharedStrings, decodeUtf8(updatedArchive[sharedStrings]), "si");
947
+ }
948
+ for (const sheetPath of sheets) {
949
+ const raw = updatedArchive[sheetPath];
950
+ if (!raw) continue;
951
+ const xml = decodeUtf8(raw);
952
+ addPart(sheetPath, xml, "is");
953
+ const formulas = extractXlsxCachedFormulaStrings(xml);
954
+ if (formulas.length > 0) {
955
+ const entries = [];
956
+ for (const f of formulas) {
957
+ if (textChunks.length > 0) {
958
+ textChunks.push("\n\n");
959
+ cursor += 2;
960
+ }
961
+ const start = cursor;
962
+ textChunks.push(f.text);
963
+ cursor += f.text.length;
964
+ entries.push({
965
+ contentStart: f.contentStart,
966
+ contentEnd: f.contentEnd,
967
+ start,
968
+ end: cursor
969
+ });
970
+ }
971
+ formulaRecords.push({ partPath: sheetPath, entries });
972
+ }
973
+ }
974
+ for (const commentPath of comments) {
975
+ const raw = updatedArchive[commentPath];
976
+ if (!raw) continue;
977
+ const { xml, stripped } = scrubXlsxCommentAuthors(decodeUtf8(raw));
978
+ if (stripped.length > 0) {
979
+ metadataCleared.push(`${commentPath}:author`);
980
+ metadataValues.push(...stripped);
981
+ }
982
+ addPart(commentPath, xml, "text");
983
+ }
984
+ const combinedText = textChunks.join("");
985
+ const result = await redactFn(combinedText);
986
+ const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
987
+ const formulaByPart = new Map(formulaRecords.map((f) => [f.partPath, f.entries]));
988
+ for (const part of parts) {
989
+ let nextXml = part.xml;
990
+ const formulaEntries = formulaByPart.get(part.partPath);
991
+ if (formulaEntries && formulaEntries.length > 0) {
992
+ const rawPatches = [];
993
+ for (const entry of formulaEntries) {
994
+ const overlapping = result.redactions.filter(
995
+ (r) => r.end > entry.start && r.start < entry.end
996
+ );
997
+ if (overlapping.length === 0) continue;
998
+ let text = combinedText.slice(entry.start, entry.end);
999
+ for (let i = overlapping.length - 1; i >= 0; i--) {
1000
+ const r = overlapping[i];
1001
+ if (!r) continue;
1002
+ const localStart = Math.max(0, r.start - entry.start);
1003
+ const localEnd = Math.min(text.length, r.end - entry.start);
1004
+ text = text.slice(0, localStart) + r.replacement + text.slice(localEnd);
1005
+ }
1006
+ rawPatches.push({
1007
+ start: entry.contentStart,
1008
+ end: entry.contentEnd,
1009
+ replacement: escapeXml(text)
1010
+ });
1011
+ }
1012
+ if (rawPatches.length > 0) {
1013
+ rawPatches.sort((a, b) => b.start - a.start);
1014
+ for (const p of rawPatches) {
1015
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
1016
+ }
1017
+ const partMap2 = replacementsByPart.get(part.partPath);
1018
+ if (partMap2 && partMap2.size > 0) {
1019
+ const freshContainers = extractXmlTextContainers(nextXml, "is", ["t"]);
1020
+ nextXml = applyXmlContainerReplacements(nextXml, freshContainers, partMap2);
1021
+ }
1022
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
1023
+ continue;
1024
+ }
1025
+ }
1026
+ const partMap = replacementsByPart.get(part.partPath);
1027
+ if (partMap) {
1028
+ nextXml = applyXmlContainerReplacements(nextXml, part.containers, partMap);
1029
+ }
1030
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
1031
+ }
1032
+ const wbRes = await redactXlsxWorkbookSheetNames(updatedArchive, redactFn);
1033
+ metadataCleared.push(...wbRes.cleared);
1034
+ metadataValues.push(...wbRes.originalValues);
1035
+ const relsRes = await redactRelsTargets(updatedArchive, redactFn);
1036
+ metadataCleared.push(...relsRes.cleared);
1037
+ metadataValues.push(...relsRes.originalValues);
1038
+ return {
1039
+ bytes: zipFiles(updatedArchive),
1040
+ extractedText: combinedText,
1041
+ redactedText: result.text,
1042
+ totalRedactions: result.redactions.length,
1043
+ counts: countRedactionsByLabel(result.redactions),
1044
+ redactions: result.redactions,
1045
+ map: result.map,
1046
+ metadataCleared,
1047
+ metadataValues,
1048
+ warnings: []
1049
+ };
1050
+ }
1051
+ var configuredWorkerSrc;
1052
+ var cachedPdfjsPromise = null;
1053
+ async function loadPdfjs(workerSrcOverride) {
1054
+ if (!cachedPdfjsPromise) {
1055
+ cachedPdfjsPromise = import('pdfjs-dist/legacy/build/pdf.mjs');
1056
+ }
1057
+ const pdfjs = await cachedPdfjsPromise;
1058
+ const workerSrc = workerSrcOverride ?? configuredWorkerSrc;
1059
+ if (workerSrc && pdfjs.GlobalWorkerOptions.workerSrc !== workerSrc) {
1060
+ pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
1061
+ }
1062
+ return pdfjs;
1063
+ }
1064
+ function isPdfTextItem(item) {
1065
+ if (!item || typeof item !== "object") return false;
1066
+ const rec = item;
1067
+ return typeof rec.str === "string" && Array.isArray(rec.transform) && rec.transform.length >= 6;
1068
+ }
1069
+ function computeItemBounds(item) {
1070
+ const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = item.transform;
1071
+ const scaleX = Math.hypot(a, b);
1072
+ const scaleY = Math.hypot(c, d);
1073
+ const fontHeight = Math.max(scaleY, scaleX, item.height || 0, 6);
1074
+ const width = typeof item.width === "number" && item.width > 0 ? item.width : fontHeight * 0.55 * Math.max(1, item.str.length);
1075
+ const isHorizontal = Math.abs(b) < 0.05 && Math.abs(c) < 0.05;
1076
+ if (isHorizontal) {
1077
+ return {
1078
+ x1: e,
1079
+ y1: f - fontHeight * 0.3,
1080
+ x2: e + width,
1081
+ y2: f + fontHeight * 1.08,
1082
+ fontHeight,
1083
+ isHorizontal: true
1084
+ };
1085
+ }
1086
+ const lenX = scaleX || 1;
1087
+ const ux = a / lenX;
1088
+ const uy = b / lenX;
1089
+ const lenY = scaleY || 1;
1090
+ const vx = c / lenY;
1091
+ const vy = d / lenY;
1092
+ const asc = fontHeight * 1.08;
1093
+ const desc = -fontHeight * 0.3;
1094
+ const corners = [
1095
+ [e + vx * desc, f + vy * desc],
1096
+ [e + ux * width + vx * desc, f + uy * width + vy * desc],
1097
+ [e + vx * asc, f + vy * asc],
1098
+ [e + ux * width + vx * asc, f + uy * width + vy * asc]
1099
+ ];
1100
+ let x1 = Number.POSITIVE_INFINITY;
1101
+ let y1 = Number.POSITIVE_INFINITY;
1102
+ let x2 = Number.NEGATIVE_INFINITY;
1103
+ let y2 = Number.NEGATIVE_INFINITY;
1104
+ for (const [cx, cy] of corners) {
1105
+ if (cx < x1) x1 = cx;
1106
+ if (cy < y1) y1 = cy;
1107
+ if (cx > x2) x2 = cx;
1108
+ if (cy > y2) y2 = cy;
1109
+ }
1110
+ return { x1, y1, x2, y2, fontHeight, isHorizontal: false };
1111
+ }
1112
+ function buildPageTextAndMap(rawItems, styles) {
1113
+ const items = [];
1114
+ let text = "";
1115
+ let prevBaselineY = null;
1116
+ let prevRightX = 0;
1117
+ let prevHadEol = false;
1118
+ for (const raw of rawItems) {
1119
+ if (!isPdfTextItem(raw)) continue;
1120
+ if (raw.str.length === 0) {
1121
+ if (raw.hasEOL) prevHadEol = true;
1122
+ continue;
1123
+ }
1124
+ const bounds = computeItemBounds(raw);
1125
+ const baselineY = raw.transform[5] ?? 0;
1126
+ const leftX = raw.transform[4] ?? 0;
1127
+ const style = raw.fontName ? styles?.[raw.fontName] : void 0;
1128
+ const fontFamily = style?.fontFamily || "sans-serif";
1129
+ if (text.length > 0) {
1130
+ const lineChanged = prevHadEol || prevBaselineY !== null && Math.abs(baselineY - prevBaselineY) > bounds.fontHeight * 0.6;
1131
+ if (lineChanged) {
1132
+ if (!text.endsWith("\n")) text += "\n";
1133
+ } else {
1134
+ const gap = leftX - prevRightX;
1135
+ const needsSpace = gap > bounds.fontHeight * 0.16 && !/\s$/.test(text) && !/^\s/.test(raw.str);
1136
+ if (needsSpace) text += " ";
1137
+ }
1138
+ }
1139
+ const start = text.length;
1140
+ text += raw.str;
1141
+ const end = text.length;
1142
+ const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = raw.transform;
1143
+ const itemWidth = typeof raw.width === "number" && raw.width > 0 ? raw.width : bounds.fontHeight * 0.55 * Math.max(1, raw.str.length);
1144
+ items.push({
1145
+ str: raw.str,
1146
+ start,
1147
+ end,
1148
+ x1: bounds.x1,
1149
+ y1: bounds.y1,
1150
+ x2: bounds.x2,
1151
+ y2: bounds.y2,
1152
+ fontHeight: bounds.fontHeight,
1153
+ fontFamily,
1154
+ width: itemWidth,
1155
+ transform: [a, b, c, d, e, f],
1156
+ isHorizontal: bounds.isHorizontal
1157
+ });
1158
+ prevBaselineY = baselineY;
1159
+ prevRightX = bounds.x2;
1160
+ prevHadEol = raw.hasEOL === true;
1161
+ }
1162
+ return { text, items };
1163
+ }
1164
+ function extractAnnotationTexts(annotations) {
1165
+ const out = [];
1166
+ for (const raw of annotations) {
1167
+ if (!raw || typeof raw !== "object") continue;
1168
+ const rec = raw;
1169
+ const snippets = [];
1170
+ if (typeof rec.url === "string" && rec.url.trim()) {
1171
+ snippets.push(rec.url.trim());
1172
+ }
1173
+ if (typeof rec.fieldValue === "string" && rec.fieldValue.trim()) {
1174
+ snippets.push(rec.fieldValue.trim());
1175
+ } else if (Array.isArray(rec.fieldValue)) {
1176
+ for (const v of rec.fieldValue) {
1177
+ if (typeof v === "string" && v.trim()) snippets.push(v.trim());
1178
+ }
1179
+ }
1180
+ if (rec.contentsObj && typeof rec.contentsObj === "object") {
1181
+ const str = rec.contentsObj.str;
1182
+ if (typeof str === "string" && str.trim()) snippets.push(str.trim());
1183
+ }
1184
+ if (typeof rec.titleObj === "object" && rec.titleObj !== null) {
1185
+ const str = rec.titleObj.str;
1186
+ if (typeof str === "string" && str.trim()) snippets.push(str.trim());
1187
+ }
1188
+ if (typeof rec.alternativeText === "string" && rec.alternativeText.trim()) {
1189
+ snippets.push(rec.alternativeText.trim());
1190
+ }
1191
+ if (snippets.length === 0) continue;
1192
+ let rect;
1193
+ if (Array.isArray(rec.rect) && rec.rect.length === 4 && rec.rect.every((n) => typeof n === "number" && Number.isFinite(n))) {
1194
+ rect = [rec.rect[0], rec.rect[1], rec.rect[2], rec.rect[3]];
1195
+ }
1196
+ out.push({ text: snippets.join(" "), rect });
1197
+ }
1198
+ return out;
1199
+ }
1200
+ function collectPdfMetadataStrings(meta) {
1201
+ const out = {};
1202
+ const sensitiveInfoKeys = [
1203
+ "Title",
1204
+ "Author",
1205
+ "Subject",
1206
+ "Keywords",
1207
+ "Creator",
1208
+ "Producer"
1209
+ ];
1210
+ if (meta.info && typeof meta.info === "object") {
1211
+ const info = meta.info;
1212
+ for (const key of sensitiveInfoKeys) {
1213
+ const value = info[key];
1214
+ if (typeof value === "string" && value.trim()) {
1215
+ out[key] = value.trim();
1216
+ }
1217
+ }
1218
+ }
1219
+ return out;
1220
+ }
1221
+ async function resolveDefaultCanvasProvider() {
1222
+ if (typeof document !== "undefined" && typeof document.createElement === "function") {
1223
+ return {
1224
+ createCanvas(width, height) {
1225
+ const canvas = document.createElement("canvas");
1226
+ canvas.width = width;
1227
+ canvas.height = height;
1228
+ return canvas;
1229
+ },
1230
+ async toPngBytes(canvas) {
1231
+ const htmlCanvas = canvas;
1232
+ const blob = await new Promise((resolve5, reject) => {
1233
+ htmlCanvas.toBlob((b) => {
1234
+ if (b) resolve5(b);
1235
+ else reject(new Error("Failed to encode PDF page canvas to PNG."));
1236
+ }, "image/png");
1237
+ });
1238
+ return new Uint8Array(await blob.arrayBuffer());
1239
+ }
1240
+ };
1241
+ }
1242
+ if (typeof OffscreenCanvas !== "undefined") {
1243
+ return {
1244
+ createCanvas(width, height) {
1245
+ return new OffscreenCanvas(width, height);
1246
+ },
1247
+ async toPngBytes(canvas) {
1248
+ const off = canvas;
1249
+ const blob = await off.convertToBlob({ type: "image/png" });
1250
+ return new Uint8Array(await blob.arrayBuffer());
1251
+ }
1252
+ };
1253
+ }
1254
+ const canvasPkg = "@napi-rs/canvas";
1255
+ const mod = await import(
1256
+ /* @vite-ignore */
1257
+ canvasPkg
1258
+ );
1259
+ return {
1260
+ createCanvas(width, height) {
1261
+ return mod.createCanvas(width, height);
1262
+ },
1263
+ toPngBytes(canvas) {
1264
+ const napiCanvas = canvas;
1265
+ return new Uint8Array(napiCanvas.toBuffer("image/png"));
1266
+ }
1267
+ };
1268
+ }
1269
+ function mergeLineBoxes(boxes) {
1270
+ if (boxes.length <= 1) return [...boxes];
1271
+ const sorted = [...boxes].sort((a, b) => {
1272
+ const cyA = (a.y1 + a.y2) / 2;
1273
+ const cyB = (b.y1 + b.y2) / 2;
1274
+ if (Math.abs(cyA - cyB) > Math.min(a.y2 - a.y1, b.y2 - b.y1) * 0.5) {
1275
+ return cyB - cyA;
1276
+ }
1277
+ return a.x1 - b.x1;
1278
+ });
1279
+ const merged = [];
1280
+ for (const box of sorted) {
1281
+ const prev = merged[merged.length - 1];
1282
+ if (prev && prev.replacement === box.replacement) {
1283
+ const hPrev = prev.y2 - prev.y1;
1284
+ const hCur = box.y2 - box.y1;
1285
+ const yOverlap = Math.min(prev.y2, box.y2) - Math.max(prev.y1, box.y1);
1286
+ const minH = Math.min(hPrev, hCur);
1287
+ const xGap = box.x1 - prev.x2;
1288
+ if (minH > 0 && yOverlap > minH * 0.45 && xGap <= Math.max(hPrev, hCur) * 1.5) {
1289
+ prev.x1 = Math.min(prev.x1, box.x1);
1290
+ prev.y1 = Math.min(prev.y1, box.y1);
1291
+ prev.x2 = Math.max(prev.x2, box.x2);
1292
+ prev.y2 = Math.max(prev.y2, box.y2);
1293
+ continue;
1294
+ }
1295
+ }
1296
+ merged.push({ ...box });
1297
+ }
1298
+ return merged;
1299
+ }
1300
+ function measureSubspanFractions(ctx, str, localStart, localEnd, fontFamily) {
1301
+ const len = Math.max(1, str.length);
1302
+ if (localStart <= 0 && localEnd >= len) {
1303
+ return { startFrac: 0, endFrac: 1 };
1304
+ }
1305
+ const isMonospace = /\bmono/i.test(fontFamily);
1306
+ if (isMonospace || !ctx?.measureText) {
1307
+ return { startFrac: localStart / len, endFrac: localEnd / len };
1308
+ }
1309
+ const prefix = str.slice(0, localStart);
1310
+ const uptoEnd = str.slice(0, localEnd);
1311
+ const families = /* @__PURE__ */ new Set([
1312
+ fontFamily,
1313
+ "Helvetica, Arial, sans-serif",
1314
+ "Times New Roman, Times, serif"
1315
+ ]);
1316
+ let minStart = 1;
1317
+ let maxEnd = 0;
1318
+ let measuredAny = false;
1319
+ ctx.save();
1320
+ for (const family of families) {
1321
+ ctx.font = `100px ${family}`;
1322
+ const fullW = ctx.measureText(str).width;
1323
+ if (!(fullW > 0)) continue;
1324
+ const startW = localStart > 0 ? ctx.measureText(prefix).width : 0;
1325
+ const endW = localEnd < len ? ctx.measureText(uptoEnd).width : fullW;
1326
+ minStart = Math.min(minStart, Math.max(0, startW / fullW));
1327
+ maxEnd = Math.max(maxEnd, Math.min(1, endW / fullW));
1328
+ measuredAny = true;
1329
+ }
1330
+ ctx.restore();
1331
+ if (!measuredAny || maxEnd <= minStart) {
1332
+ return { startFrac: localStart / len, endFrac: localEnd / len };
1333
+ }
1334
+ return { startFrac: minStart, endFrac: maxEnd };
1335
+ }
1336
+ function computePageRedactionBoxes(items, pageRedactions, ctx) {
1337
+ const boxes = [];
1338
+ for (const r of pageRedactions) {
1339
+ const rawForSpan = [];
1340
+ for (const item of items) {
1341
+ if (item.end <= r.start || item.start >= r.end) continue;
1342
+ const len = Math.max(1, item.str.length);
1343
+ const localStart = Math.max(0, r.start - item.start);
1344
+ const localEnd = Math.min(len, r.end - item.start);
1345
+ const padX = Math.max(3, item.fontHeight * 0.25);
1346
+ const padY = Math.max(1.5, item.fontHeight * 0.12);
1347
+ const { startFrac, endFrac } = measureSubspanFractions(
1348
+ ctx,
1349
+ item.str,
1350
+ localStart,
1351
+ localEnd,
1352
+ item.fontFamily
1353
+ );
1354
+ if (item.isHorizontal) {
1355
+ const spanWidth = item.x2 - item.x1;
1356
+ const subX1 = item.x1 + startFrac * spanWidth;
1357
+ const subX2 = item.x1 + endFrac * spanWidth;
1358
+ rawForSpan.push({
1359
+ x1: subX1 - padX,
1360
+ y1: item.y1 - padY,
1361
+ x2: subX2 + padX,
1362
+ y2: item.y2 + padY,
1363
+ replacement: r.replacement
1364
+ });
1365
+ } else {
1366
+ const [a, b, c, d, e, f] = item.transform;
1367
+ const scaleX = Math.hypot(a, b) || 1;
1368
+ const scaleY = Math.hypot(c, d) || 1;
1369
+ const ux = a / scaleX;
1370
+ const uy = b / scaleX;
1371
+ const vx = c / scaleY;
1372
+ const vy = d / scaleY;
1373
+ const d1 = startFrac * item.width;
1374
+ const d2 = endFrac * item.width;
1375
+ const asc = item.fontHeight * 1.12;
1376
+ const desc = -item.fontHeight * 0.34;
1377
+ const corners = [
1378
+ [e + ux * d1 + vx * desc, f + uy * d1 + vy * desc],
1379
+ [e + ux * d2 + vx * desc, f + uy * d2 + vy * desc],
1380
+ [e + ux * d1 + vx * asc, f + uy * d1 + vy * asc],
1381
+ [e + ux * d2 + vx * asc, f + uy * d2 + vy * asc]
1382
+ ];
1383
+ let bx1 = Number.POSITIVE_INFINITY;
1384
+ let by1 = Number.POSITIVE_INFINITY;
1385
+ let bx2 = Number.NEGATIVE_INFINITY;
1386
+ let by2 = Number.NEGATIVE_INFINITY;
1387
+ for (const [cx, cy] of corners) {
1388
+ if (cx < bx1) bx1 = cx;
1389
+ if (cy < by1) by1 = cy;
1390
+ if (cx > bx2) bx2 = cx;
1391
+ if (cy > by2) by2 = cy;
1392
+ }
1393
+ rawForSpan.push({
1394
+ x1: bx1 - padX,
1395
+ y1: by1 - padY,
1396
+ x2: bx2 + padX,
1397
+ y2: by2 + padY,
1398
+ replacement: r.replacement
1399
+ });
1400
+ }
1401
+ }
1402
+ boxes.push(...mergeLineBoxes(rawForSpan));
1403
+ }
1404
+ return boxes;
1405
+ }
1406
+ function drawRedactionOverlay(ctx, viewport, boxes, style) {
1407
+ const fillColor = style.fillColor ?? "#111111";
1408
+ const textColor = style.textColor ?? "#ffffff";
1409
+ const showLabels = style.showLabels !== false;
1410
+ for (const box of boxes) {
1411
+ const corners = [
1412
+ viewport.convertToViewportPoint(box.x1, box.y1),
1413
+ viewport.convertToViewportPoint(box.x2, box.y1),
1414
+ viewport.convertToViewportPoint(box.x1, box.y2),
1415
+ viewport.convertToViewportPoint(box.x2, box.y2)
1416
+ ];
1417
+ let minX = Number.POSITIVE_INFINITY;
1418
+ let minY = Number.POSITIVE_INFINITY;
1419
+ let maxX = Number.NEGATIVE_INFINITY;
1420
+ let maxY = Number.NEGATIVE_INFINITY;
1421
+ for (const pt of corners) {
1422
+ const px = Number(pt[0] ?? 0);
1423
+ const py = Number(pt[1] ?? 0);
1424
+ if (px < minX) minX = px;
1425
+ if (py < minY) minY = py;
1426
+ if (px > maxX) maxX = px;
1427
+ if (py > maxY) maxY = py;
1428
+ }
1429
+ const rx = minX;
1430
+ const ry = minY;
1431
+ const rw = maxX - minX;
1432
+ const rh = maxY - minY;
1433
+ if (rw < 1 || rh < 1) continue;
1434
+ ctx.save();
1435
+ ctx.fillStyle = fillColor;
1436
+ ctx.fillRect(rx, ry, rw, rh);
1437
+ if (showLabels && box.replacement && rw >= 24 && rh >= 10) {
1438
+ const pad = Math.min(4, rw * 0.08);
1439
+ const maxTextWidth = Math.max(4, rw - pad * 2);
1440
+ const fontSize = Math.max(8, Math.min(rh * 0.62, 22));
1441
+ ctx.beginPath();
1442
+ ctx.rect(rx, ry, rw, rh);
1443
+ ctx.clip();
1444
+ ctx.fillStyle = textColor;
1445
+ ctx.font = `600 ${fontSize.toFixed(1)}px sans-serif`;
1446
+ ctx.textAlign = "center";
1447
+ ctx.textBaseline = "middle";
1448
+ ctx.fillText(box.replacement, rx + rw / 2, ry + rh / 2 + fontSize * 0.04, maxTextWidth);
1449
+ }
1450
+ ctx.restore();
1451
+ }
1452
+ }
1453
+ async function inspectPdfDocument(bytes, pdfWorkerSrc) {
1454
+ const pdfjs = await loadPdfjs(pdfWorkerSrc);
1455
+ const loadingTask = pdfjs.getDocument({
1456
+ data: bytes.slice(),
1457
+ useSystemFonts: true,
1458
+ verbosity: 0
1459
+ });
1460
+ const doc = await loadingTask.promise;
1461
+ const meta = await doc.getMetadata().catch(() => ({ info: {}, metadata: null }));
1462
+ const metadata = collectPdfMetadataStrings(meta);
1463
+ const pages = [];
1464
+ const scannedPages = [];
1465
+ const warnings = [];
1466
+ const ops = pdfjs.OPS;
1467
+ const imageOpSet = /* @__PURE__ */ new Set([
1468
+ ops.paintImageXObject,
1469
+ ops.paintInlineImageXObject,
1470
+ ops.paintImageMaskXObject
1471
+ ]);
1472
+ for (let pageNumber = 1; pageNumber <= doc.numPages; pageNumber++) {
1473
+ const page = await doc.getPage(pageNumber);
1474
+ const textContent = await page.getTextContent();
1475
+ const { text, items } = buildPageTextAndMap(
1476
+ textContent.items,
1477
+ textContent.styles
1478
+ );
1479
+ const rawAnnotations = await page.getAnnotations().catch(() => []);
1480
+ const annotations = extractAnnotationTexts(rawAnnotations);
1481
+ let scanned = false;
1482
+ if (text.trim().length < 10) {
1483
+ const opList = await page.getOperatorList().catch(() => null);
1484
+ if (opList?.fnArray.some((fn) => imageOpSet.has(fn))) {
1485
+ scanned = true;
1486
+ scannedPages.push(pageNumber);
1487
+ }
1488
+ }
1489
+ pages.push({ pageNumber, text, items, annotations, scanned });
1490
+ }
1491
+ if (scannedPages.length > 0) {
1492
+ warnings.push(
1493
+ `PDF page(s) ${scannedPages.join(", ")} appear to be scanned images without a text layer and cannot be inspected without OCR.`
1494
+ );
1495
+ }
1496
+ return { pdfjs, loadingTask, doc, pages, metadata, scannedPages, warnings };
1497
+ }
1498
+ async function extractPdf(bytes, options) {
1499
+ const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
1500
+ try {
1501
+ const sections = inspected.pages.map((p) => {
1502
+ const annotText = p.annotations.map((a) => a.text).join("\n");
1503
+ const combined = annotText ? `${p.text}${p.text ? "\n" : ""}${annotText}` : p.text;
1504
+ return {
1505
+ id: `page-${p.pageNumber}`,
1506
+ label: `Sida ${p.pageNumber}`,
1507
+ text: combined,
1508
+ pageIndex: p.pageNumber - 1,
1509
+ scanned: p.scanned
1510
+ };
1511
+ });
1512
+ return {
1513
+ format: "pdf",
1514
+ mimeType: "application/pdf",
1515
+ text: sections.map((s) => s.text).filter((t) => t.length > 0).join("\n\n"),
1516
+ sections,
1517
+ metadata: inspected.metadata,
1518
+ warnings: inspected.warnings,
1519
+ scannedPages: inspected.scannedPages,
1520
+ totalPages: inspected.doc.numPages
1521
+ };
1522
+ } finally {
1523
+ await inspected.loadingTask.destroy();
1524
+ }
1525
+ }
1526
+ function countByLabel(redactions) {
1527
+ const counts = {};
1528
+ for (const r of redactions) {
1529
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
1530
+ }
1531
+ return counts;
1532
+ }
1533
+ async function redactPdf(bytes, redactFn, options) {
1534
+ const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
1535
+ try {
1536
+ const pageOffsets = [];
1537
+ const textChunks = [];
1538
+ let cursor = 0;
1539
+ for (let i = 0; i < inspected.pages.length; i++) {
1540
+ const page = inspected.pages[i];
1541
+ if (!page) continue;
1542
+ const hasAnyContent = page.text.length > 0 || page.annotations.some((a) => a.text.length > 0);
1543
+ if (!hasAnyContent) {
1544
+ pageOffsets.push({ pageIndex: i, textStart: cursor, textEnd: cursor, annotRanges: [] });
1545
+ continue;
1546
+ }
1547
+ if (textChunks.length > 0) {
1548
+ textChunks.push("\n\n");
1549
+ cursor += 2;
1550
+ }
1551
+ const textStart = cursor;
1552
+ if (page.text.length > 0) {
1553
+ textChunks.push(page.text);
1554
+ cursor += page.text.length;
1555
+ }
1556
+ const textEnd = cursor;
1557
+ const annotRanges = [];
1558
+ let wroteInPage = page.text.length > 0;
1559
+ for (const annot of page.annotations) {
1560
+ if (!annot.text) continue;
1561
+ if (wroteInPage) {
1562
+ textChunks.push("\n");
1563
+ cursor += 1;
1564
+ }
1565
+ const start = cursor;
1566
+ textChunks.push(annot.text);
1567
+ cursor += annot.text.length;
1568
+ wroteInPage = true;
1569
+ annotRanges.push({ start, end: cursor, rect: annot.rect });
1570
+ }
1571
+ pageOffsets.push({ pageIndex: i, textStart, textEnd, annotRanges });
1572
+ }
1573
+ const combinedText = textChunks.join("");
1574
+ const result = await redactFn(combinedText);
1575
+ const srcDoc = await PDFDocument.load(bytes, {
1576
+ ignoreEncryption: true,
1577
+ updateMetadata: false
1578
+ });
1579
+ const outDoc = await PDFDocument.create();
1580
+ const style = options?.pdfStyle ?? {};
1581
+ const scale = style.scale ?? 2.5;
1582
+ let canvasProvider = options?.canvasProvider;
1583
+ const redactedPages = [];
1584
+ for (let i = 0; i < inspected.pages.length; i++) {
1585
+ const pageInfo = inspected.pages[i];
1586
+ const offsetInfo = pageOffsets[i];
1587
+ if (!pageInfo || !offsetInfo) continue;
1588
+ const localTextRedactions = [];
1589
+ const annotBoxes = [];
1590
+ let hasAnnotPii = false;
1591
+ for (const r of result.redactions) {
1592
+ if (r.end > offsetInfo.textStart && r.start < offsetInfo.textEnd) {
1593
+ localTextRedactions.push({
1594
+ start: Math.max(0, r.start - offsetInfo.textStart),
1595
+ end: Math.min(offsetInfo.textEnd - offsetInfo.textStart, r.end - offsetInfo.textStart),
1596
+ replacement: r.replacement
1597
+ });
1598
+ }
1599
+ for (const ar of offsetInfo.annotRanges) {
1600
+ if (r.end > ar.start && r.start < ar.end) {
1601
+ hasAnnotPii = true;
1602
+ if (ar.rect) {
1603
+ annotBoxes.push({
1604
+ x1: ar.rect[0],
1605
+ y1: ar.rect[1],
1606
+ x2: ar.rect[2],
1607
+ y2: ar.rect[3],
1608
+ replacement: r.replacement
1609
+ });
1610
+ }
1611
+ }
1612
+ }
1613
+ }
1614
+ const shouldBurn = options?.burnAllPdfPages === true || localTextRedactions.length > 0 || annotBoxes.length > 0 || hasAnnotPii;
1615
+ if (!shouldBurn) {
1616
+ const [copied] = await outDoc.copyPages(srcDoc, [i]);
1617
+ if (copied) {
1618
+ copied.node.delete(PDFName.of("Annots"));
1619
+ outDoc.addPage(copied);
1620
+ }
1621
+ continue;
1622
+ }
1623
+ redactedPages.push(pageInfo.pageNumber);
1624
+ if (!canvasProvider) {
1625
+ canvasProvider = await resolveDefaultCanvasProvider();
1626
+ }
1627
+ const pdfjsPage = await inspected.doc.getPage(pageInfo.pageNumber);
1628
+ const unscaledViewport = pdfjsPage.getViewport({ scale: 1 });
1629
+ const renderViewport = pdfjsPage.getViewport({ scale });
1630
+ const canvas = canvasProvider.createCanvas(
1631
+ Math.max(1, Math.ceil(renderViewport.width)),
1632
+ Math.max(1, Math.ceil(renderViewport.height))
1633
+ );
1634
+ const ctx = canvas.getContext("2d");
1635
+ if (!ctx) {
1636
+ throw new Error("Could not acquire 2D canvas context for PDF redaction.");
1637
+ }
1638
+ await pdfjsPage.render({
1639
+ canvasContext: ctx,
1640
+ viewport: renderViewport,
1641
+ canvas,
1642
+ intent: "print"
1643
+ }).promise;
1644
+ const textBoxes = computePageRedactionBoxes(pageInfo.items, localTextRedactions, ctx);
1645
+ const allBoxes = [...textBoxes, ...annotBoxes];
1646
+ drawRedactionOverlay(ctx, renderViewport, allBoxes, style);
1647
+ const pngBytes = await canvasProvider.toPngBytes(canvas);
1648
+ const pngImage = await outDoc.embedPng(pngBytes);
1649
+ const newPage = outDoc.addPage([unscaledViewport.width, unscaledViewport.height]);
1650
+ newPage.drawImage(pngImage, {
1651
+ x: 0,
1652
+ y: 0,
1653
+ width: unscaledViewport.width,
1654
+ height: unscaledViewport.height
1655
+ });
1656
+ }
1657
+ outDoc.setTitle("");
1658
+ outDoc.setAuthor("");
1659
+ outDoc.setSubject("");
1660
+ outDoc.setKeywords([]);
1661
+ outDoc.setCreator("Maskera");
1662
+ outDoc.setProducer("Maskera");
1663
+ const outBytes = new Uint8Array(await outDoc.save({ useObjectStreams: true }));
1664
+ const metadataCleared = Object.keys(inspected.metadata);
1665
+ const metadataValues = Object.values(inspected.metadata);
1666
+ return {
1667
+ bytes: outBytes,
1668
+ extractedText: combinedText,
1669
+ redactedText: result.text,
1670
+ totalRedactions: result.redactions.length,
1671
+ counts: countByLabel(result.redactions),
1672
+ redactions: result.redactions,
1673
+ map: result.map,
1674
+ metadataCleared,
1675
+ metadataValues,
1676
+ warnings: inspected.warnings,
1677
+ scannedPages: inspected.scannedPages,
1678
+ redactedPages,
1679
+ totalPages: inspected.doc.numPages
1680
+ };
1681
+ } finally {
1682
+ await inspected.loadingTask.destroy();
1683
+ }
1684
+ }
1685
+ function normalizeForLeakCheck(value) {
1686
+ return value.replace(/\s+/g, " ").trim().toLowerCase();
1687
+ }
1688
+ function collectNonTrivialSecrets(secrets) {
1689
+ const seen = /* @__PURE__ */ new Set();
1690
+ const out = [];
1691
+ for (const raw of secrets) {
1692
+ const norm = normalizeForLeakCheck(raw);
1693
+ if (norm.length < 3 || seen.has(norm)) continue;
1694
+ seen.add(norm);
1695
+ out.push(raw.trim());
1696
+ }
1697
+ return out;
1698
+ }
1699
+ async function verifyRedactedFile(bytes, format, originalSecrets, options) {
1700
+ const candidates = collectNonTrivialSecrets(originalSecrets);
1701
+ if (candidates.length === 0) {
1702
+ return { verified: true, leaks: [] };
1703
+ }
1704
+ let haystack = "";
1705
+ if (format === "text") {
1706
+ haystack = normalizeForLeakCheck(decodeUtf8(bytes));
1707
+ } else if (format === "docx" || format === "xlsx") {
1708
+ const archive = unzipSafely(bytes);
1709
+ const parts = [];
1710
+ for (const [name, data] of Object.entries(archive)) {
1711
+ if (!/\.(?:xml|rels)$/i.test(name)) continue;
1712
+ const xml = decodeUtf8(data);
1713
+ parts.push(unescapeXml(xml));
1714
+ parts.push(unescapeXml(xml.replace(/<[^>]+>/g, "")));
1715
+ }
1716
+ haystack = normalizeForLeakCheck(parts.join("\n"));
1717
+ } else if (format === "pdf") {
1718
+ const extracted = await extractPdf(bytes, { pdfWorkerSrc: options?.pdfWorkerSrc });
1719
+ const metaValues = Object.values(extracted.metadata).join("\n");
1720
+ const rawLatin = new TextDecoder("latin1").decode(bytes);
1721
+ haystack = normalizeForLeakCheck(`${extracted.text}
1722
+ ${metaValues}
1723
+ ${rawLatin}`);
1724
+ }
1725
+ const leaks = [];
1726
+ for (const secret of candidates) {
1727
+ if (haystack.includes(normalizeForLeakCheck(secret))) {
1728
+ leaks.push(secret);
1729
+ }
1730
+ }
1731
+ return {
1732
+ verified: leaks.length === 0,
1733
+ leaks
1734
+ };
1735
+ }
1736
+ function assertSizeLimit(bytes, maxBytes, fileName) {
1737
+ if (bytes.byteLength > maxBytes) {
1738
+ const label = fileName ? `"${fileName}"` : "File";
1739
+ throw new Error(`${label} is ${bytes.byteLength} bytes (max ${maxBytes} bytes).`);
1740
+ }
1741
+ }
1742
+ function countByLabel2(redactions) {
1743
+ const counts = {};
1744
+ for (const r of redactions) {
1745
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
1746
+ }
1747
+ return counts;
1748
+ }
1749
+ async function extractFileText(bytes, options = {}) {
1750
+ const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
1751
+ assertSizeLimit(bytes, maxBytes, options.fileName);
1752
+ const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
1753
+ if (detected.format === "binary") {
1754
+ const label = options.fileName ? `"${options.fileName}"` : "File";
1755
+ throw new Error(
1756
+ `${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
1757
+ );
1758
+ }
1759
+ if (detected.format === "text") {
1760
+ const text = decodeUtf8(bytes);
1761
+ return {
1762
+ format: "text",
1763
+ mimeType: detected.mimeType,
1764
+ text,
1765
+ sections: [{ id: "body", label: options.fileName ?? "text", text }],
1766
+ metadata: {},
1767
+ warnings: [],
1768
+ scannedPages: []
1769
+ };
1770
+ }
1771
+ if (detected.format === "docx") {
1772
+ return extractDocx(bytes);
1773
+ }
1774
+ if (detected.format === "xlsx") {
1775
+ return extractXlsx(bytes);
1776
+ }
1777
+ return extractPdf(bytes, { pdfWorkerSrc: options.pdfWorkerSrc });
1778
+ }
1779
+ async function redactFile(bytes, redactFn, options = {}) {
1780
+ const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
1781
+ assertSizeLimit(bytes, maxBytes, options.fileName);
1782
+ const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
1783
+ if (detected.format === "binary") {
1784
+ const label = options.fileName ? `"${options.fileName}"` : "File";
1785
+ throw new Error(
1786
+ `${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
1787
+ );
1788
+ }
1789
+ const shouldVerify = options.verify !== false;
1790
+ if (detected.format === "text") {
1791
+ const extractedText = decodeUtf8(bytes);
1792
+ const result = await redactFn(extractedText);
1793
+ const outBytes = encodeUtf8(result.text);
1794
+ const secrets2 = result.redactions.map((r) => r.value);
1795
+ const verification2 = shouldVerify ? await verifyRedactedFile(outBytes, "text", secrets2) : { verified: true, leaks: [] };
1796
+ return {
1797
+ format: "text",
1798
+ mimeType: detected.mimeType,
1799
+ bytes: outBytes,
1800
+ extractedText,
1801
+ redactedText: result.text,
1802
+ totalRedactions: result.redactions.length,
1803
+ counts: countByLabel2(result.redactions),
1804
+ redactions: result.redactions,
1805
+ map: result.map,
1806
+ metadataCleared: [],
1807
+ warnings: [],
1808
+ scannedPages: [],
1809
+ verified: verification2.verified,
1810
+ verificationLeaks: verification2.leaks
1811
+ };
1812
+ }
1813
+ if (detected.format === "docx") {
1814
+ const doc = await redactDocx(bytes, redactFn);
1815
+ const secrets2 = [...doc.redactions.map((r) => r.value), ...doc.metadataValues];
1816
+ const verification2 = shouldVerify ? await verifyRedactedFile(doc.bytes, "docx", secrets2) : { verified: true, leaks: [] };
1817
+ return {
1818
+ format: "docx",
1819
+ mimeType: detected.mimeType,
1820
+ bytes: doc.bytes,
1821
+ extractedText: doc.extractedText,
1822
+ redactedText: doc.redactedText,
1823
+ totalRedactions: doc.totalRedactions,
1824
+ counts: doc.counts,
1825
+ redactions: doc.redactions,
1826
+ map: doc.map,
1827
+ metadataCleared: doc.metadataCleared,
1828
+ warnings: doc.warnings,
1829
+ scannedPages: [],
1830
+ verified: verification2.verified,
1831
+ verificationLeaks: verification2.leaks
1832
+ };
1833
+ }
1834
+ if (detected.format === "xlsx") {
1835
+ const sheet = await redactXlsx(bytes, redactFn);
1836
+ const secrets2 = [...sheet.redactions.map((r) => r.value), ...sheet.metadataValues];
1837
+ const verification2 = shouldVerify ? await verifyRedactedFile(sheet.bytes, "xlsx", secrets2) : { verified: true, leaks: [] };
1838
+ return {
1839
+ format: "xlsx",
1840
+ mimeType: detected.mimeType,
1841
+ bytes: sheet.bytes,
1842
+ extractedText: sheet.extractedText,
1843
+ redactedText: sheet.redactedText,
1844
+ totalRedactions: sheet.totalRedactions,
1845
+ counts: sheet.counts,
1846
+ redactions: sheet.redactions,
1847
+ map: sheet.map,
1848
+ metadataCleared: sheet.metadataCleared,
1849
+ warnings: sheet.warnings,
1850
+ scannedPages: [],
1851
+ verified: verification2.verified,
1852
+ verificationLeaks: verification2.leaks
1853
+ };
1854
+ }
1855
+ const pdf = await redactPdf(bytes, redactFn, {
1856
+ pdfStyle: options.pdfStyle,
1857
+ canvasProvider: options.canvasProvider,
1858
+ pdfWorkerSrc: options.pdfWorkerSrc,
1859
+ burnAllPdfPages: options.burnAllPdfPages
1860
+ });
1861
+ const secrets = [...pdf.redactions.map((r) => r.value), ...pdf.metadataValues];
1862
+ const verification = shouldVerify ? await verifyRedactedFile(pdf.bytes, "pdf", secrets, {
1863
+ pdfWorkerSrc: options.pdfWorkerSrc
1864
+ }) : { verified: true, leaks: [] };
1865
+ return {
1866
+ format: "pdf",
1867
+ mimeType: detected.mimeType,
1868
+ bytes: pdf.bytes,
1869
+ extractedText: pdf.extractedText,
1870
+ redactedText: pdf.redactedText,
1871
+ totalRedactions: pdf.totalRedactions,
1872
+ counts: pdf.counts,
1873
+ redactions: pdf.redactions,
1874
+ map: pdf.map,
1875
+ metadataCleared: pdf.metadataCleared,
1876
+ warnings: pdf.warnings,
1877
+ scannedPages: pdf.scannedPages,
1878
+ redactedPages: pdf.redactedPages,
1879
+ totalPages: pdf.totalPages,
1880
+ verified: verification.verified,
1881
+ verificationLeaks: verification.leaks
1882
+ };
1883
+ }
174
1884
  var WORD_CHAR = /[\p{L}\p{N}_]/u;
175
1885
  var DEFAULT_MAX_CACHE_ENTRIES = 512;
176
1886
  var MAX_CUSTOM_DETECTOR_CACHE = 64;
@@ -633,6 +2343,7 @@ function createModelProgressLogger(write = (line) => process.stderr.write(`${lin
633
2343
  };
634
2344
  }
635
2345
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
2346
+ var MAX_DOCUMENT_BYTES = MAX_DEFAULT_FILE_BYTES;
636
2347
  var MAX_SYMLINK_HOPS = 40;
637
2348
  var DEFAULT_LIST_MAX_ENTRIES = 200;
638
2349
  var HARD_LIST_MAX_ENTRIES = 1e3;
@@ -641,7 +2352,7 @@ var HARD_LIST_MAX_DEPTH = 12;
641
2352
  var DEFAULT_SEARCH_MAX_MATCHES = 50;
642
2353
  var HARD_SEARCH_MAX_MATCHES = 200;
643
2354
  var DEFAULT_SEARCH_MAX_FILES = 500;
644
- var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
2355
+ var UTF8_DECODER3 = new TextDecoder("utf-8", { fatal: true });
645
2356
  var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "dist-ssr", ".next", ".turbo"]);
646
2357
  function isWithinRoot(root, target) {
647
2358
  const rel = relative(root, target);
@@ -785,84 +2496,144 @@ function createFileGuard(roots = [process.cwd()]) {
785
2496
  await visit(baseDir, 0);
786
2497
  return { files, truncated };
787
2498
  }
2499
+ async function resolveReadableFile(filePath, maxBytes) {
2500
+ const rootsList = await getCanonicalRoots();
2501
+ const candidate = resolveAgainstBase(filePath);
2502
+ const { ancestor, tail } = await resolveExistingAncestor(candidate);
2503
+ const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
2504
+ if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
2505
+ throw new Error(
2506
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2507
+ );
2508
+ }
2509
+ const real = await realpath(candidate).catch(() => {
2510
+ throw new Error(`File not found: "${filePath}".`);
2511
+ });
2512
+ if (!rootsList.some((root) => isWithinRoot(root, real))) {
2513
+ throw new Error(
2514
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2515
+ );
2516
+ }
2517
+ const info = await stat(real);
2518
+ if (!info.isFile()) {
2519
+ throw new Error(`"${filePath}" is not a regular file.`);
2520
+ }
2521
+ if (info.size > maxBytes) {
2522
+ throw new Error(
2523
+ `File "${filePath}" is ${info.size} bytes (max ${maxBytes} bytes for local redaction).`
2524
+ );
2525
+ }
2526
+ const buffer = await readFile(real);
2527
+ return { resolvedPath: real, buffer };
2528
+ }
2529
+ async function writeCheckedBytes(filePath, data, options) {
2530
+ const rootsList = await getCanonicalRoots();
2531
+ const candidate = resolveAgainstBase(filePath);
2532
+ const targetReal = await resolveCanonicalTarget(candidate);
2533
+ if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
2534
+ throw new Error(
2535
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2536
+ );
2537
+ }
2538
+ const bytes = typeof data === "string" ? Buffer.byteLength(data, "utf8") : data.byteLength;
2539
+ if (bytes > options.maxBytes) {
2540
+ throw new Error(`Output exceeds max allowed size (${options.maxBytes} bytes).`);
2541
+ }
2542
+ await mkdir(dirname(targetReal), { recursive: true });
2543
+ const parentReal = await realpath(dirname(targetReal));
2544
+ if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
2545
+ throw new Error(
2546
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2547
+ );
2548
+ }
2549
+ await writeFile(targetReal, data, {
2550
+ ...options.encoding ? { encoding: options.encoding } : {},
2551
+ flag: options.overwrite ? "w" : "wx",
2552
+ mode: 384
2553
+ }).catch((err) => {
2554
+ if (err.code === "EEXIST") {
2555
+ throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
2556
+ }
2557
+ throw err;
2558
+ });
2559
+ return { resolvedPath: targetReal, bytes };
2560
+ }
788
2561
  return {
789
2562
  allowedRoots: rawRoots.map((r) => resolve(r)),
790
2563
  async readText(filePath) {
791
- const rootsList = await getCanonicalRoots();
792
- const candidate = resolveAgainstBase(filePath);
793
- const { ancestor, tail } = await resolveExistingAncestor(candidate);
794
- const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
795
- if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
796
- throw new Error(
797
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
798
- );
799
- }
800
- const real = await realpath(candidate).catch(() => {
801
- throw new Error(`File not found: "${filePath}".`);
802
- });
803
- if (!rootsList.some((root) => isWithinRoot(root, real))) {
804
- throw new Error(
805
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
806
- );
807
- }
808
- const info = await stat(real);
809
- if (!info.isFile()) {
810
- throw new Error(`"${filePath}" is not a regular file.`);
811
- }
812
- if (info.size > MAX_FILE_BYTES) {
813
- throw new Error(
814
- `File "${filePath}" is ${info.size} bytes (max ${MAX_FILE_BYTES} bytes for local redaction).`
815
- );
816
- }
817
- const buffer = await readFile(real);
2564
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_FILE_BYTES);
818
2565
  if (buffer.includes(0)) {
819
2566
  throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
820
2567
  }
821
2568
  let content;
822
2569
  try {
823
- content = UTF8_DECODER.decode(buffer);
2570
+ content = UTF8_DECODER3.decode(buffer);
824
2571
  } catch {
825
2572
  throw new Error(
826
2573
  `"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
827
2574
  );
828
2575
  }
829
2576
  return {
830
- resolvedPath: real,
2577
+ resolvedPath,
831
2578
  content,
832
2579
  bytes: buffer.byteLength
833
2580
  };
834
2581
  },
835
- async writeText(filePath, content, options = {}) {
836
- const rootsList = await getCanonicalRoots();
837
- const candidate = resolveAgainstBase(filePath);
838
- const targetReal = await resolveCanonicalTarget(candidate);
839
- if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
2582
+ async readDocument(filePath) {
2583
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_DOCUMENT_BYTES);
2584
+ const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2585
+ const detected = detectFileFormat(bytes, resolvedPath);
2586
+ if (detected.format === "text" && buffer.byteLength > MAX_FILE_BYTES) {
840
2587
  throw new Error(
841
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2588
+ `File "${filePath}" is ${buffer.byteLength} bytes (max ${MAX_FILE_BYTES} bytes for local text redaction).`
842
2589
  );
843
2590
  }
844
- const bytes = Buffer.byteLength(content, "utf8");
845
- if (bytes > MAX_FILE_BYTES) {
846
- throw new Error(`Output exceeds max allowed size (${MAX_FILE_BYTES} bytes).`);
847
- }
848
- await mkdir(dirname(targetReal), { recursive: true });
849
- const parentReal = await realpath(dirname(targetReal));
850
- if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
2591
+ if (detected.format === "binary") {
2592
+ if (!buffer.includes(0)) {
2593
+ throw new Error(
2594
+ `"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
2595
+ );
2596
+ }
851
2597
  throw new Error(
852
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2598
+ `"${filePath}" appears to be an unsupported binary file (${detected.mimeType}); supported formats are UTF-8 text, PDF, DOCX, and XLSX.`
853
2599
  );
854
2600
  }
855
- await writeFile(targetReal, content, {
856
- encoding: "utf8",
857
- flag: options.overwrite ? "w" : "wx",
858
- mode: 384
859
- }).catch((err) => {
860
- if (err.code === "EEXIST") {
861
- throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
862
- }
863
- throw err;
2601
+ const extracted = await extractFileText(bytes, {
2602
+ fileName: resolvedPath,
2603
+ maxBytes: MAX_DOCUMENT_BYTES
2604
+ });
2605
+ return {
2606
+ resolvedPath,
2607
+ content: extracted.text,
2608
+ bytes: buffer.byteLength,
2609
+ format: extracted.format,
2610
+ mimeType: extracted.mimeType,
2611
+ metadataFields: Object.keys(extracted.metadata),
2612
+ warnings: extracted.warnings,
2613
+ scannedPages: extracted.scannedPages,
2614
+ totalPages: extracted.totalPages
2615
+ };
2616
+ },
2617
+ async readBytes(filePath, options = {}) {
2618
+ const maxBytes = options.maxBytes ?? MAX_DOCUMENT_BYTES;
2619
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, maxBytes);
2620
+ return {
2621
+ resolvedPath,
2622
+ bytes: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
2623
+ };
2624
+ },
2625
+ async writeText(filePath, content, options = {}) {
2626
+ return writeCheckedBytes(filePath, content, {
2627
+ overwrite: options.overwrite,
2628
+ maxBytes: MAX_FILE_BYTES,
2629
+ encoding: "utf8"
2630
+ });
2631
+ },
2632
+ async writeBytes(filePath, bytes, options = {}) {
2633
+ return writeCheckedBytes(filePath, bytes, {
2634
+ overwrite: options.overwrite,
2635
+ maxBytes: options.maxBytes ?? MAX_DOCUMENT_BYTES
864
2636
  });
865
- return { resolvedPath: targetReal, bytes };
866
2637
  },
867
2638
  async listFiles(dirPath, options = {}) {
868
2639
  const { rootsList, baseDir } = await resolveAllowedDirectory(dirPath);
@@ -908,19 +2679,36 @@ function createFileGuard(roots = [process.cwd()]) {
908
2679
  let scannedFiles = 0;
909
2680
  let truncated = walkTruncated;
910
2681
  for (const file of files) {
911
- if (file.bytes > MAX_FILE_BYTES) continue;
2682
+ if (file.bytes > MAX_DOCUMENT_BYTES) continue;
912
2683
  let buffer;
913
2684
  try {
914
2685
  buffer = await readFile(file.realPath);
915
2686
  } catch {
916
2687
  continue;
917
2688
  }
918
- if (buffer.includes(0)) continue;
919
2689
  let text;
920
- try {
921
- text = UTF8_DECODER.decode(buffer);
922
- } catch {
923
- continue;
2690
+ if (!buffer.includes(0)) {
2691
+ if (file.bytes > MAX_FILE_BYTES) continue;
2692
+ try {
2693
+ text = UTF8_DECODER3.decode(buffer);
2694
+ } catch {
2695
+ continue;
2696
+ }
2697
+ } else {
2698
+ const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2699
+ const detected = detectFileFormat(bytes, file.realPath);
2700
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
2701
+ continue;
2702
+ }
2703
+ try {
2704
+ const extracted = await extractFileText(bytes, {
2705
+ fileName: file.realPath,
2706
+ maxBytes: MAX_DOCUMENT_BYTES
2707
+ });
2708
+ text = extracted.text;
2709
+ } catch {
2710
+ continue;
2711
+ }
924
2712
  }
925
2713
  scannedFiles += 1;
926
2714
  const lines = text.split(/\r?\n/);
@@ -1185,11 +2973,13 @@ var SessionVault = class {
1185
2973
  redacted: originalInput,
1186
2974
  counts: {},
1187
2975
  totalRedactions: 0,
1188
- map: {}
2976
+ map: {},
2977
+ redactions: []
1189
2978
  };
1190
2979
  }
1191
2980
  const counts = {};
1192
2981
  const localMap = {};
2982
+ const appliedRedactions = [];
1193
2983
  const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
1194
2984
  let redacted = "";
1195
2985
  let cursor = 0;
@@ -1229,6 +3019,7 @@ var SessionVault = class {
1229
3019
  }
1230
3020
  localMap[token] = r.value;
1231
3021
  counts[r.label] = (counts[r.label] ?? 0) + 1;
3022
+ appliedRedactions.push({ ...r, replacement: token });
1232
3023
  redacted += originalInput.slice(cursor, r.start) + token;
1233
3024
  cursor = r.end;
1234
3025
  }
@@ -1238,7 +3029,8 @@ var SessionVault = class {
1238
3029
  redacted,
1239
3030
  counts,
1240
3031
  totalRedactions: result.redactions.length,
1241
- map: localMap
3032
+ map: localMap,
3033
+ redactions: appliedRedactions
1242
3034
  };
1243
3035
  }
1244
3036
  restore(text, options) {
@@ -1456,9 +3248,9 @@ var TOOLS = [
1456
3248
  },
1457
3249
  {
1458
3250
  name: "maskera_read_file",
1459
- 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.",
3251
+ 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.",
1460
3252
  annotations: {
1461
- title: "Read local file with PII redaction",
3253
+ title: "Read local file or document with PII redaction",
1462
3254
  readOnlyHint: true,
1463
3255
  destructiveHint: false,
1464
3256
  idempotentHint: false,
@@ -1469,7 +3261,7 @@ var TOOLS = [
1469
3261
  properties: {
1470
3262
  path: {
1471
3263
  type: "string",
1472
- description: "Path to a UTF-8 file inside the allowed workspace roots."
3264
+ description: "Path to a UTF-8 text, PDF, DOCX, or XLSX file inside allowed workspace roots."
1473
3265
  },
1474
3266
  session_id: {
1475
3267
  type: "string",
@@ -1498,15 +3290,102 @@ var TOOLS = [
1498
3290
  properties: {
1499
3291
  path: { type: "string" },
1500
3292
  bytes: { type: "integer" },
3293
+ format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
1501
3294
  redacted: { type: "string" },
1502
3295
  session_id: { type: "string" },
1503
3296
  counts: COUNTS_SCHEMA,
1504
3297
  total_redactions: { type: "integer" },
1505
- mode: { type: "string", enum: ["hybrid", "rules"] }
3298
+ mode: { type: "string", enum: ["hybrid", "rules"] },
3299
+ total_pages: { type: "integer" },
3300
+ scanned_pages: { type: "array", items: { type: "integer" } },
3301
+ metadata_fields: { type: "array", items: { type: "string" } },
3302
+ warnings: { type: "array", items: { type: "string" } }
1506
3303
  },
1507
3304
  required: ["path", "bytes", "redacted", "session_id", "counts", "total_redactions", "mode"]
1508
3305
  }
1509
3306
  },
3307
+ {
3308
+ name: "maskera_redact_file",
3309
+ 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.",
3310
+ annotations: {
3311
+ title: "Redact local PDF/DOCX/XLSX/text file to disk",
3312
+ readOnlyHint: false,
3313
+ destructiveHint: false,
3314
+ idempotentHint: false,
3315
+ openWorldHint: false
3316
+ },
3317
+ inputSchema: {
3318
+ type: "object",
3319
+ properties: {
3320
+ input_path: {
3321
+ type: "string",
3322
+ description: "Source file path (PDF, DOCX, XLSX, or UTF-8 text) inside allowed roots."
3323
+ },
3324
+ output_path: {
3325
+ type: "string",
3326
+ description: "Destination path for the redacted file inside allowed roots."
3327
+ },
3328
+ session_id: {
3329
+ type: "string",
3330
+ description: "Optional session ID to share placeholder numbering across files."
3331
+ },
3332
+ overwrite: {
3333
+ type: "boolean",
3334
+ description: "Allow overwriting an existing output file. Default false."
3335
+ },
3336
+ show_labels: {
3337
+ type: "boolean",
3338
+ description: "Draw placeholder labels (e.g. [NAMN_1]) inside burned PDF boxes. Default true."
3339
+ },
3340
+ mode: {
3341
+ type: "string",
3342
+ enum: ["auto", "rules"],
3343
+ description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
3344
+ },
3345
+ profile: {
3346
+ type: "string",
3347
+ enum: ["general", "clinical"],
3348
+ description: 'Optional built-in precision profile (default "general").'
3349
+ },
3350
+ custom_terms: {
3351
+ type: "array",
3352
+ items: { type: "string" },
3353
+ description: "Optional extra protected words (client names, project codenames)."
3354
+ }
3355
+ },
3356
+ required: ["input_path", "output_path"]
3357
+ },
3358
+ outputSchema: {
3359
+ type: "object",
3360
+ properties: {
3361
+ input_path: { type: "string" },
3362
+ output_path: { type: "string" },
3363
+ format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
3364
+ bytes: { type: "integer" },
3365
+ session_id: { type: "string" },
3366
+ counts: COUNTS_SCHEMA,
3367
+ total_redactions: { type: "integer" },
3368
+ mode: { type: "string", enum: ["hybrid", "rules"] },
3369
+ verified: { type: "boolean" },
3370
+ metadata_cleared: { type: "array", items: { type: "string" } },
3371
+ redacted_pages: { type: "array", items: { type: "integer" } },
3372
+ total_pages: { type: "integer" },
3373
+ scanned_pages: { type: "array", items: { type: "integer" } },
3374
+ warnings: { type: "array", items: { type: "string" } }
3375
+ },
3376
+ required: [
3377
+ "input_path",
3378
+ "output_path",
3379
+ "format",
3380
+ "bytes",
3381
+ "session_id",
3382
+ "counts",
3383
+ "total_redactions",
3384
+ "mode",
3385
+ "verified"
3386
+ ]
3387
+ }
3388
+ },
1510
3389
  {
1511
3390
  name: "maskera_write_file",
1512
3391
  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.",
@@ -1801,7 +3680,7 @@ var TOOLS = [
1801
3680
  }
1802
3681
  }
1803
3682
  ];
1804
- var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_clear_session"]);
3683
+ var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_redact_file", "maskera_clear_session"]);
1805
3684
  var CODE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1806
3685
  ".ts",
1807
3686
  ".tsx",
@@ -2310,7 +4189,7 @@ function createMaskeraMcpServer(options = {}) {
2310
4189
  }
2311
4190
  const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
2312
4191
  const resolvedInputPath = resolveInputPath(args.path, owner, requestedSession);
2313
- const file = await files.readText(resolvedInputPath);
4192
+ const file = await files.readDocument(resolvedInputPath);
2314
4193
  const profile = asProfile(args.profile) ?? defaultProfile;
2315
4194
  const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
2316
4195
  const { result, modeUsed } = await engine.redact(file.content, {
@@ -2333,11 +4212,109 @@ function createMaskeraMcpServer(options = {}) {
2333
4212
  toolOk({
2334
4213
  path: safePath,
2335
4214
  bytes: file.bytes,
4215
+ format: file.format,
2336
4216
  redacted: applied.redacted,
2337
4217
  session_id: applied.sessionId,
2338
4218
  counts: applied.counts,
2339
4219
  total_redactions: applied.totalRedactions,
2340
- mode: modeUsed
4220
+ mode: modeUsed,
4221
+ ...file.totalPages !== void 0 ? { total_pages: file.totalPages } : {},
4222
+ ...file.scannedPages.length > 0 ? { scanned_pages: file.scannedPages } : {},
4223
+ ...file.metadataFields.length > 0 ? { metadata_fields: file.metadataFields } : {},
4224
+ ...file.warnings.length > 0 ? { warnings: file.warnings } : {}
4225
+ })
4226
+ );
4227
+ }
4228
+ if (name === "maskera_redact_file") {
4229
+ if (typeof args.input_path !== "string") {
4230
+ return finish(toolError("Missing required string: input_path"));
4231
+ }
4232
+ if (typeof args.output_path !== "string") {
4233
+ return finish(toolError("Missing required string: output_path"));
4234
+ }
4235
+ const requestedMode = asMode(args.mode);
4236
+ if (engine.status().defaultMode === "auto" && requestedMode === "rules") {
4237
+ return finish(
4238
+ toolError(
4239
+ 'Downgrading mode to "rules" is not allowed on maskera_redact_file when the server runs in hybrid "auto" mode.'
4240
+ )
4241
+ );
4242
+ }
4243
+ const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
4244
+ const resolvedInputPath = resolveInputPath(args.input_path, owner, requestedSession);
4245
+ const resolvedOutputPath = resolveInputPath(args.output_path, owner, requestedSession);
4246
+ const source = await files.readBytes(resolvedInputPath);
4247
+ const profile = asProfile(args.profile) ?? defaultProfile;
4248
+ const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
4249
+ let sessionId = requestedSession ?? "";
4250
+ let modeUsed = engine.status().defaultMode === "rules" ? "rules" : "hybrid";
4251
+ const redactedDoc = await redactFile(
4252
+ source.bytes,
4253
+ async (text) => {
4254
+ const eng = await engine.redact(text, {
4255
+ mode: requestedMode,
4256
+ profile,
4257
+ customTerms
4258
+ });
4259
+ modeUsed = eng.modeUsed;
4260
+ const applied = vault.apply(text, eng.result, sessionId || void 0, owner);
4261
+ sessionId = applied.sessionId;
4262
+ return {
4263
+ text: applied.redacted,
4264
+ redactions: applied.redactions,
4265
+ map: applied.map,
4266
+ restore: (t) => vault.restore(t, { sessionId: applied.sessionId, owner }).restored
4267
+ };
4268
+ },
4269
+ {
4270
+ fileName: source.resolvedPath,
4271
+ pdfStyle: { showLabels: args.show_labels !== false },
4272
+ verify: true
4273
+ }
4274
+ );
4275
+ if (!redactedDoc.verified) {
4276
+ return finish(
4277
+ toolError(
4278
+ `Post-redaction verification detected ${redactedDoc.verificationLeaks.length} residual item(s) in the output file; refused to write unverified output.`
4279
+ )
4280
+ );
4281
+ }
4282
+ const written = await files.writeBytes(resolvedOutputPath, redactedDoc.bytes, {
4283
+ overwrite: args.overwrite === true
4284
+ });
4285
+ const safeInputPath = await redactResolvedPath(source.resolvedPath, {
4286
+ owner,
4287
+ sessionId: sessionId || void 0,
4288
+ mode: requestedMode,
4289
+ profile,
4290
+ customTerms
4291
+ });
4292
+ const safeOutputPath = await redactResolvedPath(written.resolvedPath, {
4293
+ owner,
4294
+ sessionId: sessionId || void 0,
4295
+ mode: requestedMode,
4296
+ profile,
4297
+ customTerms
4298
+ });
4299
+ telemetrySessionId = sessionId || void 0;
4300
+ telemetryRedactions = redactedDoc.totalRedactions;
4301
+ telemetryCounts = redactedDoc.counts;
4302
+ return finish(
4303
+ toolOk({
4304
+ input_path: safeInputPath,
4305
+ output_path: safeOutputPath,
4306
+ format: redactedDoc.format,
4307
+ bytes: written.bytes,
4308
+ session_id: sessionId,
4309
+ counts: redactedDoc.counts,
4310
+ total_redactions: redactedDoc.totalRedactions,
4311
+ mode: modeUsed,
4312
+ verified: redactedDoc.verified,
4313
+ metadata_cleared: redactedDoc.metadataCleared,
4314
+ ...redactedDoc.redactedPages ? { redacted_pages: redactedDoc.redactedPages } : {},
4315
+ ...redactedDoc.totalPages !== void 0 ? { total_pages: redactedDoc.totalPages } : {},
4316
+ ...redactedDoc.scannedPages.length > 0 ? { scanned_pages: redactedDoc.scannedPages } : {},
4317
+ ...redactedDoc.warnings.length > 0 ? { warnings: redactedDoc.warnings } : {}
2341
4318
  })
2342
4319
  );
2343
4320
  }
@@ -4733,7 +6710,38 @@ function deriveProxySessionId(headers, body) {
4733
6710
  }
4734
6711
  var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
4735
6712
  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;
4736
- var DATA_URI_ANY_RE = /^data:([^;,]+);base64,/i;
6713
+ var DATA_URI_ANY_RE = /^data:([^;,]+);base64,([A-Za-z0-9+/=\s]+)$/i;
6714
+ async function tryRedactBase64Document(encoded, mediaType, fileName, redactDocument, noteBinary) {
6715
+ if (!redactDocument) {
6716
+ noteBinary(mediaType);
6717
+ return encoded;
6718
+ }
6719
+ try {
6720
+ const rawBuf = Buffer.from(encoded, "base64");
6721
+ if (rawBuf.byteLength === 0 || rawBuf.byteLength > MAX_BODY_BYTES) {
6722
+ noteBinary(mediaType);
6723
+ return encoded;
6724
+ }
6725
+ const bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
6726
+ const detected = detectFileFormat(bytes, fileName, mediaType);
6727
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
6728
+ noteBinary(mediaType);
6729
+ return encoded;
6730
+ }
6731
+ const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
6732
+ if (!res.verified) {
6733
+ noteBinary(`${mediaType} (unverified)`);
6734
+ return encoded;
6735
+ }
6736
+ if (res.scannedPages.length > 0) {
6737
+ noteBinary(`${mediaType} (scanned)`);
6738
+ }
6739
+ return Buffer.from(res.bytes).toString("base64");
6740
+ } catch {
6741
+ noteBinary(mediaType);
6742
+ return encoded;
6743
+ }
6744
+ }
4737
6745
  async function redactBase64Utf8(encoded, redactString, kind) {
4738
6746
  try {
4739
6747
  const rawBuf = Buffer.from(encoded, "base64");
@@ -4796,17 +6804,37 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4796
6804
  await redactContentBlocks(block.output, kind);
4797
6805
  }
4798
6806
  if (typeof block.file_data === "string") {
6807
+ const fileName = typeof block.filename === "string" ? block.filename : void 0;
4799
6808
  const match = DATA_URI_TEXT_BASE64_RE.exec(block.file_data);
4800
6809
  if (match?.[1] && match[2]) {
4801
6810
  const nextB64 = await redactBase64Utf8(match[2], redactString, kind);
4802
6811
  block.file_data = `data:${match[1]};base64,${nextB64}`;
4803
6812
  } else if (block.file_data.startsWith("data:")) {
4804
- const anyMime = DATA_URI_ANY_RE.exec(block.file_data)?.[1] ?? "application/octet-stream";
4805
- noteBinary(anyMime);
6813
+ const anyMatch = DATA_URI_ANY_RE.exec(block.file_data);
6814
+ const anyMime = anyMatch?.[1] ?? "application/octet-stream";
6815
+ const b64Payload = anyMatch?.[2];
6816
+ if (b64Payload) {
6817
+ const nextB64 = await tryRedactBase64Document(
6818
+ b64Payload,
6819
+ anyMime,
6820
+ fileName,
6821
+ options.redactDocument,
6822
+ noteBinary
6823
+ );
6824
+ block.file_data = `data:${anyMime};base64,${nextB64}`;
6825
+ } else {
6826
+ noteBinary(anyMime);
6827
+ }
4806
6828
  } else {
4807
6829
  const rawBuf = Buffer.from(block.file_data, "base64");
4808
6830
  if (rawBuf.includes(0)) {
4809
- noteBinary("application/octet-stream");
6831
+ block.file_data = await tryRedactBase64Document(
6832
+ block.file_data,
6833
+ "application/octet-stream",
6834
+ fileName,
6835
+ options.redactDocument,
6836
+ noteBinary
6837
+ );
4810
6838
  } else {
4811
6839
  block.file_data = await redactBase64Utf8(block.file_data, redactString, kind);
4812
6840
  }
@@ -4817,6 +6845,18 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4817
6845
  block.source.data = await redactString(block.source.data, kind);
4818
6846
  } 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)) {
4819
6847
  block.source.data = await redactBase64Utf8(block.source.data, redactString, kind);
6848
+ } else if (block.source.type === "base64" && typeof block.source.data === "string") {
6849
+ const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
6850
+ if (blockType !== "image" && blockType !== "input_image") {
6851
+ const docTitle = typeof block.title === "string" ? block.title : void 0;
6852
+ block.source.data = await tryRedactBase64Document(
6853
+ block.source.data,
6854
+ mediaType,
6855
+ docTitle,
6856
+ options.redactDocument,
6857
+ noteBinary
6858
+ );
6859
+ }
4820
6860
  } else if (block.source.type === "base64") {
4821
6861
  const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
4822
6862
  if (blockType !== "image" && blockType !== "input_image") {
@@ -4897,7 +6937,9 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4897
6937
  for (const batchItem of clone.requests) {
4898
6938
  if (isPlainObject(batchItem) && isPlainObject(batchItem.params)) {
4899
6939
  batchItem.params = await redactLlmRequestBody(batchItem.params, redactString, {
4900
- mutate: true
6940
+ mutate: true,
6941
+ onBinaryAttachment: options.onBinaryAttachment,
6942
+ redactDocument: options.redactDocument
4901
6943
  });
4902
6944
  }
4903
6945
  }
@@ -6504,7 +8546,43 @@ async function startMaskeraProxy(options = {}) {
6504
8546
  mutate: true,
6505
8547
  onBinaryAttachment: (kind) => {
6506
8548
  binaryAttachments.add(kind);
6507
- }
8549
+ },
8550
+ redactDocument: async (bytes, info) => redactFile(
8551
+ bytes,
8552
+ async (text) => {
8553
+ const { result } = await engine.redact(text, {
8554
+ profile: options.profile,
8555
+ customTerms: options.customTerms
8556
+ });
8557
+ const applied = vault.apply(text, result, sessionId, proxyVaultOwner);
8558
+ stats.redactions += applied.totalRedactions;
8559
+ mergeCounts(stats.counts, applied.counts);
8560
+ if (applied.totalRedactions > 0) {
8561
+ if (!messageTokensForSession) {
8562
+ messageTokensForSession = /* @__PURE__ */ new Set();
8563
+ messageTokensBySession.set(sessionId, messageTokensForSession);
8564
+ }
8565
+ for (const tok of Object.keys(applied.map)) {
8566
+ messageTokensForSession.add(tok);
8567
+ }
8568
+ }
8569
+ if (messagePreviews.length < 6 && applied.redacted.trim()) {
8570
+ const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
8571
+ messagePreviews.push(snippet);
8572
+ }
8573
+ return {
8574
+ text: applied.redacted,
8575
+ redactions: applied.redactions,
8576
+ map: applied.map,
8577
+ restore: (t) => vault.restore(t, { sessionId, owner: proxyVaultOwner }).restored
8578
+ };
8579
+ },
8580
+ {
8581
+ fileName: info.fileName,
8582
+ mimeType: info.mimeType,
8583
+ verify: true
8584
+ }
8585
+ )
6508
8586
  }
6509
8587
  );
6510
8588
  redactedPreview.push(...messagePreviews.length > 0 ? messagePreviews : fallbackPreviews);