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