@maskera/mcp 0.4.7 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -4
- package/dist/cli.js +3235 -749
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +76 -4
- package/dist/index.js +3092 -696
- package/dist/index.js.map +1 -1
- package/package.json +10 -3
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
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 {
|
|
6
|
+
import { unzipSync, zipSync } from 'fflate';
|
|
7
|
+
import { PDFDocument, PDFName } from 'pdf-lib';
|
|
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';
|
|
9
11
|
import { randomUUID, createHash } from 'crypto';
|
|
@@ -12,6 +14,1714 @@ import { homedir } from 'os';
|
|
|
12
14
|
import { createServer } from 'http';
|
|
13
15
|
import * as zlib from 'zlib';
|
|
14
16
|
|
|
17
|
+
var MAX_DEFAULT_FILE_BYTES = 25 * 1024 * 1024;
|
|
18
|
+
var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
|
|
19
|
+
var TEXT_MIME_BY_EXT = {
|
|
20
|
+
".txt": "text/plain",
|
|
21
|
+
".md": "text/markdown",
|
|
22
|
+
".markdown": "text/markdown",
|
|
23
|
+
".csv": "text/csv",
|
|
24
|
+
".tsv": "text/tab-separated-values",
|
|
25
|
+
".json": "application/json",
|
|
26
|
+
".jsonl": "application/x-ndjson",
|
|
27
|
+
".xml": "application/xml",
|
|
28
|
+
".yaml": "application/yaml",
|
|
29
|
+
".yml": "application/yaml",
|
|
30
|
+
".html": "text/html",
|
|
31
|
+
".htm": "text/html",
|
|
32
|
+
".log": "text/plain",
|
|
33
|
+
".sql": "text/plain",
|
|
34
|
+
".ts": "text/plain",
|
|
35
|
+
".tsx": "text/plain",
|
|
36
|
+
".js": "text/plain",
|
|
37
|
+
".mjs": "text/plain",
|
|
38
|
+
".py": "text/plain"
|
|
39
|
+
};
|
|
40
|
+
function extractExtension(fileName) {
|
|
41
|
+
if (!fileName) return "";
|
|
42
|
+
const base = fileName.split(/[\\/]/).pop() ?? "";
|
|
43
|
+
const dot = base.lastIndexOf(".");
|
|
44
|
+
if (dot <= 0) return "";
|
|
45
|
+
return base.slice(dot).toLowerCase();
|
|
46
|
+
}
|
|
47
|
+
function hasPdfHeader(bytes) {
|
|
48
|
+
const limit = Math.min(bytes.byteLength, 1024);
|
|
49
|
+
for (let i = 0; i + 4 < limit; i++) {
|
|
50
|
+
if (bytes[i] === 37 && // %
|
|
51
|
+
bytes[i + 1] === 80 && // P
|
|
52
|
+
bytes[i + 2] === 68 && // D
|
|
53
|
+
bytes[i + 3] === 70 && // F
|
|
54
|
+
bytes[i + 4] === 45) {
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
function hasZipHeader(bytes) {
|
|
61
|
+
if (bytes.byteLength < 4) return false;
|
|
62
|
+
return bytes[0] === 80 && bytes[1] === 75 && (bytes[2] === 3 && bytes[3] === 4 || bytes[2] === 5 && bytes[3] === 6 || bytes[2] === 7 && bytes[3] === 8);
|
|
63
|
+
}
|
|
64
|
+
function detectOfficeZipFormat(bytes) {
|
|
65
|
+
try {
|
|
66
|
+
let isDocx = false;
|
|
67
|
+
let isXlsx = false;
|
|
68
|
+
let entriesSeen = 0;
|
|
69
|
+
unzipSync(bytes, {
|
|
70
|
+
filter(file) {
|
|
71
|
+
entriesSeen += 1;
|
|
72
|
+
if (entriesSeen > 2e3) return false;
|
|
73
|
+
const name = file.name.toLowerCase();
|
|
74
|
+
if (name === "word/document.xml") isDocx = true;
|
|
75
|
+
if (name === "xl/workbook.xml") isXlsx = true;
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
if (isDocx) return "docx";
|
|
80
|
+
if (isXlsx) return "xlsx";
|
|
81
|
+
return null;
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function mimeTypeForFormat(format2, fileName) {
|
|
87
|
+
const ext = extractExtension(fileName);
|
|
88
|
+
return TEXT_MIME_BY_EXT[ext] ?? "text/plain";
|
|
89
|
+
}
|
|
90
|
+
function detectFileFormat(bytes, fileName, mimeType) {
|
|
91
|
+
const ext = extractExtension(fileName);
|
|
92
|
+
const normalizedMime = mimeType?.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
93
|
+
if (hasPdfHeader(bytes)) {
|
|
94
|
+
return { format: "pdf", mimeType: "application/pdf", extension: ".pdf" };
|
|
95
|
+
}
|
|
96
|
+
if (hasZipHeader(bytes)) {
|
|
97
|
+
const office = detectOfficeZipFormat(bytes);
|
|
98
|
+
if (office === "docx") {
|
|
99
|
+
return {
|
|
100
|
+
format: "docx",
|
|
101
|
+
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
102
|
+
extension: ".docx"
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
if (office === "xlsx") {
|
|
106
|
+
return {
|
|
107
|
+
format: "xlsx",
|
|
108
|
+
mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
109
|
+
extension: ".xlsx"
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
format: "binary",
|
|
114
|
+
mimeType: normalizedMime || "application/zip",
|
|
115
|
+
extension: ext || ".zip"
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
for (let i = 0; i < bytes.byteLength; i++) {
|
|
119
|
+
if (bytes[i] === 0) {
|
|
120
|
+
return {
|
|
121
|
+
format: "binary",
|
|
122
|
+
mimeType: normalizedMime || "application/octet-stream",
|
|
123
|
+
extension: ext
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
UTF8_DECODER.decode(bytes);
|
|
129
|
+
return {
|
|
130
|
+
format: "text",
|
|
131
|
+
mimeType: normalizedMime && (normalizedMime.startsWith("text/") || normalizedMime.includes("json")) ? normalizedMime : mimeTypeForFormat("text", fileName),
|
|
132
|
+
extension: ext || ".txt"
|
|
133
|
+
};
|
|
134
|
+
} catch {
|
|
135
|
+
return {
|
|
136
|
+
format: "binary",
|
|
137
|
+
mimeType: normalizedMime || "application/octet-stream",
|
|
138
|
+
extension: ext
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
var MAX_ZIP_ENTRIES = 2e3;
|
|
143
|
+
var MAX_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
|
|
144
|
+
var UTF8_DECODER2 = new TextDecoder("utf-8", { fatal: false });
|
|
145
|
+
var UTF8_ENCODER = new TextEncoder();
|
|
146
|
+
function decodeUtf8(bytes) {
|
|
147
|
+
return UTF8_DECODER2.decode(bytes);
|
|
148
|
+
}
|
|
149
|
+
function encodeUtf8(text) {
|
|
150
|
+
return UTF8_ENCODER.encode(text);
|
|
151
|
+
}
|
|
152
|
+
function unzipSafely(bytes) {
|
|
153
|
+
let entryCount = 0;
|
|
154
|
+
let totalUncompressed = 0;
|
|
155
|
+
const files = unzipSync(bytes, {
|
|
156
|
+
filter(file) {
|
|
157
|
+
entryCount += 1;
|
|
158
|
+
if (entryCount > MAX_ZIP_ENTRIES) {
|
|
159
|
+
throw new Error(`Archive exceeds max allowed entry count (${MAX_ZIP_ENTRIES}).`);
|
|
160
|
+
}
|
|
161
|
+
totalUncompressed += file.originalSize;
|
|
162
|
+
if (totalUncompressed > MAX_ZIP_UNCOMPRESSED_BYTES) {
|
|
163
|
+
throw new Error(
|
|
164
|
+
`Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
let actualBytes = 0;
|
|
171
|
+
for (const data of Object.values(files)) {
|
|
172
|
+
actualBytes += data.byteLength;
|
|
173
|
+
if (actualBytes > MAX_ZIP_UNCOMPRESSED_BYTES) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
`Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return files;
|
|
180
|
+
}
|
|
181
|
+
function zipFiles(files) {
|
|
182
|
+
return zipSync(files, { level: 6 });
|
|
183
|
+
}
|
|
184
|
+
function unescapeXml(value) {
|
|
185
|
+
return value.replace(
|
|
186
|
+
/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,
|
|
187
|
+
(match, entity) => {
|
|
188
|
+
if (entity === "amp") return "&";
|
|
189
|
+
if (entity === "lt") return "<";
|
|
190
|
+
if (entity === "gt") return ">";
|
|
191
|
+
if (entity === "quot") return '"';
|
|
192
|
+
if (entity === "apos") return "'";
|
|
193
|
+
if (entity.startsWith("#x") || entity.startsWith("#X")) {
|
|
194
|
+
const code = Number.parseInt(entity.slice(2), 16);
|
|
195
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : match;
|
|
196
|
+
}
|
|
197
|
+
if (entity.startsWith("#")) {
|
|
198
|
+
const code = Number.parseInt(entity.slice(1), 10);
|
|
199
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : match;
|
|
200
|
+
}
|
|
201
|
+
return match;
|
|
202
|
+
}
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
function escapeXml(value) {
|
|
206
|
+
let out = "";
|
|
207
|
+
for (let i = 0; i < value.length; i++) {
|
|
208
|
+
const ch = value[i] ?? "";
|
|
209
|
+
const code = value.charCodeAt(i);
|
|
210
|
+
if (code < 32 && code !== 9 && code !== 10 && code !== 13) continue;
|
|
211
|
+
if (ch === "&") out += "&";
|
|
212
|
+
else if (ch === "<") out += "<";
|
|
213
|
+
else if (ch === ">") out += ">";
|
|
214
|
+
else if (ch === '"') out += """;
|
|
215
|
+
else if (ch === "'") out += "'";
|
|
216
|
+
else out += ch;
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
function escapeRegexLiteral(value) {
|
|
221
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
222
|
+
}
|
|
223
|
+
function extractXmlTextContainers(xml, containerTag, textTags, options) {
|
|
224
|
+
const escapedContainer = escapeRegexLiteral(containerTag);
|
|
225
|
+
const containerRe = new RegExp(
|
|
226
|
+
`<${escapedContainer}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${escapedContainer}>`,
|
|
227
|
+
"g"
|
|
228
|
+
);
|
|
229
|
+
const sepTags = options?.separatorTags ?? {};
|
|
230
|
+
const sepTagNames = Object.keys(sepTags);
|
|
231
|
+
const allTagAlternation = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
|
|
232
|
+
const tokenRe = new RegExp(
|
|
233
|
+
`<(${allTagAlternation})(?:\\s[^>]*)?\\/>|<(${textTags.map(escapeRegexLiteral).join("|")})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\2>`,
|
|
234
|
+
"g"
|
|
235
|
+
);
|
|
236
|
+
const containers = [];
|
|
237
|
+
let containerMatch = containerRe.exec(xml);
|
|
238
|
+
while (containerMatch !== null) {
|
|
239
|
+
const inner = containerMatch[1] ?? "";
|
|
240
|
+
const openEndOffset = containerMatch.index + containerMatch[0].indexOf(">") + 1;
|
|
241
|
+
const nodes = [];
|
|
242
|
+
let combined = "";
|
|
243
|
+
tokenRe.lastIndex = 0;
|
|
244
|
+
let tok = tokenRe.exec(inner);
|
|
245
|
+
while (tok !== null) {
|
|
246
|
+
const selfClosingName = tok[1];
|
|
247
|
+
if (selfClosingName !== void 0) {
|
|
248
|
+
const sepChar = sepTags[selfClosingName];
|
|
249
|
+
if (sepChar) {
|
|
250
|
+
combined += sepChar;
|
|
251
|
+
}
|
|
252
|
+
tok = tokenRe.exec(inner);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const tagName = tok[2] ?? "";
|
|
256
|
+
const attrs = tok[3] ?? "";
|
|
257
|
+
const rawContent = tok[4] ?? "";
|
|
258
|
+
const openTag = `<${tagName}${attrs}>`;
|
|
259
|
+
const unescaped = unescapeXml(rawContent);
|
|
260
|
+
const tagStart = openEndOffset + tok.index;
|
|
261
|
+
const contentStart = tagStart + openTag.length;
|
|
262
|
+
const contentEnd = contentStart + rawContent.length;
|
|
263
|
+
const combinedStart = combined.length;
|
|
264
|
+
combined += unescaped;
|
|
265
|
+
const combinedEnd = combined.length;
|
|
266
|
+
nodes.push({
|
|
267
|
+
tagStart,
|
|
268
|
+
contentStart,
|
|
269
|
+
contentEnd,
|
|
270
|
+
openTag,
|
|
271
|
+
text: unescaped,
|
|
272
|
+
combinedStart,
|
|
273
|
+
combinedEnd
|
|
274
|
+
});
|
|
275
|
+
tok = tokenRe.exec(inner);
|
|
276
|
+
}
|
|
277
|
+
if (nodes.length > 0) {
|
|
278
|
+
containers.push({ text: combined, nodes });
|
|
279
|
+
}
|
|
280
|
+
containerMatch = containerRe.exec(xml);
|
|
281
|
+
}
|
|
282
|
+
return containers;
|
|
283
|
+
}
|
|
284
|
+
function ensurePreserveSpace(openTag, nextText) {
|
|
285
|
+
if (!nextText) return openTag;
|
|
286
|
+
const needsPreserve = /^\s|\s$/.test(nextText);
|
|
287
|
+
if (!needsPreserve || openTag.includes("xml:space=")) return openTag;
|
|
288
|
+
return `${openTag.slice(0, -1)} xml:space="preserve">`;
|
|
289
|
+
}
|
|
290
|
+
function applyXmlContainerReplacements(xml, containers, replacementsByContainer) {
|
|
291
|
+
const rawPatches = [];
|
|
292
|
+
for (const [containerIndex, spans] of replacementsByContainer.entries()) {
|
|
293
|
+
if (spans.length === 0) continue;
|
|
294
|
+
const container = containers[containerIndex];
|
|
295
|
+
if (!container) continue;
|
|
296
|
+
const sortedSpans = [...spans].sort((a, b) => a.start - b.start);
|
|
297
|
+
const nextNodeTexts = container.nodes.map((node) => node.text);
|
|
298
|
+
for (let s = sortedSpans.length - 1; s >= 0; s--) {
|
|
299
|
+
const span = sortedSpans[s];
|
|
300
|
+
if (!span || span.end <= span.start) continue;
|
|
301
|
+
let placedReplacement = false;
|
|
302
|
+
for (let n = 0; n < container.nodes.length; n++) {
|
|
303
|
+
const node = container.nodes[n];
|
|
304
|
+
if (!node) continue;
|
|
305
|
+
const overlapStart = Math.max(span.start, node.combinedStart);
|
|
306
|
+
const overlapEnd = Math.min(span.end, node.combinedEnd);
|
|
307
|
+
if (overlapEnd <= overlapStart) continue;
|
|
308
|
+
const localStart = overlapStart - node.combinedStart;
|
|
309
|
+
const localEnd = overlapEnd - node.combinedStart;
|
|
310
|
+
const current = nextNodeTexts[n] ?? "";
|
|
311
|
+
const insert = placedReplacement ? "" : span.replacement;
|
|
312
|
+
placedReplacement = true;
|
|
313
|
+
nextNodeTexts[n] = current.slice(0, localStart) + insert + current.slice(localEnd);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
for (let n = 0; n < container.nodes.length; n++) {
|
|
317
|
+
const node = container.nodes[n];
|
|
318
|
+
const nextText = nextNodeTexts[n];
|
|
319
|
+
if (!node || nextText === void 0 || nextText === node.text) continue;
|
|
320
|
+
const nextOpenTag = ensurePreserveSpace(node.openTag, nextText);
|
|
321
|
+
rawPatches.push({
|
|
322
|
+
start: node.tagStart,
|
|
323
|
+
end: node.contentEnd,
|
|
324
|
+
replacement: `${nextOpenTag}${escapeXml(nextText)}`
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (rawPatches.length === 0) return xml;
|
|
329
|
+
rawPatches.sort((a, b) => b.start - a.start);
|
|
330
|
+
let out = xml;
|
|
331
|
+
for (const patch of rawPatches) {
|
|
332
|
+
out = out.slice(0, patch.start) + patch.replacement + out.slice(patch.end);
|
|
333
|
+
}
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
function scrubXmlMetadata(xml, tagNames) {
|
|
337
|
+
const found = {};
|
|
338
|
+
const cleared = [];
|
|
339
|
+
let nextXml = xml;
|
|
340
|
+
for (const tag of tagNames) {
|
|
341
|
+
const escaped = escapeRegexLiteral(tag);
|
|
342
|
+
const re = new RegExp(`(<${escaped}(?:\\s[^>]*)?>)([\\s\\S]*?)(<\\/${escaped}>)`, "g");
|
|
343
|
+
nextXml = nextXml.replace(re, (_match, open, inner, close) => {
|
|
344
|
+
const text = unescapeXml(inner).trim();
|
|
345
|
+
if (text.length > 0) {
|
|
346
|
+
found[tag] = text;
|
|
347
|
+
cleared.push(tag);
|
|
348
|
+
}
|
|
349
|
+
return `${open}${close}`;
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
return { xml: nextXml, found, cleared };
|
|
353
|
+
}
|
|
354
|
+
var CORE_META_TAGS = [
|
|
355
|
+
"dc:creator",
|
|
356
|
+
"cp:lastModifiedBy",
|
|
357
|
+
"dc:title",
|
|
358
|
+
"dc:subject",
|
|
359
|
+
"dc:description",
|
|
360
|
+
"cp:keywords"
|
|
361
|
+
];
|
|
362
|
+
var APP_META_TAGS = ["Company", "Manager"];
|
|
363
|
+
var DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
|
364
|
+
var XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
365
|
+
var DOCX_TEXT_PART_RE = /^word\/(?:document|header\d+|footer\d+|footnotes|endnotes|comments)\.xml$/i;
|
|
366
|
+
var XLSX_SHEET_PART_RE = /^xl\/worksheets\/sheet\d+\.xml$/i;
|
|
367
|
+
var XLSX_COMMENT_PART_RE = /^xl\/comments\d*\.xml$/i;
|
|
368
|
+
function countRedactionsByLabel(redactions) {
|
|
369
|
+
const counts = {};
|
|
370
|
+
for (const r of redactions) {
|
|
371
|
+
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
372
|
+
}
|
|
373
|
+
return counts;
|
|
374
|
+
}
|
|
375
|
+
function scrubDocxReviewAuthors(xml) {
|
|
376
|
+
const stripped = [];
|
|
377
|
+
const next = xml.replace(
|
|
378
|
+
/(<w:(?:comment|ins|del|moveFrom|moveTo)\b[^>]*?\bw:author=")([^"]*)(")/g,
|
|
379
|
+
(_m, open, val, close) => {
|
|
380
|
+
const cleaned = unescapeXml(val).trim();
|
|
381
|
+
if (cleaned) stripped.push(cleaned);
|
|
382
|
+
return `${open}${close}`;
|
|
383
|
+
}
|
|
384
|
+
);
|
|
385
|
+
return { xml: next, stripped };
|
|
386
|
+
}
|
|
387
|
+
function scrubXlsxCommentAuthors(xml) {
|
|
388
|
+
const stripped = [];
|
|
389
|
+
const next = xml.replace(
|
|
390
|
+
/(<author(?:\s[^>]*)?>)([\s\S]*?)(<\/author>)/g,
|
|
391
|
+
(_m, open, inner, close) => {
|
|
392
|
+
const cleaned = unescapeXml(inner).trim();
|
|
393
|
+
if (cleaned) stripped.push(cleaned);
|
|
394
|
+
return `${open}${close}`;
|
|
395
|
+
}
|
|
396
|
+
);
|
|
397
|
+
return { xml: next, stripped };
|
|
398
|
+
}
|
|
399
|
+
async function redactRelsTargets(archive, redactFn) {
|
|
400
|
+
const cleared = [];
|
|
401
|
+
const originalValues = [];
|
|
402
|
+
for (const [entryName, raw] of Object.entries(archive)) {
|
|
403
|
+
if (!entryName.toLowerCase().endsWith(".rels")) continue;
|
|
404
|
+
const xml = decodeUtf8(raw);
|
|
405
|
+
const relRe = /<Relationship\b[^>]*>/g;
|
|
406
|
+
const patches = [];
|
|
407
|
+
let relMatch = relRe.exec(xml);
|
|
408
|
+
while (relMatch !== null) {
|
|
409
|
+
const tag = relMatch[0];
|
|
410
|
+
const targetMatch = /\bTarget="([^"]*)"/.exec(tag);
|
|
411
|
+
if (targetMatch?.[1]) {
|
|
412
|
+
const rawTarget = unescapeXml(targetMatch[1]);
|
|
413
|
+
const isExternal = /\bTargetMode="External"/i.test(tag) || /^(?:mailto:|tel:|https?:)/i.test(rawTarget);
|
|
414
|
+
if (isExternal) {
|
|
415
|
+
const res = await redactFn(rawTarget);
|
|
416
|
+
if (res.redactions.length > 0) {
|
|
417
|
+
for (const r of res.redactions) originalValues.push(r.value);
|
|
418
|
+
const nextTag = tag.replace(/\bTarget="([^"]*)"/, `Target="${escapeXml(res.text)}"`);
|
|
419
|
+
patches.push({
|
|
420
|
+
start: relMatch.index,
|
|
421
|
+
end: relMatch.index + tag.length,
|
|
422
|
+
replacement: nextTag
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
relMatch = relRe.exec(xml);
|
|
428
|
+
}
|
|
429
|
+
if (patches.length > 0) {
|
|
430
|
+
let nextXml = xml;
|
|
431
|
+
for (let i = patches.length - 1; i >= 0; i--) {
|
|
432
|
+
const p = patches[i];
|
|
433
|
+
if (!p) continue;
|
|
434
|
+
nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
|
|
435
|
+
}
|
|
436
|
+
archive[entryName] = encodeUtf8(nextXml);
|
|
437
|
+
cleared.push(`${entryName}:Target`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return { cleared, originalValues };
|
|
441
|
+
}
|
|
442
|
+
async function redactDocxInstrText(xml, redactFn) {
|
|
443
|
+
const originalValues = [];
|
|
444
|
+
const instrRe = /(<w:instrText(?:\s[^>]*)?>)([\s\S]*?)(<\/w:instrText>)/g;
|
|
445
|
+
const patches = [];
|
|
446
|
+
let m = instrRe.exec(xml);
|
|
447
|
+
while (m !== null) {
|
|
448
|
+
const open = m[1] ?? "";
|
|
449
|
+
const rawInner = m[2] ?? "";
|
|
450
|
+
const close = m[3] ?? "";
|
|
451
|
+
const text = unescapeXml(rawInner);
|
|
452
|
+
if (text.trim().length > 0) {
|
|
453
|
+
const res = await redactFn(text);
|
|
454
|
+
if (res.redactions.length > 0) {
|
|
455
|
+
for (const r of res.redactions) originalValues.push(r.value);
|
|
456
|
+
patches.push({
|
|
457
|
+
start: m.index,
|
|
458
|
+
end: m.index + m[0].length,
|
|
459
|
+
replacement: `${open}${escapeXml(res.text)}${close}`
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
m = instrRe.exec(xml);
|
|
464
|
+
}
|
|
465
|
+
if (patches.length === 0) return { xml, originalValues };
|
|
466
|
+
let out = xml;
|
|
467
|
+
for (let i = patches.length - 1; i >= 0; i--) {
|
|
468
|
+
const p = patches[i];
|
|
469
|
+
if (!p) continue;
|
|
470
|
+
out = out.slice(0, p.start) + p.replacement + out.slice(p.end);
|
|
471
|
+
}
|
|
472
|
+
return { xml: out, originalValues };
|
|
473
|
+
}
|
|
474
|
+
function sanitizeExcelSheetName(raw, usedNames) {
|
|
475
|
+
let cleaned = raw.replace(/[\\/?*[\]:]/g, "").replace(/\s+/g, " ").trim();
|
|
476
|
+
if (!cleaned) cleaned = "Sheet";
|
|
477
|
+
if (cleaned.length > 31) cleaned = cleaned.slice(0, 31).trim();
|
|
478
|
+
let candidate = cleaned;
|
|
479
|
+
let suffix = 2;
|
|
480
|
+
while (usedNames.has(candidate.toLowerCase())) {
|
|
481
|
+
const tag = `_${suffix}`;
|
|
482
|
+
candidate = `${cleaned.slice(0, Math.max(1, 31 - tag.length))}${tag}`;
|
|
483
|
+
suffix += 1;
|
|
484
|
+
}
|
|
485
|
+
usedNames.add(candidate.toLowerCase());
|
|
486
|
+
return candidate;
|
|
487
|
+
}
|
|
488
|
+
async function redactXlsxWorkbookSheetNames(archive, redactFn) {
|
|
489
|
+
const wbKey = Object.keys(archive).find((k) => k.toLowerCase() === "xl/workbook.xml");
|
|
490
|
+
if (!wbKey || !archive[wbKey]) return { cleared: [], originalValues: [] };
|
|
491
|
+
const xml = decodeUtf8(archive[wbKey]);
|
|
492
|
+
const sheetRe = /<sheet\b[^>]*>/g;
|
|
493
|
+
const usedNames = /* @__PURE__ */ new Set();
|
|
494
|
+
const patches = [];
|
|
495
|
+
const originalValues = [];
|
|
496
|
+
let m = sheetRe.exec(xml);
|
|
497
|
+
while (m !== null) {
|
|
498
|
+
const tag = m[0];
|
|
499
|
+
const nameMatch = /\bname="([^"]*)"/.exec(tag);
|
|
500
|
+
if (nameMatch?.[1]) {
|
|
501
|
+
const sheetName = unescapeXml(nameMatch[1]);
|
|
502
|
+
const res = await redactFn(sheetName);
|
|
503
|
+
if (res.redactions.length > 0) {
|
|
504
|
+
for (const r of res.redactions) originalValues.push(r.value);
|
|
505
|
+
const safeName = sanitizeExcelSheetName(res.text, usedNames);
|
|
506
|
+
const nextTag = tag.replace(/\bname="([^"]*)"/, `name="${escapeXml(safeName)}"`);
|
|
507
|
+
patches.push({
|
|
508
|
+
start: m.index,
|
|
509
|
+
end: m.index + tag.length,
|
|
510
|
+
replacement: nextTag
|
|
511
|
+
});
|
|
512
|
+
} else {
|
|
513
|
+
usedNames.add(sheetName.toLowerCase());
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
m = sheetRe.exec(xml);
|
|
517
|
+
}
|
|
518
|
+
if (patches.length === 0) return { cleared: [], originalValues: [] };
|
|
519
|
+
let nextXml = xml;
|
|
520
|
+
for (let i = patches.length - 1; i >= 0; i--) {
|
|
521
|
+
const p = patches[i];
|
|
522
|
+
if (!p) continue;
|
|
523
|
+
nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
|
|
524
|
+
}
|
|
525
|
+
archive[wbKey] = encodeUtf8(nextXml);
|
|
526
|
+
return { cleared: [`${wbKey}:sheetName`], originalValues };
|
|
527
|
+
}
|
|
528
|
+
function listDocxTextParts(entryNames) {
|
|
529
|
+
return entryNames.filter((name) => DOCX_TEXT_PART_RE.test(name)).sort((a, b) => {
|
|
530
|
+
if (a.toLowerCase() === "word/document.xml") return -1;
|
|
531
|
+
if (b.toLowerCase() === "word/document.xml") return 1;
|
|
532
|
+
return a.localeCompare(b);
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
function listXlsxParts(entryNames) {
|
|
536
|
+
const sharedStrings = entryNames.find((n) => n.toLowerCase() === "xl/sharedstrings.xml");
|
|
537
|
+
const sheets = entryNames.filter((n) => XLSX_SHEET_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
|
|
538
|
+
const comments = entryNames.filter((n) => XLSX_COMMENT_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
|
|
539
|
+
return { sharedStrings, sheets, comments };
|
|
540
|
+
}
|
|
541
|
+
function extractOfficeMetadata(archive) {
|
|
542
|
+
const metadata = {};
|
|
543
|
+
const cleared = [];
|
|
544
|
+
const updatedArchive = { ...archive };
|
|
545
|
+
const coreKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/core.xml");
|
|
546
|
+
if (coreKey && archive[coreKey]) {
|
|
547
|
+
const res = scrubXmlMetadata(decodeUtf8(archive[coreKey]), CORE_META_TAGS);
|
|
548
|
+
Object.assign(metadata, res.found);
|
|
549
|
+
cleared.push(...res.cleared);
|
|
550
|
+
updatedArchive[coreKey] = encodeUtf8(res.xml);
|
|
551
|
+
}
|
|
552
|
+
const appKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/app.xml");
|
|
553
|
+
if (appKey && archive[appKey]) {
|
|
554
|
+
const res = scrubXmlMetadata(decodeUtf8(archive[appKey]), APP_META_TAGS);
|
|
555
|
+
Object.assign(metadata, res.found);
|
|
556
|
+
cleared.push(...res.cleared);
|
|
557
|
+
updatedArchive[appKey] = encodeUtf8(res.xml);
|
|
558
|
+
}
|
|
559
|
+
return { metadata, cleared, updatedArchive };
|
|
560
|
+
}
|
|
561
|
+
function mapRedactionsToPartContainers(parts, redactions) {
|
|
562
|
+
const byPart = /* @__PURE__ */ new Map();
|
|
563
|
+
for (const r of redactions) {
|
|
564
|
+
for (const part of parts) {
|
|
565
|
+
let partMap = byPart.get(part.partPath);
|
|
566
|
+
for (let i = 0; i < part.containerOffsets.length; i++) {
|
|
567
|
+
const range = part.containerOffsets[i];
|
|
568
|
+
if (!range) continue;
|
|
569
|
+
if (r.end <= range.start || r.start >= range.end) continue;
|
|
570
|
+
const localStart = Math.max(0, r.start - range.start);
|
|
571
|
+
const localEnd = Math.min(range.end - range.start, r.end - range.start);
|
|
572
|
+
if (localEnd <= localStart) continue;
|
|
573
|
+
if (!partMap) {
|
|
574
|
+
partMap = /* @__PURE__ */ new Map();
|
|
575
|
+
byPart.set(part.partPath, partMap);
|
|
576
|
+
}
|
|
577
|
+
const list = partMap.get(i) ?? [];
|
|
578
|
+
list.push({ start: localStart, end: localEnd, replacement: r.replacement });
|
|
579
|
+
partMap.set(i, list);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return byPart;
|
|
584
|
+
}
|
|
585
|
+
function extractDocx(bytes) {
|
|
586
|
+
const archive = unzipSafely(bytes);
|
|
587
|
+
const parts = listDocxTextParts(Object.keys(archive));
|
|
588
|
+
const sections = [];
|
|
589
|
+
for (const partPath of parts) {
|
|
590
|
+
const raw = archive[partPath];
|
|
591
|
+
if (!raw) continue;
|
|
592
|
+
const xml = decodeUtf8(raw);
|
|
593
|
+
const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
|
|
594
|
+
separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
|
|
595
|
+
});
|
|
596
|
+
const partText = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
|
|
597
|
+
if (partText.length > 0) {
|
|
598
|
+
sections.push({
|
|
599
|
+
id: partPath,
|
|
600
|
+
label: partPath.replace(/^word\//i, "").replace(/\.xml$/i, ""),
|
|
601
|
+
text: partText
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
const { metadata } = extractOfficeMetadata(archive);
|
|
606
|
+
const fullText = sections.map((s) => s.text).join("\n\n");
|
|
607
|
+
return {
|
|
608
|
+
format: "docx",
|
|
609
|
+
mimeType: DOCX_MIME,
|
|
610
|
+
text: fullText,
|
|
611
|
+
sections,
|
|
612
|
+
metadata,
|
|
613
|
+
warnings: [],
|
|
614
|
+
scannedPages: []
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
async function redactDocx(bytes, redactFn) {
|
|
618
|
+
const archive = unzipSafely(bytes);
|
|
619
|
+
const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
|
|
620
|
+
const metadataValues = Object.values(metadata);
|
|
621
|
+
const partPaths = listDocxTextParts(Object.keys(updatedArchive));
|
|
622
|
+
const parts = [];
|
|
623
|
+
const textChunks = [];
|
|
624
|
+
let cursor = 0;
|
|
625
|
+
for (const partPath of partPaths) {
|
|
626
|
+
const raw = updatedArchive[partPath];
|
|
627
|
+
if (!raw) continue;
|
|
628
|
+
const rawXml = decodeUtf8(raw);
|
|
629
|
+
const { xml, stripped } = scrubDocxReviewAuthors(rawXml);
|
|
630
|
+
if (stripped.length > 0) {
|
|
631
|
+
metadataCleared.push(`${partPath}:w:author`);
|
|
632
|
+
metadataValues.push(...stripped);
|
|
633
|
+
}
|
|
634
|
+
const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
|
|
635
|
+
separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
|
|
636
|
+
});
|
|
637
|
+
const containerOffsets = [];
|
|
638
|
+
for (const container of containers) {
|
|
639
|
+
if (container.text.length === 0) {
|
|
640
|
+
containerOffsets.push({ start: cursor, end: cursor });
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
if (textChunks.length > 0) {
|
|
644
|
+
textChunks.push("\n\n");
|
|
645
|
+
cursor += 2;
|
|
646
|
+
}
|
|
647
|
+
const start = cursor;
|
|
648
|
+
textChunks.push(container.text);
|
|
649
|
+
cursor += container.text.length;
|
|
650
|
+
containerOffsets.push({ start, end: cursor });
|
|
651
|
+
}
|
|
652
|
+
parts.push({ partPath, xml, containers, containerOffsets });
|
|
653
|
+
}
|
|
654
|
+
const combinedText = textChunks.join("");
|
|
655
|
+
const result = await redactFn(combinedText);
|
|
656
|
+
const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
|
|
657
|
+
for (const part of parts) {
|
|
658
|
+
const partMap = replacementsByPart.get(part.partPath);
|
|
659
|
+
let nextXml = partMap ? applyXmlContainerReplacements(part.xml, part.containers, partMap) : part.xml;
|
|
660
|
+
const instr = await redactDocxInstrText(nextXml, redactFn);
|
|
661
|
+
if (instr.originalValues.length > 0) {
|
|
662
|
+
nextXml = instr.xml;
|
|
663
|
+
metadataCleared.push(`${part.partPath}:w:instrText`);
|
|
664
|
+
metadataValues.push(...instr.originalValues);
|
|
665
|
+
}
|
|
666
|
+
updatedArchive[part.partPath] = encodeUtf8(nextXml);
|
|
667
|
+
}
|
|
668
|
+
const relsRes = await redactRelsTargets(updatedArchive, redactFn);
|
|
669
|
+
metadataCleared.push(...relsRes.cleared);
|
|
670
|
+
metadataValues.push(...relsRes.originalValues);
|
|
671
|
+
return {
|
|
672
|
+
bytes: zipFiles(updatedArchive),
|
|
673
|
+
extractedText: combinedText,
|
|
674
|
+
redactedText: result.text,
|
|
675
|
+
totalRedactions: result.redactions.length,
|
|
676
|
+
counts: countRedactionsByLabel(result.redactions),
|
|
677
|
+
redactions: result.redactions,
|
|
678
|
+
map: result.map,
|
|
679
|
+
metadataCleared,
|
|
680
|
+
metadataValues,
|
|
681
|
+
warnings: []
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
function extractXlsxCachedFormulaStrings(xml) {
|
|
685
|
+
const out = [];
|
|
686
|
+
const cellRe = /<c\b[^>]*\bt="str"[^>]*>([\s\S]*?)<\/c>/g;
|
|
687
|
+
let m = cellRe.exec(xml);
|
|
688
|
+
while (m !== null) {
|
|
689
|
+
const inner = m[1] ?? "";
|
|
690
|
+
const vMatch = /<v(?:\s[^>]*)?>([\s\S]*?)<\/v>/.exec(inner);
|
|
691
|
+
if (vMatch) {
|
|
692
|
+
const openEnd = m.index + m[0].indexOf(">") + 1;
|
|
693
|
+
const vOpenEnd = vMatch.index + vMatch[0].indexOf(">") + 1;
|
|
694
|
+
const rawContent = vMatch[1] ?? "";
|
|
695
|
+
const contentStart = openEnd + vOpenEnd;
|
|
696
|
+
const contentEnd = contentStart + rawContent.length;
|
|
697
|
+
out.push({ contentStart, contentEnd, text: unescapeXml(rawContent) });
|
|
698
|
+
}
|
|
699
|
+
m = cellRe.exec(xml);
|
|
700
|
+
}
|
|
701
|
+
return out;
|
|
702
|
+
}
|
|
703
|
+
function extractXlsx(bytes) {
|
|
704
|
+
const archive = unzipSafely(bytes);
|
|
705
|
+
const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(archive));
|
|
706
|
+
const sections = [];
|
|
707
|
+
if (sharedStrings && archive[sharedStrings]) {
|
|
708
|
+
const xml = decodeUtf8(archive[sharedStrings]);
|
|
709
|
+
const containers = extractXmlTextContainers(xml, "si", ["t"]);
|
|
710
|
+
const text = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
|
|
711
|
+
if (text) {
|
|
712
|
+
sections.push({ id: sharedStrings, label: "sharedStrings", text });
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
for (const sheetPath of sheets) {
|
|
716
|
+
const raw = archive[sheetPath];
|
|
717
|
+
if (!raw) continue;
|
|
718
|
+
const xml = decodeUtf8(raw);
|
|
719
|
+
const inlineContainers = extractXmlTextContainers(xml, "is", ["t"]);
|
|
720
|
+
const formulaStrings = extractXlsxCachedFormulaStrings(xml);
|
|
721
|
+
const lines = [
|
|
722
|
+
...inlineContainers.map((c) => c.text),
|
|
723
|
+
...formulaStrings.map((f) => f.text)
|
|
724
|
+
].filter((t) => t.length > 0);
|
|
725
|
+
if (lines.length > 0) {
|
|
726
|
+
sections.push({
|
|
727
|
+
id: sheetPath,
|
|
728
|
+
label: sheetPath.replace(/^xl\/worksheets\//i, "").replace(/\.xml$/i, ""),
|
|
729
|
+
text: lines.join("\n\n")
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
for (const commentPath of comments) {
|
|
734
|
+
const raw = archive[commentPath];
|
|
735
|
+
if (!raw) continue;
|
|
736
|
+
const xml = decodeUtf8(raw);
|
|
737
|
+
const commentContainers = extractXmlTextContainers(xml, "text", ["t"]);
|
|
738
|
+
const lines = commentContainers.map((c) => c.text).filter((t) => t.length > 0);
|
|
739
|
+
if (lines.length > 0) {
|
|
740
|
+
sections.push({
|
|
741
|
+
id: commentPath,
|
|
742
|
+
label: commentPath.replace(/^xl\//i, "").replace(/\.xml$/i, ""),
|
|
743
|
+
text: lines.join("\n\n")
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
const { metadata } = extractOfficeMetadata(archive);
|
|
748
|
+
return {
|
|
749
|
+
format: "xlsx",
|
|
750
|
+
mimeType: XLSX_MIME,
|
|
751
|
+
text: sections.map((s) => s.text).join("\n\n"),
|
|
752
|
+
sections,
|
|
753
|
+
metadata,
|
|
754
|
+
warnings: [],
|
|
755
|
+
scannedPages: []
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
async function redactXlsx(bytes, redactFn) {
|
|
759
|
+
const archive = unzipSafely(bytes);
|
|
760
|
+
const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
|
|
761
|
+
const metadataValues = Object.values(metadata);
|
|
762
|
+
const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(updatedArchive));
|
|
763
|
+
const parts = [];
|
|
764
|
+
const formulaRecords = [];
|
|
765
|
+
const textChunks = [];
|
|
766
|
+
let cursor = 0;
|
|
767
|
+
const addPart = (partPath, xml, containerTag) => {
|
|
768
|
+
const containers = extractXmlTextContainers(xml, containerTag, ["t"]);
|
|
769
|
+
const containerOffsets = [];
|
|
770
|
+
for (const container of containers) {
|
|
771
|
+
if (container.text.length === 0) {
|
|
772
|
+
containerOffsets.push({ start: cursor, end: cursor });
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if (textChunks.length > 0) {
|
|
776
|
+
textChunks.push("\n\n");
|
|
777
|
+
cursor += 2;
|
|
778
|
+
}
|
|
779
|
+
const start = cursor;
|
|
780
|
+
textChunks.push(container.text);
|
|
781
|
+
cursor += container.text.length;
|
|
782
|
+
containerOffsets.push({ start, end: cursor });
|
|
783
|
+
}
|
|
784
|
+
parts.push({ partPath, xml, containers, containerOffsets });
|
|
785
|
+
};
|
|
786
|
+
if (sharedStrings && updatedArchive[sharedStrings]) {
|
|
787
|
+
addPart(sharedStrings, decodeUtf8(updatedArchive[sharedStrings]), "si");
|
|
788
|
+
}
|
|
789
|
+
for (const sheetPath of sheets) {
|
|
790
|
+
const raw = updatedArchive[sheetPath];
|
|
791
|
+
if (!raw) continue;
|
|
792
|
+
const xml = decodeUtf8(raw);
|
|
793
|
+
addPart(sheetPath, xml, "is");
|
|
794
|
+
const formulas = extractXlsxCachedFormulaStrings(xml);
|
|
795
|
+
if (formulas.length > 0) {
|
|
796
|
+
const entries = [];
|
|
797
|
+
for (const f of formulas) {
|
|
798
|
+
if (textChunks.length > 0) {
|
|
799
|
+
textChunks.push("\n\n");
|
|
800
|
+
cursor += 2;
|
|
801
|
+
}
|
|
802
|
+
const start = cursor;
|
|
803
|
+
textChunks.push(f.text);
|
|
804
|
+
cursor += f.text.length;
|
|
805
|
+
entries.push({
|
|
806
|
+
contentStart: f.contentStart,
|
|
807
|
+
contentEnd: f.contentEnd,
|
|
808
|
+
start,
|
|
809
|
+
end: cursor
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
formulaRecords.push({ partPath: sheetPath, entries });
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
for (const commentPath of comments) {
|
|
816
|
+
const raw = updatedArchive[commentPath];
|
|
817
|
+
if (!raw) continue;
|
|
818
|
+
const { xml, stripped } = scrubXlsxCommentAuthors(decodeUtf8(raw));
|
|
819
|
+
if (stripped.length > 0) {
|
|
820
|
+
metadataCleared.push(`${commentPath}:author`);
|
|
821
|
+
metadataValues.push(...stripped);
|
|
822
|
+
}
|
|
823
|
+
addPart(commentPath, xml, "text");
|
|
824
|
+
}
|
|
825
|
+
const combinedText = textChunks.join("");
|
|
826
|
+
const result = await redactFn(combinedText);
|
|
827
|
+
const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
|
|
828
|
+
const formulaByPart = new Map(formulaRecords.map((f) => [f.partPath, f.entries]));
|
|
829
|
+
for (const part of parts) {
|
|
830
|
+
let nextXml = part.xml;
|
|
831
|
+
const formulaEntries = formulaByPart.get(part.partPath);
|
|
832
|
+
if (formulaEntries && formulaEntries.length > 0) {
|
|
833
|
+
const rawPatches = [];
|
|
834
|
+
for (const entry of formulaEntries) {
|
|
835
|
+
const overlapping = result.redactions.filter(
|
|
836
|
+
(r) => r.end > entry.start && r.start < entry.end
|
|
837
|
+
);
|
|
838
|
+
if (overlapping.length === 0) continue;
|
|
839
|
+
let text = combinedText.slice(entry.start, entry.end);
|
|
840
|
+
for (let i = overlapping.length - 1; i >= 0; i--) {
|
|
841
|
+
const r = overlapping[i];
|
|
842
|
+
if (!r) continue;
|
|
843
|
+
const localStart = Math.max(0, r.start - entry.start);
|
|
844
|
+
const localEnd = Math.min(text.length, r.end - entry.start);
|
|
845
|
+
text = text.slice(0, localStart) + r.replacement + text.slice(localEnd);
|
|
846
|
+
}
|
|
847
|
+
rawPatches.push({
|
|
848
|
+
start: entry.contentStart,
|
|
849
|
+
end: entry.contentEnd,
|
|
850
|
+
replacement: escapeXml(text)
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
if (rawPatches.length > 0) {
|
|
854
|
+
rawPatches.sort((a, b) => b.start - a.start);
|
|
855
|
+
for (const p of rawPatches) {
|
|
856
|
+
nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
|
|
857
|
+
}
|
|
858
|
+
const partMap2 = replacementsByPart.get(part.partPath);
|
|
859
|
+
if (partMap2 && partMap2.size > 0) {
|
|
860
|
+
const freshContainers = extractXmlTextContainers(nextXml, "is", ["t"]);
|
|
861
|
+
nextXml = applyXmlContainerReplacements(nextXml, freshContainers, partMap2);
|
|
862
|
+
}
|
|
863
|
+
updatedArchive[part.partPath] = encodeUtf8(nextXml);
|
|
864
|
+
continue;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
const partMap = replacementsByPart.get(part.partPath);
|
|
868
|
+
if (partMap) {
|
|
869
|
+
nextXml = applyXmlContainerReplacements(nextXml, part.containers, partMap);
|
|
870
|
+
}
|
|
871
|
+
updatedArchive[part.partPath] = encodeUtf8(nextXml);
|
|
872
|
+
}
|
|
873
|
+
const wbRes = await redactXlsxWorkbookSheetNames(updatedArchive, redactFn);
|
|
874
|
+
metadataCleared.push(...wbRes.cleared);
|
|
875
|
+
metadataValues.push(...wbRes.originalValues);
|
|
876
|
+
const relsRes = await redactRelsTargets(updatedArchive, redactFn);
|
|
877
|
+
metadataCleared.push(...relsRes.cleared);
|
|
878
|
+
metadataValues.push(...relsRes.originalValues);
|
|
879
|
+
return {
|
|
880
|
+
bytes: zipFiles(updatedArchive),
|
|
881
|
+
extractedText: combinedText,
|
|
882
|
+
redactedText: result.text,
|
|
883
|
+
totalRedactions: result.redactions.length,
|
|
884
|
+
counts: countRedactionsByLabel(result.redactions),
|
|
885
|
+
redactions: result.redactions,
|
|
886
|
+
map: result.map,
|
|
887
|
+
metadataCleared,
|
|
888
|
+
metadataValues,
|
|
889
|
+
warnings: []
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
var configuredWorkerSrc;
|
|
893
|
+
var cachedPdfjsPromise = null;
|
|
894
|
+
async function loadPdfjs(workerSrcOverride) {
|
|
895
|
+
if (!cachedPdfjsPromise) {
|
|
896
|
+
cachedPdfjsPromise = import('pdfjs-dist/legacy/build/pdf.mjs');
|
|
897
|
+
}
|
|
898
|
+
const pdfjs = await cachedPdfjsPromise;
|
|
899
|
+
const workerSrc = workerSrcOverride ?? configuredWorkerSrc;
|
|
900
|
+
if (workerSrc && pdfjs.GlobalWorkerOptions.workerSrc !== workerSrc) {
|
|
901
|
+
pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
|
|
902
|
+
}
|
|
903
|
+
return pdfjs;
|
|
904
|
+
}
|
|
905
|
+
function isPdfTextItem(item) {
|
|
906
|
+
if (!item || typeof item !== "object") return false;
|
|
907
|
+
const rec = item;
|
|
908
|
+
return typeof rec.str === "string" && Array.isArray(rec.transform) && rec.transform.length >= 6;
|
|
909
|
+
}
|
|
910
|
+
function computeItemBounds(item) {
|
|
911
|
+
const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = item.transform;
|
|
912
|
+
const scaleX = Math.hypot(a, b);
|
|
913
|
+
const scaleY = Math.hypot(c, d);
|
|
914
|
+
const fontHeight = Math.max(scaleY, scaleX, item.height || 0, 6);
|
|
915
|
+
const width = typeof item.width === "number" && item.width > 0 ? item.width : fontHeight * 0.55 * Math.max(1, item.str.length);
|
|
916
|
+
const isHorizontal = Math.abs(b) < 0.05 && Math.abs(c) < 0.05;
|
|
917
|
+
if (isHorizontal) {
|
|
918
|
+
return {
|
|
919
|
+
x1: e,
|
|
920
|
+
y1: f - fontHeight * 0.3,
|
|
921
|
+
x2: e + width,
|
|
922
|
+
y2: f + fontHeight * 1.08,
|
|
923
|
+
fontHeight,
|
|
924
|
+
isHorizontal: true
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
const lenX = scaleX || 1;
|
|
928
|
+
const ux = a / lenX;
|
|
929
|
+
const uy = b / lenX;
|
|
930
|
+
const lenY = scaleY || 1;
|
|
931
|
+
const vx = c / lenY;
|
|
932
|
+
const vy = d / lenY;
|
|
933
|
+
const asc = fontHeight * 1.08;
|
|
934
|
+
const desc = -fontHeight * 0.3;
|
|
935
|
+
const corners = [
|
|
936
|
+
[e + vx * desc, f + vy * desc],
|
|
937
|
+
[e + ux * width + vx * desc, f + uy * width + vy * desc],
|
|
938
|
+
[e + vx * asc, f + vy * asc],
|
|
939
|
+
[e + ux * width + vx * asc, f + uy * width + vy * asc]
|
|
940
|
+
];
|
|
941
|
+
let x1 = Number.POSITIVE_INFINITY;
|
|
942
|
+
let y1 = Number.POSITIVE_INFINITY;
|
|
943
|
+
let x2 = Number.NEGATIVE_INFINITY;
|
|
944
|
+
let y2 = Number.NEGATIVE_INFINITY;
|
|
945
|
+
for (const [cx, cy] of corners) {
|
|
946
|
+
if (cx < x1) x1 = cx;
|
|
947
|
+
if (cy < y1) y1 = cy;
|
|
948
|
+
if (cx > x2) x2 = cx;
|
|
949
|
+
if (cy > y2) y2 = cy;
|
|
950
|
+
}
|
|
951
|
+
return { x1, y1, x2, y2, fontHeight, isHorizontal: false };
|
|
952
|
+
}
|
|
953
|
+
function buildPageTextAndMap(rawItems, styles) {
|
|
954
|
+
const items = [];
|
|
955
|
+
let text = "";
|
|
956
|
+
let prevBaselineY = null;
|
|
957
|
+
let prevRightX = 0;
|
|
958
|
+
let prevHadEol = false;
|
|
959
|
+
for (const raw of rawItems) {
|
|
960
|
+
if (!isPdfTextItem(raw)) continue;
|
|
961
|
+
if (raw.str.length === 0) {
|
|
962
|
+
if (raw.hasEOL) prevHadEol = true;
|
|
963
|
+
continue;
|
|
964
|
+
}
|
|
965
|
+
const bounds = computeItemBounds(raw);
|
|
966
|
+
const baselineY = raw.transform[5] ?? 0;
|
|
967
|
+
const leftX = raw.transform[4] ?? 0;
|
|
968
|
+
const style = raw.fontName ? styles?.[raw.fontName] : void 0;
|
|
969
|
+
const fontFamily = style?.fontFamily || "sans-serif";
|
|
970
|
+
if (text.length > 0) {
|
|
971
|
+
const lineChanged = prevHadEol || prevBaselineY !== null && Math.abs(baselineY - prevBaselineY) > bounds.fontHeight * 0.6;
|
|
972
|
+
if (lineChanged) {
|
|
973
|
+
if (!text.endsWith("\n")) text += "\n";
|
|
974
|
+
} else {
|
|
975
|
+
const gap = leftX - prevRightX;
|
|
976
|
+
const needsSpace = gap > bounds.fontHeight * 0.16 && !/\s$/.test(text) && !/^\s/.test(raw.str);
|
|
977
|
+
if (needsSpace) text += " ";
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
const start = text.length;
|
|
981
|
+
text += raw.str;
|
|
982
|
+
const end = text.length;
|
|
983
|
+
const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = raw.transform;
|
|
984
|
+
const itemWidth = typeof raw.width === "number" && raw.width > 0 ? raw.width : bounds.fontHeight * 0.55 * Math.max(1, raw.str.length);
|
|
985
|
+
items.push({
|
|
986
|
+
str: raw.str,
|
|
987
|
+
start,
|
|
988
|
+
end,
|
|
989
|
+
x1: bounds.x1,
|
|
990
|
+
y1: bounds.y1,
|
|
991
|
+
x2: bounds.x2,
|
|
992
|
+
y2: bounds.y2,
|
|
993
|
+
fontHeight: bounds.fontHeight,
|
|
994
|
+
fontFamily,
|
|
995
|
+
width: itemWidth,
|
|
996
|
+
transform: [a, b, c, d, e, f],
|
|
997
|
+
isHorizontal: bounds.isHorizontal
|
|
998
|
+
});
|
|
999
|
+
prevBaselineY = baselineY;
|
|
1000
|
+
prevRightX = bounds.x2;
|
|
1001
|
+
prevHadEol = raw.hasEOL === true;
|
|
1002
|
+
}
|
|
1003
|
+
return { text, items };
|
|
1004
|
+
}
|
|
1005
|
+
function extractAnnotationTexts(annotations) {
|
|
1006
|
+
const out = [];
|
|
1007
|
+
for (const raw of annotations) {
|
|
1008
|
+
if (!raw || typeof raw !== "object") continue;
|
|
1009
|
+
const rec = raw;
|
|
1010
|
+
const snippets = [];
|
|
1011
|
+
if (typeof rec.url === "string" && rec.url.trim()) {
|
|
1012
|
+
snippets.push(rec.url.trim());
|
|
1013
|
+
}
|
|
1014
|
+
if (typeof rec.fieldValue === "string" && rec.fieldValue.trim()) {
|
|
1015
|
+
snippets.push(rec.fieldValue.trim());
|
|
1016
|
+
} else if (Array.isArray(rec.fieldValue)) {
|
|
1017
|
+
for (const v of rec.fieldValue) {
|
|
1018
|
+
if (typeof v === "string" && v.trim()) snippets.push(v.trim());
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (rec.contentsObj && typeof rec.contentsObj === "object") {
|
|
1022
|
+
const str = rec.contentsObj.str;
|
|
1023
|
+
if (typeof str === "string" && str.trim()) snippets.push(str.trim());
|
|
1024
|
+
}
|
|
1025
|
+
if (typeof rec.titleObj === "object" && rec.titleObj !== null) {
|
|
1026
|
+
const str = rec.titleObj.str;
|
|
1027
|
+
if (typeof str === "string" && str.trim()) snippets.push(str.trim());
|
|
1028
|
+
}
|
|
1029
|
+
if (typeof rec.alternativeText === "string" && rec.alternativeText.trim()) {
|
|
1030
|
+
snippets.push(rec.alternativeText.trim());
|
|
1031
|
+
}
|
|
1032
|
+
if (snippets.length === 0) continue;
|
|
1033
|
+
let rect;
|
|
1034
|
+
if (Array.isArray(rec.rect) && rec.rect.length === 4 && rec.rect.every((n) => typeof n === "number" && Number.isFinite(n))) {
|
|
1035
|
+
rect = [rec.rect[0], rec.rect[1], rec.rect[2], rec.rect[3]];
|
|
1036
|
+
}
|
|
1037
|
+
out.push({ text: snippets.join(" "), rect });
|
|
1038
|
+
}
|
|
1039
|
+
return out;
|
|
1040
|
+
}
|
|
1041
|
+
function collectPdfMetadataStrings(meta) {
|
|
1042
|
+
const out = {};
|
|
1043
|
+
const sensitiveInfoKeys = [
|
|
1044
|
+
"Title",
|
|
1045
|
+
"Author",
|
|
1046
|
+
"Subject",
|
|
1047
|
+
"Keywords",
|
|
1048
|
+
"Creator",
|
|
1049
|
+
"Producer"
|
|
1050
|
+
];
|
|
1051
|
+
if (meta.info && typeof meta.info === "object") {
|
|
1052
|
+
const info = meta.info;
|
|
1053
|
+
for (const key of sensitiveInfoKeys) {
|
|
1054
|
+
const value = info[key];
|
|
1055
|
+
if (typeof value === "string" && value.trim()) {
|
|
1056
|
+
out[key] = value.trim();
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
return out;
|
|
1061
|
+
}
|
|
1062
|
+
async function resolveDefaultCanvasProvider() {
|
|
1063
|
+
if (typeof document !== "undefined" && typeof document.createElement === "function") {
|
|
1064
|
+
return {
|
|
1065
|
+
createCanvas(width, height) {
|
|
1066
|
+
const canvas = document.createElement("canvas");
|
|
1067
|
+
canvas.width = width;
|
|
1068
|
+
canvas.height = height;
|
|
1069
|
+
return canvas;
|
|
1070
|
+
},
|
|
1071
|
+
async toPngBytes(canvas) {
|
|
1072
|
+
const htmlCanvas = canvas;
|
|
1073
|
+
const blob = await new Promise((resolve5, reject) => {
|
|
1074
|
+
htmlCanvas.toBlob((b) => {
|
|
1075
|
+
if (b) resolve5(b);
|
|
1076
|
+
else reject(new Error("Failed to encode PDF page canvas to PNG."));
|
|
1077
|
+
}, "image/png");
|
|
1078
|
+
});
|
|
1079
|
+
return new Uint8Array(await blob.arrayBuffer());
|
|
1080
|
+
}
|
|
1081
|
+
};
|
|
1082
|
+
}
|
|
1083
|
+
if (typeof OffscreenCanvas !== "undefined") {
|
|
1084
|
+
return {
|
|
1085
|
+
createCanvas(width, height) {
|
|
1086
|
+
return new OffscreenCanvas(width, height);
|
|
1087
|
+
},
|
|
1088
|
+
async toPngBytes(canvas) {
|
|
1089
|
+
const off = canvas;
|
|
1090
|
+
const blob = await off.convertToBlob({ type: "image/png" });
|
|
1091
|
+
return new Uint8Array(await blob.arrayBuffer());
|
|
1092
|
+
}
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
const canvasPkg = "@napi-rs/canvas";
|
|
1096
|
+
const mod = await import(
|
|
1097
|
+
/* @vite-ignore */
|
|
1098
|
+
canvasPkg
|
|
1099
|
+
);
|
|
1100
|
+
return {
|
|
1101
|
+
createCanvas(width, height) {
|
|
1102
|
+
return mod.createCanvas(width, height);
|
|
1103
|
+
},
|
|
1104
|
+
toPngBytes(canvas) {
|
|
1105
|
+
const napiCanvas = canvas;
|
|
1106
|
+
return new Uint8Array(napiCanvas.toBuffer("image/png"));
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
function mergeLineBoxes(boxes) {
|
|
1111
|
+
if (boxes.length <= 1) return [...boxes];
|
|
1112
|
+
const sorted = [...boxes].sort((a, b) => {
|
|
1113
|
+
const cyA = (a.y1 + a.y2) / 2;
|
|
1114
|
+
const cyB = (b.y1 + b.y2) / 2;
|
|
1115
|
+
if (Math.abs(cyA - cyB) > Math.min(a.y2 - a.y1, b.y2 - b.y1) * 0.5) {
|
|
1116
|
+
return cyB - cyA;
|
|
1117
|
+
}
|
|
1118
|
+
return a.x1 - b.x1;
|
|
1119
|
+
});
|
|
1120
|
+
const merged = [];
|
|
1121
|
+
for (const box of sorted) {
|
|
1122
|
+
const prev = merged[merged.length - 1];
|
|
1123
|
+
if (prev && prev.replacement === box.replacement) {
|
|
1124
|
+
const hPrev = prev.y2 - prev.y1;
|
|
1125
|
+
const hCur = box.y2 - box.y1;
|
|
1126
|
+
const yOverlap = Math.min(prev.y2, box.y2) - Math.max(prev.y1, box.y1);
|
|
1127
|
+
const minH = Math.min(hPrev, hCur);
|
|
1128
|
+
const xGap = box.x1 - prev.x2;
|
|
1129
|
+
if (minH > 0 && yOverlap > minH * 0.45 && xGap <= Math.max(hPrev, hCur) * 1.5) {
|
|
1130
|
+
prev.x1 = Math.min(prev.x1, box.x1);
|
|
1131
|
+
prev.y1 = Math.min(prev.y1, box.y1);
|
|
1132
|
+
prev.x2 = Math.max(prev.x2, box.x2);
|
|
1133
|
+
prev.y2 = Math.max(prev.y2, box.y2);
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
merged.push({ ...box });
|
|
1138
|
+
}
|
|
1139
|
+
return merged;
|
|
1140
|
+
}
|
|
1141
|
+
function measureSubspanFractions(ctx, str, localStart, localEnd, fontFamily) {
|
|
1142
|
+
const len = Math.max(1, str.length);
|
|
1143
|
+
if (localStart <= 0 && localEnd >= len) {
|
|
1144
|
+
return { startFrac: 0, endFrac: 1 };
|
|
1145
|
+
}
|
|
1146
|
+
const isMonospace = /\bmono/i.test(fontFamily);
|
|
1147
|
+
if (isMonospace || !ctx?.measureText) {
|
|
1148
|
+
return { startFrac: localStart / len, endFrac: localEnd / len };
|
|
1149
|
+
}
|
|
1150
|
+
const prefix = str.slice(0, localStart);
|
|
1151
|
+
const uptoEnd = str.slice(0, localEnd);
|
|
1152
|
+
const families = /* @__PURE__ */ new Set([
|
|
1153
|
+
fontFamily,
|
|
1154
|
+
"Helvetica, Arial, sans-serif",
|
|
1155
|
+
"Times New Roman, Times, serif"
|
|
1156
|
+
]);
|
|
1157
|
+
let minStart = 1;
|
|
1158
|
+
let maxEnd = 0;
|
|
1159
|
+
let measuredAny = false;
|
|
1160
|
+
ctx.save();
|
|
1161
|
+
for (const family of families) {
|
|
1162
|
+
ctx.font = `100px ${family}`;
|
|
1163
|
+
const fullW = ctx.measureText(str).width;
|
|
1164
|
+
if (!(fullW > 0)) continue;
|
|
1165
|
+
const startW = localStart > 0 ? ctx.measureText(prefix).width : 0;
|
|
1166
|
+
const endW = localEnd < len ? ctx.measureText(uptoEnd).width : fullW;
|
|
1167
|
+
minStart = Math.min(minStart, Math.max(0, startW / fullW));
|
|
1168
|
+
maxEnd = Math.max(maxEnd, Math.min(1, endW / fullW));
|
|
1169
|
+
measuredAny = true;
|
|
1170
|
+
}
|
|
1171
|
+
ctx.restore();
|
|
1172
|
+
if (!measuredAny || maxEnd <= minStart) {
|
|
1173
|
+
return { startFrac: localStart / len, endFrac: localEnd / len };
|
|
1174
|
+
}
|
|
1175
|
+
return { startFrac: minStart, endFrac: maxEnd };
|
|
1176
|
+
}
|
|
1177
|
+
function computePageRedactionBoxes(items, pageRedactions, ctx) {
|
|
1178
|
+
const boxes = [];
|
|
1179
|
+
for (const r of pageRedactions) {
|
|
1180
|
+
const rawForSpan = [];
|
|
1181
|
+
for (const item of items) {
|
|
1182
|
+
if (item.end <= r.start || item.start >= r.end) continue;
|
|
1183
|
+
const len = Math.max(1, item.str.length);
|
|
1184
|
+
const localStart = Math.max(0, r.start - item.start);
|
|
1185
|
+
const localEnd = Math.min(len, r.end - item.start);
|
|
1186
|
+
const padX = Math.max(3, item.fontHeight * 0.25);
|
|
1187
|
+
const padY = Math.max(1.5, item.fontHeight * 0.12);
|
|
1188
|
+
const { startFrac, endFrac } = measureSubspanFractions(
|
|
1189
|
+
ctx,
|
|
1190
|
+
item.str,
|
|
1191
|
+
localStart,
|
|
1192
|
+
localEnd,
|
|
1193
|
+
item.fontFamily
|
|
1194
|
+
);
|
|
1195
|
+
if (item.isHorizontal) {
|
|
1196
|
+
const spanWidth = item.x2 - item.x1;
|
|
1197
|
+
const subX1 = item.x1 + startFrac * spanWidth;
|
|
1198
|
+
const subX2 = item.x1 + endFrac * spanWidth;
|
|
1199
|
+
rawForSpan.push({
|
|
1200
|
+
x1: subX1 - padX,
|
|
1201
|
+
y1: item.y1 - padY,
|
|
1202
|
+
x2: subX2 + padX,
|
|
1203
|
+
y2: item.y2 + padY,
|
|
1204
|
+
replacement: r.replacement
|
|
1205
|
+
});
|
|
1206
|
+
} else {
|
|
1207
|
+
const [a, b, c, d, e, f] = item.transform;
|
|
1208
|
+
const scaleX = Math.hypot(a, b) || 1;
|
|
1209
|
+
const scaleY = Math.hypot(c, d) || 1;
|
|
1210
|
+
const ux = a / scaleX;
|
|
1211
|
+
const uy = b / scaleX;
|
|
1212
|
+
const vx = c / scaleY;
|
|
1213
|
+
const vy = d / scaleY;
|
|
1214
|
+
const d1 = startFrac * item.width;
|
|
1215
|
+
const d2 = endFrac * item.width;
|
|
1216
|
+
const asc = item.fontHeight * 1.12;
|
|
1217
|
+
const desc = -item.fontHeight * 0.34;
|
|
1218
|
+
const corners = [
|
|
1219
|
+
[e + ux * d1 + vx * desc, f + uy * d1 + vy * desc],
|
|
1220
|
+
[e + ux * d2 + vx * desc, f + uy * d2 + vy * desc],
|
|
1221
|
+
[e + ux * d1 + vx * asc, f + uy * d1 + vy * asc],
|
|
1222
|
+
[e + ux * d2 + vx * asc, f + uy * d2 + vy * asc]
|
|
1223
|
+
];
|
|
1224
|
+
let bx1 = Number.POSITIVE_INFINITY;
|
|
1225
|
+
let by1 = Number.POSITIVE_INFINITY;
|
|
1226
|
+
let bx2 = Number.NEGATIVE_INFINITY;
|
|
1227
|
+
let by2 = Number.NEGATIVE_INFINITY;
|
|
1228
|
+
for (const [cx, cy] of corners) {
|
|
1229
|
+
if (cx < bx1) bx1 = cx;
|
|
1230
|
+
if (cy < by1) by1 = cy;
|
|
1231
|
+
if (cx > bx2) bx2 = cx;
|
|
1232
|
+
if (cy > by2) by2 = cy;
|
|
1233
|
+
}
|
|
1234
|
+
rawForSpan.push({
|
|
1235
|
+
x1: bx1 - padX,
|
|
1236
|
+
y1: by1 - padY,
|
|
1237
|
+
x2: bx2 + padX,
|
|
1238
|
+
y2: by2 + padY,
|
|
1239
|
+
replacement: r.replacement
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
boxes.push(...mergeLineBoxes(rawForSpan));
|
|
1244
|
+
}
|
|
1245
|
+
return boxes;
|
|
1246
|
+
}
|
|
1247
|
+
function drawRedactionOverlay(ctx, viewport, boxes, style) {
|
|
1248
|
+
const fillColor = style.fillColor ?? "#111111";
|
|
1249
|
+
const textColor = style.textColor ?? "#ffffff";
|
|
1250
|
+
const showLabels = style.showLabels !== false;
|
|
1251
|
+
for (const box of boxes) {
|
|
1252
|
+
const corners = [
|
|
1253
|
+
viewport.convertToViewportPoint(box.x1, box.y1),
|
|
1254
|
+
viewport.convertToViewportPoint(box.x2, box.y1),
|
|
1255
|
+
viewport.convertToViewportPoint(box.x1, box.y2),
|
|
1256
|
+
viewport.convertToViewportPoint(box.x2, box.y2)
|
|
1257
|
+
];
|
|
1258
|
+
let minX = Number.POSITIVE_INFINITY;
|
|
1259
|
+
let minY = Number.POSITIVE_INFINITY;
|
|
1260
|
+
let maxX = Number.NEGATIVE_INFINITY;
|
|
1261
|
+
let maxY = Number.NEGATIVE_INFINITY;
|
|
1262
|
+
for (const pt of corners) {
|
|
1263
|
+
const px = Number(pt[0] ?? 0);
|
|
1264
|
+
const py = Number(pt[1] ?? 0);
|
|
1265
|
+
if (px < minX) minX = px;
|
|
1266
|
+
if (py < minY) minY = py;
|
|
1267
|
+
if (px > maxX) maxX = px;
|
|
1268
|
+
if (py > maxY) maxY = py;
|
|
1269
|
+
}
|
|
1270
|
+
const rx = minX;
|
|
1271
|
+
const ry = minY;
|
|
1272
|
+
const rw = maxX - minX;
|
|
1273
|
+
const rh = maxY - minY;
|
|
1274
|
+
if (rw < 1 || rh < 1) continue;
|
|
1275
|
+
ctx.save();
|
|
1276
|
+
ctx.fillStyle = fillColor;
|
|
1277
|
+
ctx.fillRect(rx, ry, rw, rh);
|
|
1278
|
+
if (showLabels && box.replacement && rw >= 24 && rh >= 10) {
|
|
1279
|
+
const pad = Math.min(4, rw * 0.08);
|
|
1280
|
+
const maxTextWidth = Math.max(4, rw - pad * 2);
|
|
1281
|
+
const fontSize = Math.max(8, Math.min(rh * 0.62, 22));
|
|
1282
|
+
ctx.beginPath();
|
|
1283
|
+
ctx.rect(rx, ry, rw, rh);
|
|
1284
|
+
ctx.clip();
|
|
1285
|
+
ctx.fillStyle = textColor;
|
|
1286
|
+
ctx.font = `600 ${fontSize.toFixed(1)}px sans-serif`;
|
|
1287
|
+
ctx.textAlign = "center";
|
|
1288
|
+
ctx.textBaseline = "middle";
|
|
1289
|
+
ctx.fillText(box.replacement, rx + rw / 2, ry + rh / 2 + fontSize * 0.04, maxTextWidth);
|
|
1290
|
+
}
|
|
1291
|
+
ctx.restore();
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
async function inspectPdfDocument(bytes, pdfWorkerSrc) {
|
|
1295
|
+
const pdfjs = await loadPdfjs(pdfWorkerSrc);
|
|
1296
|
+
const loadingTask = pdfjs.getDocument({
|
|
1297
|
+
data: bytes.slice(),
|
|
1298
|
+
useSystemFonts: true,
|
|
1299
|
+
verbosity: 0
|
|
1300
|
+
});
|
|
1301
|
+
const doc = await loadingTask.promise;
|
|
1302
|
+
const meta = await doc.getMetadata().catch(() => ({ info: {}, metadata: null }));
|
|
1303
|
+
const metadata = collectPdfMetadataStrings(meta);
|
|
1304
|
+
const pages = [];
|
|
1305
|
+
const scannedPages = [];
|
|
1306
|
+
const warnings = [];
|
|
1307
|
+
const ops = pdfjs.OPS;
|
|
1308
|
+
const imageOpSet = /* @__PURE__ */ new Set([
|
|
1309
|
+
ops.paintImageXObject,
|
|
1310
|
+
ops.paintInlineImageXObject,
|
|
1311
|
+
ops.paintImageMaskXObject
|
|
1312
|
+
]);
|
|
1313
|
+
for (let pageNumber = 1; pageNumber <= doc.numPages; pageNumber++) {
|
|
1314
|
+
const page = await doc.getPage(pageNumber);
|
|
1315
|
+
const textContent = await page.getTextContent();
|
|
1316
|
+
const { text, items } = buildPageTextAndMap(
|
|
1317
|
+
textContent.items,
|
|
1318
|
+
textContent.styles
|
|
1319
|
+
);
|
|
1320
|
+
const rawAnnotations = await page.getAnnotations().catch(() => []);
|
|
1321
|
+
const annotations = extractAnnotationTexts(rawAnnotations);
|
|
1322
|
+
let scanned = false;
|
|
1323
|
+
if (text.trim().length < 10) {
|
|
1324
|
+
const opList = await page.getOperatorList().catch(() => null);
|
|
1325
|
+
if (opList?.fnArray.some((fn) => imageOpSet.has(fn))) {
|
|
1326
|
+
scanned = true;
|
|
1327
|
+
scannedPages.push(pageNumber);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
pages.push({ pageNumber, text, items, annotations, scanned });
|
|
1331
|
+
}
|
|
1332
|
+
if (scannedPages.length > 0) {
|
|
1333
|
+
warnings.push(
|
|
1334
|
+
`PDF page(s) ${scannedPages.join(", ")} appear to be scanned images without a text layer and cannot be inspected without OCR.`
|
|
1335
|
+
);
|
|
1336
|
+
}
|
|
1337
|
+
return { pdfjs, loadingTask, doc, pages, metadata, scannedPages, warnings };
|
|
1338
|
+
}
|
|
1339
|
+
async function extractPdf(bytes, options) {
|
|
1340
|
+
const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
|
|
1341
|
+
try {
|
|
1342
|
+
const sections = inspected.pages.map((p) => {
|
|
1343
|
+
const annotText = p.annotations.map((a) => a.text).join("\n");
|
|
1344
|
+
const combined = annotText ? `${p.text}${p.text ? "\n" : ""}${annotText}` : p.text;
|
|
1345
|
+
return {
|
|
1346
|
+
id: `page-${p.pageNumber}`,
|
|
1347
|
+
label: `Sida ${p.pageNumber}`,
|
|
1348
|
+
text: combined,
|
|
1349
|
+
pageIndex: p.pageNumber - 1,
|
|
1350
|
+
scanned: p.scanned
|
|
1351
|
+
};
|
|
1352
|
+
});
|
|
1353
|
+
return {
|
|
1354
|
+
format: "pdf",
|
|
1355
|
+
mimeType: "application/pdf",
|
|
1356
|
+
text: sections.map((s) => s.text).filter((t) => t.length > 0).join("\n\n"),
|
|
1357
|
+
sections,
|
|
1358
|
+
metadata: inspected.metadata,
|
|
1359
|
+
warnings: inspected.warnings,
|
|
1360
|
+
scannedPages: inspected.scannedPages,
|
|
1361
|
+
totalPages: inspected.doc.numPages
|
|
1362
|
+
};
|
|
1363
|
+
} finally {
|
|
1364
|
+
await inspected.loadingTask.destroy();
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
function countByLabel(redactions) {
|
|
1368
|
+
const counts = {};
|
|
1369
|
+
for (const r of redactions) {
|
|
1370
|
+
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
1371
|
+
}
|
|
1372
|
+
return counts;
|
|
1373
|
+
}
|
|
1374
|
+
async function redactPdf(bytes, redactFn, options) {
|
|
1375
|
+
const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
|
|
1376
|
+
try {
|
|
1377
|
+
const pageOffsets = [];
|
|
1378
|
+
const textChunks = [];
|
|
1379
|
+
let cursor = 0;
|
|
1380
|
+
for (let i = 0; i < inspected.pages.length; i++) {
|
|
1381
|
+
const page = inspected.pages[i];
|
|
1382
|
+
if (!page) continue;
|
|
1383
|
+
const hasAnyContent = page.text.length > 0 || page.annotations.some((a) => a.text.length > 0);
|
|
1384
|
+
if (!hasAnyContent) {
|
|
1385
|
+
pageOffsets.push({ pageIndex: i, textStart: cursor, textEnd: cursor, annotRanges: [] });
|
|
1386
|
+
continue;
|
|
1387
|
+
}
|
|
1388
|
+
if (textChunks.length > 0) {
|
|
1389
|
+
textChunks.push("\n\n");
|
|
1390
|
+
cursor += 2;
|
|
1391
|
+
}
|
|
1392
|
+
const textStart = cursor;
|
|
1393
|
+
if (page.text.length > 0) {
|
|
1394
|
+
textChunks.push(page.text);
|
|
1395
|
+
cursor += page.text.length;
|
|
1396
|
+
}
|
|
1397
|
+
const textEnd = cursor;
|
|
1398
|
+
const annotRanges = [];
|
|
1399
|
+
let wroteInPage = page.text.length > 0;
|
|
1400
|
+
for (const annot of page.annotations) {
|
|
1401
|
+
if (!annot.text) continue;
|
|
1402
|
+
if (wroteInPage) {
|
|
1403
|
+
textChunks.push("\n");
|
|
1404
|
+
cursor += 1;
|
|
1405
|
+
}
|
|
1406
|
+
const start = cursor;
|
|
1407
|
+
textChunks.push(annot.text);
|
|
1408
|
+
cursor += annot.text.length;
|
|
1409
|
+
wroteInPage = true;
|
|
1410
|
+
annotRanges.push({ start, end: cursor, rect: annot.rect });
|
|
1411
|
+
}
|
|
1412
|
+
pageOffsets.push({ pageIndex: i, textStart, textEnd, annotRanges });
|
|
1413
|
+
}
|
|
1414
|
+
const combinedText = textChunks.join("");
|
|
1415
|
+
const result = await redactFn(combinedText);
|
|
1416
|
+
const srcDoc = await PDFDocument.load(bytes, {
|
|
1417
|
+
ignoreEncryption: true,
|
|
1418
|
+
updateMetadata: false
|
|
1419
|
+
});
|
|
1420
|
+
const outDoc = await PDFDocument.create();
|
|
1421
|
+
const style = options?.pdfStyle ?? {};
|
|
1422
|
+
const scale = style.scale ?? 2.5;
|
|
1423
|
+
let canvasProvider = options?.canvasProvider;
|
|
1424
|
+
const redactedPages = [];
|
|
1425
|
+
for (let i = 0; i < inspected.pages.length; i++) {
|
|
1426
|
+
const pageInfo = inspected.pages[i];
|
|
1427
|
+
const offsetInfo = pageOffsets[i];
|
|
1428
|
+
if (!pageInfo || !offsetInfo) continue;
|
|
1429
|
+
const localTextRedactions = [];
|
|
1430
|
+
const annotBoxes = [];
|
|
1431
|
+
let hasAnnotPii = false;
|
|
1432
|
+
for (const r of result.redactions) {
|
|
1433
|
+
if (r.end > offsetInfo.textStart && r.start < offsetInfo.textEnd) {
|
|
1434
|
+
localTextRedactions.push({
|
|
1435
|
+
start: Math.max(0, r.start - offsetInfo.textStart),
|
|
1436
|
+
end: Math.min(offsetInfo.textEnd - offsetInfo.textStart, r.end - offsetInfo.textStart),
|
|
1437
|
+
replacement: r.replacement
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
for (const ar of offsetInfo.annotRanges) {
|
|
1441
|
+
if (r.end > ar.start && r.start < ar.end) {
|
|
1442
|
+
hasAnnotPii = true;
|
|
1443
|
+
if (ar.rect) {
|
|
1444
|
+
annotBoxes.push({
|
|
1445
|
+
x1: ar.rect[0],
|
|
1446
|
+
y1: ar.rect[1],
|
|
1447
|
+
x2: ar.rect[2],
|
|
1448
|
+
y2: ar.rect[3],
|
|
1449
|
+
replacement: r.replacement
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
const shouldBurn = options?.burnAllPdfPages === true || localTextRedactions.length > 0 || annotBoxes.length > 0 || hasAnnotPii;
|
|
1456
|
+
if (!shouldBurn) {
|
|
1457
|
+
const [copied] = await outDoc.copyPages(srcDoc, [i]);
|
|
1458
|
+
if (copied) {
|
|
1459
|
+
copied.node.delete(PDFName.of("Annots"));
|
|
1460
|
+
outDoc.addPage(copied);
|
|
1461
|
+
}
|
|
1462
|
+
continue;
|
|
1463
|
+
}
|
|
1464
|
+
redactedPages.push(pageInfo.pageNumber);
|
|
1465
|
+
if (!canvasProvider) {
|
|
1466
|
+
canvasProvider = await resolveDefaultCanvasProvider();
|
|
1467
|
+
}
|
|
1468
|
+
const pdfjsPage = await inspected.doc.getPage(pageInfo.pageNumber);
|
|
1469
|
+
const unscaledViewport = pdfjsPage.getViewport({ scale: 1 });
|
|
1470
|
+
const renderViewport = pdfjsPage.getViewport({ scale });
|
|
1471
|
+
const canvas = canvasProvider.createCanvas(
|
|
1472
|
+
Math.max(1, Math.ceil(renderViewport.width)),
|
|
1473
|
+
Math.max(1, Math.ceil(renderViewport.height))
|
|
1474
|
+
);
|
|
1475
|
+
const ctx = canvas.getContext("2d");
|
|
1476
|
+
if (!ctx) {
|
|
1477
|
+
throw new Error("Could not acquire 2D canvas context for PDF redaction.");
|
|
1478
|
+
}
|
|
1479
|
+
await pdfjsPage.render({
|
|
1480
|
+
canvasContext: ctx,
|
|
1481
|
+
viewport: renderViewport,
|
|
1482
|
+
canvas,
|
|
1483
|
+
intent: "print"
|
|
1484
|
+
}).promise;
|
|
1485
|
+
const textBoxes = computePageRedactionBoxes(pageInfo.items, localTextRedactions, ctx);
|
|
1486
|
+
const allBoxes = [...textBoxes, ...annotBoxes];
|
|
1487
|
+
drawRedactionOverlay(ctx, renderViewport, allBoxes, style);
|
|
1488
|
+
const pngBytes = await canvasProvider.toPngBytes(canvas);
|
|
1489
|
+
const pngImage = await outDoc.embedPng(pngBytes);
|
|
1490
|
+
const newPage = outDoc.addPage([unscaledViewport.width, unscaledViewport.height]);
|
|
1491
|
+
newPage.drawImage(pngImage, {
|
|
1492
|
+
x: 0,
|
|
1493
|
+
y: 0,
|
|
1494
|
+
width: unscaledViewport.width,
|
|
1495
|
+
height: unscaledViewport.height
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
outDoc.setTitle("");
|
|
1499
|
+
outDoc.setAuthor("");
|
|
1500
|
+
outDoc.setSubject("");
|
|
1501
|
+
outDoc.setKeywords([]);
|
|
1502
|
+
outDoc.setCreator("Maskera");
|
|
1503
|
+
outDoc.setProducer("Maskera");
|
|
1504
|
+
const outBytes = new Uint8Array(await outDoc.save({ useObjectStreams: true }));
|
|
1505
|
+
const metadataCleared = Object.keys(inspected.metadata);
|
|
1506
|
+
const metadataValues = Object.values(inspected.metadata);
|
|
1507
|
+
return {
|
|
1508
|
+
bytes: outBytes,
|
|
1509
|
+
extractedText: combinedText,
|
|
1510
|
+
redactedText: result.text,
|
|
1511
|
+
totalRedactions: result.redactions.length,
|
|
1512
|
+
counts: countByLabel(result.redactions),
|
|
1513
|
+
redactions: result.redactions,
|
|
1514
|
+
map: result.map,
|
|
1515
|
+
metadataCleared,
|
|
1516
|
+
metadataValues,
|
|
1517
|
+
warnings: inspected.warnings,
|
|
1518
|
+
scannedPages: inspected.scannedPages,
|
|
1519
|
+
redactedPages,
|
|
1520
|
+
totalPages: inspected.doc.numPages
|
|
1521
|
+
};
|
|
1522
|
+
} finally {
|
|
1523
|
+
await inspected.loadingTask.destroy();
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
function normalizeForLeakCheck(value) {
|
|
1527
|
+
return value.replace(/\s+/g, " ").trim().toLowerCase();
|
|
1528
|
+
}
|
|
1529
|
+
function collectNonTrivialSecrets(secrets) {
|
|
1530
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1531
|
+
const out = [];
|
|
1532
|
+
for (const raw of secrets) {
|
|
1533
|
+
const norm = normalizeForLeakCheck(raw);
|
|
1534
|
+
if (norm.length < 3 || seen.has(norm)) continue;
|
|
1535
|
+
seen.add(norm);
|
|
1536
|
+
out.push(raw.trim());
|
|
1537
|
+
}
|
|
1538
|
+
return out;
|
|
1539
|
+
}
|
|
1540
|
+
async function verifyRedactedFile(bytes, format2, originalSecrets, options) {
|
|
1541
|
+
const candidates = collectNonTrivialSecrets(originalSecrets);
|
|
1542
|
+
if (candidates.length === 0) {
|
|
1543
|
+
return { verified: true, leaks: [] };
|
|
1544
|
+
}
|
|
1545
|
+
let haystack = "";
|
|
1546
|
+
if (format2 === "text") {
|
|
1547
|
+
haystack = normalizeForLeakCheck(decodeUtf8(bytes));
|
|
1548
|
+
} else if (format2 === "docx" || format2 === "xlsx") {
|
|
1549
|
+
const archive = unzipSafely(bytes);
|
|
1550
|
+
const parts = [];
|
|
1551
|
+
for (const [name, data] of Object.entries(archive)) {
|
|
1552
|
+
if (!/\.(?:xml|rels)$/i.test(name)) continue;
|
|
1553
|
+
const xml = decodeUtf8(data);
|
|
1554
|
+
parts.push(unescapeXml(xml));
|
|
1555
|
+
parts.push(unescapeXml(xml.replace(/<[^>]+>/g, "")));
|
|
1556
|
+
}
|
|
1557
|
+
haystack = normalizeForLeakCheck(parts.join("\n"));
|
|
1558
|
+
} else if (format2 === "pdf") {
|
|
1559
|
+
const extracted = await extractPdf(bytes, { pdfWorkerSrc: options?.pdfWorkerSrc });
|
|
1560
|
+
const metaValues = Object.values(extracted.metadata).join("\n");
|
|
1561
|
+
const rawLatin = new TextDecoder("latin1").decode(bytes);
|
|
1562
|
+
haystack = normalizeForLeakCheck(`${extracted.text}
|
|
1563
|
+
${metaValues}
|
|
1564
|
+
${rawLatin}`);
|
|
1565
|
+
}
|
|
1566
|
+
const leaks = [];
|
|
1567
|
+
for (const secret of candidates) {
|
|
1568
|
+
if (haystack.includes(normalizeForLeakCheck(secret))) {
|
|
1569
|
+
leaks.push(secret);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
return {
|
|
1573
|
+
verified: leaks.length === 0,
|
|
1574
|
+
leaks
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
function assertSizeLimit(bytes, maxBytes, fileName) {
|
|
1578
|
+
if (bytes.byteLength > maxBytes) {
|
|
1579
|
+
const label = fileName ? `"${fileName}"` : "File";
|
|
1580
|
+
throw new Error(`${label} is ${bytes.byteLength} bytes (max ${maxBytes} bytes).`);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
function countByLabel2(redactions) {
|
|
1584
|
+
const counts = {};
|
|
1585
|
+
for (const r of redactions) {
|
|
1586
|
+
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
1587
|
+
}
|
|
1588
|
+
return counts;
|
|
1589
|
+
}
|
|
1590
|
+
async function extractFileText(bytes, options = {}) {
|
|
1591
|
+
const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
|
|
1592
|
+
assertSizeLimit(bytes, maxBytes, options.fileName);
|
|
1593
|
+
const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
|
|
1594
|
+
if (detected.format === "binary") {
|
|
1595
|
+
const label = options.fileName ? `"${options.fileName}"` : "File";
|
|
1596
|
+
throw new Error(
|
|
1597
|
+
`${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
|
|
1598
|
+
);
|
|
1599
|
+
}
|
|
1600
|
+
if (detected.format === "text") {
|
|
1601
|
+
const text = decodeUtf8(bytes);
|
|
1602
|
+
return {
|
|
1603
|
+
format: "text",
|
|
1604
|
+
mimeType: detected.mimeType,
|
|
1605
|
+
text,
|
|
1606
|
+
sections: [{ id: "body", label: options.fileName ?? "text", text }],
|
|
1607
|
+
metadata: {},
|
|
1608
|
+
warnings: [],
|
|
1609
|
+
scannedPages: []
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
if (detected.format === "docx") {
|
|
1613
|
+
return extractDocx(bytes);
|
|
1614
|
+
}
|
|
1615
|
+
if (detected.format === "xlsx") {
|
|
1616
|
+
return extractXlsx(bytes);
|
|
1617
|
+
}
|
|
1618
|
+
return extractPdf(bytes, { pdfWorkerSrc: options.pdfWorkerSrc });
|
|
1619
|
+
}
|
|
1620
|
+
async function redactFile(bytes, redactFn, options = {}) {
|
|
1621
|
+
const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
|
|
1622
|
+
assertSizeLimit(bytes, maxBytes, options.fileName);
|
|
1623
|
+
const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
|
|
1624
|
+
if (detected.format === "binary") {
|
|
1625
|
+
const label = options.fileName ? `"${options.fileName}"` : "File";
|
|
1626
|
+
throw new Error(
|
|
1627
|
+
`${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
|
|
1628
|
+
);
|
|
1629
|
+
}
|
|
1630
|
+
const shouldVerify = options.verify !== false;
|
|
1631
|
+
if (detected.format === "text") {
|
|
1632
|
+
const extractedText = decodeUtf8(bytes);
|
|
1633
|
+
const result = await redactFn(extractedText);
|
|
1634
|
+
const outBytes = encodeUtf8(result.text);
|
|
1635
|
+
const secrets2 = result.redactions.map((r) => r.value);
|
|
1636
|
+
const verification2 = shouldVerify ? await verifyRedactedFile(outBytes, "text", secrets2) : { verified: true, leaks: [] };
|
|
1637
|
+
return {
|
|
1638
|
+
format: "text",
|
|
1639
|
+
mimeType: detected.mimeType,
|
|
1640
|
+
bytes: outBytes,
|
|
1641
|
+
extractedText,
|
|
1642
|
+
redactedText: result.text,
|
|
1643
|
+
totalRedactions: result.redactions.length,
|
|
1644
|
+
counts: countByLabel2(result.redactions),
|
|
1645
|
+
redactions: result.redactions,
|
|
1646
|
+
map: result.map,
|
|
1647
|
+
metadataCleared: [],
|
|
1648
|
+
warnings: [],
|
|
1649
|
+
scannedPages: [],
|
|
1650
|
+
verified: verification2.verified,
|
|
1651
|
+
verificationLeaks: verification2.leaks
|
|
1652
|
+
};
|
|
1653
|
+
}
|
|
1654
|
+
if (detected.format === "docx") {
|
|
1655
|
+
const doc = await redactDocx(bytes, redactFn);
|
|
1656
|
+
const secrets2 = [...doc.redactions.map((r) => r.value), ...doc.metadataValues];
|
|
1657
|
+
const verification2 = shouldVerify ? await verifyRedactedFile(doc.bytes, "docx", secrets2) : { verified: true, leaks: [] };
|
|
1658
|
+
return {
|
|
1659
|
+
format: "docx",
|
|
1660
|
+
mimeType: detected.mimeType,
|
|
1661
|
+
bytes: doc.bytes,
|
|
1662
|
+
extractedText: doc.extractedText,
|
|
1663
|
+
redactedText: doc.redactedText,
|
|
1664
|
+
totalRedactions: doc.totalRedactions,
|
|
1665
|
+
counts: doc.counts,
|
|
1666
|
+
redactions: doc.redactions,
|
|
1667
|
+
map: doc.map,
|
|
1668
|
+
metadataCleared: doc.metadataCleared,
|
|
1669
|
+
warnings: doc.warnings,
|
|
1670
|
+
scannedPages: [],
|
|
1671
|
+
verified: verification2.verified,
|
|
1672
|
+
verificationLeaks: verification2.leaks
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
if (detected.format === "xlsx") {
|
|
1676
|
+
const sheet = await redactXlsx(bytes, redactFn);
|
|
1677
|
+
const secrets2 = [...sheet.redactions.map((r) => r.value), ...sheet.metadataValues];
|
|
1678
|
+
const verification2 = shouldVerify ? await verifyRedactedFile(sheet.bytes, "xlsx", secrets2) : { verified: true, leaks: [] };
|
|
1679
|
+
return {
|
|
1680
|
+
format: "xlsx",
|
|
1681
|
+
mimeType: detected.mimeType,
|
|
1682
|
+
bytes: sheet.bytes,
|
|
1683
|
+
extractedText: sheet.extractedText,
|
|
1684
|
+
redactedText: sheet.redactedText,
|
|
1685
|
+
totalRedactions: sheet.totalRedactions,
|
|
1686
|
+
counts: sheet.counts,
|
|
1687
|
+
redactions: sheet.redactions,
|
|
1688
|
+
map: sheet.map,
|
|
1689
|
+
metadataCleared: sheet.metadataCleared,
|
|
1690
|
+
warnings: sheet.warnings,
|
|
1691
|
+
scannedPages: [],
|
|
1692
|
+
verified: verification2.verified,
|
|
1693
|
+
verificationLeaks: verification2.leaks
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
const pdf = await redactPdf(bytes, redactFn, {
|
|
1697
|
+
pdfStyle: options.pdfStyle,
|
|
1698
|
+
canvasProvider: options.canvasProvider,
|
|
1699
|
+
pdfWorkerSrc: options.pdfWorkerSrc,
|
|
1700
|
+
burnAllPdfPages: options.burnAllPdfPages
|
|
1701
|
+
});
|
|
1702
|
+
const secrets = [...pdf.redactions.map((r) => r.value), ...pdf.metadataValues];
|
|
1703
|
+
const verification = shouldVerify ? await verifyRedactedFile(pdf.bytes, "pdf", secrets, {
|
|
1704
|
+
pdfWorkerSrc: options.pdfWorkerSrc
|
|
1705
|
+
}) : { verified: true, leaks: [] };
|
|
1706
|
+
return {
|
|
1707
|
+
format: "pdf",
|
|
1708
|
+
mimeType: detected.mimeType,
|
|
1709
|
+
bytes: pdf.bytes,
|
|
1710
|
+
extractedText: pdf.extractedText,
|
|
1711
|
+
redactedText: pdf.redactedText,
|
|
1712
|
+
totalRedactions: pdf.totalRedactions,
|
|
1713
|
+
counts: pdf.counts,
|
|
1714
|
+
redactions: pdf.redactions,
|
|
1715
|
+
map: pdf.map,
|
|
1716
|
+
metadataCleared: pdf.metadataCleared,
|
|
1717
|
+
warnings: pdf.warnings,
|
|
1718
|
+
scannedPages: pdf.scannedPages,
|
|
1719
|
+
redactedPages: pdf.redactedPages,
|
|
1720
|
+
totalPages: pdf.totalPages,
|
|
1721
|
+
verified: verification.verified,
|
|
1722
|
+
verificationLeaks: verification.leaks
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
15
1725
|
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
16
1726
|
var DEFAULT_MAX_CACHE_ENTRIES = 512;
|
|
17
1727
|
var MAX_CUSTOM_DETECTOR_CACHE = 64;
|
|
@@ -87,6 +1797,7 @@ function normalizeMixedScriptHomoglyphs(text) {
|
|
|
87
1797
|
});
|
|
88
1798
|
return { text: normalized, changed };
|
|
89
1799
|
}
|
|
1800
|
+
var COMPOUND_WINDOW_RADIUS = 120;
|
|
90
1801
|
async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, existing) {
|
|
91
1802
|
const candidates = [];
|
|
92
1803
|
SWEDISH_HYPHEN_COMPOUND_RE.lastIndex = 0;
|
|
@@ -101,28 +1812,47 @@ async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, e
|
|
|
101
1812
|
}
|
|
102
1813
|
}
|
|
103
1814
|
if (candidates.length === 0) return [];
|
|
104
|
-
const
|
|
1815
|
+
const windows = [];
|
|
105
1816
|
for (const c of candidates) {
|
|
106
|
-
|
|
1817
|
+
let winStart = Math.max(0, c.prefixStart - COMPOUND_WINDOW_RADIUS);
|
|
1818
|
+
while (winStart > 0 && WORD_CHAR.test(text[winStart - 1] ?? "")) winStart--;
|
|
1819
|
+
let winEnd = Math.min(text.length, c.hyphenIndex + 1 + COMPOUND_WINDOW_RADIUS);
|
|
1820
|
+
while (winEnd < text.length && WORD_CHAR.test(text[winEnd] ?? "")) winEnd++;
|
|
1821
|
+
const prev = windows[windows.length - 1];
|
|
1822
|
+
if (prev && winStart <= prev.end + 40) {
|
|
1823
|
+
prev.end = Math.max(prev.end, winEnd);
|
|
1824
|
+
prev.items.push(c);
|
|
1825
|
+
} else {
|
|
1826
|
+
windows.push({ start: winStart, end: winEnd, items: [c] });
|
|
1827
|
+
}
|
|
107
1828
|
}
|
|
108
|
-
const probeText = chars.join("");
|
|
109
|
-
const probeRes = await redactWithNer(probeText, {
|
|
110
|
-
recognizer: ner,
|
|
111
|
-
detectors: [...detectors],
|
|
112
|
-
profile
|
|
113
|
-
});
|
|
114
1829
|
const extra = [];
|
|
115
|
-
for (const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
1830
|
+
for (const win of windows) {
|
|
1831
|
+
const slice = text.slice(win.start, win.end);
|
|
1832
|
+
const chars = slice.split("");
|
|
1833
|
+
for (const c of win.items) {
|
|
1834
|
+
chars[c.hyphenIndex - win.start] = " ";
|
|
1835
|
+
}
|
|
1836
|
+
const probeText = chars.join("");
|
|
1837
|
+
const probeRes = await redactWithNer(probeText, {
|
|
1838
|
+
recognizer: ner,
|
|
1839
|
+
detectors: [...detectors],
|
|
1840
|
+
profile
|
|
1841
|
+
});
|
|
1842
|
+
for (const r of probeRes.redactions) {
|
|
1843
|
+
if (!COMPOUND_NER_LABELS.has(r.label)) continue;
|
|
1844
|
+
const absStart = win.start + r.start;
|
|
1845
|
+
const absEnd = win.start + r.end;
|
|
1846
|
+
for (const c of win.items) {
|
|
1847
|
+
if (absStart <= c.prefixStart && absEnd >= c.prefixEnd && absEnd <= c.hyphenIndex) {
|
|
1848
|
+
extra.push({
|
|
1849
|
+
start: c.prefixStart,
|
|
1850
|
+
end: c.prefixEnd,
|
|
1851
|
+
label: r.label,
|
|
1852
|
+
value: text.slice(c.prefixStart, c.prefixEnd)
|
|
1853
|
+
});
|
|
1854
|
+
break;
|
|
1855
|
+
}
|
|
126
1856
|
}
|
|
127
1857
|
}
|
|
128
1858
|
}
|
|
@@ -178,47 +1908,54 @@ function createMaskeraEngine(options = {}) {
|
|
|
178
1908
|
const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
|
|
179
1909
|
const revision = options.nerOptions?.revision ?? (model === MASKERA_SV_NER_MODEL ? MASKERA_SV_NER_REVISION : void 0);
|
|
180
1910
|
const maxCacheEntries = Math.max(0, options.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES);
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
let
|
|
1911
|
+
const localPath = options.nerOptions?.localModelPath;
|
|
1912
|
+
const hasLocalQ8 = typeof localPath === "string" && existsSync(join(localPath, model, "onnx", "model_quantized.onnx"));
|
|
1913
|
+
const dtype = options.nerOptions?.dtype ?? (localPath && !hasLocalQ8 ? "q4" : "q8");
|
|
1914
|
+
let lifecycle = { phase: "idle", recognizer: options.recognizer ?? null };
|
|
1915
|
+
let loadAttempt = 0;
|
|
185
1916
|
const spanCache = /* @__PURE__ */ new Map();
|
|
186
1917
|
const customDetectorCache = /* @__PURE__ */ new Map();
|
|
187
1918
|
let cacheHits = 0;
|
|
188
1919
|
let cacheMisses = 0;
|
|
189
|
-
function
|
|
190
|
-
if (
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
1920
|
+
function ensureRecognizerLoading() {
|
|
1921
|
+
if (lifecycle.phase === "loading" || lifecycle.phase === "ready") {
|
|
1922
|
+
return lifecycle.recognizer;
|
|
1923
|
+
}
|
|
1924
|
+
const recognizer = lifecycle.recognizer ?? createNerRecognizer({
|
|
1925
|
+
...options.nerOptions,
|
|
1926
|
+
model,
|
|
1927
|
+
revision,
|
|
1928
|
+
dtype
|
|
1929
|
+
});
|
|
1930
|
+
loadAttempt += 1;
|
|
1931
|
+
const attempt = loadAttempt;
|
|
1932
|
+
const startedAt = Date.now();
|
|
1933
|
+
lifecycle = { phase: "loading", recognizer, startedAt, attempt };
|
|
1934
|
+
options.onModelStatus?.({ phase: "loading", model, dtype });
|
|
1935
|
+
void recognizer.ready.then(
|
|
1936
|
+
() => {
|
|
1937
|
+
if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
|
|
1938
|
+
lifecycle = { phase: "ready", recognizer };
|
|
204
1939
|
options.onModelStatus?.({
|
|
205
1940
|
phase: "ready",
|
|
206
1941
|
model,
|
|
207
|
-
elapsedMs: Date.now() -
|
|
1942
|
+
elapsedMs: Date.now() - startedAt
|
|
208
1943
|
});
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
1944
|
+
}
|
|
1945
|
+
},
|
|
1946
|
+
(err) => {
|
|
1947
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1948
|
+
if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
|
|
1949
|
+
lifecycle = { phase: "failed", recognizer, error: message };
|
|
213
1950
|
options.onModelStatus?.({
|
|
214
1951
|
phase: "error",
|
|
215
1952
|
model,
|
|
216
|
-
elapsedMs: Date.now() -
|
|
1953
|
+
elapsedMs: Date.now() - startedAt,
|
|
217
1954
|
error: message
|
|
218
1955
|
});
|
|
219
1956
|
}
|
|
220
|
-
|
|
221
|
-
|
|
1957
|
+
}
|
|
1958
|
+
);
|
|
222
1959
|
return recognizer;
|
|
223
1960
|
}
|
|
224
1961
|
function getCustomDetector(rawTerms) {
|
|
@@ -245,19 +1982,9 @@ function createMaskeraEngine(options = {}) {
|
|
|
245
1982
|
}
|
|
246
1983
|
return {
|
|
247
1984
|
warmup() {
|
|
248
|
-
if (defaultMode !== "auto"
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
void ner.ready.then(
|
|
252
|
-
() => {
|
|
253
|
-
nerLoaded = true;
|
|
254
|
-
nerError = null;
|
|
255
|
-
},
|
|
256
|
-
(err) => {
|
|
257
|
-
warmupStarted = false;
|
|
258
|
-
nerError = err instanceof Error ? err.message : String(err);
|
|
259
|
-
}
|
|
260
|
-
);
|
|
1985
|
+
if (defaultMode !== "auto") return;
|
|
1986
|
+
if (lifecycle.phase === "loading" || lifecycle.phase === "ready") return;
|
|
1987
|
+
ensureRecognizerLoading();
|
|
261
1988
|
},
|
|
262
1989
|
clearCache() {
|
|
263
1990
|
spanCache.clear();
|
|
@@ -330,8 +2057,8 @@ function createMaskeraEngine(options = {}) {
|
|
|
330
2057
|
modeUsed: "rules"
|
|
331
2058
|
};
|
|
332
2059
|
}
|
|
2060
|
+
const ner = ensureRecognizerLoading();
|
|
333
2061
|
try {
|
|
334
|
-
const ner = getRecognizer();
|
|
335
2062
|
const canonical = canonicalize(text);
|
|
336
2063
|
const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
|
|
337
2064
|
const isIdentity = canonical.identity && !homoglyph.changed;
|
|
@@ -362,8 +2089,13 @@ function createMaskeraEngine(options = {}) {
|
|
|
362
2089
|
return end > start ? [{ start, end, label: d.label, value: text.slice(start, end) }] : [];
|
|
363
2090
|
})
|
|
364
2091
|
);
|
|
365
|
-
|
|
366
|
-
|
|
2092
|
+
if (lifecycle.phase === "loading") {
|
|
2093
|
+
const elapsedMs = Date.now() - lifecycle.startedAt;
|
|
2094
|
+
lifecycle = { phase: "ready", recognizer: ner };
|
|
2095
|
+
options.onModelStatus?.({ phase: "ready", model, elapsedMs });
|
|
2096
|
+
} else if (lifecycle.phase !== "ready") {
|
|
2097
|
+
lifecycle = { phase: "ready", recognizer: ner };
|
|
2098
|
+
}
|
|
367
2099
|
if (cacheKey) {
|
|
368
2100
|
if (spanCache.size >= maxCacheEntries) {
|
|
369
2101
|
const oldest = spanCache.keys().next().value;
|
|
@@ -381,7 +2113,13 @@ function createMaskeraEngine(options = {}) {
|
|
|
381
2113
|
return { result, modeUsed: "hybrid" };
|
|
382
2114
|
} catch (err) {
|
|
383
2115
|
const message = err instanceof Error ? err.message : String(err);
|
|
384
|
-
|
|
2116
|
+
if (lifecycle.phase === "loading") {
|
|
2117
|
+
const elapsedMs = Date.now() - lifecycle.startedAt;
|
|
2118
|
+
lifecycle = { phase: "failed", recognizer: ner, error: message };
|
|
2119
|
+
options.onModelStatus?.({ phase: "error", model, elapsedMs, error: message });
|
|
2120
|
+
} else {
|
|
2121
|
+
lifecycle = { phase: "failed", recognizer: ner, error: message };
|
|
2122
|
+
}
|
|
385
2123
|
throw new Error(
|
|
386
2124
|
`Hybrid NER failed to run (${message}). Pass mode="rules" explicitly if you only want deterministic structured redaction.`
|
|
387
2125
|
);
|
|
@@ -392,8 +2130,9 @@ function createMaskeraEngine(options = {}) {
|
|
|
392
2130
|
defaultMode,
|
|
393
2131
|
model,
|
|
394
2132
|
revision: revision ?? "local",
|
|
395
|
-
|
|
396
|
-
|
|
2133
|
+
nerPhase: lifecycle.phase,
|
|
2134
|
+
nerLoaded: lifecycle.phase === "ready",
|
|
2135
|
+
nerError: lifecycle.phase === "failed" ? lifecycle.error : null,
|
|
397
2136
|
cacheSize: spanCache.size,
|
|
398
2137
|
cacheHits,
|
|
399
2138
|
cacheMisses
|
|
@@ -408,35 +2147,44 @@ function downloadSize(dtype) {
|
|
|
408
2147
|
}
|
|
409
2148
|
function createModelProgressLogger(write = (line) => process.stderr.write(`${line}
|
|
410
2149
|
`), delayMs = 350) {
|
|
411
|
-
let
|
|
412
|
-
let announcedLoading = false;
|
|
2150
|
+
let state = { tag: "quiet" };
|
|
413
2151
|
return (event) => {
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
2152
|
+
switch (event.phase) {
|
|
2153
|
+
case "loading": {
|
|
2154
|
+
if (state.tag === "delayed") clearTimeout(state.timer);
|
|
2155
|
+
const timer = setTimeout(() => {
|
|
2156
|
+
state = { tag: "announced" };
|
|
2157
|
+
write(
|
|
2158
|
+
`[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
|
|
2159
|
+
);
|
|
2160
|
+
}, delayMs);
|
|
2161
|
+
timer.unref?.();
|
|
2162
|
+
state = { tag: "delayed", timer };
|
|
2163
|
+
return;
|
|
2164
|
+
}
|
|
2165
|
+
case "ready": {
|
|
2166
|
+
if (state.tag === "delayed") {
|
|
2167
|
+
clearTimeout(state.timer);
|
|
2168
|
+
} else if (state.tag === "announced") {
|
|
2169
|
+
write(`[maskera] Swedish ONNX model ready (${event.elapsedMs ?? 0}ms).`);
|
|
2170
|
+
}
|
|
2171
|
+
state = { tag: "quiet" };
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
case "error": {
|
|
2175
|
+
if (state.tag === "delayed") {
|
|
2176
|
+
clearTimeout(state.timer);
|
|
2177
|
+
} else if (state.tag === "announced") {
|
|
2178
|
+
write(`[maskera] Swedish ONNX model load failed: ${event.error ?? "unknown error"}`);
|
|
2179
|
+
}
|
|
2180
|
+
state = { tag: "quiet" };
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
436
2183
|
}
|
|
437
2184
|
};
|
|
438
2185
|
}
|
|
439
2186
|
var MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
2187
|
+
var MAX_DOCUMENT_BYTES = MAX_DEFAULT_FILE_BYTES;
|
|
440
2188
|
var MAX_SYMLINK_HOPS = 40;
|
|
441
2189
|
var DEFAULT_LIST_MAX_ENTRIES = 200;
|
|
442
2190
|
var HARD_LIST_MAX_ENTRIES = 1e3;
|
|
@@ -445,7 +2193,7 @@ var HARD_LIST_MAX_DEPTH = 12;
|
|
|
445
2193
|
var DEFAULT_SEARCH_MAX_MATCHES = 50;
|
|
446
2194
|
var HARD_SEARCH_MAX_MATCHES = 200;
|
|
447
2195
|
var DEFAULT_SEARCH_MAX_FILES = 500;
|
|
448
|
-
var
|
|
2196
|
+
var UTF8_DECODER3 = new TextDecoder("utf-8", { fatal: true });
|
|
449
2197
|
var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "dist-ssr", ".next", ".turbo"]);
|
|
450
2198
|
function isWithinRoot(root, target) {
|
|
451
2199
|
const rel = relative(root, target);
|
|
@@ -586,87 +2334,147 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
586
2334
|
files.push({ relPath, realPath: real, bytes: info.size });
|
|
587
2335
|
}
|
|
588
2336
|
}
|
|
589
|
-
await visit(baseDir, 0);
|
|
590
|
-
return { files, truncated };
|
|
2337
|
+
await visit(baseDir, 0);
|
|
2338
|
+
return { files, truncated };
|
|
2339
|
+
}
|
|
2340
|
+
async function resolveReadableFile(filePath, maxBytes) {
|
|
2341
|
+
const rootsList = await getCanonicalRoots();
|
|
2342
|
+
const candidate = resolveAgainstBase(filePath);
|
|
2343
|
+
const { ancestor, tail } = await resolveExistingAncestor(candidate);
|
|
2344
|
+
const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
|
|
2345
|
+
if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
|
|
2346
|
+
throw new Error(
|
|
2347
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
2348
|
+
);
|
|
2349
|
+
}
|
|
2350
|
+
const real = await realpath(candidate).catch(() => {
|
|
2351
|
+
throw new Error(`File not found: "${filePath}".`);
|
|
2352
|
+
});
|
|
2353
|
+
if (!rootsList.some((root) => isWithinRoot(root, real))) {
|
|
2354
|
+
throw new Error(
|
|
2355
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
2356
|
+
);
|
|
2357
|
+
}
|
|
2358
|
+
const info = await stat(real);
|
|
2359
|
+
if (!info.isFile()) {
|
|
2360
|
+
throw new Error(`"${filePath}" is not a regular file.`);
|
|
2361
|
+
}
|
|
2362
|
+
if (info.size > maxBytes) {
|
|
2363
|
+
throw new Error(
|
|
2364
|
+
`File "${filePath}" is ${info.size} bytes (max ${maxBytes} bytes for local redaction).`
|
|
2365
|
+
);
|
|
2366
|
+
}
|
|
2367
|
+
const buffer = await readFile(real);
|
|
2368
|
+
return { resolvedPath: real, buffer };
|
|
2369
|
+
}
|
|
2370
|
+
async function writeCheckedBytes(filePath, data, options) {
|
|
2371
|
+
const rootsList = await getCanonicalRoots();
|
|
2372
|
+
const candidate = resolveAgainstBase(filePath);
|
|
2373
|
+
const targetReal = await resolveCanonicalTarget(candidate);
|
|
2374
|
+
if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
|
|
2375
|
+
throw new Error(
|
|
2376
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
2377
|
+
);
|
|
2378
|
+
}
|
|
2379
|
+
const bytes = typeof data === "string" ? Buffer.byteLength(data, "utf8") : data.byteLength;
|
|
2380
|
+
if (bytes > options.maxBytes) {
|
|
2381
|
+
throw new Error(`Output exceeds max allowed size (${options.maxBytes} bytes).`);
|
|
2382
|
+
}
|
|
2383
|
+
await mkdir(dirname(targetReal), { recursive: true });
|
|
2384
|
+
const parentReal = await realpath(dirname(targetReal));
|
|
2385
|
+
if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
|
|
2386
|
+
throw new Error(
|
|
2387
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
2388
|
+
);
|
|
2389
|
+
}
|
|
2390
|
+
await writeFile(targetReal, data, {
|
|
2391
|
+
...options.encoding ? { encoding: options.encoding } : {},
|
|
2392
|
+
flag: options.overwrite ? "w" : "wx",
|
|
2393
|
+
mode: 384
|
|
2394
|
+
}).catch((err) => {
|
|
2395
|
+
if (err.code === "EEXIST") {
|
|
2396
|
+
throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
|
|
2397
|
+
}
|
|
2398
|
+
throw err;
|
|
2399
|
+
});
|
|
2400
|
+
return { resolvedPath: targetReal, bytes };
|
|
591
2401
|
}
|
|
592
2402
|
return {
|
|
593
2403
|
allowedRoots: rawRoots.map((r) => resolve(r)),
|
|
594
2404
|
async readText(filePath) {
|
|
595
|
-
const
|
|
596
|
-
const candidate = resolveAgainstBase(filePath);
|
|
597
|
-
const { ancestor, tail } = await resolveExistingAncestor(candidate);
|
|
598
|
-
const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
|
|
599
|
-
if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
|
|
600
|
-
throw new Error(
|
|
601
|
-
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
602
|
-
);
|
|
603
|
-
}
|
|
604
|
-
const real = await realpath(candidate).catch(() => {
|
|
605
|
-
throw new Error(`File not found: "${filePath}".`);
|
|
606
|
-
});
|
|
607
|
-
if (!rootsList.some((root) => isWithinRoot(root, real))) {
|
|
608
|
-
throw new Error(
|
|
609
|
-
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
610
|
-
);
|
|
611
|
-
}
|
|
612
|
-
const info = await stat(real);
|
|
613
|
-
if (!info.isFile()) {
|
|
614
|
-
throw new Error(`"${filePath}" is not a regular file.`);
|
|
615
|
-
}
|
|
616
|
-
if (info.size > MAX_FILE_BYTES) {
|
|
617
|
-
throw new Error(
|
|
618
|
-
`File "${filePath}" is ${info.size} bytes (max ${MAX_FILE_BYTES} bytes for local redaction).`
|
|
619
|
-
);
|
|
620
|
-
}
|
|
621
|
-
const buffer = await readFile(real);
|
|
2405
|
+
const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_FILE_BYTES);
|
|
622
2406
|
if (buffer.includes(0)) {
|
|
623
2407
|
throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
|
|
624
2408
|
}
|
|
625
2409
|
let content;
|
|
626
2410
|
try {
|
|
627
|
-
content =
|
|
2411
|
+
content = UTF8_DECODER3.decode(buffer);
|
|
628
2412
|
} catch {
|
|
629
2413
|
throw new Error(
|
|
630
2414
|
`"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
|
|
631
2415
|
);
|
|
632
2416
|
}
|
|
633
2417
|
return {
|
|
634
|
-
resolvedPath
|
|
2418
|
+
resolvedPath,
|
|
635
2419
|
content,
|
|
636
2420
|
bytes: buffer.byteLength
|
|
637
2421
|
};
|
|
638
2422
|
},
|
|
639
|
-
async
|
|
640
|
-
const
|
|
641
|
-
const
|
|
642
|
-
const
|
|
643
|
-
if (
|
|
2423
|
+
async readDocument(filePath) {
|
|
2424
|
+
const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_DOCUMENT_BYTES);
|
|
2425
|
+
const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
2426
|
+
const detected = detectFileFormat(bytes, resolvedPath);
|
|
2427
|
+
if (detected.format === "text" && buffer.byteLength > MAX_FILE_BYTES) {
|
|
644
2428
|
throw new Error(
|
|
645
|
-
`
|
|
2429
|
+
`File "${filePath}" is ${buffer.byteLength} bytes (max ${MAX_FILE_BYTES} bytes for local text redaction).`
|
|
646
2430
|
);
|
|
647
2431
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
|
|
2432
|
+
if (detected.format === "binary") {
|
|
2433
|
+
if (!buffer.includes(0)) {
|
|
2434
|
+
throw new Error(
|
|
2435
|
+
`"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
|
|
2436
|
+
);
|
|
2437
|
+
}
|
|
655
2438
|
throw new Error(
|
|
656
|
-
`
|
|
2439
|
+
`"${filePath}" appears to be an unsupported binary file (${detected.mimeType}); supported formats are UTF-8 text, PDF, DOCX, and XLSX.`
|
|
657
2440
|
);
|
|
658
2441
|
}
|
|
659
|
-
await
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
2442
|
+
const extracted = await extractFileText(bytes, {
|
|
2443
|
+
fileName: resolvedPath,
|
|
2444
|
+
maxBytes: MAX_DOCUMENT_BYTES
|
|
2445
|
+
});
|
|
2446
|
+
return {
|
|
2447
|
+
resolvedPath,
|
|
2448
|
+
content: extracted.text,
|
|
2449
|
+
bytes: buffer.byteLength,
|
|
2450
|
+
format: extracted.format,
|
|
2451
|
+
mimeType: extracted.mimeType,
|
|
2452
|
+
metadataFields: Object.keys(extracted.metadata),
|
|
2453
|
+
warnings: extracted.warnings,
|
|
2454
|
+
scannedPages: extracted.scannedPages,
|
|
2455
|
+
totalPages: extracted.totalPages
|
|
2456
|
+
};
|
|
2457
|
+
},
|
|
2458
|
+
async readBytes(filePath, options = {}) {
|
|
2459
|
+
const maxBytes = options.maxBytes ?? MAX_DOCUMENT_BYTES;
|
|
2460
|
+
const { resolvedPath, buffer } = await resolveReadableFile(filePath, maxBytes);
|
|
2461
|
+
return {
|
|
2462
|
+
resolvedPath,
|
|
2463
|
+
bytes: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
|
|
2464
|
+
};
|
|
2465
|
+
},
|
|
2466
|
+
async writeText(filePath, content, options = {}) {
|
|
2467
|
+
return writeCheckedBytes(filePath, content, {
|
|
2468
|
+
overwrite: options.overwrite,
|
|
2469
|
+
maxBytes: MAX_FILE_BYTES,
|
|
2470
|
+
encoding: "utf8"
|
|
2471
|
+
});
|
|
2472
|
+
},
|
|
2473
|
+
async writeBytes(filePath, bytes, options = {}) {
|
|
2474
|
+
return writeCheckedBytes(filePath, bytes, {
|
|
2475
|
+
overwrite: options.overwrite,
|
|
2476
|
+
maxBytes: options.maxBytes ?? MAX_DOCUMENT_BYTES
|
|
668
2477
|
});
|
|
669
|
-
return { resolvedPath: targetReal, bytes };
|
|
670
2478
|
},
|
|
671
2479
|
async listFiles(dirPath, options = {}) {
|
|
672
2480
|
const { rootsList, baseDir } = await resolveAllowedDirectory(dirPath);
|
|
@@ -712,19 +2520,36 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
712
2520
|
let scannedFiles = 0;
|
|
713
2521
|
let truncated = walkTruncated;
|
|
714
2522
|
for (const file of files) {
|
|
715
|
-
if (file.bytes >
|
|
2523
|
+
if (file.bytes > MAX_DOCUMENT_BYTES) continue;
|
|
716
2524
|
let buffer;
|
|
717
2525
|
try {
|
|
718
2526
|
buffer = await readFile(file.realPath);
|
|
719
2527
|
} catch {
|
|
720
2528
|
continue;
|
|
721
2529
|
}
|
|
722
|
-
if (buffer.includes(0)) continue;
|
|
723
2530
|
let text;
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
2531
|
+
if (!buffer.includes(0)) {
|
|
2532
|
+
if (file.bytes > MAX_FILE_BYTES) continue;
|
|
2533
|
+
try {
|
|
2534
|
+
text = UTF8_DECODER3.decode(buffer);
|
|
2535
|
+
} catch {
|
|
2536
|
+
continue;
|
|
2537
|
+
}
|
|
2538
|
+
} else {
|
|
2539
|
+
const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
2540
|
+
const detected = detectFileFormat(bytes, file.realPath);
|
|
2541
|
+
if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
|
|
2542
|
+
continue;
|
|
2543
|
+
}
|
|
2544
|
+
try {
|
|
2545
|
+
const extracted = await extractFileText(bytes, {
|
|
2546
|
+
fileName: file.realPath,
|
|
2547
|
+
maxBytes: MAX_DOCUMENT_BYTES
|
|
2548
|
+
});
|
|
2549
|
+
text = extracted.text;
|
|
2550
|
+
} catch {
|
|
2551
|
+
continue;
|
|
2552
|
+
}
|
|
728
2553
|
}
|
|
729
2554
|
scannedFiles += 1;
|
|
730
2555
|
const lines = text.split(/\r?\n/);
|
|
@@ -989,11 +2814,13 @@ var SessionVault = class {
|
|
|
989
2814
|
redacted: originalInput,
|
|
990
2815
|
counts: {},
|
|
991
2816
|
totalRedactions: 0,
|
|
992
|
-
map: {}
|
|
2817
|
+
map: {},
|
|
2818
|
+
redactions: []
|
|
993
2819
|
};
|
|
994
2820
|
}
|
|
995
2821
|
const counts = {};
|
|
996
2822
|
const localMap = {};
|
|
2823
|
+
const appliedRedactions = [];
|
|
997
2824
|
const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
|
|
998
2825
|
let redacted = "";
|
|
999
2826
|
let cursor = 0;
|
|
@@ -1033,6 +2860,7 @@ var SessionVault = class {
|
|
|
1033
2860
|
}
|
|
1034
2861
|
localMap[token] = r.value;
|
|
1035
2862
|
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
2863
|
+
appliedRedactions.push({ ...r, replacement: token });
|
|
1036
2864
|
redacted += originalInput.slice(cursor, r.start) + token;
|
|
1037
2865
|
cursor = r.end;
|
|
1038
2866
|
}
|
|
@@ -1042,7 +2870,8 @@ var SessionVault = class {
|
|
|
1042
2870
|
redacted,
|
|
1043
2871
|
counts,
|
|
1044
2872
|
totalRedactions: result.redactions.length,
|
|
1045
|
-
map: localMap
|
|
2873
|
+
map: localMap,
|
|
2874
|
+
redactions: appliedRedactions
|
|
1046
2875
|
};
|
|
1047
2876
|
}
|
|
1048
2877
|
restore(text, options) {
|
|
@@ -1260,9 +3089,9 @@ var TOOLS = [
|
|
|
1260
3089
|
},
|
|
1261
3090
|
{
|
|
1262
3091
|
name: "maskera_read_file",
|
|
1263
|
-
description: "Read a local UTF-8 text file and redact Swedish PII BEFORE returning its contents to the model. Keeps raw PII strictly in local memory under session_id so the cloud LLM never sees real names or personal IDs.",
|
|
3092
|
+
description: "Read a local UTF-8 text, PDF, DOCX, or XLSX file and redact Swedish PII BEFORE returning its contents to the model. Keeps raw PII strictly in local memory under session_id so the cloud LLM never sees real names or personal IDs.",
|
|
1264
3093
|
annotations: {
|
|
1265
|
-
title: "Read local file with PII redaction",
|
|
3094
|
+
title: "Read local file or document with PII redaction",
|
|
1266
3095
|
readOnlyHint: true,
|
|
1267
3096
|
destructiveHint: false,
|
|
1268
3097
|
idempotentHint: false,
|
|
@@ -1273,7 +3102,7 @@ var TOOLS = [
|
|
|
1273
3102
|
properties: {
|
|
1274
3103
|
path: {
|
|
1275
3104
|
type: "string",
|
|
1276
|
-
description: "Path to a UTF-8 file inside
|
|
3105
|
+
description: "Path to a UTF-8 text, PDF, DOCX, or XLSX file inside allowed workspace roots."
|
|
1277
3106
|
},
|
|
1278
3107
|
session_id: {
|
|
1279
3108
|
type: "string",
|
|
@@ -1302,15 +3131,102 @@ var TOOLS = [
|
|
|
1302
3131
|
properties: {
|
|
1303
3132
|
path: { type: "string" },
|
|
1304
3133
|
bytes: { type: "integer" },
|
|
3134
|
+
format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
|
|
1305
3135
|
redacted: { type: "string" },
|
|
1306
3136
|
session_id: { type: "string" },
|
|
1307
3137
|
counts: COUNTS_SCHEMA,
|
|
1308
3138
|
total_redactions: { type: "integer" },
|
|
1309
|
-
mode: { type: "string", enum: ["hybrid", "rules"] }
|
|
3139
|
+
mode: { type: "string", enum: ["hybrid", "rules"] },
|
|
3140
|
+
total_pages: { type: "integer" },
|
|
3141
|
+
scanned_pages: { type: "array", items: { type: "integer" } },
|
|
3142
|
+
metadata_fields: { type: "array", items: { type: "string" } },
|
|
3143
|
+
warnings: { type: "array", items: { type: "string" } }
|
|
1310
3144
|
},
|
|
1311
3145
|
required: ["path", "bytes", "redacted", "session_id", "counts", "total_redactions", "mode"]
|
|
1312
3146
|
}
|
|
1313
3147
|
},
|
|
3148
|
+
{
|
|
3149
|
+
name: "maskera_redact_file",
|
|
3150
|
+
description: "Redact Swedish PII inside a local PDF, DOCX, XLSX, or UTF-8 text file and write a verified clean file directly to disk without exposing raw PII to the model. For PDFs, affected pages are rasterized and burned so zero raw text survives in the PDF stream; metadata is stripped.",
|
|
3151
|
+
annotations: {
|
|
3152
|
+
title: "Redact local PDF/DOCX/XLSX/text file to disk",
|
|
3153
|
+
readOnlyHint: false,
|
|
3154
|
+
destructiveHint: false,
|
|
3155
|
+
idempotentHint: false,
|
|
3156
|
+
openWorldHint: false
|
|
3157
|
+
},
|
|
3158
|
+
inputSchema: {
|
|
3159
|
+
type: "object",
|
|
3160
|
+
properties: {
|
|
3161
|
+
input_path: {
|
|
3162
|
+
type: "string",
|
|
3163
|
+
description: "Source file path (PDF, DOCX, XLSX, or UTF-8 text) inside allowed roots."
|
|
3164
|
+
},
|
|
3165
|
+
output_path: {
|
|
3166
|
+
type: "string",
|
|
3167
|
+
description: "Destination path for the redacted file inside allowed roots."
|
|
3168
|
+
},
|
|
3169
|
+
session_id: {
|
|
3170
|
+
type: "string",
|
|
3171
|
+
description: "Optional session ID to share placeholder numbering across files."
|
|
3172
|
+
},
|
|
3173
|
+
overwrite: {
|
|
3174
|
+
type: "boolean",
|
|
3175
|
+
description: "Allow overwriting an existing output file. Default false."
|
|
3176
|
+
},
|
|
3177
|
+
show_labels: {
|
|
3178
|
+
type: "boolean",
|
|
3179
|
+
description: "Draw placeholder labels (e.g. [NAMN_1]) inside burned PDF boxes. Default true."
|
|
3180
|
+
},
|
|
3181
|
+
mode: {
|
|
3182
|
+
type: "string",
|
|
3183
|
+
enum: ["auto", "rules"],
|
|
3184
|
+
description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
|
|
3185
|
+
},
|
|
3186
|
+
profile: {
|
|
3187
|
+
type: "string",
|
|
3188
|
+
enum: ["general", "clinical"],
|
|
3189
|
+
description: 'Optional built-in precision profile (default "general").'
|
|
3190
|
+
},
|
|
3191
|
+
custom_terms: {
|
|
3192
|
+
type: "array",
|
|
3193
|
+
items: { type: "string" },
|
|
3194
|
+
description: "Optional extra protected words (client names, project codenames)."
|
|
3195
|
+
}
|
|
3196
|
+
},
|
|
3197
|
+
required: ["input_path", "output_path"]
|
|
3198
|
+
},
|
|
3199
|
+
outputSchema: {
|
|
3200
|
+
type: "object",
|
|
3201
|
+
properties: {
|
|
3202
|
+
input_path: { type: "string" },
|
|
3203
|
+
output_path: { type: "string" },
|
|
3204
|
+
format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
|
|
3205
|
+
bytes: { type: "integer" },
|
|
3206
|
+
session_id: { type: "string" },
|
|
3207
|
+
counts: COUNTS_SCHEMA,
|
|
3208
|
+
total_redactions: { type: "integer" },
|
|
3209
|
+
mode: { type: "string", enum: ["hybrid", "rules"] },
|
|
3210
|
+
verified: { type: "boolean" },
|
|
3211
|
+
metadata_cleared: { type: "array", items: { type: "string" } },
|
|
3212
|
+
redacted_pages: { type: "array", items: { type: "integer" } },
|
|
3213
|
+
total_pages: { type: "integer" },
|
|
3214
|
+
scanned_pages: { type: "array", items: { type: "integer" } },
|
|
3215
|
+
warnings: { type: "array", items: { type: "string" } }
|
|
3216
|
+
},
|
|
3217
|
+
required: [
|
|
3218
|
+
"input_path",
|
|
3219
|
+
"output_path",
|
|
3220
|
+
"format",
|
|
3221
|
+
"bytes",
|
|
3222
|
+
"session_id",
|
|
3223
|
+
"counts",
|
|
3224
|
+
"total_redactions",
|
|
3225
|
+
"mode",
|
|
3226
|
+
"verified"
|
|
3227
|
+
]
|
|
3228
|
+
}
|
|
3229
|
+
},
|
|
1314
3230
|
{
|
|
1315
3231
|
name: "maskera_write_file",
|
|
1316
3232
|
description: "Restore Maskera placeholders from a local session_id and write the restored text directly to a local file without echoing raw PII back into the LLM context.",
|
|
@@ -1605,7 +3521,7 @@ var TOOLS = [
|
|
|
1605
3521
|
}
|
|
1606
3522
|
}
|
|
1607
3523
|
];
|
|
1608
|
-
var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_clear_session"]);
|
|
3524
|
+
var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_redact_file", "maskera_clear_session"]);
|
|
1609
3525
|
var CODE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
1610
3526
|
".ts",
|
|
1611
3527
|
".tsx",
|
|
@@ -1698,6 +3614,7 @@ function enforceSessionSecretsRedacted(text, sessionMap) {
|
|
|
1698
3614
|
}
|
|
1699
3615
|
return { text: out, extraRedactions };
|
|
1700
3616
|
}
|
|
3617
|
+
var MAX_CLIENT_SESSIONS = 500;
|
|
1701
3618
|
function createMaskeraMcpServer(options = {}) {
|
|
1702
3619
|
const engine = options.engine ?? createMaskeraEngine();
|
|
1703
3620
|
const vault = options.vault ?? new SessionVault();
|
|
@@ -1708,8 +3625,24 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1708
3625
|
const approvalBaseUrl = options.approvalBaseUrl;
|
|
1709
3626
|
const requestElicitation = options.requestElicitation;
|
|
1710
3627
|
const onToolCall = options.onToolCall;
|
|
1711
|
-
|
|
3628
|
+
const clientSessions = /* @__PURE__ */ new Map();
|
|
1712
3629
|
const ownerPathAliases = /* @__PURE__ */ new Map();
|
|
3630
|
+
function getClientHandshake(owner) {
|
|
3631
|
+
return clientSessions.get(owner) ?? { status: "uninitialized" };
|
|
3632
|
+
}
|
|
3633
|
+
function setClientInitialized(owner, protocolVersion, supportsElicitation) {
|
|
3634
|
+
if (clientSessions.has(owner)) {
|
|
3635
|
+
clientSessions.delete(owner);
|
|
3636
|
+
} else if (clientSessions.size >= MAX_CLIENT_SESSIONS) {
|
|
3637
|
+
const oldest = clientSessions.keys().next().value;
|
|
3638
|
+
if (oldest !== void 0) clientSessions.delete(oldest);
|
|
3639
|
+
}
|
|
3640
|
+
clientSessions.set(owner, {
|
|
3641
|
+
status: "initialized",
|
|
3642
|
+
protocolVersion,
|
|
3643
|
+
supportsElicitation
|
|
3644
|
+
});
|
|
3645
|
+
}
|
|
1713
3646
|
function getPathAliasBucket(owner) {
|
|
1714
3647
|
let bucket = ownerPathAliases.get(owner);
|
|
1715
3648
|
if (!bucket) {
|
|
@@ -1900,7 +3833,8 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1900
3833
|
return toolOk(await input.execute());
|
|
1901
3834
|
}
|
|
1902
3835
|
if (policy.approvalMode === "native") {
|
|
1903
|
-
|
|
3836
|
+
const handshake = getClientHandshake(policy.sessionOwner);
|
|
3837
|
+
if (!requestElicitation || handshake.status !== "initialized" || !handshake.supportsElicitation) {
|
|
1904
3838
|
return toolError(
|
|
1905
3839
|
`Approval mode "native" requires an MCP client with elicitation support. Reconnect with approval_mode=browser or write restored output directly via maskera_write_file.`
|
|
1906
3840
|
);
|
|
@@ -2065,6 +3999,9 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2065
3999
|
if (resumed.status === "not_found") {
|
|
2066
4000
|
return finish(toolError(`Unknown approval request_id "${requestId}".`));
|
|
2067
4001
|
}
|
|
4002
|
+
if (resumed.status === "failed") {
|
|
4003
|
+
return finish(toolError(`Approval request "${requestId}" failed: ${resumed.error}`));
|
|
4004
|
+
}
|
|
2068
4005
|
if (resumed.status === "completed") {
|
|
2069
4006
|
return finish(
|
|
2070
4007
|
toolOk({
|
|
@@ -2093,7 +4030,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2093
4030
|
}
|
|
2094
4031
|
const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
|
|
2095
4032
|
const resolvedInputPath = resolveInputPath(args.path, owner, requestedSession);
|
|
2096
|
-
const file = await files.
|
|
4033
|
+
const file = await files.readDocument(resolvedInputPath);
|
|
2097
4034
|
const profile = asProfile(args.profile) ?? defaultProfile;
|
|
2098
4035
|
const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
|
|
2099
4036
|
const { result, modeUsed } = await engine.redact(file.content, {
|
|
@@ -2116,11 +4053,109 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2116
4053
|
toolOk({
|
|
2117
4054
|
path: safePath,
|
|
2118
4055
|
bytes: file.bytes,
|
|
4056
|
+
format: file.format,
|
|
2119
4057
|
redacted: applied.redacted,
|
|
2120
4058
|
session_id: applied.sessionId,
|
|
2121
4059
|
counts: applied.counts,
|
|
2122
4060
|
total_redactions: applied.totalRedactions,
|
|
2123
|
-
mode: modeUsed
|
|
4061
|
+
mode: modeUsed,
|
|
4062
|
+
...file.totalPages !== void 0 ? { total_pages: file.totalPages } : {},
|
|
4063
|
+
...file.scannedPages.length > 0 ? { scanned_pages: file.scannedPages } : {},
|
|
4064
|
+
...file.metadataFields.length > 0 ? { metadata_fields: file.metadataFields } : {},
|
|
4065
|
+
...file.warnings.length > 0 ? { warnings: file.warnings } : {}
|
|
4066
|
+
})
|
|
4067
|
+
);
|
|
4068
|
+
}
|
|
4069
|
+
if (name === "maskera_redact_file") {
|
|
4070
|
+
if (typeof args.input_path !== "string") {
|
|
4071
|
+
return finish(toolError("Missing required string: input_path"));
|
|
4072
|
+
}
|
|
4073
|
+
if (typeof args.output_path !== "string") {
|
|
4074
|
+
return finish(toolError("Missing required string: output_path"));
|
|
4075
|
+
}
|
|
4076
|
+
const requestedMode = asMode(args.mode);
|
|
4077
|
+
if (engine.status().defaultMode === "auto" && requestedMode === "rules") {
|
|
4078
|
+
return finish(
|
|
4079
|
+
toolError(
|
|
4080
|
+
'Downgrading mode to "rules" is not allowed on maskera_redact_file when the server runs in hybrid "auto" mode.'
|
|
4081
|
+
)
|
|
4082
|
+
);
|
|
4083
|
+
}
|
|
4084
|
+
const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
|
|
4085
|
+
const resolvedInputPath = resolveInputPath(args.input_path, owner, requestedSession);
|
|
4086
|
+
const resolvedOutputPath = resolveInputPath(args.output_path, owner, requestedSession);
|
|
4087
|
+
const source = await files.readBytes(resolvedInputPath);
|
|
4088
|
+
const profile = asProfile(args.profile) ?? defaultProfile;
|
|
4089
|
+
const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
|
|
4090
|
+
let sessionId = requestedSession ?? "";
|
|
4091
|
+
let modeUsed = engine.status().defaultMode === "rules" ? "rules" : "hybrid";
|
|
4092
|
+
const redactedDoc = await redactFile(
|
|
4093
|
+
source.bytes,
|
|
4094
|
+
async (text) => {
|
|
4095
|
+
const eng = await engine.redact(text, {
|
|
4096
|
+
mode: requestedMode,
|
|
4097
|
+
profile,
|
|
4098
|
+
customTerms
|
|
4099
|
+
});
|
|
4100
|
+
modeUsed = eng.modeUsed;
|
|
4101
|
+
const applied = vault.apply(text, eng.result, sessionId || void 0, owner);
|
|
4102
|
+
sessionId = applied.sessionId;
|
|
4103
|
+
return {
|
|
4104
|
+
text: applied.redacted,
|
|
4105
|
+
redactions: applied.redactions,
|
|
4106
|
+
map: applied.map,
|
|
4107
|
+
restore: (t) => vault.restore(t, { sessionId: applied.sessionId, owner }).restored
|
|
4108
|
+
};
|
|
4109
|
+
},
|
|
4110
|
+
{
|
|
4111
|
+
fileName: source.resolvedPath,
|
|
4112
|
+
pdfStyle: { showLabels: args.show_labels !== false },
|
|
4113
|
+
verify: true
|
|
4114
|
+
}
|
|
4115
|
+
);
|
|
4116
|
+
if (!redactedDoc.verified) {
|
|
4117
|
+
return finish(
|
|
4118
|
+
toolError(
|
|
4119
|
+
`Post-redaction verification detected ${redactedDoc.verificationLeaks.length} residual item(s) in the output file; refused to write unverified output.`
|
|
4120
|
+
)
|
|
4121
|
+
);
|
|
4122
|
+
}
|
|
4123
|
+
const written = await files.writeBytes(resolvedOutputPath, redactedDoc.bytes, {
|
|
4124
|
+
overwrite: args.overwrite === true
|
|
4125
|
+
});
|
|
4126
|
+
const safeInputPath = await redactResolvedPath(source.resolvedPath, {
|
|
4127
|
+
owner,
|
|
4128
|
+
sessionId: sessionId || void 0,
|
|
4129
|
+
mode: requestedMode,
|
|
4130
|
+
profile,
|
|
4131
|
+
customTerms
|
|
4132
|
+
});
|
|
4133
|
+
const safeOutputPath = await redactResolvedPath(written.resolvedPath, {
|
|
4134
|
+
owner,
|
|
4135
|
+
sessionId: sessionId || void 0,
|
|
4136
|
+
mode: requestedMode,
|
|
4137
|
+
profile,
|
|
4138
|
+
customTerms
|
|
4139
|
+
});
|
|
4140
|
+
telemetrySessionId = sessionId || void 0;
|
|
4141
|
+
telemetryRedactions = redactedDoc.totalRedactions;
|
|
4142
|
+
telemetryCounts = redactedDoc.counts;
|
|
4143
|
+
return finish(
|
|
4144
|
+
toolOk({
|
|
4145
|
+
input_path: safeInputPath,
|
|
4146
|
+
output_path: safeOutputPath,
|
|
4147
|
+
format: redactedDoc.format,
|
|
4148
|
+
bytes: written.bytes,
|
|
4149
|
+
session_id: sessionId,
|
|
4150
|
+
counts: redactedDoc.counts,
|
|
4151
|
+
total_redactions: redactedDoc.totalRedactions,
|
|
4152
|
+
mode: modeUsed,
|
|
4153
|
+
verified: redactedDoc.verified,
|
|
4154
|
+
metadata_cleared: redactedDoc.metadataCleared,
|
|
4155
|
+
...redactedDoc.redactedPages ? { redacted_pages: redactedDoc.redactedPages } : {},
|
|
4156
|
+
...redactedDoc.totalPages !== void 0 ? { total_pages: redactedDoc.totalPages } : {},
|
|
4157
|
+
...redactedDoc.scannedPages.length > 0 ? { scanned_pages: redactedDoc.scannedPages } : {},
|
|
4158
|
+
...redactedDoc.warnings.length > 0 ? { warnings: redactedDoc.warnings } : {}
|
|
2124
4159
|
})
|
|
2125
4160
|
);
|
|
2126
4161
|
}
|
|
@@ -2291,6 +4326,17 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2291
4326
|
}
|
|
2292
4327
|
return {
|
|
2293
4328
|
vault,
|
|
4329
|
+
getClientState(owner) {
|
|
4330
|
+
return getClientHandshake(owner ?? options.sessionOwner ?? "default");
|
|
4331
|
+
},
|
|
4332
|
+
clearOwner(owner) {
|
|
4333
|
+
clientSessions.delete(owner);
|
|
4334
|
+
ownerPathAliases.delete(owner);
|
|
4335
|
+
},
|
|
4336
|
+
clearAllOwners() {
|
|
4337
|
+
clientSessions.clear();
|
|
4338
|
+
ownerPathAliases.clear();
|
|
4339
|
+
},
|
|
2294
4340
|
async handleMessage(raw, policyOverride) {
|
|
2295
4341
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
2296
4342
|
return {
|
|
@@ -2317,9 +4363,10 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2317
4363
|
if (req.method === "initialize") {
|
|
2318
4364
|
const params = asObject(req.params);
|
|
2319
4365
|
const clientCaps = asObject(params.capabilities);
|
|
2320
|
-
|
|
4366
|
+
const supportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
|
|
2321
4367
|
const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
|
|
2322
4368
|
const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
|
|
4369
|
+
setClientInitialized(policy.sessionOwner, protocolVersion, supportsElicitation);
|
|
2323
4370
|
return {
|
|
2324
4371
|
jsonrpc: "2.0",
|
|
2325
4372
|
id,
|
|
@@ -3283,6 +5330,22 @@ function normalizeOwner2(owner) {
|
|
|
3283
5330
|
const trimmed = owner?.trim();
|
|
3284
5331
|
return trimmed || DEFAULT_OWNER2;
|
|
3285
5332
|
}
|
|
5333
|
+
function toSummary(record) {
|
|
5334
|
+
const { state } = record;
|
|
5335
|
+
const decidedAt = state.status === "pending" ? null : state.decidedAt;
|
|
5336
|
+
const base = {
|
|
5337
|
+
id: record.id,
|
|
5338
|
+
tool: record.tool,
|
|
5339
|
+
reason: record.reason,
|
|
5340
|
+
sessionId: record.sessionId,
|
|
5341
|
+
placeholderCount: record.placeholderCount,
|
|
5342
|
+
status: state.status,
|
|
5343
|
+
createdAt: record.createdAt,
|
|
5344
|
+
expiresAt: record.expiresAt,
|
|
5345
|
+
decidedAt
|
|
5346
|
+
};
|
|
5347
|
+
return state.status === "failed" ? { ...base, error: state.error } : base;
|
|
5348
|
+
}
|
|
3286
5349
|
var ApprovalBroker = class {
|
|
3287
5350
|
constructor(ttlMs = DEFAULT_TTL_MS) {
|
|
3288
5351
|
this.records = /* @__PURE__ */ new Map();
|
|
@@ -3292,9 +5355,9 @@ var ApprovalBroker = class {
|
|
|
3292
5355
|
expireStale(now = Date.now()) {
|
|
3293
5356
|
let changed = false;
|
|
3294
5357
|
for (const record of this.records.values()) {
|
|
3295
|
-
if (record.
|
|
3296
|
-
record.
|
|
3297
|
-
record.
|
|
5358
|
+
if ((record.state.status === "pending" || record.state.status === "approved") && now >= record.state.expiresAtMs) {
|
|
5359
|
+
const decidedAt = record.state.status === "approved" ? record.state.decidedAt : null;
|
|
5360
|
+
record.state = { status: "expired", decidedAt };
|
|
3298
5361
|
changed = true;
|
|
3299
5362
|
}
|
|
3300
5363
|
}
|
|
@@ -3323,70 +5386,93 @@ var ApprovalBroker = class {
|
|
|
3323
5386
|
}
|
|
3324
5387
|
const now = Date.now();
|
|
3325
5388
|
const id = `apr_${randomUUID().slice(0, 12)}`;
|
|
3326
|
-
const
|
|
5389
|
+
const expiresAtMs = now + this.ttlMs;
|
|
5390
|
+
const record = {
|
|
3327
5391
|
id,
|
|
5392
|
+
owner: normalizeOwner2(input.owner),
|
|
3328
5393
|
tool: input.tool,
|
|
3329
5394
|
reason: input.reason,
|
|
3330
5395
|
sessionId: input.sessionId ?? null,
|
|
3331
5396
|
placeholderCount: input.placeholderCount,
|
|
3332
|
-
status: "pending",
|
|
3333
5397
|
createdAt: new Date(now).toISOString(),
|
|
3334
|
-
expiresAt: new Date(
|
|
3335
|
-
|
|
5398
|
+
expiresAt: new Date(expiresAtMs).toISOString(),
|
|
5399
|
+
state: {
|
|
5400
|
+
status: "pending",
|
|
5401
|
+
expiresAtMs,
|
|
5402
|
+
execute: input.execute
|
|
5403
|
+
}
|
|
3336
5404
|
};
|
|
3337
|
-
this.records.set(id,
|
|
3338
|
-
owner: normalizeOwner2(input.owner),
|
|
3339
|
-
summary,
|
|
3340
|
-
expiresAtMs: now + this.ttlMs,
|
|
3341
|
-
execute: input.execute
|
|
3342
|
-
});
|
|
5405
|
+
this.records.set(id, record);
|
|
3343
5406
|
this.notify();
|
|
3344
|
-
return
|
|
5407
|
+
return toSummary(record);
|
|
3345
5408
|
}
|
|
3346
5409
|
list() {
|
|
3347
5410
|
this.expireStale();
|
|
3348
|
-
return [...this.records.values()].map(
|
|
5411
|
+
return [...this.records.values()].map(toSummary).reverse();
|
|
3349
5412
|
}
|
|
3350
5413
|
decide(id, decision) {
|
|
3351
5414
|
this.expireStale();
|
|
3352
5415
|
const record = this.records.get(id.trim());
|
|
3353
5416
|
if (!record) return null;
|
|
3354
|
-
if (record.
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
5417
|
+
if (record.state.status !== "pending") return toSummary(record);
|
|
5418
|
+
const decidedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5419
|
+
if (decision === "approve") {
|
|
5420
|
+
record.state = {
|
|
5421
|
+
status: "approved",
|
|
5422
|
+
expiresAtMs: record.state.expiresAtMs,
|
|
5423
|
+
decidedAt,
|
|
5424
|
+
execute: record.state.execute
|
|
5425
|
+
};
|
|
5426
|
+
} else {
|
|
5427
|
+
record.state = { status: "declined", decidedAt };
|
|
3359
5428
|
}
|
|
3360
5429
|
this.notify();
|
|
3361
|
-
return
|
|
5430
|
+
return toSummary(record);
|
|
3362
5431
|
}
|
|
3363
5432
|
async resume(id, owner) {
|
|
3364
5433
|
this.expireStale();
|
|
3365
|
-
const
|
|
5434
|
+
const key = id.trim();
|
|
5435
|
+
const record = this.records.get(key);
|
|
3366
5436
|
if (!record) return { status: "not_found" };
|
|
3367
5437
|
if (owner !== void 0 && record.owner !== normalizeOwner2(owner)) {
|
|
3368
5438
|
return { status: "not_found" };
|
|
3369
5439
|
}
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
5440
|
+
switch (record.state.status) {
|
|
5441
|
+
case "pending":
|
|
5442
|
+
case "executing":
|
|
5443
|
+
case "declined":
|
|
5444
|
+
case "expired":
|
|
5445
|
+
return { status: record.state.status, summary: toSummary(record) };
|
|
5446
|
+
case "completed":
|
|
5447
|
+
return { status: "already_completed", summary: toSummary(record) };
|
|
5448
|
+
case "failed":
|
|
5449
|
+
return { status: "failed", error: record.state.error, summary: toSummary(record) };
|
|
5450
|
+
case "approved": {
|
|
5451
|
+
const { decidedAt, execute } = record.state;
|
|
5452
|
+
const inFlight = (async () => {
|
|
5453
|
+
try {
|
|
5454
|
+
const result = await execute();
|
|
5455
|
+
record.state = { status: "completed", decidedAt };
|
|
5456
|
+
if (this.records.get(key) === record) this.notify();
|
|
5457
|
+
return { status: "completed", result, summary: toSummary(record) };
|
|
5458
|
+
} catch (err) {
|
|
5459
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
5460
|
+
record.state = { status: "failed", decidedAt, error };
|
|
5461
|
+
if (this.records.get(key) === record) this.notify();
|
|
5462
|
+
return { status: "failed", error, summary: toSummary(record) };
|
|
5463
|
+
}
|
|
5464
|
+
})();
|
|
5465
|
+
record.state = { status: "executing", decidedAt, inFlight };
|
|
5466
|
+
this.notify();
|
|
5467
|
+
return await inFlight;
|
|
5468
|
+
}
|
|
3376
5469
|
}
|
|
3377
|
-
const run = record.execute;
|
|
3378
|
-
record.execute = null;
|
|
3379
|
-
const result = await run();
|
|
3380
|
-
record.summary.status = "completed";
|
|
3381
|
-
this.notify();
|
|
3382
|
-
return { status: "completed", result, summary: { ...record.summary } };
|
|
3383
5470
|
}
|
|
3384
5471
|
clearOwner(owner) {
|
|
3385
5472
|
const resolvedOwner = normalizeOwner2(owner);
|
|
3386
5473
|
let changed = false;
|
|
3387
5474
|
for (const [id, record] of this.records.entries()) {
|
|
3388
5475
|
if (record.owner === resolvedOwner) {
|
|
3389
|
-
record.execute = null;
|
|
3390
5476
|
this.records.delete(id);
|
|
3391
5477
|
changed = true;
|
|
3392
5478
|
}
|
|
@@ -3775,13 +5861,93 @@ function renderInspectorHtml(info) {
|
|
|
3775
5861
|
const stUniq = document.getElementById("st-uniq");
|
|
3776
5862
|
const stModel = document.getElementById("st-model");
|
|
3777
5863
|
const SAMPLE_PROMPT = "Skriv ett kort mejl till Anna Lindqvist (provnamn.maskera@example.com, 19900101-2385) och bekr\xE4fta m\xF6tet.";
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
|
|
5864
|
+
const VISIBLE_APPROVAL_STATUSES = new Set(["pending", "approved", "executing", "declined", "failed"]);
|
|
5865
|
+
const state = {
|
|
5866
|
+
connection: "connecting",
|
|
5867
|
+
items: [],
|
|
5868
|
+
approvals: [],
|
|
5869
|
+
selfTest: { phase: "idle" },
|
|
5870
|
+
vaultView: "hidden",
|
|
5871
|
+
expansion: { mode: "auto" },
|
|
5872
|
+
};
|
|
5873
|
+
|
|
5874
|
+
function isExpanded(itemId, index) {
|
|
5875
|
+
if (state.expansion.mode === "auto") return index === 0;
|
|
5876
|
+
return state.expansion.openIds.has(itemId);
|
|
5877
|
+
}
|
|
5878
|
+
|
|
5879
|
+
function transition(event) {
|
|
5880
|
+
switch (event.type) {
|
|
5881
|
+
case "sse_open":
|
|
5882
|
+
state.connection = "live";
|
|
5883
|
+
return;
|
|
5884
|
+
case "sse_error":
|
|
5885
|
+
state.connection = "reconnecting";
|
|
5886
|
+
return;
|
|
5887
|
+
case "sse_init":
|
|
5888
|
+
state.connection = "live";
|
|
5889
|
+
state.items = event.items || [];
|
|
5890
|
+
state.approvals = event.approvals || [];
|
|
5891
|
+
renderApprovals();
|
|
5892
|
+
render();
|
|
5893
|
+
void refreshStatus();
|
|
5894
|
+
return;
|
|
5895
|
+
case "sse_approvals":
|
|
5896
|
+
state.approvals = event.approvals || [];
|
|
5897
|
+
renderApprovals();
|
|
5898
|
+
void refreshStatus();
|
|
5899
|
+
return;
|
|
5900
|
+
case "sse_request":
|
|
5901
|
+
state.items.unshift(event.item);
|
|
5902
|
+
if (state.items.length > 100) state.items.length = 100;
|
|
5903
|
+
render();
|
|
5904
|
+
void refreshStatus();
|
|
5905
|
+
if (state.vaultView === "revealed") void refreshVault();
|
|
5906
|
+
return;
|
|
5907
|
+
case "cleared":
|
|
5908
|
+
state.items = [];
|
|
5909
|
+
state.approvals = [];
|
|
5910
|
+
state.expansion = { mode: "auto" };
|
|
5911
|
+
renderApprovals();
|
|
5912
|
+
render();
|
|
5913
|
+
void refreshStatus();
|
|
5914
|
+
void refreshVault();
|
|
5915
|
+
return;
|
|
5916
|
+
case "toggle_item": {
|
|
5917
|
+
const openIds =
|
|
5918
|
+
state.expansion.mode === "manual"
|
|
5919
|
+
? new Set(state.expansion.openIds)
|
|
5920
|
+
: new Set(state.items[0]?.id ? [state.items[0].id] : []);
|
|
5921
|
+
if (event.open) openIds.add(event.id);
|
|
5922
|
+
else openIds.delete(event.id);
|
|
5923
|
+
state.expansion = { mode: "manual", openIds };
|
|
5924
|
+
return;
|
|
5925
|
+
}
|
|
5926
|
+
case "toggle_vault":
|
|
5927
|
+
state.vaultView = state.vaultView === "revealed" ? "hidden" : "revealed";
|
|
5928
|
+
revealBtn.classList.toggle("active", state.vaultView === "revealed");
|
|
5929
|
+
revealBtn.textContent = state.vaultView === "revealed" ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
|
|
5930
|
+
void refreshVault();
|
|
5931
|
+
return;
|
|
5932
|
+
case "selftest_start":
|
|
5933
|
+
state.selfTest = { phase: "running" };
|
|
5934
|
+
renderReceipt();
|
|
5935
|
+
return;
|
|
5936
|
+
case "selftest_done":
|
|
5937
|
+
state.selfTest = { phase: "done", receipt: event.receipt };
|
|
5938
|
+
renderReceipt();
|
|
5939
|
+
void refreshStatus();
|
|
5940
|
+
return;
|
|
5941
|
+
case "selftest_error":
|
|
5942
|
+
state.selfTest = { phase: "error", message: event.message };
|
|
5943
|
+
renderReceipt();
|
|
5944
|
+
return;
|
|
5945
|
+
case "selftest_close":
|
|
5946
|
+
state.selfTest = { phase: "idle" };
|
|
5947
|
+
renderReceipt();
|
|
5948
|
+
return;
|
|
5949
|
+
}
|
|
5950
|
+
}
|
|
3785
5951
|
|
|
3786
5952
|
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&":"&","<":"<",">":">",'"':""","'":"'" }[c]));
|
|
3787
5953
|
const highlightTokens = (s) => esc(s).replace(/\\[[A-Z\xC5\xC4\xD6][A-Z\xC5\xC4\xD60-9_]*_\\d+\\]/g, (m) => '<span class="tok">' + m + "</span>");
|
|
@@ -3797,11 +5963,17 @@ function renderInspectorHtml(info) {
|
|
|
3797
5963
|
};
|
|
3798
5964
|
|
|
3799
5965
|
function renderReceipt() {
|
|
3800
|
-
|
|
3801
|
-
|
|
5966
|
+
selftestBtn.disabled = state.selfTest.phase === "running";
|
|
5967
|
+
selftestBtn.textContent = state.selfTest.phase === "running" ? "K\xF6r sj\xE4lvtest..." : "K\xF6r sj\xE4lvtest";
|
|
5968
|
+
if (state.selfTest.phase === "idle" || state.selfTest.phase === "running") {
|
|
5969
|
+
if (state.selfTest.phase === "idle") receiptRoot.innerHTML = "";
|
|
5970
|
+
return;
|
|
5971
|
+
}
|
|
5972
|
+
if (state.selfTest.phase === "error") {
|
|
5973
|
+
receiptRoot.innerHTML = '<section class="receipt-box"><h2>Sj\xE4lvtest misslyckades</h2><p>' + esc(state.selfTest.message) + '</p></section>';
|
|
3802
5974
|
return;
|
|
3803
5975
|
}
|
|
3804
|
-
const r =
|
|
5976
|
+
const r = state.selfTest.receipt;
|
|
3805
5977
|
const checksHtml = (r.checks || []).map((c) => {
|
|
3806
5978
|
const cls = c.status === "fail" ? " fail" : "";
|
|
3807
5979
|
return '<li><span class="receipt-tag' + cls + '">[' + esc(c.status) + ']</span><span><strong>' + esc(c.name) + ':</strong> ' + esc(c.detail) + '</span></li>';
|
|
@@ -3827,29 +5999,22 @@ function renderInspectorHtml(info) {
|
|
|
3827
5999
|
const closeBtn = document.getElementById("close-receipt-btn");
|
|
3828
6000
|
if (closeBtn) {
|
|
3829
6001
|
closeBtn.addEventListener("click", () => {
|
|
3830
|
-
|
|
3831
|
-
renderReceipt();
|
|
6002
|
+
transition({ type: "selftest_close" });
|
|
3832
6003
|
});
|
|
3833
6004
|
}
|
|
3834
6005
|
}
|
|
3835
6006
|
|
|
3836
6007
|
selftestBtn.addEventListener("click", async () => {
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
selftestBtn.textContent = "K\xF6r sj\xE4lvtest...";
|
|
6008
|
+
if (state.selfTest.phase === "running") return;
|
|
6009
|
+
transition({ type: "selftest_start" });
|
|
3840
6010
|
try {
|
|
3841
6011
|
const r = await fetch("/_maskera/self-test", {
|
|
3842
6012
|
method: "POST",
|
|
3843
6013
|
headers: { "x-maskera-action": "self-test" },
|
|
3844
6014
|
});
|
|
3845
|
-
|
|
3846
|
-
renderReceipt();
|
|
3847
|
-
await refreshStatus();
|
|
6015
|
+
transition({ type: "selftest_done", receipt: await r.json() });
|
|
3848
6016
|
} catch (err) {
|
|
3849
|
-
|
|
3850
|
-
} finally {
|
|
3851
|
-
selftestBtn.disabled = false;
|
|
3852
|
-
selftestBtn.textContent = prevText;
|
|
6017
|
+
transition({ type: "selftest_error", message: String(err) });
|
|
3853
6018
|
}
|
|
3854
6019
|
});
|
|
3855
6020
|
|
|
@@ -3877,7 +6042,7 @@ function renderInspectorHtml(info) {
|
|
|
3877
6042
|
}
|
|
3878
6043
|
|
|
3879
6044
|
function renderApprovals() {
|
|
3880
|
-
const visible = (approvals || []).filter((a) =>
|
|
6045
|
+
const visible = (state.approvals || []).filter((a) => VISIBLE_APPROVAL_STATUSES.has(a.status));
|
|
3881
6046
|
if (!visible.length) {
|
|
3882
6047
|
approvalsRoot.innerHTML = "";
|
|
3883
6048
|
return;
|
|
@@ -3885,7 +6050,7 @@ function renderInspectorHtml(info) {
|
|
|
3885
6050
|
const rows = visible.map((a) => {
|
|
3886
6051
|
const btns = a.status === "pending"
|
|
3887
6052
|
? '<div class="actions"><button type="button" class="primary" data-apr="' + esc(a.id) + '" data-act="approve">Godk\xE4nn</button><button type="button" data-apr="' + esc(a.id) + '" data-act="decline">Neka</button></div>'
|
|
3888
|
-
: '<span class="badge">' + esc(a.status) + "</span>";
|
|
6053
|
+
: '<span class="badge' + (a.status === "failed" ? " err" : "") + '">' + esc(a.status) + "</span>";
|
|
3889
6054
|
return '<div class="approval-row" id="approval-' + esc(a.id) + '"><div><strong>' + esc(a.tool) + '</strong> \xB7 ' + esc(a.reason) + '<div class="approval-meta">F\xF6rfr\xE5gan ' + esc(a.id) + (a.sessionId ? ' \xB7 session ' + esc(a.sessionId) : '') + ' \xB7 ' + esc(a.placeholderCount) + ' v\xE4rden</div></div>' + btns + '</div>';
|
|
3890
6055
|
}).join("");
|
|
3891
6056
|
approvalsRoot.innerHTML = '<section class="approvals"><h2>V\xE4ntande godk\xE4nnanden (r\xE5 PII)</h2>' + rows + "</section>";
|
|
@@ -3899,7 +6064,7 @@ function renderInspectorHtml(info) {
|
|
|
3899
6064
|
}
|
|
3900
6065
|
|
|
3901
6066
|
async function refreshVault() {
|
|
3902
|
-
if (
|
|
6067
|
+
if (state.vaultView !== "revealed") { vaultRoot.innerHTML = ""; return; }
|
|
3903
6068
|
try {
|
|
3904
6069
|
const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
|
|
3905
6070
|
const d = await r.json();
|
|
@@ -3911,7 +6076,7 @@ function renderInspectorHtml(info) {
|
|
|
3911
6076
|
}
|
|
3912
6077
|
|
|
3913
6078
|
function render() {
|
|
3914
|
-
if (!items.length) {
|
|
6079
|
+
if (!state.items.length) {
|
|
3915
6080
|
feedEl.innerHTML =
|
|
3916
6081
|
'<div class="empty"><p class="empty-title">Inga anrop \xE4nnu.</p>' +
|
|
3917
6082
|
'Skicka ett prov fr\xE5n din klient s\xE5 visas maskeringen h\xE4r:' +
|
|
@@ -3929,17 +6094,13 @@ function renderInspectorHtml(info) {
|
|
|
3929
6094
|
}
|
|
3930
6095
|
return;
|
|
3931
6096
|
}
|
|
3932
|
-
|
|
3933
|
-
openIds.add(items[0].id);
|
|
3934
|
-
}
|
|
3935
|
-
for (const it of items) seenIds.add(it.id);
|
|
3936
|
-
feedEl.innerHTML = '<div class="list">' + items.map((it) => {
|
|
6097
|
+
feedEl.innerHTML = '<div class="list">' + state.items.map((it, idx) => {
|
|
3937
6098
|
const time = formatLocalTime(it.timestamp);
|
|
3938
6099
|
const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
|
|
3939
6100
|
const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
|
|
3940
6101
|
const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
|
|
3941
6102
|
const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
|
|
3942
|
-
const isOpen =
|
|
6103
|
+
const isOpen = isExpanded(it.id, idx);
|
|
3943
6104
|
return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
|
|
3944
6105
|
'<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>' +
|
|
3945
6106
|
'<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
|
|
@@ -3949,67 +6110,36 @@ function renderInspectorHtml(info) {
|
|
|
3949
6110
|
det.addEventListener("toggle", () => {
|
|
3950
6111
|
const id = det.getAttribute("data-id");
|
|
3951
6112
|
if (!id) return;
|
|
3952
|
-
|
|
3953
|
-
if (det.open) openIds.add(id);
|
|
3954
|
-
else openIds.delete(id);
|
|
6113
|
+
transition({ type: "toggle_item", id, open: det.open });
|
|
3955
6114
|
});
|
|
3956
6115
|
}
|
|
3957
6116
|
}
|
|
3958
6117
|
|
|
3959
6118
|
revealBtn.addEventListener("click", () => {
|
|
3960
|
-
|
|
3961
|
-
revealBtn.classList.toggle("active", reveal);
|
|
3962
|
-
revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
|
|
3963
|
-
void refreshVault();
|
|
6119
|
+
transition({ type: "toggle_vault" });
|
|
3964
6120
|
});
|
|
3965
6121
|
|
|
3966
6122
|
clearBtn.addEventListener("click", async () => {
|
|
3967
6123
|
await fetch("/_maskera/clear", { method: "POST", headers: { "x-maskera-action": "clear" } });
|
|
3968
|
-
|
|
3969
|
-
approvals = [];
|
|
3970
|
-
userToggled = false;
|
|
3971
|
-
openIds.clear();
|
|
3972
|
-
seenIds.clear();
|
|
3973
|
-
renderApprovals();
|
|
3974
|
-
render();
|
|
3975
|
-
await refreshStatus();
|
|
3976
|
-
await refreshVault();
|
|
6124
|
+
transition({ type: "cleared" });
|
|
3977
6125
|
});
|
|
3978
6126
|
|
|
3979
6127
|
const es = new EventSource("/_maskera/events");
|
|
6128
|
+
es.addEventListener("open", () => transition({ type: "sse_open" }));
|
|
6129
|
+
es.addEventListener("error", () => transition({ type: "sse_error" }));
|
|
3980
6130
|
es.addEventListener("init", (ev) => {
|
|
3981
6131
|
const data = JSON.parse(ev.data);
|
|
3982
|
-
items
|
|
3983
|
-
approvals = data.approvals || [];
|
|
3984
|
-
renderApprovals();
|
|
3985
|
-
render();
|
|
3986
|
-
void refreshStatus();
|
|
6132
|
+
transition({ type: "sse_init", items: data.items, approvals: data.approvals });
|
|
3987
6133
|
});
|
|
3988
6134
|
es.addEventListener("approvals", (ev) => {
|
|
3989
6135
|
const data = JSON.parse(ev.data);
|
|
3990
|
-
approvals
|
|
3991
|
-
renderApprovals();
|
|
3992
|
-
void refreshStatus();
|
|
6136
|
+
transition({ type: "sse_approvals", approvals: data.approvals });
|
|
3993
6137
|
});
|
|
3994
6138
|
es.addEventListener("request", (ev) => {
|
|
3995
|
-
|
|
3996
|
-
items.unshift(next);
|
|
3997
|
-
if (items.length > 100) items.length = 100;
|
|
3998
|
-
if (!userToggled && openIds.size === 0 && next?.id) openIds.add(next.id);
|
|
3999
|
-
render();
|
|
4000
|
-
void refreshStatus();
|
|
4001
|
-
if (reveal) void refreshVault();
|
|
6139
|
+
transition({ type: "sse_request", item: JSON.parse(ev.data) });
|
|
4002
6140
|
});
|
|
4003
6141
|
es.addEventListener("cleared", () => {
|
|
4004
|
-
|
|
4005
|
-
approvals = [];
|
|
4006
|
-
userToggled = false;
|
|
4007
|
-
openIds.clear();
|
|
4008
|
-
seenIds.clear();
|
|
4009
|
-
renderApprovals();
|
|
4010
|
-
render();
|
|
4011
|
-
void refreshStatus();
|
|
4012
|
-
void refreshVault();
|
|
6142
|
+
transition({ type: "cleared" });
|
|
4013
6143
|
});
|
|
4014
6144
|
void refreshStatus();
|
|
4015
6145
|
})();
|
|
@@ -4584,7 +6714,38 @@ function deriveProxySessionId(headers, body) {
|
|
|
4584
6714
|
}
|
|
4585
6715
|
var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
|
|
4586
6716
|
var DATA_URI_TEXT_BASE64_RE = /^data:((?:text\/[a-z0-9.+-]+|application\/(?:json|xml|csv|x-ndjson|javascript))[^;,]*);base64,([A-Za-z0-9+/=\s]+)$/i;
|
|
4587
|
-
var DATA_URI_ANY_RE = /^data:([^;,]+);base64
|
|
6717
|
+
var DATA_URI_ANY_RE = /^data:([^;,]+);base64,([A-Za-z0-9+/=\s]+)$/i;
|
|
6718
|
+
async function tryRedactBase64Document(encoded, mediaType, fileName, redactDocument, noteBinary) {
|
|
6719
|
+
if (!redactDocument) {
|
|
6720
|
+
noteBinary(mediaType);
|
|
6721
|
+
return encoded;
|
|
6722
|
+
}
|
|
6723
|
+
try {
|
|
6724
|
+
const rawBuf = Buffer.from(encoded, "base64");
|
|
6725
|
+
if (rawBuf.byteLength === 0 || rawBuf.byteLength > MAX_BODY_BYTES) {
|
|
6726
|
+
noteBinary(mediaType);
|
|
6727
|
+
return encoded;
|
|
6728
|
+
}
|
|
6729
|
+
const bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
|
|
6730
|
+
const detected = detectFileFormat(bytes, fileName, mediaType);
|
|
6731
|
+
if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
|
|
6732
|
+
noteBinary(mediaType);
|
|
6733
|
+
return encoded;
|
|
6734
|
+
}
|
|
6735
|
+
const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
|
|
6736
|
+
if (!res.verified) {
|
|
6737
|
+
noteBinary(`${mediaType} (unverified)`);
|
|
6738
|
+
return encoded;
|
|
6739
|
+
}
|
|
6740
|
+
if (res.scannedPages.length > 0) {
|
|
6741
|
+
noteBinary(`${mediaType} (scanned)`);
|
|
6742
|
+
}
|
|
6743
|
+
return Buffer.from(res.bytes).toString("base64");
|
|
6744
|
+
} catch {
|
|
6745
|
+
noteBinary(mediaType);
|
|
6746
|
+
return encoded;
|
|
6747
|
+
}
|
|
6748
|
+
}
|
|
4588
6749
|
async function redactBase64Utf8(encoded, redactString, kind) {
|
|
4589
6750
|
try {
|
|
4590
6751
|
const rawBuf = Buffer.from(encoded, "base64");
|
|
@@ -4647,17 +6808,37 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
4647
6808
|
await redactContentBlocks(block.output, kind);
|
|
4648
6809
|
}
|
|
4649
6810
|
if (typeof block.file_data === "string") {
|
|
6811
|
+
const fileName = typeof block.filename === "string" ? block.filename : void 0;
|
|
4650
6812
|
const match = DATA_URI_TEXT_BASE64_RE.exec(block.file_data);
|
|
4651
6813
|
if (match?.[1] && match[2]) {
|
|
4652
6814
|
const nextB64 = await redactBase64Utf8(match[2], redactString, kind);
|
|
4653
6815
|
block.file_data = `data:${match[1]};base64,${nextB64}`;
|
|
4654
6816
|
} else if (block.file_data.startsWith("data:")) {
|
|
4655
|
-
const
|
|
4656
|
-
|
|
6817
|
+
const anyMatch = DATA_URI_ANY_RE.exec(block.file_data);
|
|
6818
|
+
const anyMime = anyMatch?.[1] ?? "application/octet-stream";
|
|
6819
|
+
const b64Payload = anyMatch?.[2];
|
|
6820
|
+
if (b64Payload) {
|
|
6821
|
+
const nextB64 = await tryRedactBase64Document(
|
|
6822
|
+
b64Payload,
|
|
6823
|
+
anyMime,
|
|
6824
|
+
fileName,
|
|
6825
|
+
options.redactDocument,
|
|
6826
|
+
noteBinary
|
|
6827
|
+
);
|
|
6828
|
+
block.file_data = `data:${anyMime};base64,${nextB64}`;
|
|
6829
|
+
} else {
|
|
6830
|
+
noteBinary(anyMime);
|
|
6831
|
+
}
|
|
4657
6832
|
} else {
|
|
4658
6833
|
const rawBuf = Buffer.from(block.file_data, "base64");
|
|
4659
6834
|
if (rawBuf.includes(0)) {
|
|
4660
|
-
|
|
6835
|
+
block.file_data = await tryRedactBase64Document(
|
|
6836
|
+
block.file_data,
|
|
6837
|
+
"application/octet-stream",
|
|
6838
|
+
fileName,
|
|
6839
|
+
options.redactDocument,
|
|
6840
|
+
noteBinary
|
|
6841
|
+
);
|
|
4661
6842
|
} else {
|
|
4662
6843
|
block.file_data = await redactBase64Utf8(block.file_data, redactString, kind);
|
|
4663
6844
|
}
|
|
@@ -4668,6 +6849,18 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
4668
6849
|
block.source.data = await redactString(block.source.data, kind);
|
|
4669
6850
|
} else if (block.source.type === "base64" && typeof block.source.data === "string" && typeof block.source.media_type === "string" && TEXT_BASE64_MEDIA_RE.test(block.source.media_type)) {
|
|
4670
6851
|
block.source.data = await redactBase64Utf8(block.source.data, redactString, kind);
|
|
6852
|
+
} else if (block.source.type === "base64" && typeof block.source.data === "string") {
|
|
6853
|
+
const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
|
|
6854
|
+
if (blockType !== "image" && blockType !== "input_image") {
|
|
6855
|
+
const docTitle = typeof block.title === "string" ? block.title : void 0;
|
|
6856
|
+
block.source.data = await tryRedactBase64Document(
|
|
6857
|
+
block.source.data,
|
|
6858
|
+
mediaType,
|
|
6859
|
+
docTitle,
|
|
6860
|
+
options.redactDocument,
|
|
6861
|
+
noteBinary
|
|
6862
|
+
);
|
|
6863
|
+
}
|
|
4671
6864
|
} else if (block.source.type === "base64") {
|
|
4672
6865
|
const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
|
|
4673
6866
|
if (blockType !== "image" && blockType !== "input_image") {
|
|
@@ -4748,7 +6941,9 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
4748
6941
|
for (const batchItem of clone.requests) {
|
|
4749
6942
|
if (isPlainObject(batchItem) && isPlainObject(batchItem.params)) {
|
|
4750
6943
|
batchItem.params = await redactLlmRequestBody(batchItem.params, redactString, {
|
|
4751
|
-
mutate: true
|
|
6944
|
+
mutate: true,
|
|
6945
|
+
onBinaryAttachment: options.onBinaryAttachment,
|
|
6946
|
+
redactDocument: options.redactDocument
|
|
4752
6947
|
});
|
|
4753
6948
|
}
|
|
4754
6949
|
}
|
|
@@ -4951,173 +7146,229 @@ function restoreLlmResponseBody(body, map, options = {}) {
|
|
|
4951
7146
|
}
|
|
4952
7147
|
return clone;
|
|
4953
7148
|
}
|
|
4954
|
-
function
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
const r = streams.get(key);
|
|
4969
|
-
if (!r) return "";
|
|
4970
|
-
streams.delete(key);
|
|
4971
|
-
return r.flush();
|
|
4972
|
-
}
|
|
4973
|
-
function flushBufferedToolArgs(key) {
|
|
4974
|
-
const raw = bufferedToolArgs.get(key);
|
|
4975
|
-
if (raw === void 0) return "";
|
|
4976
|
-
bufferedToolArgs.delete(key);
|
|
4977
|
-
const name = toolNames.get(key);
|
|
4978
|
-
if (shouldSkipToolArgRestore(name, raw)) return raw;
|
|
4979
|
-
return restoreJsonEncodedText(raw, map);
|
|
4980
|
-
}
|
|
4981
|
-
function drainRemainingStreams() {
|
|
4982
|
-
const events = [];
|
|
4983
|
-
for (const key of [...bufferedToolArgs.keys()]) {
|
|
4984
|
-
const full = flushBufferedToolArgs(key);
|
|
4985
|
-
if (!full) continue;
|
|
4986
|
-
if (key.startsWith("openai_chat_tool:")) {
|
|
4987
|
-
const [, cIdx, tIdx] = key.split(":");
|
|
4988
|
-
events.push(
|
|
4989
|
-
`data: ${JSON.stringify({
|
|
4990
|
-
choices: [
|
|
4991
|
-
{
|
|
4992
|
-
index: Number(cIdx ?? 0),
|
|
4993
|
-
delta: {
|
|
4994
|
-
tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: full } }]
|
|
4995
|
-
}
|
|
4996
|
-
}
|
|
4997
|
-
]
|
|
4998
|
-
})}`
|
|
4999
|
-
);
|
|
5000
|
-
} else if (key.startsWith("anth_json:")) {
|
|
5001
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5002
|
-
events.push(
|
|
5003
|
-
`event: content_block_delta
|
|
5004
|
-
data: ${JSON.stringify({
|
|
5005
|
-
type: "content_block_delta",
|
|
5006
|
-
index: idx,
|
|
5007
|
-
delta: { type: "input_json_delta", partial_json: full }
|
|
5008
|
-
})}`
|
|
5009
|
-
);
|
|
5010
|
-
} else if (key.startsWith("resp_args:")) {
|
|
5011
|
-
const outputIdx = Number(key.split(":")[1] ?? 0);
|
|
5012
|
-
events.push(
|
|
5013
|
-
`event: response.function_call_arguments.delta
|
|
5014
|
-
data: ${JSON.stringify({
|
|
5015
|
-
type: "response.function_call_arguments.delta",
|
|
5016
|
-
output_index: outputIdx,
|
|
5017
|
-
delta: full
|
|
5018
|
-
})}`
|
|
5019
|
-
);
|
|
7149
|
+
function channelKey(d) {
|
|
7150
|
+
switch (d.protocol) {
|
|
7151
|
+
case "anthropic":
|
|
7152
|
+
return `anthropic:${d.kind}:${d.index}`;
|
|
7153
|
+
case "openai_chat":
|
|
7154
|
+
return d.kind === "tool_args" ? `openai_chat:tool_args:${d.choiceIndex}:${d.toolIndex}` : `openai_chat:${d.kind}:${d.choiceIndex}`;
|
|
7155
|
+
case "openai_responses":
|
|
7156
|
+
switch (d.kind) {
|
|
7157
|
+
case "text":
|
|
7158
|
+
return `openai_responses:text:${d.outputIndex}:${d.contentIndex}`;
|
|
7159
|
+
case "reasoning":
|
|
7160
|
+
return `openai_responses:reasoning:${d.outputIndex}:${d.summaryIndex}`;
|
|
7161
|
+
case "tool_args":
|
|
7162
|
+
return `openai_responses:tool_args:${d.outputIndex}`;
|
|
5020
7163
|
}
|
|
5021
|
-
|
|
5022
|
-
|
|
5023
|
-
|
|
5024
|
-
|
|
5025
|
-
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
`
|
|
5029
|
-
);
|
|
5030
|
-
} else if (key.startsWith("openai_chat_tool:")) {
|
|
5031
|
-
const [, cIdx, tIdx] = key.split(":");
|
|
5032
|
-
events.push(
|
|
5033
|
-
`data: ${JSON.stringify({
|
|
5034
|
-
choices: [
|
|
5035
|
-
{
|
|
5036
|
-
index: Number(cIdx ?? 0),
|
|
5037
|
-
delta: {
|
|
5038
|
-
tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
|
|
5039
|
-
}
|
|
5040
|
-
}
|
|
5041
|
-
]
|
|
5042
|
-
})}`
|
|
5043
|
-
);
|
|
5044
|
-
} else if (key.startsWith("anth_text:")) {
|
|
5045
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5046
|
-
events.push(
|
|
5047
|
-
`event: content_block_delta
|
|
7164
|
+
}
|
|
7165
|
+
}
|
|
7166
|
+
function formatChannelEvent(descriptor, payload) {
|
|
7167
|
+
switch (descriptor.protocol) {
|
|
7168
|
+
case "anthropic":
|
|
7169
|
+
switch (descriptor.kind) {
|
|
7170
|
+
case "text":
|
|
7171
|
+
return `event: content_block_delta
|
|
5048
7172
|
data: ${JSON.stringify({
|
|
5049
7173
|
type: "content_block_delta",
|
|
5050
|
-
index:
|
|
5051
|
-
delta: { type: "text_delta", text:
|
|
5052
|
-
})}
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5056
|
-
events.push(
|
|
5057
|
-
`event: content_block_delta
|
|
7174
|
+
index: descriptor.index,
|
|
7175
|
+
delta: { type: "text_delta", text: payload }
|
|
7176
|
+
})}`;
|
|
7177
|
+
case "thinking":
|
|
7178
|
+
return `event: content_block_delta
|
|
5058
7179
|
data: ${JSON.stringify({
|
|
5059
7180
|
type: "content_block_delta",
|
|
5060
|
-
index:
|
|
5061
|
-
delta: { type: "thinking_delta", thinking:
|
|
5062
|
-
})}
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5066
|
-
events.push(
|
|
5067
|
-
`event: content_block_delta
|
|
7181
|
+
index: descriptor.index,
|
|
7182
|
+
delta: { type: "thinking_delta", thinking: payload }
|
|
7183
|
+
})}`;
|
|
7184
|
+
case "tool_json":
|
|
7185
|
+
return `event: content_block_delta
|
|
5068
7186
|
data: ${JSON.stringify({
|
|
5069
7187
|
type: "content_block_delta",
|
|
5070
|
-
index:
|
|
5071
|
-
delta: { type: "input_json_delta", partial_json:
|
|
5072
|
-
})}
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
7188
|
+
index: descriptor.index,
|
|
7189
|
+
delta: { type: "input_json_delta", partial_json: payload }
|
|
7190
|
+
})}`;
|
|
7191
|
+
}
|
|
7192
|
+
break;
|
|
7193
|
+
case "openai_chat":
|
|
7194
|
+
switch (descriptor.kind) {
|
|
7195
|
+
case "text":
|
|
7196
|
+
return `data: ${JSON.stringify({
|
|
7197
|
+
choices: [{ index: descriptor.choiceIndex, delta: { content: payload } }]
|
|
7198
|
+
})}`;
|
|
7199
|
+
case "reasoning":
|
|
7200
|
+
return `data: ${JSON.stringify({
|
|
7201
|
+
choices: [{ index: descriptor.choiceIndex, delta: { reasoning_content: payload } }]
|
|
7202
|
+
})}`;
|
|
7203
|
+
case "reasoning_plain":
|
|
7204
|
+
return `data: ${JSON.stringify({
|
|
7205
|
+
choices: [{ index: descriptor.choiceIndex, delta: { reasoning: payload } }]
|
|
7206
|
+
})}`;
|
|
7207
|
+
case "tool_args":
|
|
7208
|
+
return `data: ${JSON.stringify({
|
|
7209
|
+
choices: [
|
|
7210
|
+
{
|
|
7211
|
+
index: descriptor.choiceIndex,
|
|
7212
|
+
delta: {
|
|
7213
|
+
tool_calls: [{ index: descriptor.toolIndex, function: { arguments: payload } }]
|
|
7214
|
+
}
|
|
7215
|
+
}
|
|
7216
|
+
]
|
|
7217
|
+
})}`;
|
|
7218
|
+
}
|
|
7219
|
+
break;
|
|
7220
|
+
case "openai_responses":
|
|
7221
|
+
switch (descriptor.kind) {
|
|
7222
|
+
case "text":
|
|
7223
|
+
return `event: response.output_text.delta
|
|
5078
7224
|
data: ${JSON.stringify({
|
|
5079
7225
|
type: "response.output_text.delta",
|
|
5080
|
-
output_index:
|
|
5081
|
-
content_index:
|
|
5082
|
-
delta:
|
|
5083
|
-
})}
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5087
|
-
events.push(
|
|
5088
|
-
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
|
|
5089
|
-
);
|
|
5090
|
-
} else if (key.startsWith("openai_chat_reasoning_plain:")) {
|
|
5091
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5092
|
-
events.push(
|
|
5093
|
-
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning: tail } }] })}`
|
|
5094
|
-
);
|
|
5095
|
-
} else if (key.startsWith("resp_reasoning:")) {
|
|
5096
|
-
const [, outputIdx, summaryIdx] = key.split(":");
|
|
5097
|
-
events.push(
|
|
5098
|
-
`event: response.reasoning_summary_text.delta
|
|
7226
|
+
output_index: descriptor.outputIndex,
|
|
7227
|
+
content_index: descriptor.contentIndex,
|
|
7228
|
+
delta: payload
|
|
7229
|
+
})}`;
|
|
7230
|
+
case "reasoning":
|
|
7231
|
+
return `event: response.reasoning_summary_text.delta
|
|
5099
7232
|
data: ${JSON.stringify({
|
|
5100
7233
|
type: "response.reasoning_summary_text.delta",
|
|
5101
|
-
output_index:
|
|
5102
|
-
summary_index:
|
|
5103
|
-
delta:
|
|
5104
|
-
})}
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
const outputIdx = Number(key.split(":")[1] ?? 0);
|
|
5108
|
-
events.push(
|
|
5109
|
-
`event: response.function_call_arguments.delta
|
|
7234
|
+
output_index: descriptor.outputIndex,
|
|
7235
|
+
summary_index: descriptor.summaryIndex,
|
|
7236
|
+
delta: payload
|
|
7237
|
+
})}`;
|
|
7238
|
+
case "tool_args":
|
|
7239
|
+
return `event: response.function_call_arguments.delta
|
|
5110
7240
|
data: ${JSON.stringify({
|
|
5111
7241
|
type: "response.function_call_arguments.delta",
|
|
5112
|
-
output_index:
|
|
5113
|
-
delta:
|
|
5114
|
-
})}
|
|
5115
|
-
|
|
7242
|
+
output_index: descriptor.outputIndex,
|
|
7243
|
+
delta: payload
|
|
7244
|
+
})}`;
|
|
7245
|
+
}
|
|
7246
|
+
}
|
|
7247
|
+
}
|
|
7248
|
+
function createSseRestorer(map, options = {}) {
|
|
7249
|
+
const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
|
|
7250
|
+
const channels = /* @__PURE__ */ new Map();
|
|
7251
|
+
const frame = { buffer: "", pendingCr: false };
|
|
7252
|
+
function pushStream(descriptor, chunk, useReasoningMap = false) {
|
|
7253
|
+
const key = channelKey(descriptor);
|
|
7254
|
+
let entry = channels.get(key);
|
|
7255
|
+
if (entry?.category !== "stream") {
|
|
7256
|
+
entry = {
|
|
7257
|
+
category: "stream",
|
|
7258
|
+
descriptor,
|
|
7259
|
+
restorer: new StreamingRestorer(useReasoningMap ? reasoningMap : map)
|
|
7260
|
+
};
|
|
7261
|
+
channels.set(key, entry);
|
|
7262
|
+
}
|
|
7263
|
+
return entry.restorer.push(chunk);
|
|
7264
|
+
}
|
|
7265
|
+
function closeStream(descriptor) {
|
|
7266
|
+
const key = channelKey(descriptor);
|
|
7267
|
+
const entry = channels.get(key);
|
|
7268
|
+
if (entry?.category !== "stream") return "";
|
|
7269
|
+
channels.delete(key);
|
|
7270
|
+
return entry.restorer.flush();
|
|
7271
|
+
}
|
|
7272
|
+
function createToolState(toolName) {
|
|
7273
|
+
if (isMaskeraVaultToolName(toolName)) {
|
|
7274
|
+
return { mode: "passthrough", toolName };
|
|
7275
|
+
}
|
|
7276
|
+
if (toolName === "execute") {
|
|
7277
|
+
return { mode: "buffering_execute", toolName, raw: "" };
|
|
7278
|
+
}
|
|
7279
|
+
return {
|
|
7280
|
+
mode: "streaming",
|
|
7281
|
+
toolName,
|
|
7282
|
+
restorer: new StreamingRestorer(map, { escapeForJsonString: true })
|
|
7283
|
+
};
|
|
7284
|
+
}
|
|
7285
|
+
function setToolName(descriptor, toolName) {
|
|
7286
|
+
const key = channelKey(descriptor);
|
|
7287
|
+
const existing = channels.get(key);
|
|
7288
|
+
if (existing?.category === "tool" && existing.state.toolName === toolName) {
|
|
7289
|
+
return;
|
|
7290
|
+
}
|
|
7291
|
+
channels.set(key, {
|
|
7292
|
+
category: "tool",
|
|
7293
|
+
descriptor,
|
|
7294
|
+
state: createToolState(toolName)
|
|
7295
|
+
});
|
|
7296
|
+
}
|
|
7297
|
+
function pushToolDelta(descriptor, delta) {
|
|
7298
|
+
const key = channelKey(descriptor);
|
|
7299
|
+
let entry = channels.get(key);
|
|
7300
|
+
if (entry?.category !== "tool") {
|
|
7301
|
+
entry = {
|
|
7302
|
+
category: "tool",
|
|
7303
|
+
descriptor,
|
|
7304
|
+
state: {
|
|
7305
|
+
mode: "streaming",
|
|
7306
|
+
toolName: null,
|
|
7307
|
+
restorer: new StreamingRestorer(map, { escapeForJsonString: true })
|
|
7308
|
+
}
|
|
7309
|
+
};
|
|
7310
|
+
channels.set(key, entry);
|
|
7311
|
+
}
|
|
7312
|
+
switch (entry.state.mode) {
|
|
7313
|
+
case "passthrough":
|
|
7314
|
+
return delta;
|
|
7315
|
+
case "buffering_execute":
|
|
7316
|
+
entry.state.raw += delta;
|
|
7317
|
+
return "";
|
|
7318
|
+
case "streaming":
|
|
7319
|
+
return entry.state.restorer.push(delta);
|
|
7320
|
+
case "closed":
|
|
7321
|
+
return delta;
|
|
7322
|
+
}
|
|
7323
|
+
}
|
|
7324
|
+
function flushToolState(state) {
|
|
7325
|
+
switch (state.mode) {
|
|
7326
|
+
case "passthrough":
|
|
7327
|
+
case "closed":
|
|
7328
|
+
return "";
|
|
7329
|
+
case "buffering_execute":
|
|
7330
|
+
if (!state.raw) return "";
|
|
7331
|
+
return shouldSkipToolArgRestore(state.toolName, state.raw) ? state.raw : restoreJsonEncodedText(state.raw, map);
|
|
7332
|
+
case "streaming":
|
|
7333
|
+
return state.restorer.flush();
|
|
7334
|
+
}
|
|
7335
|
+
}
|
|
7336
|
+
function closeTool(descriptor, retainNameUntilItemDone = false) {
|
|
7337
|
+
const key = channelKey(descriptor);
|
|
7338
|
+
const entry = channels.get(key);
|
|
7339
|
+
if (entry?.category !== "tool") return { tail: "", toolName: null };
|
|
7340
|
+
const toolName = entry.state.toolName;
|
|
7341
|
+
const tail = flushToolState(entry.state);
|
|
7342
|
+
if (retainNameUntilItemDone) {
|
|
7343
|
+
entry.state = { mode: "closed", toolName };
|
|
7344
|
+
} else {
|
|
7345
|
+
channels.delete(key);
|
|
7346
|
+
}
|
|
7347
|
+
return { tail, toolName };
|
|
7348
|
+
}
|
|
7349
|
+
function consumeToolName(descriptor) {
|
|
7350
|
+
const key = channelKey(descriptor);
|
|
7351
|
+
const entry = channels.get(key);
|
|
7352
|
+
if (entry?.category !== "tool") return null;
|
|
7353
|
+
const name = entry.state.toolName;
|
|
7354
|
+
channels.delete(key);
|
|
7355
|
+
return name;
|
|
7356
|
+
}
|
|
7357
|
+
function drainRemainingStreams() {
|
|
7358
|
+
const toolEvents = [];
|
|
7359
|
+
const streamEvents = [];
|
|
7360
|
+
for (const [key, entry] of [...channels.entries()]) {
|
|
7361
|
+
channels.delete(key);
|
|
7362
|
+
if (entry.category === "tool") {
|
|
7363
|
+
const tail = flushToolState(entry.state);
|
|
7364
|
+
if (tail) toolEvents.push(formatChannelEvent(entry.descriptor, tail));
|
|
7365
|
+
} else {
|
|
7366
|
+
const tail = entry.restorer.flush();
|
|
7367
|
+
if (tail) streamEvents.push(formatChannelEvent(entry.descriptor, tail));
|
|
5116
7368
|
}
|
|
5117
7369
|
}
|
|
5118
|
-
return
|
|
7370
|
+
return [...toolEvents, ...streamEvents];
|
|
5119
7371
|
}
|
|
5120
|
-
let sseBuffer = "";
|
|
5121
7372
|
function processEventBlock(block) {
|
|
5122
7373
|
const lines = block.split("\n");
|
|
5123
7374
|
const outLines = [];
|
|
@@ -5145,177 +7396,136 @@ data: ${JSON.stringify({
|
|
|
5145
7396
|
continue;
|
|
5146
7397
|
}
|
|
5147
7398
|
if (parsed.type === "content_block_start" && isPlainObject(parsed.content_block)) {
|
|
5148
|
-
const
|
|
7399
|
+
const index = typeof parsed.index === "number" ? parsed.index : 0;
|
|
5149
7400
|
if (parsed.content_block.type === "tool_use" && typeof parsed.content_block.name === "string") {
|
|
5150
|
-
|
|
7401
|
+
setToolName(
|
|
7402
|
+
{ protocol: "anthropic", kind: "tool_json", index },
|
|
7403
|
+
parsed.content_block.name
|
|
7404
|
+
);
|
|
5151
7405
|
}
|
|
5152
7406
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5153
7407
|
continue;
|
|
5154
7408
|
}
|
|
5155
7409
|
if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
|
|
5156
|
-
const
|
|
7410
|
+
const index = typeof parsed.index === "number" ? parsed.index : 0;
|
|
5157
7411
|
if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
|
|
5158
|
-
parsed.delta.text =
|
|
7412
|
+
parsed.delta.text = pushStream(
|
|
7413
|
+
{ protocol: "anthropic", kind: "text", index },
|
|
7414
|
+
parsed.delta.text
|
|
7415
|
+
);
|
|
5159
7416
|
} else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
|
|
5160
|
-
parsed.delta.thinking =
|
|
5161
|
-
|
|
7417
|
+
parsed.delta.thinking = pushStream(
|
|
7418
|
+
{ protocol: "anthropic", kind: "thinking", index },
|
|
7419
|
+
parsed.delta.thinking,
|
|
7420
|
+
true
|
|
5162
7421
|
);
|
|
5163
7422
|
} else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
|
|
5164
|
-
|
|
5165
|
-
|
|
5166
|
-
|
|
5167
|
-
|
|
5168
|
-
parsed.delta.partial_json = "";
|
|
5169
|
-
} else {
|
|
5170
|
-
parsed.delta.partial_json = getStream(key, true).push(parsed.delta.partial_json);
|
|
5171
|
-
}
|
|
7423
|
+
parsed.delta.partial_json = pushToolDelta(
|
|
7424
|
+
{ protocol: "anthropic", kind: "tool_json", index },
|
|
7425
|
+
parsed.delta.partial_json
|
|
7426
|
+
);
|
|
5172
7427
|
}
|
|
5173
7428
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5174
7429
|
continue;
|
|
5175
7430
|
}
|
|
5176
7431
|
if (parsed.type === "content_block_stop") {
|
|
5177
|
-
const
|
|
5178
|
-
const
|
|
5179
|
-
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
|
|
5184
|
-
|
|
5185
|
-
|
|
5186
|
-
|
|
5187
|
-
|
|
5188
|
-
}
|
|
5189
|
-
const
|
|
5190
|
-
if (
|
|
5191
|
-
extraEvents.push(
|
|
5192
|
-
`event: content_block_delta
|
|
5193
|
-
data: ${JSON.stringify({
|
|
5194
|
-
type: "content_block_delta",
|
|
5195
|
-
index: idx,
|
|
5196
|
-
delta: { type: "thinking_delta", thinking: thinkingTail }
|
|
5197
|
-
})}`
|
|
5198
|
-
);
|
|
5199
|
-
}
|
|
5200
|
-
const jsonKey = `anth_json:${idx}`;
|
|
5201
|
-
const jsonTail = flushBufferedToolArgs(jsonKey) || flushStream(jsonKey);
|
|
5202
|
-
toolNames.delete(jsonKey);
|
|
5203
|
-
if (jsonTail) {
|
|
5204
|
-
extraEvents.push(
|
|
5205
|
-
`event: content_block_delta
|
|
5206
|
-
data: ${JSON.stringify({
|
|
5207
|
-
type: "content_block_delta",
|
|
5208
|
-
index: idx,
|
|
5209
|
-
delta: { type: "input_json_delta", partial_json: jsonTail }
|
|
5210
|
-
})}`
|
|
5211
|
-
);
|
|
5212
|
-
}
|
|
7432
|
+
const index = typeof parsed.index === "number" ? parsed.index : 0;
|
|
7433
|
+
const textDesc = { protocol: "anthropic", kind: "text", index };
|
|
7434
|
+
const textTail = closeStream(textDesc);
|
|
7435
|
+
if (textTail) extraEvents.push(formatChannelEvent(textDesc, textTail));
|
|
7436
|
+
const thinkingDesc = {
|
|
7437
|
+
protocol: "anthropic",
|
|
7438
|
+
kind: "thinking",
|
|
7439
|
+
index
|
|
7440
|
+
};
|
|
7441
|
+
const thinkingTail = closeStream(thinkingDesc);
|
|
7442
|
+
if (thinkingTail) extraEvents.push(formatChannelEvent(thinkingDesc, thinkingTail));
|
|
7443
|
+
const toolDesc = { protocol: "anthropic", kind: "tool_json", index };
|
|
7444
|
+
const { tail: jsonTail } = closeTool(toolDesc);
|
|
7445
|
+
if (jsonTail) extraEvents.push(formatChannelEvent(toolDesc, jsonTail));
|
|
5213
7446
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5214
7447
|
continue;
|
|
5215
7448
|
}
|
|
5216
7449
|
if (Array.isArray(parsed.choices)) {
|
|
5217
7450
|
for (const choice of parsed.choices) {
|
|
5218
7451
|
if (!isPlainObject(choice)) continue;
|
|
5219
|
-
const
|
|
7452
|
+
const choiceIndex = typeof choice.index === "number" ? choice.index : 0;
|
|
5220
7453
|
const delta = choice.delta;
|
|
5221
7454
|
if (isPlainObject(delta)) {
|
|
5222
7455
|
if (typeof delta.content === "string") {
|
|
5223
|
-
delta.content =
|
|
7456
|
+
delta.content = pushStream(
|
|
7457
|
+
{ protocol: "openai_chat", kind: "text", choiceIndex },
|
|
7458
|
+
delta.content
|
|
7459
|
+
);
|
|
5224
7460
|
}
|
|
5225
7461
|
if (typeof delta.reasoning_content === "string") {
|
|
5226
|
-
delta.reasoning_content =
|
|
5227
|
-
|
|
5228
|
-
|
|
7462
|
+
delta.reasoning_content = pushStream(
|
|
7463
|
+
{ protocol: "openai_chat", kind: "reasoning", choiceIndex },
|
|
7464
|
+
delta.reasoning_content,
|
|
5229
7465
|
true
|
|
5230
|
-
)
|
|
7466
|
+
);
|
|
5231
7467
|
}
|
|
5232
7468
|
if (typeof delta.reasoning === "string") {
|
|
5233
|
-
delta.reasoning =
|
|
5234
|
-
|
|
7469
|
+
delta.reasoning = pushStream(
|
|
7470
|
+
{ protocol: "openai_chat", kind: "reasoning_plain", choiceIndex },
|
|
7471
|
+
delta.reasoning,
|
|
7472
|
+
true
|
|
5235
7473
|
);
|
|
5236
7474
|
}
|
|
5237
7475
|
if (Array.isArray(delta.tool_calls)) {
|
|
5238
7476
|
for (const call of delta.tool_calls) {
|
|
5239
7477
|
if (!isPlainObject(call)) continue;
|
|
5240
|
-
const
|
|
5241
|
-
const
|
|
7478
|
+
const toolIndex = typeof call.index === "number" ? call.index : 0;
|
|
7479
|
+
const toolDesc = {
|
|
7480
|
+
protocol: "openai_chat",
|
|
7481
|
+
kind: "tool_args",
|
|
7482
|
+
choiceIndex,
|
|
7483
|
+
toolIndex
|
|
7484
|
+
};
|
|
5242
7485
|
if (isPlainObject(call.function)) {
|
|
5243
7486
|
if (typeof call.function.name === "string" && call.function.name) {
|
|
5244
|
-
|
|
7487
|
+
setToolName(toolDesc, call.function.name);
|
|
5245
7488
|
}
|
|
5246
7489
|
if (typeof call.function.arguments === "string") {
|
|
5247
|
-
|
|
5248
|
-
if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
|
|
5249
|
-
bufferedToolArgs.set(
|
|
5250
|
-
key,
|
|
5251
|
-
(bufferedToolArgs.get(key) ?? "") + call.function.arguments
|
|
5252
|
-
);
|
|
5253
|
-
call.function.arguments = "";
|
|
5254
|
-
} else {
|
|
5255
|
-
call.function.arguments = getStream(key, true).push(call.function.arguments);
|
|
5256
|
-
}
|
|
7490
|
+
call.function.arguments = pushToolDelta(toolDesc, call.function.arguments);
|
|
5257
7491
|
}
|
|
5258
7492
|
}
|
|
5259
7493
|
}
|
|
5260
7494
|
}
|
|
5261
7495
|
}
|
|
5262
7496
|
if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
|
|
5263
|
-
const textTail =
|
|
7497
|
+
const textTail = closeStream({ protocol: "openai_chat", kind: "text", choiceIndex });
|
|
5264
7498
|
if (textTail) {
|
|
5265
7499
|
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
5266
7500
|
const d = choice.delta;
|
|
5267
7501
|
d.content = (typeof d.content === "string" ? d.content : "") + textTail;
|
|
5268
7502
|
}
|
|
5269
|
-
const reasoningTail =
|
|
7503
|
+
const reasoningTail = closeStream({
|
|
7504
|
+
protocol: "openai_chat",
|
|
7505
|
+
kind: "reasoning",
|
|
7506
|
+
choiceIndex
|
|
7507
|
+
});
|
|
5270
7508
|
if (reasoningTail) {
|
|
5271
7509
|
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
5272
7510
|
const d = choice.delta;
|
|
5273
7511
|
d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
|
|
5274
7512
|
}
|
|
5275
|
-
const reasoningPlainTail =
|
|
7513
|
+
const reasoningPlainTail = closeStream({
|
|
7514
|
+
protocol: "openai_chat",
|
|
7515
|
+
kind: "reasoning_plain",
|
|
7516
|
+
choiceIndex
|
|
7517
|
+
});
|
|
5276
7518
|
if (reasoningPlainTail) {
|
|
5277
7519
|
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
5278
7520
|
const d = choice.delta;
|
|
5279
7521
|
d.reasoning = (typeof d.reasoning === "string" ? d.reasoning : "") + reasoningPlainTail;
|
|
5280
7522
|
}
|
|
5281
|
-
const
|
|
5282
|
-
|
|
5283
|
-
|
|
5284
|
-
|
|
5285
|
-
|
|
5286
|
-
|
|
5287
|
-
if (!fullArgs) continue;
|
|
5288
|
-
extraEvents.push(
|
|
5289
|
-
`data: ${JSON.stringify({
|
|
5290
|
-
choices: [
|
|
5291
|
-
{
|
|
5292
|
-
index: cIdx,
|
|
5293
|
-
delta: {
|
|
5294
|
-
tool_calls: [{ index: tIdx, function: { arguments: fullArgs } }]
|
|
5295
|
-
}
|
|
5296
|
-
}
|
|
5297
|
-
]
|
|
5298
|
-
})}`
|
|
5299
|
-
);
|
|
5300
|
-
}
|
|
5301
|
-
for (const key of [...streams.keys()]) {
|
|
5302
|
-
if (!key.startsWith(toolPrefix)) continue;
|
|
5303
|
-
const tIdx = Number(key.slice(toolPrefix.length) || 0);
|
|
5304
|
-
const toolTail = flushStream(key);
|
|
5305
|
-
toolNames.delete(key);
|
|
5306
|
-
if (!toolTail) continue;
|
|
5307
|
-
extraEvents.push(
|
|
5308
|
-
`data: ${JSON.stringify({
|
|
5309
|
-
choices: [
|
|
5310
|
-
{
|
|
5311
|
-
index: cIdx,
|
|
5312
|
-
delta: {
|
|
5313
|
-
tool_calls: [{ index: tIdx, function: { arguments: toolTail } }]
|
|
5314
|
-
}
|
|
5315
|
-
}
|
|
5316
|
-
]
|
|
5317
|
-
})}`
|
|
5318
|
-
);
|
|
7523
|
+
for (const [key, entry] of [...channels.entries()]) {
|
|
7524
|
+
if (entry.category === "tool" && entry.descriptor.protocol === "openai_chat" && entry.descriptor.choiceIndex === choiceIndex) {
|
|
7525
|
+
channels.delete(key);
|
|
7526
|
+
const tail = flushToolState(entry.state);
|
|
7527
|
+
if (tail) extraEvents.push(formatChannelEvent(entry.descriptor, tail));
|
|
7528
|
+
}
|
|
5319
7529
|
}
|
|
5320
7530
|
}
|
|
5321
7531
|
}
|
|
@@ -5324,31 +7534,36 @@ data: ${JSON.stringify({
|
|
|
5324
7534
|
}
|
|
5325
7535
|
if (parsed.type === "response.output_item.added" && isPlainObject(parsed.item)) {
|
|
5326
7536
|
if (parsed.item.type === "function_call" && typeof parsed.item.name === "string") {
|
|
5327
|
-
|
|
7537
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7538
|
+
setToolName(
|
|
7539
|
+
{ protocol: "openai_responses", kind: "tool_args", outputIndex },
|
|
7540
|
+
parsed.item.name
|
|
7541
|
+
);
|
|
5328
7542
|
}
|
|
5329
7543
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5330
7544
|
continue;
|
|
5331
7545
|
}
|
|
5332
7546
|
if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
|
|
5333
|
-
const
|
|
5334
|
-
parsed.
|
|
7547
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7548
|
+
const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
|
|
7549
|
+
parsed.delta = pushStream(
|
|
7550
|
+
{ protocol: "openai_responses", kind: "text", outputIndex, contentIndex },
|
|
7551
|
+
parsed.delta
|
|
7552
|
+
);
|
|
5335
7553
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5336
7554
|
continue;
|
|
5337
7555
|
}
|
|
5338
7556
|
if (parsed.type === "response.output_text.done") {
|
|
5339
|
-
const
|
|
5340
|
-
const
|
|
5341
|
-
|
|
5342
|
-
|
|
5343
|
-
|
|
5344
|
-
|
|
5345
|
-
|
|
5346
|
-
|
|
5347
|
-
|
|
5348
|
-
|
|
5349
|
-
})}`
|
|
5350
|
-
);
|
|
5351
|
-
}
|
|
7557
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7558
|
+
const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
|
|
7559
|
+
const desc = {
|
|
7560
|
+
protocol: "openai_responses",
|
|
7561
|
+
kind: "text",
|
|
7562
|
+
outputIndex,
|
|
7563
|
+
contentIndex
|
|
7564
|
+
};
|
|
7565
|
+
const tail = closeStream(desc);
|
|
7566
|
+
if (tail) extraEvents.push(formatChannelEvent(desc, tail));
|
|
5352
7567
|
if (typeof parsed.text === "string") {
|
|
5353
7568
|
parsed.text = restorePlainText(parsed.text, map);
|
|
5354
7569
|
}
|
|
@@ -5356,25 +7571,26 @@ data: ${JSON.stringify({
|
|
|
5356
7571
|
continue;
|
|
5357
7572
|
}
|
|
5358
7573
|
if (parsed.type === "response.reasoning_summary_text.delta" && typeof parsed.delta === "string") {
|
|
5359
|
-
const
|
|
5360
|
-
parsed.
|
|
7574
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7575
|
+
const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
|
|
7576
|
+
parsed.delta = pushStream(
|
|
7577
|
+
{ protocol: "openai_responses", kind: "reasoning", outputIndex, summaryIndex },
|
|
7578
|
+
parsed.delta
|
|
7579
|
+
);
|
|
5361
7580
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5362
7581
|
continue;
|
|
5363
7582
|
}
|
|
5364
7583
|
if (parsed.type === "response.reasoning_summary_text.done") {
|
|
5365
|
-
const
|
|
5366
|
-
const
|
|
5367
|
-
|
|
5368
|
-
|
|
5369
|
-
|
|
5370
|
-
|
|
5371
|
-
|
|
5372
|
-
|
|
5373
|
-
|
|
5374
|
-
|
|
5375
|
-
})}`
|
|
5376
|
-
);
|
|
5377
|
-
}
|
|
7584
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7585
|
+
const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
|
|
7586
|
+
const desc = {
|
|
7587
|
+
protocol: "openai_responses",
|
|
7588
|
+
kind: "reasoning",
|
|
7589
|
+
outputIndex,
|
|
7590
|
+
summaryIndex
|
|
7591
|
+
};
|
|
7592
|
+
const tail = closeStream(desc);
|
|
7593
|
+
if (tail) extraEvents.push(formatChannelEvent(desc, tail));
|
|
5378
7594
|
if (typeof parsed.text === "string") {
|
|
5379
7595
|
parsed.text = restorePlainText(parsed.text, map);
|
|
5380
7596
|
}
|
|
@@ -5382,32 +7598,24 @@ data: ${JSON.stringify({
|
|
|
5382
7598
|
continue;
|
|
5383
7599
|
}
|
|
5384
7600
|
if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
|
|
5385
|
-
const
|
|
5386
|
-
|
|
5387
|
-
|
|
5388
|
-
|
|
5389
|
-
|
|
5390
|
-
} else {
|
|
5391
|
-
parsed.delta = getStream(key, true).push(parsed.delta);
|
|
5392
|
-
}
|
|
7601
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7602
|
+
parsed.delta = pushToolDelta(
|
|
7603
|
+
{ protocol: "openai_responses", kind: "tool_args", outputIndex },
|
|
7604
|
+
parsed.delta
|
|
7605
|
+
);
|
|
5393
7606
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5394
7607
|
continue;
|
|
5395
7608
|
}
|
|
5396
7609
|
if (parsed.type === "response.function_call_arguments.done") {
|
|
5397
|
-
const
|
|
5398
|
-
const
|
|
5399
|
-
|
|
5400
|
-
|
|
5401
|
-
|
|
5402
|
-
|
|
5403
|
-
|
|
5404
|
-
|
|
5405
|
-
|
|
5406
|
-
delta: tail
|
|
5407
|
-
})}`
|
|
5408
|
-
);
|
|
5409
|
-
}
|
|
5410
|
-
if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(name, parsed.arguments)) {
|
|
7610
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7611
|
+
const desc = {
|
|
7612
|
+
protocol: "openai_responses",
|
|
7613
|
+
kind: "tool_args",
|
|
7614
|
+
outputIndex
|
|
7615
|
+
};
|
|
7616
|
+
const { tail, toolName } = closeTool(desc, true);
|
|
7617
|
+
if (tail) extraEvents.push(formatChannelEvent(desc, tail));
|
|
7618
|
+
if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(toolName, parsed.arguments)) {
|
|
5411
7619
|
parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
|
|
5412
7620
|
}
|
|
5413
7621
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
@@ -5427,9 +7635,13 @@ data: ${JSON.stringify({
|
|
|
5427
7635
|
}
|
|
5428
7636
|
if (parsed.type === "response.output_item.done" && isPlainObject(parsed.item)) {
|
|
5429
7637
|
const item = parsed.item;
|
|
5430
|
-
const
|
|
5431
|
-
const
|
|
5432
|
-
|
|
7638
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
7639
|
+
const trackedName = consumeToolName({
|
|
7640
|
+
protocol: "openai_responses",
|
|
7641
|
+
kind: "tool_args",
|
|
7642
|
+
outputIndex
|
|
7643
|
+
});
|
|
7644
|
+
const name = typeof item.name === "string" ? item.name : trackedName;
|
|
5433
7645
|
if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(name, item.arguments)) {
|
|
5434
7646
|
item.arguments = restoreJsonEncodedText(item.arguments, map);
|
|
5435
7647
|
}
|
|
@@ -5462,19 +7674,18 @@ data: ${JSON.stringify({
|
|
|
5462
7674
|
|
|
5463
7675
|
${joined}` : joined;
|
|
5464
7676
|
}
|
|
5465
|
-
let pendingCr = false;
|
|
5466
7677
|
return {
|
|
5467
7678
|
push(chunk) {
|
|
5468
|
-
let text = pendingCr ? `\r${chunk}` : chunk;
|
|
5469
|
-
pendingCr = text.endsWith("\r");
|
|
5470
|
-
if (pendingCr) text = text.slice(0, -1);
|
|
5471
|
-
|
|
7679
|
+
let text = frame.pendingCr ? `\r${chunk}` : chunk;
|
|
7680
|
+
frame.pendingCr = text.endsWith("\r");
|
|
7681
|
+
if (frame.pendingCr) text = text.slice(0, -1);
|
|
7682
|
+
frame.buffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
5472
7683
|
let out = "";
|
|
5473
7684
|
for (; ; ) {
|
|
5474
|
-
const sep3 =
|
|
7685
|
+
const sep3 = frame.buffer.indexOf("\n\n");
|
|
5475
7686
|
if (sep3 < 0) break;
|
|
5476
|
-
const block =
|
|
5477
|
-
|
|
7687
|
+
const block = frame.buffer.slice(0, sep3);
|
|
7688
|
+
frame.buffer = frame.buffer.slice(sep3 + 2);
|
|
5478
7689
|
out += `${processEventBlock(block)}
|
|
5479
7690
|
|
|
5480
7691
|
`;
|
|
@@ -5482,14 +7693,14 @@ ${joined}` : joined;
|
|
|
5482
7693
|
return out;
|
|
5483
7694
|
},
|
|
5484
7695
|
flush() {
|
|
5485
|
-
if (pendingCr) {
|
|
5486
|
-
|
|
5487
|
-
pendingCr = false;
|
|
7696
|
+
if (frame.pendingCr) {
|
|
7697
|
+
frame.buffer += "\n";
|
|
7698
|
+
frame.pendingCr = false;
|
|
5488
7699
|
}
|
|
5489
7700
|
const parts = [];
|
|
5490
|
-
if (
|
|
5491
|
-
parts.push(processEventBlock(
|
|
5492
|
-
|
|
7701
|
+
if (frame.buffer) {
|
|
7702
|
+
parts.push(processEventBlock(frame.buffer));
|
|
7703
|
+
frame.buffer = "";
|
|
5493
7704
|
}
|
|
5494
7705
|
const drained = drainRemainingStreams();
|
|
5495
7706
|
if (drained.length > 0) {
|
|
@@ -5692,6 +7903,42 @@ function parseScopedMcpPolicy(urlPath, base) {
|
|
|
5692
7903
|
}
|
|
5693
7904
|
return { allowRawRestore, readOnly, approvalMode };
|
|
5694
7905
|
}
|
|
7906
|
+
var McpSessionStore = class {
|
|
7907
|
+
constructor(onDispose, options = {}) {
|
|
7908
|
+
this.active = /* @__PURE__ */ new Map();
|
|
7909
|
+
this.closed = /* @__PURE__ */ new Set();
|
|
7910
|
+
this.onDispose = onDispose;
|
|
7911
|
+
this.maxActive = options.maxActive ?? 200;
|
|
7912
|
+
this.maxClosed = options.maxClosed ?? 500;
|
|
7913
|
+
}
|
|
7914
|
+
open(policy) {
|
|
7915
|
+
const id = `mcp_${randomUUID().slice(0, 16)}`;
|
|
7916
|
+
if (this.active.size >= this.maxActive) {
|
|
7917
|
+
const oldest = this.active.keys().next().value;
|
|
7918
|
+
if (oldest !== void 0) {
|
|
7919
|
+
this.close(oldest);
|
|
7920
|
+
}
|
|
7921
|
+
}
|
|
7922
|
+
this.closed.delete(id);
|
|
7923
|
+
this.active.set(id, policy);
|
|
7924
|
+
return id;
|
|
7925
|
+
}
|
|
7926
|
+
lookup(id) {
|
|
7927
|
+
const policy = this.active.get(id);
|
|
7928
|
+
if (policy) return { status: "active", policy };
|
|
7929
|
+
if (this.closed.has(id)) return { status: "closed" };
|
|
7930
|
+
return { status: "unknown" };
|
|
7931
|
+
}
|
|
7932
|
+
close(id) {
|
|
7933
|
+
this.active.delete(id);
|
|
7934
|
+
this.closed.add(id);
|
|
7935
|
+
this.onDispose(id);
|
|
7936
|
+
if (this.closed.size > this.maxClosed) {
|
|
7937
|
+
const first = this.closed.values().next().value;
|
|
7938
|
+
if (first !== void 0) this.closed.delete(first);
|
|
7939
|
+
}
|
|
7940
|
+
}
|
|
7941
|
+
};
|
|
5695
7942
|
async function startMaskeraProxy(options = {}) {
|
|
5696
7943
|
const host = options.host ?? "127.0.0.1";
|
|
5697
7944
|
if (!options.allowNonLoopback && !isLoopbackBindHost(host)) {
|
|
@@ -5718,8 +7965,12 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5718
7965
|
readOnly: options.readOnly ?? false,
|
|
5719
7966
|
approvalMode: options.approvalMode ?? "automatic"
|
|
5720
7967
|
};
|
|
5721
|
-
const
|
|
5722
|
-
|
|
7968
|
+
const mcpSessionStore = new McpSessionStore((sessionId) => {
|
|
7969
|
+
const owner = `mcp:${sessionId}`;
|
|
7970
|
+
vault.clearOwner(owner);
|
|
7971
|
+
approvals.clearOwner(owner);
|
|
7972
|
+
mcpServerInstance?.clearOwner(owner);
|
|
7973
|
+
});
|
|
5723
7974
|
const messageTokensBySession = /* @__PURE__ */ new Map();
|
|
5724
7975
|
const externalToolTokensBySession = /* @__PURE__ */ new Map();
|
|
5725
7976
|
if (auditLogPath) {
|
|
@@ -5901,6 +8152,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5901
8152
|
}
|
|
5902
8153
|
vault.clearAll();
|
|
5903
8154
|
approvals.clearAll();
|
|
8155
|
+
mcpServerInstance?.clearAllOwners();
|
|
5904
8156
|
engine.clearCache();
|
|
5905
8157
|
inspector.clear();
|
|
5906
8158
|
messageTokensBySession.clear();
|
|
@@ -6051,14 +8303,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6051
8303
|
const incomingSessionId = typeof req.headers["mcp-session-id"] === "string" ? req.headers["mcp-session-id"].trim() : "";
|
|
6052
8304
|
if (method === "DELETE") {
|
|
6053
8305
|
if (incomingSessionId) {
|
|
6054
|
-
|
|
6055
|
-
closedMcpSessions.add(incomingSessionId);
|
|
6056
|
-
vault.clearOwner(`mcp:${incomingSessionId}`);
|
|
6057
|
-
approvals.clearOwner(`mcp:${incomingSessionId}`);
|
|
6058
|
-
if (closedMcpSessions.size > 500) {
|
|
6059
|
-
const first = closedMcpSessions.values().next().value;
|
|
6060
|
-
if (first !== void 0) closedMcpSessions.delete(first);
|
|
6061
|
-
}
|
|
8306
|
+
mcpSessionStore.close(incomingSessionId);
|
|
6062
8307
|
}
|
|
6063
8308
|
res.writeHead(204, INSPECTOR_SECURITY_HEADERS);
|
|
6064
8309
|
res.end();
|
|
@@ -6086,7 +8331,8 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6086
8331
|
res.end(JSON.stringify({ error: `Unsupported HTTP method ${method} for /mcp.` }));
|
|
6087
8332
|
return;
|
|
6088
8333
|
}
|
|
6089
|
-
|
|
8334
|
+
const incomingSessionState = incomingSessionId ? mcpSessionStore.lookup(incomingSessionId) : null;
|
|
8335
|
+
if (incomingSessionState?.status === "closed") {
|
|
6090
8336
|
res.writeHead(404, {
|
|
6091
8337
|
...INSPECTOR_SECURITY_HEADERS,
|
|
6092
8338
|
"content-type": "application/json; charset=utf-8"
|
|
@@ -6114,7 +8360,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6114
8360
|
}
|
|
6115
8361
|
const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
|
|
6116
8362
|
const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
|
|
6117
|
-
if (!isInit &&
|
|
8363
|
+
if (!isInit && incomingSessionState?.status === "unknown") {
|
|
6118
8364
|
res.writeHead(404, {
|
|
6119
8365
|
...INSPECTOR_SECURITY_HEADERS,
|
|
6120
8366
|
"content-type": "application/json; charset=utf-8"
|
|
@@ -6122,22 +8368,10 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6122
8368
|
res.end(JSON.stringify({ error: "Unknown MCP session." }));
|
|
6123
8369
|
return;
|
|
6124
8370
|
}
|
|
6125
|
-
const sessionBasePolicy =
|
|
8371
|
+
const sessionBasePolicy = incomingSessionState?.status === "active" ? incomingSessionState.policy : baseMcpPolicy;
|
|
6126
8372
|
const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
|
|
6127
8373
|
const mcpServer = getMcpServer();
|
|
6128
|
-
|
|
6129
|
-
if (isInit) {
|
|
6130
|
-
responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
|
|
6131
|
-
if (mcpSessions.size >= 200) {
|
|
6132
|
-
const oldest = mcpSessions.keys().next().value;
|
|
6133
|
-
if (oldest !== void 0) {
|
|
6134
|
-
mcpSessions.delete(oldest);
|
|
6135
|
-
vault.clearOwner(`mcp:${oldest}`);
|
|
6136
|
-
approvals.clearOwner(`mcp:${oldest}`);
|
|
6137
|
-
}
|
|
6138
|
-
}
|
|
6139
|
-
mcpSessions.set(responseSessionId, effectivePolicy);
|
|
6140
|
-
}
|
|
8374
|
+
const responseSessionId = isInit ? mcpSessionStore.open(effectivePolicy) : incomingSessionId;
|
|
6141
8375
|
const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
|
|
6142
8376
|
const scopedPolicy = { ...effectivePolicy, sessionOwner };
|
|
6143
8377
|
const responses = [];
|
|
@@ -6316,7 +8550,43 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6316
8550
|
mutate: true,
|
|
6317
8551
|
onBinaryAttachment: (kind) => {
|
|
6318
8552
|
binaryAttachments.add(kind);
|
|
6319
|
-
}
|
|
8553
|
+
},
|
|
8554
|
+
redactDocument: async (bytes, info) => redactFile(
|
|
8555
|
+
bytes,
|
|
8556
|
+
async (text) => {
|
|
8557
|
+
const { result } = await engine.redact(text, {
|
|
8558
|
+
profile: options.profile,
|
|
8559
|
+
customTerms: options.customTerms
|
|
8560
|
+
});
|
|
8561
|
+
const applied = vault.apply(text, result, sessionId, proxyVaultOwner);
|
|
8562
|
+
stats.redactions += applied.totalRedactions;
|
|
8563
|
+
mergeCounts(stats.counts, applied.counts);
|
|
8564
|
+
if (applied.totalRedactions > 0) {
|
|
8565
|
+
if (!messageTokensForSession) {
|
|
8566
|
+
messageTokensForSession = /* @__PURE__ */ new Set();
|
|
8567
|
+
messageTokensBySession.set(sessionId, messageTokensForSession);
|
|
8568
|
+
}
|
|
8569
|
+
for (const tok of Object.keys(applied.map)) {
|
|
8570
|
+
messageTokensForSession.add(tok);
|
|
8571
|
+
}
|
|
8572
|
+
}
|
|
8573
|
+
if (messagePreviews.length < 6 && applied.redacted.trim()) {
|
|
8574
|
+
const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
|
|
8575
|
+
messagePreviews.push(snippet);
|
|
8576
|
+
}
|
|
8577
|
+
return {
|
|
8578
|
+
text: applied.redacted,
|
|
8579
|
+
redactions: applied.redactions,
|
|
8580
|
+
map: applied.map,
|
|
8581
|
+
restore: (t) => vault.restore(t, { sessionId, owner: proxyVaultOwner }).restored
|
|
8582
|
+
};
|
|
8583
|
+
},
|
|
8584
|
+
{
|
|
8585
|
+
fileName: info.fileName,
|
|
8586
|
+
mimeType: info.mimeType,
|
|
8587
|
+
verify: true
|
|
8588
|
+
}
|
|
8589
|
+
)
|
|
6320
8590
|
}
|
|
6321
8591
|
);
|
|
6322
8592
|
redactedPreview.push(...messagePreviews.length > 0 ? messagePreviews : fallbackPreviews);
|
|
@@ -6604,6 +8874,7 @@ ${body}`
|
|
|
6604
8874
|
const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
|
|
6605
8875
|
boundPort = actualPort;
|
|
6606
8876
|
boundUrl = `http://${host}:${actualPort}`;
|
|
8877
|
+
let lifecycle = { phase: "listening" };
|
|
6607
8878
|
return {
|
|
6608
8879
|
host,
|
|
6609
8880
|
port: actualPort,
|
|
@@ -6621,12 +8892,22 @@ ${body}`
|
|
|
6621
8892
|
sessions: vault.list().length
|
|
6622
8893
|
}),
|
|
6623
8894
|
close: async () => {
|
|
6624
|
-
|
|
6625
|
-
|
|
6626
|
-
|
|
6627
|
-
|
|
6628
|
-
|
|
6629
|
-
|
|
8895
|
+
if (lifecycle.phase === "closed") return;
|
|
8896
|
+
if (lifecycle.phase === "closing") return lifecycle.promise;
|
|
8897
|
+
const closingPromise = (async () => {
|
|
8898
|
+
try {
|
|
8899
|
+
unsubscribeApprovals();
|
|
8900
|
+
inspector.closeAll();
|
|
8901
|
+
await new Promise((resolveClose, rejectClose) => {
|
|
8902
|
+
server.close((err) => err ? rejectClose(err) : resolveClose());
|
|
8903
|
+
});
|
|
8904
|
+
await auditChain;
|
|
8905
|
+
} finally {
|
|
8906
|
+
lifecycle = { phase: "closed" };
|
|
8907
|
+
}
|
|
8908
|
+
})();
|
|
8909
|
+
lifecycle = { phase: "closing", promise: closingPromise };
|
|
8910
|
+
return closingPromise;
|
|
6630
8911
|
}
|
|
6631
8912
|
};
|
|
6632
8913
|
}
|
|
@@ -6901,6 +9182,113 @@ async function runService(options) {
|
|
|
6901
9182
|
detail: running ? `Installed and started ${serviceName} (${serviceFile}). Listening on ${proxyUrl}.` : `Installed ${serviceName} (${serviceFile}). Check logs if ${proxyUrl} is still warming up.`
|
|
6902
9183
|
};
|
|
6903
9184
|
}
|
|
9185
|
+
|
|
9186
|
+
// src/stdio.ts
|
|
9187
|
+
function parseElicitationResponse(resp) {
|
|
9188
|
+
if (resp.error) return { action: "cancel" };
|
|
9189
|
+
const resultObj = resp.result && typeof resp.result === "object" ? resp.result : {};
|
|
9190
|
+
const action = resultObj.action === "accept" || resultObj.action === "decline" || resultObj.action === "cancel" ? resultObj.action : "cancel";
|
|
9191
|
+
const content = resultObj.content && typeof resultObj.content === "object" && !Array.isArray(resultObj.content) ? resultObj.content : void 0;
|
|
9192
|
+
return { action, content };
|
|
9193
|
+
}
|
|
9194
|
+
function createStdioMcpTransport(options) {
|
|
9195
|
+
let state = {
|
|
9196
|
+
phase: "open",
|
|
9197
|
+
nextServerReqId: 1,
|
|
9198
|
+
pending: /* @__PURE__ */ new Map()
|
|
9199
|
+
};
|
|
9200
|
+
let chain = Promise.resolve();
|
|
9201
|
+
return {
|
|
9202
|
+
get phase() {
|
|
9203
|
+
return state.phase;
|
|
9204
|
+
},
|
|
9205
|
+
requestElicitation(req) {
|
|
9206
|
+
if (state.phase === "closed") {
|
|
9207
|
+
return Promise.resolve({ action: "cancel" });
|
|
9208
|
+
}
|
|
9209
|
+
const id = `maskera_elicit_${state.nextServerReqId++}`;
|
|
9210
|
+
const pending = state.pending;
|
|
9211
|
+
return new Promise((resolveReq) => {
|
|
9212
|
+
pending.set(id, resolveReq);
|
|
9213
|
+
options.writeStdout(
|
|
9214
|
+
`${JSON.stringify({
|
|
9215
|
+
jsonrpc: "2.0",
|
|
9216
|
+
id,
|
|
9217
|
+
method: "elicitation/create",
|
|
9218
|
+
params: req
|
|
9219
|
+
})}
|
|
9220
|
+
`
|
|
9221
|
+
);
|
|
9222
|
+
});
|
|
9223
|
+
},
|
|
9224
|
+
handleLine(line, handleMessage) {
|
|
9225
|
+
if (state.phase === "closed") return;
|
|
9226
|
+
const trimmed = line.trim();
|
|
9227
|
+
if (!trimmed) return;
|
|
9228
|
+
let parsed;
|
|
9229
|
+
try {
|
|
9230
|
+
parsed = JSON.parse(trimmed);
|
|
9231
|
+
} catch {
|
|
9232
|
+
chain = chain.then(() => {
|
|
9233
|
+
options.writeStdout(
|
|
9234
|
+
`${JSON.stringify({
|
|
9235
|
+
jsonrpc: "2.0",
|
|
9236
|
+
id: null,
|
|
9237
|
+
error: { code: -32700, message: "Parse error" }
|
|
9238
|
+
})}
|
|
9239
|
+
`
|
|
9240
|
+
);
|
|
9241
|
+
});
|
|
9242
|
+
return;
|
|
9243
|
+
}
|
|
9244
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && !("method" in parsed) && typeof parsed.id === "string") {
|
|
9245
|
+
const resp = parsed;
|
|
9246
|
+
const resolvePending = state.pending.get(resp.id);
|
|
9247
|
+
if (resolvePending) {
|
|
9248
|
+
state.pending.delete(resp.id);
|
|
9249
|
+
resolvePending(parseElicitationResponse(resp));
|
|
9250
|
+
return;
|
|
9251
|
+
}
|
|
9252
|
+
}
|
|
9253
|
+
chain = chain.then(async () => {
|
|
9254
|
+
try {
|
|
9255
|
+
const response = await handleMessage(parsed);
|
|
9256
|
+
if (response) {
|
|
9257
|
+
options.writeStdout(`${JSON.stringify(response)}
|
|
9258
|
+
`);
|
|
9259
|
+
}
|
|
9260
|
+
} catch (err) {
|
|
9261
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
9262
|
+
options.writeStderr(`[maskera-mcp] internal error: ${message}
|
|
9263
|
+
`);
|
|
9264
|
+
const maybeId = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.id : void 0;
|
|
9265
|
+
if (typeof maybeId === "string" || typeof maybeId === "number" || maybeId === null) {
|
|
9266
|
+
options.writeStdout(
|
|
9267
|
+
`${JSON.stringify({
|
|
9268
|
+
jsonrpc: "2.0",
|
|
9269
|
+
id: maybeId,
|
|
9270
|
+
error: { code: -32603, message: "Internal error" }
|
|
9271
|
+
})}
|
|
9272
|
+
`
|
|
9273
|
+
);
|
|
9274
|
+
}
|
|
9275
|
+
}
|
|
9276
|
+
});
|
|
9277
|
+
},
|
|
9278
|
+
close() {
|
|
9279
|
+
if (state.phase === "closed") return;
|
|
9280
|
+
const pendingResolvers = [...state.pending.values()];
|
|
9281
|
+
state.pending.clear();
|
|
9282
|
+
state = { phase: "closed" };
|
|
9283
|
+
for (const resolvePending of pendingResolvers) {
|
|
9284
|
+
resolvePending({ action: "cancel" });
|
|
9285
|
+
}
|
|
9286
|
+
},
|
|
9287
|
+
whenIdle() {
|
|
9288
|
+
return chain;
|
|
9289
|
+
}
|
|
9290
|
+
};
|
|
9291
|
+
}
|
|
6904
9292
|
function openUrlInBrowser(url, platform = process.platform) {
|
|
6905
9293
|
try {
|
|
6906
9294
|
let cmd;
|
|
@@ -6994,25 +9382,33 @@ async function runWrap(options) {
|
|
|
6994
9382
|
stdio: "inherit",
|
|
6995
9383
|
env: childEnv
|
|
6996
9384
|
});
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
7000
|
-
|
|
7001
|
-
if (!child.killed) child.kill("SIGTERM");
|
|
9385
|
+
let childState = { phase: "running" };
|
|
9386
|
+
const forwardSignal = (sig) => {
|
|
9387
|
+
if (childState.phase !== "running") return;
|
|
9388
|
+
if (!child.killed) child.kill(sig);
|
|
7002
9389
|
};
|
|
9390
|
+
const forwardSigInt = () => forwardSignal("SIGINT");
|
|
9391
|
+
const forwardSigTerm = () => forwardSignal("SIGTERM");
|
|
7003
9392
|
process.on("SIGINT", forwardSigInt);
|
|
7004
9393
|
process.on("SIGTERM", forwardSigTerm);
|
|
7005
9394
|
const { exitCode, signal } = await new Promise((resolveExit, rejectExit) => {
|
|
7006
|
-
|
|
9395
|
+
const cleanupSignals = () => {
|
|
9396
|
+
process.off("SIGINT", forwardSigInt);
|
|
9397
|
+
process.off("SIGTERM", forwardSigTerm);
|
|
9398
|
+
};
|
|
9399
|
+
child.on("error", (err) => {
|
|
9400
|
+
if (childState.phase !== "running") return;
|
|
9401
|
+
childState = { phase: "failed", error: err };
|
|
9402
|
+
cleanupSignals();
|
|
9403
|
+
rejectExit(err);
|
|
9404
|
+
});
|
|
7007
9405
|
child.on("exit", (code, sig) => {
|
|
7008
|
-
|
|
7009
|
-
|
|
7010
|
-
|
|
7011
|
-
|
|
9406
|
+
if (childState.phase !== "running") return;
|
|
9407
|
+
const resolvedCode = code ?? (sig ? 1 : 0);
|
|
9408
|
+
childState = { phase: "exited", exitCode: resolvedCode, signal: sig };
|
|
9409
|
+
cleanupSignals();
|
|
9410
|
+
resolveExit({ exitCode: resolvedCode, signal: sig });
|
|
7012
9411
|
});
|
|
7013
|
-
}).finally(() => {
|
|
7014
|
-
process.off("SIGINT", forwardSigInt);
|
|
7015
|
-
process.off("SIGTERM", forwardSigTerm);
|
|
7016
9412
|
});
|
|
7017
9413
|
const session = running.stats();
|
|
7018
9414
|
let receiptSavedPath;
|
|
@@ -7061,7 +9457,7 @@ function isServiceAction(value) {
|
|
|
7061
9457
|
function parseArgs(argv) {
|
|
7062
9458
|
let startIndex = 0;
|
|
7063
9459
|
let command = "mcp";
|
|
7064
|
-
if (argv[0] === "proxy" || argv[0] === "wrap" || argv[0] === "guard" || argv[0] === "mcp" || argv[0] === "install" || argv[0] === "doctor" || argv[0] === "service") {
|
|
9460
|
+
if (argv[0] === "proxy" || argv[0] === "wrap" || argv[0] === "guard" || argv[0] === "redact" || argv[0] === "mcp" || argv[0] === "install" || argv[0] === "doctor" || argv[0] === "service") {
|
|
7065
9461
|
command = argv[0];
|
|
7066
9462
|
startIndex = 1;
|
|
7067
9463
|
}
|
|
@@ -7089,6 +9485,9 @@ function parseArgs(argv) {
|
|
|
7089
9485
|
let redact2 = false;
|
|
7090
9486
|
let noProxy = process.env.MASKERA_GUARD_NO_PROXY === "1";
|
|
7091
9487
|
let file;
|
|
9488
|
+
let outFile;
|
|
9489
|
+
let overwrite = false;
|
|
9490
|
+
let showLabels = true;
|
|
7092
9491
|
let client;
|
|
7093
9492
|
let transport = "stdio";
|
|
7094
9493
|
let mcpUrl;
|
|
@@ -7222,6 +9621,14 @@ function parseArgs(argv) {
|
|
|
7222
9621
|
const { value, nextIndex } = takeValue(flag, arg, i, true);
|
|
7223
9622
|
i = nextIndex;
|
|
7224
9623
|
file = value;
|
|
9624
|
+
} else if (flag === "--out" || flag === "-o") {
|
|
9625
|
+
const { value, nextIndex } = takeValue(flag, arg, i, true);
|
|
9626
|
+
i = nextIndex;
|
|
9627
|
+
outFile = value;
|
|
9628
|
+
} else if (flag === "--overwrite") {
|
|
9629
|
+
overwrite = true;
|
|
9630
|
+
} else if (flag === "--no-labels") {
|
|
9631
|
+
showLabels = false;
|
|
7225
9632
|
} else if (flag === "--transport") {
|
|
7226
9633
|
const { value, nextIndex } = takeValue(flag, arg, i);
|
|
7227
9634
|
i = nextIndex;
|
|
@@ -7255,6 +9662,8 @@ function parseArgs(argv) {
|
|
|
7255
9662
|
`Unknown client "${arg}". Expected one of: ${SUPPORTED_CLIENTS.join(", ")}, or all.`
|
|
7256
9663
|
);
|
|
7257
9664
|
}
|
|
9665
|
+
} else if (command === "redact" && !arg.startsWith("-") && !file) {
|
|
9666
|
+
file = arg;
|
|
7258
9667
|
} else if (command === "service" && !arg.startsWith("-") && !serviceAction) {
|
|
7259
9668
|
if (!isServiceAction(arg)) {
|
|
7260
9669
|
throw new Error(`Unknown service action "${arg}". Expected: install, status, or uninstall.`);
|
|
@@ -7294,6 +9703,9 @@ function parseArgs(argv) {
|
|
|
7294
9703
|
redact: redact2,
|
|
7295
9704
|
noProxy,
|
|
7296
9705
|
file,
|
|
9706
|
+
outFile,
|
|
9707
|
+
overwrite,
|
|
9708
|
+
showLabels,
|
|
7297
9709
|
client,
|
|
7298
9710
|
transport,
|
|
7299
9711
|
mcpUrl,
|
|
@@ -7319,16 +9731,18 @@ function printHelp() {
|
|
|
7319
9731
|
" maskera-mcp [mcp] [--root <dir>] [--no-raw-restore] [--read-only] [--approval-mode automatic|native] [--rules-only]",
|
|
7320
9732
|
" maskera-mcp proxy [--port 8787] [--host 127.0.0.1] [--root <dir>] [--open] [--upstream <url>] [--audit-log <file.jsonl>] [--no-raw-restore] [--read-only] [--approval-mode automatic|browser] [--rules-only] [--no-restore] [--block-binary]",
|
|
7321
9733
|
" maskera-mcp wrap [flags] -- <cmd> [args...]",
|
|
7322
|
-
" maskera-mcp guard [--redact] [--file <path>] [--proxy-url <url>] [--no-proxy] [--rules-only]",
|
|
9734
|
+
" maskera-mcp guard [--redact] [--file <path>] [--out <path>] [--overwrite] [--proxy-url <url>] [--no-proxy] [--rules-only]",
|
|
9735
|
+
" maskera-mcp redact <file> [-o|--out <path>] [--overwrite] [--no-labels] [--profile general|clinical] [--rules-only] [--json]",
|
|
7323
9736
|
` maskera-mcp install [client|all] [--transport stdio|http] [--url <http://127.0.0.1:8787/mcp>] [--root <dir>] [--apply] [--project] [--with-hook] [--no-raw-restore] [--read-only] [--config <path>] [--receipt <file.json>] [--no-verify] [--dry-run]`,
|
|
7324
9737
|
" maskera-mcp doctor [--root <dir>] [--proxy-url <url>] [--receipt <file.json>] [--rules-only] [--json]",
|
|
7325
9738
|
" maskera-mcp service <install|status|uninstall> [--port 8787] [--root <dir>] [--no-raw-restore] [--rules-only] [--dry-run] [--json]",
|
|
7326
9739
|
"",
|
|
7327
9740
|
"Subcommands:",
|
|
7328
|
-
" mcp (default) Start MCP stdio server (read/write/list/search files,
|
|
9741
|
+
" mcp (default) Start MCP stdio server (read/write/redact/list/search UTF-8/PDF/DOCX/XLSX files, restore, prompts, resources)",
|
|
7329
9742
|
" proxy Start local Anthropic/OpenAI HTTP reverse proxy + Streamable HTTP /mcp + live inspector",
|
|
7330
9743
|
" wrap One-command launcher: starts ephemeral local proxy, verifies 0 leaks, runs any CLI with proxy env vars, prints session receipt on exit",
|
|
7331
|
-
" guard Check stdin/
|
|
9744
|
+
" guard Check stdin or UTF-8/PDF/DOCX/XLSX file for PII (exits 2 if PII found, or outputs redacted text/file with --redact)",
|
|
9745
|
+
" redact Redact a local PDF, DOCX, XLSX, or UTF-8 text file to a verified clean output file on disk",
|
|
7332
9746
|
` install Auto-detect or configure an MCP client (${SUPPORTED_CLIENTS.join(", ")}, or all) + optional guard hook (--with-hook) + setup receipt`,
|
|
7333
9747
|
" doctor Verify Node runtime, workspace roots, local Swedish PII roundtrip, and running proxy + /mcp",
|
|
7334
9748
|
" service Install, inspect, or remove a local launchd (macOS) or systemd --user (Linux) background proxy service",
|
|
@@ -7596,22 +10010,161 @@ Verify: ${primary.verifyStep}
|
|
|
7596
10010
|
if (receipt && !receipt.ok) process.exit(1);
|
|
7597
10011
|
return;
|
|
7598
10012
|
}
|
|
10013
|
+
if (args.command === "redact") {
|
|
10014
|
+
if (!args.file) {
|
|
10015
|
+
throw new Error(
|
|
10016
|
+
"Missing input file. Usage: maskera-mcp redact <file> [-o <out>] [--overwrite]"
|
|
10017
|
+
);
|
|
10018
|
+
}
|
|
10019
|
+
const buf = await readFile(args.file);
|
|
10020
|
+
if (buf.byteLength > MAX_DEFAULT_FILE_BYTES) {
|
|
10021
|
+
throw new Error(
|
|
10022
|
+
`"${args.file}" is ${buf.byteLength} bytes (max ${MAX_DEFAULT_FILE_BYTES} bytes).`
|
|
10023
|
+
);
|
|
10024
|
+
}
|
|
10025
|
+
const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
10026
|
+
const engine2 = buildEngine(args);
|
|
10027
|
+
let modeUsed = args.defaultMode === "rules" ? "rules" : "hybrid";
|
|
10028
|
+
const res = await redactFile(
|
|
10029
|
+
bytes,
|
|
10030
|
+
async (text) => {
|
|
10031
|
+
const eng = await engine2.redact(text, {
|
|
10032
|
+
mode: args.defaultMode,
|
|
10033
|
+
profile: args.profile,
|
|
10034
|
+
customTerms: args.customTerms.length > 0 ? args.customTerms : void 0
|
|
10035
|
+
});
|
|
10036
|
+
modeUsed = eng.modeUsed;
|
|
10037
|
+
return eng.result;
|
|
10038
|
+
},
|
|
10039
|
+
{
|
|
10040
|
+
fileName: args.file,
|
|
10041
|
+
pdfStyle: { showLabels: args.showLabels },
|
|
10042
|
+
verify: true
|
|
10043
|
+
}
|
|
10044
|
+
);
|
|
10045
|
+
if (!res.verified) {
|
|
10046
|
+
throw new Error(
|
|
10047
|
+
`Post-redaction verification detected ${res.verificationLeaks.length} residual item(s); refused to write output.`
|
|
10048
|
+
);
|
|
10049
|
+
}
|
|
10050
|
+
const ext = extname(args.file);
|
|
10051
|
+
const stem = ext ? basename(args.file, ext) : basename(args.file);
|
|
10052
|
+
const targetPath = args.outFile ?? join(dirname(args.file), `${stem}.masked${ext}`);
|
|
10053
|
+
await writeFile(targetPath, res.bytes, {
|
|
10054
|
+
flag: args.overwrite ? "w" : "wx",
|
|
10055
|
+
mode: 384
|
|
10056
|
+
}).catch((err) => {
|
|
10057
|
+
if (err.code === "EEXIST") {
|
|
10058
|
+
throw new Error(
|
|
10059
|
+
`Output file already exists: "${targetPath}". Pass --overwrite to replace it.`
|
|
10060
|
+
);
|
|
10061
|
+
}
|
|
10062
|
+
throw err;
|
|
10063
|
+
});
|
|
10064
|
+
const summary = {
|
|
10065
|
+
input: args.file,
|
|
10066
|
+
output: targetPath,
|
|
10067
|
+
format: res.format,
|
|
10068
|
+
bytes: res.bytes.byteLength,
|
|
10069
|
+
mode: modeUsed,
|
|
10070
|
+
totalRedactions: res.totalRedactions,
|
|
10071
|
+
counts: res.counts,
|
|
10072
|
+
verified: res.verified,
|
|
10073
|
+
metadataCleared: res.metadataCleared,
|
|
10074
|
+
...res.redactedPages ? { redactedPages: res.redactedPages } : {},
|
|
10075
|
+
...res.totalPages !== void 0 ? { totalPages: res.totalPages } : {},
|
|
10076
|
+
...res.scannedPages.length > 0 ? { scannedPages: res.scannedPages } : {},
|
|
10077
|
+
...res.warnings.length > 0 ? { warnings: res.warnings } : {}
|
|
10078
|
+
};
|
|
10079
|
+
if (args.json) {
|
|
10080
|
+
process.stdout.write(`${JSON.stringify(summary, null, 2)}
|
|
10081
|
+
`);
|
|
10082
|
+
} else {
|
|
10083
|
+
const countList = Object.entries(res.counts).map(([k, v]) => `${k}=${v}`).join(", ") || "none";
|
|
10084
|
+
process.stdout.write(
|
|
10085
|
+
`Redacted ${args.file} -> ${targetPath} (${res.format}, ${res.totalRedactions} redaction(s): ${countList}, verified=true)
|
|
10086
|
+
`
|
|
10087
|
+
);
|
|
10088
|
+
if (res.metadataCleared.length > 0) {
|
|
10089
|
+
process.stdout.write(`Metadata cleared: ${res.metadataCleared.join(", ")}
|
|
10090
|
+
`);
|
|
10091
|
+
}
|
|
10092
|
+
for (const warning of res.warnings) {
|
|
10093
|
+
process.stderr.write(`[maskera] Warning: ${warning}
|
|
10094
|
+
`);
|
|
10095
|
+
}
|
|
10096
|
+
}
|
|
10097
|
+
return;
|
|
10098
|
+
}
|
|
7599
10099
|
if (args.command === "guard") {
|
|
7600
10100
|
let raw;
|
|
7601
10101
|
if (args.file) {
|
|
7602
10102
|
const buf = await readFile(args.file);
|
|
7603
|
-
|
|
10103
|
+
const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
10104
|
+
const detected = detectFileFormat(bytes, args.file);
|
|
10105
|
+
if (detected.format === "binary") {
|
|
10106
|
+
if (!buf.includes(0)) {
|
|
10107
|
+
throw new Error(`"${args.file}" is not valid UTF-8 text; convert it to UTF-8 first.`);
|
|
10108
|
+
}
|
|
7604
10109
|
throw new Error(
|
|
7605
|
-
`"${args.file}"
|
|
10110
|
+
`"${args.file}" appears to be an unsupported binary file (${detected.mimeType}); supported formats are UTF-8 text, PDF, DOCX, and XLSX.`
|
|
7606
10111
|
);
|
|
7607
10112
|
}
|
|
7608
|
-
if (
|
|
7609
|
-
|
|
10113
|
+
if (args.redact && args.outFile) {
|
|
10114
|
+
if (buf.byteLength > MAX_DEFAULT_FILE_BYTES) {
|
|
10115
|
+
throw new Error(
|
|
10116
|
+
`"${args.file}" is ${buf.byteLength} bytes (max ${MAX_DEFAULT_FILE_BYTES} bytes).`
|
|
10117
|
+
);
|
|
10118
|
+
}
|
|
10119
|
+
const engine2 = buildEngine(args);
|
|
10120
|
+
const docRes = await redactFile(
|
|
10121
|
+
bytes,
|
|
10122
|
+
async (text) => {
|
|
10123
|
+
const eng = await engine2.redact(text, {
|
|
10124
|
+
mode: args.defaultMode,
|
|
10125
|
+
profile: args.profile,
|
|
10126
|
+
customTerms: args.customTerms.length > 0 ? args.customTerms : void 0
|
|
10127
|
+
});
|
|
10128
|
+
return eng.result;
|
|
10129
|
+
},
|
|
10130
|
+
{
|
|
10131
|
+
fileName: args.file,
|
|
10132
|
+
pdfStyle: { showLabels: args.showLabels },
|
|
10133
|
+
verify: true
|
|
10134
|
+
}
|
|
10135
|
+
);
|
|
10136
|
+
if (!docRes.verified) {
|
|
10137
|
+
throw new Error(
|
|
10138
|
+
`Post-redaction verification detected ${docRes.verificationLeaks.length} residual item(s); refused to write output.`
|
|
10139
|
+
);
|
|
10140
|
+
}
|
|
10141
|
+
await writeFile(args.outFile, docRes.bytes, {
|
|
10142
|
+
flag: args.overwrite ? "w" : "wx",
|
|
10143
|
+
mode: 384
|
|
10144
|
+
});
|
|
10145
|
+
for (const warning of docRes.warnings) {
|
|
10146
|
+
process.stderr.write(`[maskera-guard] Warning: ${warning}
|
|
10147
|
+
`);
|
|
10148
|
+
}
|
|
10149
|
+
return;
|
|
7610
10150
|
}
|
|
7611
|
-
|
|
10151
|
+
if (detected.format === "text") {
|
|
10152
|
+
if (buf.byteLength > MAX_GUARD_INPUT_BYTES) {
|
|
10153
|
+
throw new Error(
|
|
10154
|
+
`"${args.file}" is ${buf.byteLength} bytes (max ${MAX_GUARD_INPUT_BYTES} bytes for guard).`
|
|
10155
|
+
);
|
|
10156
|
+
}
|
|
7612
10157
|
raw = new TextDecoder("utf-8", { fatal: true }).decode(buf);
|
|
7613
|
-
}
|
|
7614
|
-
|
|
10158
|
+
} else {
|
|
10159
|
+
const extracted = await extractFileText(bytes, {
|
|
10160
|
+
fileName: args.file,
|
|
10161
|
+
maxBytes: MAX_DEFAULT_FILE_BYTES
|
|
10162
|
+
});
|
|
10163
|
+
for (const warning of extracted.warnings) {
|
|
10164
|
+
process.stderr.write(`[maskera-guard] Warning: ${warning}
|
|
10165
|
+
`);
|
|
10166
|
+
}
|
|
10167
|
+
raw = extracted.text;
|
|
7615
10168
|
}
|
|
7616
10169
|
} else {
|
|
7617
10170
|
raw = await readStdinAll();
|
|
@@ -7736,30 +10289,24 @@ Verify: ${primary.verifyStep}
|
|
|
7736
10289
|
if (args.openInspector) {
|
|
7737
10290
|
openUrlInBrowser(running.inspectorUrl);
|
|
7738
10291
|
}
|
|
10292
|
+
let shutdownState = "running";
|
|
7739
10293
|
const shutdown = () => {
|
|
10294
|
+
if (shutdownState !== "running") return;
|
|
10295
|
+
shutdownState = "shutting_down";
|
|
7740
10296
|
void running.close().finally(() => process.exit(0));
|
|
7741
10297
|
};
|
|
7742
10298
|
process.on("SIGINT", shutdown);
|
|
7743
10299
|
process.on("SIGTERM", shutdown);
|
|
7744
10300
|
return;
|
|
7745
10301
|
}
|
|
7746
|
-
|
|
7747
|
-
|
|
7748
|
-
|
|
7749
|
-
|
|
7750
|
-
|
|
7751
|
-
|
|
7752
|
-
|
|
7753
|
-
|
|
7754
|
-
jsonrpc: "2.0",
|
|
7755
|
-
id,
|
|
7756
|
-
method: "elicitation/create",
|
|
7757
|
-
params: req
|
|
7758
|
-
})}
|
|
7759
|
-
`
|
|
7760
|
-
);
|
|
7761
|
-
});
|
|
7762
|
-
};
|
|
10302
|
+
const transport = createStdioMcpTransport({
|
|
10303
|
+
writeStdout: (line) => {
|
|
10304
|
+
process.stdout.write(line);
|
|
10305
|
+
},
|
|
10306
|
+
writeStderr: (line) => {
|
|
10307
|
+
process.stderr.write(line);
|
|
10308
|
+
}
|
|
10309
|
+
});
|
|
7763
10310
|
const server = createMaskeraMcpServer({
|
|
7764
10311
|
engine,
|
|
7765
10312
|
allowedRoots: args.roots,
|
|
@@ -7768,76 +10315,15 @@ Verify: ${primary.verifyStep}
|
|
|
7768
10315
|
allowRawRestore: args.allowRawRestore,
|
|
7769
10316
|
readOnly: args.readOnly,
|
|
7770
10317
|
approvalMode: args.approvalMode,
|
|
7771
|
-
requestElicitation
|
|
10318
|
+
requestElicitation: (req) => transport.requestElicitation(req)
|
|
7772
10319
|
});
|
|
7773
10320
|
engine.warmup();
|
|
7774
|
-
let chain = Promise.resolve();
|
|
7775
10321
|
const rl = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
|
|
7776
10322
|
rl.on("line", (line) => {
|
|
7777
|
-
|
|
7778
|
-
if (!trimmed) return;
|
|
7779
|
-
let parsed;
|
|
7780
|
-
try {
|
|
7781
|
-
parsed = JSON.parse(trimmed);
|
|
7782
|
-
} catch {
|
|
7783
|
-
chain = chain.then(() => {
|
|
7784
|
-
process.stdout.write(
|
|
7785
|
-
`${JSON.stringify({
|
|
7786
|
-
jsonrpc: "2.0",
|
|
7787
|
-
id: null,
|
|
7788
|
-
error: { code: -32700, message: "Parse error" }
|
|
7789
|
-
})}
|
|
7790
|
-
`
|
|
7791
|
-
);
|
|
7792
|
-
});
|
|
7793
|
-
return;
|
|
7794
|
-
}
|
|
7795
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && !("method" in parsed) && typeof parsed.id === "string") {
|
|
7796
|
-
const resp = parsed;
|
|
7797
|
-
const pending = pendingClientResponses.get(resp.id);
|
|
7798
|
-
if (pending) {
|
|
7799
|
-
pendingClientResponses.delete(resp.id);
|
|
7800
|
-
if (resp.error) {
|
|
7801
|
-
pending.resolve({ action: "cancel" });
|
|
7802
|
-
} else {
|
|
7803
|
-
const resultObj = resp.result && typeof resp.result === "object" ? resp.result : {};
|
|
7804
|
-
const action = resultObj.action === "accept" || resultObj.action === "decline" || resultObj.action === "cancel" ? resultObj.action : "cancel";
|
|
7805
|
-
const content = resultObj.content && typeof resultObj.content === "object" && !Array.isArray(resultObj.content) ? resultObj.content : void 0;
|
|
7806
|
-
pending.resolve({ action, content });
|
|
7807
|
-
}
|
|
7808
|
-
return;
|
|
7809
|
-
}
|
|
7810
|
-
}
|
|
7811
|
-
chain = chain.then(async () => {
|
|
7812
|
-
try {
|
|
7813
|
-
const response = await server.handleMessage(parsed);
|
|
7814
|
-
if (response) {
|
|
7815
|
-
process.stdout.write(`${JSON.stringify(response)}
|
|
7816
|
-
`);
|
|
7817
|
-
}
|
|
7818
|
-
} catch (err) {
|
|
7819
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
7820
|
-
process.stderr.write(`[maskera-mcp] internal error: ${message}
|
|
7821
|
-
`);
|
|
7822
|
-
const maybeId = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.id : void 0;
|
|
7823
|
-
if (typeof maybeId === "string" || typeof maybeId === "number" || maybeId === null) {
|
|
7824
|
-
process.stdout.write(
|
|
7825
|
-
`${JSON.stringify({
|
|
7826
|
-
jsonrpc: "2.0",
|
|
7827
|
-
id: maybeId,
|
|
7828
|
-
error: { code: -32603, message: "Internal error" }
|
|
7829
|
-
})}
|
|
7830
|
-
`
|
|
7831
|
-
);
|
|
7832
|
-
}
|
|
7833
|
-
}
|
|
7834
|
-
});
|
|
10323
|
+
transport.handleLine(line, (msg) => server.handleMessage(msg));
|
|
7835
10324
|
});
|
|
7836
10325
|
rl.on("close", () => {
|
|
7837
|
-
|
|
7838
|
-
pending.resolve({ action: "cancel" });
|
|
7839
|
-
}
|
|
7840
|
-
pendingClientResponses.clear();
|
|
10326
|
+
transport.close();
|
|
7841
10327
|
});
|
|
7842
10328
|
}
|
|
7843
10329
|
var isGuardCommand = process.argv[2] === "guard";
|