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