@maskera/mcp 0.4.0 → 0.4.2
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 +15 -1
- package/dist/cli.js +1166 -231
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +53 -8
- package/dist/index.js +1048 -132
- package/dist/index.js.map +1 -1
- package/package.json +13 -3
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { randomUUID, createHash } from 'crypto';
|
|
2
2
|
import { constants } from 'fs';
|
|
3
3
|
import { readFile, mkdir, realpath, writeFile, stat, access, appendFile, unlink, readdir, lstat, readlink } from 'fs/promises';
|
|
4
|
-
import { dirname, resolve, join, isAbsolute, relative, sep, delimiter } from 'path';
|
|
5
|
-
import {
|
|
4
|
+
import { dirname, resolve, join, isAbsolute, relative, sep, delimiter, extname, posix } from 'path';
|
|
5
|
+
import { createRequire } from 'module';
|
|
6
|
+
import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
|
|
6
7
|
import { spawn, spawnSync } from 'child_process';
|
|
7
8
|
import { homedir } from 'os';
|
|
8
9
|
import { createServer } from 'http';
|
|
@@ -11,6 +12,11 @@ import * as zlib from 'zlib';
|
|
|
11
12
|
// src/approvals.ts
|
|
12
13
|
var DEFAULT_TTL_MS = 5 * 60 * 1e3;
|
|
13
14
|
var MAX_RECORDS = 50;
|
|
15
|
+
var DEFAULT_OWNER = "default";
|
|
16
|
+
function normalizeOwner(owner) {
|
|
17
|
+
const trimmed = owner?.trim();
|
|
18
|
+
return trimmed || DEFAULT_OWNER;
|
|
19
|
+
}
|
|
14
20
|
var ApprovalBroker = class {
|
|
15
21
|
constructor(ttlMs = DEFAULT_TTL_MS) {
|
|
16
22
|
this.records = /* @__PURE__ */ new Map();
|
|
@@ -63,6 +69,7 @@ var ApprovalBroker = class {
|
|
|
63
69
|
decidedAt: null
|
|
64
70
|
};
|
|
65
71
|
this.records.set(id, {
|
|
72
|
+
owner: normalizeOwner(input.owner),
|
|
66
73
|
summary,
|
|
67
74
|
expiresAtMs: now + this.ttlMs,
|
|
68
75
|
execute: input.execute
|
|
@@ -87,10 +94,13 @@ var ApprovalBroker = class {
|
|
|
87
94
|
this.notify();
|
|
88
95
|
return { ...record.summary };
|
|
89
96
|
}
|
|
90
|
-
async resume(id) {
|
|
97
|
+
async resume(id, owner) {
|
|
91
98
|
this.expireStale();
|
|
92
99
|
const record = this.records.get(id.trim());
|
|
93
100
|
if (!record) return { status: "not_found" };
|
|
101
|
+
if (owner !== void 0 && record.owner !== normalizeOwner(owner)) {
|
|
102
|
+
return { status: "not_found" };
|
|
103
|
+
}
|
|
94
104
|
const { status } = record.summary;
|
|
95
105
|
if (status === "pending" || status === "declined" || status === "expired") {
|
|
96
106
|
return { status, summary: { ...record.summary } };
|
|
@@ -105,6 +115,18 @@ var ApprovalBroker = class {
|
|
|
105
115
|
this.notify();
|
|
106
116
|
return { status: "completed", result, summary: { ...record.summary } };
|
|
107
117
|
}
|
|
118
|
+
clearOwner(owner) {
|
|
119
|
+
const resolvedOwner = normalizeOwner(owner);
|
|
120
|
+
let changed = false;
|
|
121
|
+
for (const [id, record] of this.records.entries()) {
|
|
122
|
+
if (record.owner === resolvedOwner) {
|
|
123
|
+
record.execute = null;
|
|
124
|
+
this.records.delete(id);
|
|
125
|
+
changed = true;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (changed) this.notify();
|
|
129
|
+
}
|
|
108
130
|
clearAll() {
|
|
109
131
|
this.records.clear();
|
|
110
132
|
this.notify();
|
|
@@ -113,6 +135,119 @@ var ApprovalBroker = class {
|
|
|
113
135
|
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
114
136
|
var DEFAULT_MAX_CACHE_ENTRIES = 512;
|
|
115
137
|
var MAX_CUSTOM_DETECTOR_CACHE = 64;
|
|
138
|
+
var CYRILLIC_CONFUSABLES = {
|
|
139
|
+
"\u0410": "A",
|
|
140
|
+
"\u0412": "B",
|
|
141
|
+
"\u0421": "C",
|
|
142
|
+
"\u0415": "E",
|
|
143
|
+
"\u041D": "H",
|
|
144
|
+
"\u0406": "I",
|
|
145
|
+
"\u0408": "J",
|
|
146
|
+
"\u041A": "K",
|
|
147
|
+
"\u041C": "M",
|
|
148
|
+
"\u041E": "O",
|
|
149
|
+
"\u0420": "P",
|
|
150
|
+
"\u0405": "S",
|
|
151
|
+
"\u0422": "T",
|
|
152
|
+
"\u0423": "Y",
|
|
153
|
+
"\u0425": "X",
|
|
154
|
+
"\u0430": "a",
|
|
155
|
+
"\u0432": "b",
|
|
156
|
+
"\u0441": "c",
|
|
157
|
+
"\u0435": "e",
|
|
158
|
+
"\u043D": "h",
|
|
159
|
+
"\u0456": "i",
|
|
160
|
+
"\u0458": "j",
|
|
161
|
+
"\u043A": "k",
|
|
162
|
+
"\u043C": "m",
|
|
163
|
+
"\u043E": "o",
|
|
164
|
+
"\u0440": "p",
|
|
165
|
+
"\u0455": "s",
|
|
166
|
+
"\u0442": "t",
|
|
167
|
+
"\u0443": "y",
|
|
168
|
+
"\u0445": "x"
|
|
169
|
+
};
|
|
170
|
+
var HAS_CYRILLIC_RE = /[\u0400-\u04ff]/;
|
|
171
|
+
var LATIN_LETTER_RE = /[A-Za-z\u00c0-\u024f]/;
|
|
172
|
+
var WORD_TOKEN_RE = new RegExp("\\p{L}+", "gu");
|
|
173
|
+
var SWEDISH_HYPHEN_COMPOUND_RE = /\b([A-ZÅÄÖÉ][a-zåäöé]{2,})-([a-zåäöé]{3,})\b/g;
|
|
174
|
+
var COMPOUND_NER_LABELS = /* @__PURE__ */ new Set(["NAMN", "ORG", "PLATS"]);
|
|
175
|
+
function normalizeMixedScriptHomoglyphs(text) {
|
|
176
|
+
if (!HAS_CYRILLIC_RE.test(text)) return { text, changed: false };
|
|
177
|
+
let latinCount = 0;
|
|
178
|
+
let cyrillicCount = 0;
|
|
179
|
+
for (const ch of text) {
|
|
180
|
+
if (LATIN_LETTER_RE.test(ch)) latinCount += 1;
|
|
181
|
+
else if (HAS_CYRILLIC_RE.test(ch)) cyrillicCount += 1;
|
|
182
|
+
}
|
|
183
|
+
const majorityLatin = latinCount > 0 && latinCount >= cyrillicCount * 2;
|
|
184
|
+
let changed = false;
|
|
185
|
+
const normalized = text.replace(WORD_TOKEN_RE, (word) => {
|
|
186
|
+
if (!HAS_CYRILLIC_RE.test(word)) return word;
|
|
187
|
+
const hasLatin = LATIN_LETTER_RE.test(word);
|
|
188
|
+
if (!hasLatin && !majorityLatin) return word;
|
|
189
|
+
if (!hasLatin) {
|
|
190
|
+
for (const ch of word) {
|
|
191
|
+
if (HAS_CYRILLIC_RE.test(ch) && !(ch in CYRILLIC_CONFUSABLES)) return word;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
let out = "";
|
|
195
|
+
let wordChanged = false;
|
|
196
|
+
for (const ch of word) {
|
|
197
|
+
const mapped = CYRILLIC_CONFUSABLES[ch];
|
|
198
|
+
if (mapped !== void 0) {
|
|
199
|
+
out += mapped;
|
|
200
|
+
wordChanged = true;
|
|
201
|
+
} else {
|
|
202
|
+
out += ch;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (wordChanged) changed = true;
|
|
206
|
+
return out;
|
|
207
|
+
});
|
|
208
|
+
return { text: normalized, changed };
|
|
209
|
+
}
|
|
210
|
+
async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, existing) {
|
|
211
|
+
const candidates = [];
|
|
212
|
+
SWEDISH_HYPHEN_COMPOUND_RE.lastIndex = 0;
|
|
213
|
+
for (let m = SWEDISH_HYPHEN_COMPOUND_RE.exec(text); m !== null; m = SWEDISH_HYPHEN_COMPOUND_RE.exec(text)) {
|
|
214
|
+
const prefix = m[1];
|
|
215
|
+
if (!prefix) continue;
|
|
216
|
+
const prefixStart = m.index;
|
|
217
|
+
const prefixEnd = prefixStart + prefix.length;
|
|
218
|
+
const alreadyCovered = existing.some((d) => d.start < prefixEnd && d.end > prefixStart);
|
|
219
|
+
if (!alreadyCovered) {
|
|
220
|
+
candidates.push({ prefixStart, prefixEnd, hyphenIndex: prefixEnd });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (candidates.length === 0) return [];
|
|
224
|
+
const chars = text.split("");
|
|
225
|
+
for (const c of candidates) {
|
|
226
|
+
chars[c.hyphenIndex] = " ";
|
|
227
|
+
}
|
|
228
|
+
const probeText = chars.join("");
|
|
229
|
+
const probeRes = await redactWithNer(probeText, {
|
|
230
|
+
recognizer: ner,
|
|
231
|
+
detectors: [...detectors],
|
|
232
|
+
profile
|
|
233
|
+
});
|
|
234
|
+
const extra = [];
|
|
235
|
+
for (const r of probeRes.redactions) {
|
|
236
|
+
if (!COMPOUND_NER_LABELS.has(r.label)) continue;
|
|
237
|
+
for (const c of candidates) {
|
|
238
|
+
if (r.start <= c.prefixStart && r.end >= c.prefixEnd && r.end <= c.hyphenIndex) {
|
|
239
|
+
extra.push({
|
|
240
|
+
start: c.prefixStart,
|
|
241
|
+
end: c.prefixEnd,
|
|
242
|
+
label: r.label,
|
|
243
|
+
value: text.slice(c.prefixStart, c.prefixEnd)
|
|
244
|
+
});
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return extra;
|
|
250
|
+
}
|
|
116
251
|
function escapeRegExp(value) {
|
|
117
252
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
118
253
|
}
|
|
@@ -120,7 +255,7 @@ function normalizeCustomTerms(rawTerms) {
|
|
|
120
255
|
const unique = /* @__PURE__ */ new Map();
|
|
121
256
|
for (const raw of rawTerms) {
|
|
122
257
|
if (typeof raw !== "string") continue;
|
|
123
|
-
const trimmed = raw.trim();
|
|
258
|
+
const trimmed = canonicalize(raw.trim()).text.trim();
|
|
124
259
|
if (trimmed.length < 2 || trimmed.length > 160) continue;
|
|
125
260
|
const folded = trimmed.toLowerCase();
|
|
126
261
|
if (!unique.has(folded)) unique.set(folded, trimmed);
|
|
@@ -274,12 +409,28 @@ function createMaskeraEngine(options = {}) {
|
|
|
274
409
|
}
|
|
275
410
|
const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
|
|
276
411
|
if (requestedMode === "rules") {
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
412
|
+
const canonical = canonicalize(text);
|
|
413
|
+
const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
|
|
414
|
+
let result;
|
|
415
|
+
if (canonical.identity && !homoglyph.changed) {
|
|
416
|
+
result = req.profile === "clinical" ? redactFromDetections(
|
|
417
|
+
text,
|
|
418
|
+
runDetectors(text, detectors).filter(
|
|
419
|
+
(d) => clinicalPrecisionFilter(d, text, "rule")
|
|
420
|
+
)
|
|
421
|
+
) : redact(text, { detectors });
|
|
422
|
+
} else {
|
|
423
|
+
const detected = runDetectors(homoglyph.text, detectors);
|
|
424
|
+
const filtered = req.profile === "clinical" ? detected.filter((d) => clinicalPrecisionFilter(d, homoglyph.text, "rule")) : detected;
|
|
425
|
+
const mapped = [];
|
|
426
|
+
for (const d of filtered) {
|
|
427
|
+
const [start, end] = canonical.span(d.start, d.end);
|
|
428
|
+
if (end > start) {
|
|
429
|
+
mapped.push({ start, end, label: d.label, value: text.slice(start, end) });
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
result = redactFromDetections(text, mapped);
|
|
433
|
+
}
|
|
283
434
|
if (cacheKey) {
|
|
284
435
|
if (spanCache.size >= maxCacheEntries) {
|
|
285
436
|
const oldest = spanCache.keys().next().value;
|
|
@@ -301,11 +452,36 @@ function createMaskeraEngine(options = {}) {
|
|
|
301
452
|
}
|
|
302
453
|
try {
|
|
303
454
|
const ner = getRecognizer();
|
|
304
|
-
const
|
|
455
|
+
const canonical = canonicalize(text);
|
|
456
|
+
const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
|
|
457
|
+
const isIdentity = canonical.identity && !homoglyph.changed;
|
|
458
|
+
const nerInput = isIdentity ? text : homoglyph.text;
|
|
459
|
+
const baseRes = await redactWithNer(nerInput, {
|
|
305
460
|
recognizer: ner,
|
|
306
461
|
detectors,
|
|
307
462
|
profile: req.profile
|
|
308
463
|
});
|
|
464
|
+
const baseDetections = baseRes.redactions.map((r) => ({
|
|
465
|
+
start: r.start,
|
|
466
|
+
end: r.end,
|
|
467
|
+
label: r.label,
|
|
468
|
+
value: nerInput.slice(r.start, r.end)
|
|
469
|
+
}));
|
|
470
|
+
const compoundExtras = await detectHyphenatedCompoundPrefixes(
|
|
471
|
+
nerInput,
|
|
472
|
+
ner,
|
|
473
|
+
detectors,
|
|
474
|
+
req.profile,
|
|
475
|
+
baseDetections
|
|
476
|
+
);
|
|
477
|
+
const combined = compoundExtras.length > 0 ? [...baseDetections, ...compoundExtras] : baseDetections;
|
|
478
|
+
const result = isIdentity && compoundExtras.length === 0 ? baseRes : redactFromDetections(
|
|
479
|
+
text,
|
|
480
|
+
combined.flatMap((d) => {
|
|
481
|
+
const [start, end] = canonical.span(d.start, d.end);
|
|
482
|
+
return end > start ? [{ start, end, label: d.label, value: text.slice(start, end) }] : [];
|
|
483
|
+
})
|
|
484
|
+
);
|
|
309
485
|
nerLoaded = true;
|
|
310
486
|
nerError = null;
|
|
311
487
|
if (cacheKey) {
|
|
@@ -597,7 +773,8 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
597
773
|
}
|
|
598
774
|
await writeFile(targetReal, content, {
|
|
599
775
|
encoding: "utf8",
|
|
600
|
-
flag: options.overwrite ? "w" : "wx"
|
|
776
|
+
flag: options.overwrite ? "w" : "wx",
|
|
777
|
+
mode: 384
|
|
601
778
|
}).catch((err) => {
|
|
602
779
|
if (err.code === "EEXIST") {
|
|
603
780
|
throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
|
|
@@ -673,7 +850,7 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
673
850
|
matches.push({
|
|
674
851
|
path: file.relPath,
|
|
675
852
|
line: i + 1,
|
|
676
|
-
lineText: lineText.length >
|
|
853
|
+
lineText: lineText.length > 16384 ? lineText.slice(0, 16384) : lineText
|
|
677
854
|
});
|
|
678
855
|
if (matches.length >= maxMatches) {
|
|
679
856
|
truncated = true;
|
|
@@ -857,7 +1034,18 @@ ${MASKERA_SKILL_MARKDOWN}`
|
|
|
857
1034
|
}
|
|
858
1035
|
var DEFAULT_MAX_SESSIONS = 100;
|
|
859
1036
|
var DEFAULT_MAX_ENTITIES_PER_SESSION = 5e3;
|
|
1037
|
+
var DEFAULT_OWNER2 = "default";
|
|
860
1038
|
var EXISTING_TOKEN_RE = /\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]/g;
|
|
1039
|
+
function hasOwn(obj, key) {
|
|
1040
|
+
return Object.hasOwn(obj, key);
|
|
1041
|
+
}
|
|
1042
|
+
function ownerStorageKey(owner, id) {
|
|
1043
|
+
return `${owner}\0${id}`;
|
|
1044
|
+
}
|
|
1045
|
+
function normalizeOwner2(owner) {
|
|
1046
|
+
const trimmed = owner?.trim();
|
|
1047
|
+
return trimmed || DEFAULT_OWNER2;
|
|
1048
|
+
}
|
|
861
1049
|
function valueKey(label, value) {
|
|
862
1050
|
return `${label.length}:${label}:${value}`;
|
|
863
1051
|
}
|
|
@@ -874,12 +1062,14 @@ var SessionVault = class {
|
|
|
874
1062
|
this.maxSessions = Math.max(1, maxSessions);
|
|
875
1063
|
this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
|
|
876
1064
|
}
|
|
877
|
-
getOrCreate(sessionId) {
|
|
1065
|
+
getOrCreate(sessionId, owner) {
|
|
878
1066
|
const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
|
|
879
|
-
const
|
|
1067
|
+
const resolvedOwner = normalizeOwner2(owner);
|
|
1068
|
+
const storageKey = ownerStorageKey(resolvedOwner, id);
|
|
1069
|
+
const existing = this.sessions.get(storageKey);
|
|
880
1070
|
if (existing) {
|
|
881
|
-
this.sessions.delete(
|
|
882
|
-
this.sessions.set(
|
|
1071
|
+
this.sessions.delete(storageKey);
|
|
1072
|
+
this.sessions.set(storageKey, existing);
|
|
883
1073
|
existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
884
1074
|
return existing;
|
|
885
1075
|
}
|
|
@@ -890,14 +1080,15 @@ var SessionVault = class {
|
|
|
890
1080
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
891
1081
|
const created = {
|
|
892
1082
|
id,
|
|
1083
|
+
owner: resolvedOwner,
|
|
893
1084
|
createdAt: now,
|
|
894
1085
|
updatedAt: now,
|
|
895
1086
|
tokenByKey: /* @__PURE__ */ new Map(),
|
|
896
|
-
map:
|
|
1087
|
+
map: /* @__PURE__ */ Object.create(null),
|
|
897
1088
|
counters: /* @__PURE__ */ new Map(),
|
|
898
1089
|
countsByLabel: {}
|
|
899
1090
|
};
|
|
900
|
-
this.sessions.set(
|
|
1091
|
+
this.sessions.set(storageKey, created);
|
|
901
1092
|
return created;
|
|
902
1093
|
}
|
|
903
1094
|
/**
|
|
@@ -905,8 +1096,8 @@ var SessionVault = class {
|
|
|
905
1096
|
* the same entity receives the exact same placeholder across multiple calls
|
|
906
1097
|
* and files in the same session, while avoiding collisions with literal text.
|
|
907
1098
|
*/
|
|
908
|
-
apply(originalInput, result, sessionId) {
|
|
909
|
-
const session = this.getOrCreate(sessionId);
|
|
1099
|
+
apply(originalInput, result, sessionId, owner) {
|
|
1100
|
+
const session = this.getOrCreate(sessionId, owner);
|
|
910
1101
|
if (result.redactions.length === 0) {
|
|
911
1102
|
return {
|
|
912
1103
|
sessionId: session.id,
|
|
@@ -932,7 +1123,7 @@ var SessionVault = class {
|
|
|
932
1123
|
for (; ; ) {
|
|
933
1124
|
next += 1;
|
|
934
1125
|
const candidate = `[${r.label}_${next}]`;
|
|
935
|
-
if (!(
|
|
1126
|
+
if (!hasOwn(session.map, candidate) && !existingTokens?.has(candidate)) {
|
|
936
1127
|
token = candidate;
|
|
937
1128
|
break;
|
|
938
1129
|
}
|
|
@@ -981,7 +1172,8 @@ var SessionVault = class {
|
|
|
981
1172
|
if (!normalizedId) {
|
|
982
1173
|
throw new Error("Provide either session_id or map to restore placeholders.");
|
|
983
1174
|
}
|
|
984
|
-
const
|
|
1175
|
+
const resolvedOwner = normalizeOwner2(options.owner);
|
|
1176
|
+
const session = this.sessions.get(ownerStorageKey(resolvedOwner, normalizedId));
|
|
985
1177
|
if (!session) {
|
|
986
1178
|
throw new Error(`Unknown session_id "${normalizedId}".`);
|
|
987
1179
|
}
|
|
@@ -991,8 +1183,35 @@ var SessionVault = class {
|
|
|
991
1183
|
knownPlaceholders: Object.keys(session.map).length
|
|
992
1184
|
};
|
|
993
1185
|
}
|
|
994
|
-
|
|
995
|
-
|
|
1186
|
+
/**
|
|
1187
|
+
* Picks the session that restores `text` when the caller named none.
|
|
1188
|
+
* Confined strictly to sessions belonging to `owner` so a missing session_id
|
|
1189
|
+
* can never read another client's or the proxy's vault entries.
|
|
1190
|
+
*/
|
|
1191
|
+
resolveSessionFor(text, owner) {
|
|
1192
|
+
const resolvedOwner = normalizeOwner2(owner);
|
|
1193
|
+
const tokens = [...new Set(text.match(EXISTING_TOKEN_RE) ?? [])];
|
|
1194
|
+
const candidates = [...this.sessions.values()].filter(
|
|
1195
|
+
(s) => s.owner === resolvedOwner && tokens.every((token) => hasOwn(s.map, token))
|
|
1196
|
+
);
|
|
1197
|
+
if (candidates.length === 0) {
|
|
1198
|
+
throw new Error(
|
|
1199
|
+
tokens.length > 0 ? `No local session knows ${tokens.slice(0, 3).join(", ")}. Read the source with maskera_read_file or maskera_redact first, then pass its session_id.` : "No local session exists yet. Read the source with maskera_read_file or maskera_redact first, then pass its session_id."
|
|
1200
|
+
);
|
|
1201
|
+
}
|
|
1202
|
+
const restorations = new Set(candidates.map((s) => restore(text, s.map)));
|
|
1203
|
+
if (restorations.size > 1) {
|
|
1204
|
+
throw new Error(
|
|
1205
|
+
`The placeholders match ${candidates.length} sessions that restore them differently (${candidates.map((s) => s.id).join(", ")}). Pass the session_id from the maskera_read_file result.`
|
|
1206
|
+
);
|
|
1207
|
+
}
|
|
1208
|
+
const latest = candidates[candidates.length - 1];
|
|
1209
|
+
if (!latest) throw new Error("No local session can restore this text.");
|
|
1210
|
+
return latest.id;
|
|
1211
|
+
}
|
|
1212
|
+
getMap(sessionId, owner) {
|
|
1213
|
+
const resolvedOwner = normalizeOwner2(owner);
|
|
1214
|
+
const session = this.sessions.get(ownerStorageKey(resolvedOwner, sessionId.trim()));
|
|
996
1215
|
return session ? { ...session.map } : {};
|
|
997
1216
|
}
|
|
998
1217
|
entries() {
|
|
@@ -1007,17 +1226,44 @@ var SessionVault = class {
|
|
|
1007
1226
|
clearAll() {
|
|
1008
1227
|
this.sessions.clear();
|
|
1009
1228
|
}
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1229
|
+
clearOwner(owner) {
|
|
1230
|
+
const resolvedOwner = normalizeOwner2(owner);
|
|
1231
|
+
let removed = 0;
|
|
1232
|
+
for (const [key, entry] of this.sessions.entries()) {
|
|
1233
|
+
if (entry.owner === resolvedOwner) {
|
|
1234
|
+
this.sessions.delete(key);
|
|
1235
|
+
removed += 1;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
return removed;
|
|
1018
1239
|
}
|
|
1019
|
-
|
|
1020
|
-
|
|
1240
|
+
list(owner) {
|
|
1241
|
+
const resolvedOwner = owner !== void 0 ? normalizeOwner2(owner) : void 0;
|
|
1242
|
+
const out = [];
|
|
1243
|
+
for (const s of this.sessions.values()) {
|
|
1244
|
+
if (resolvedOwner !== void 0 && s.owner !== resolvedOwner) continue;
|
|
1245
|
+
out.push({
|
|
1246
|
+
sessionId: s.id,
|
|
1247
|
+
entityCount: Object.keys(s.map).length,
|
|
1248
|
+
countsByLabel: { ...s.countsByLabel },
|
|
1249
|
+
createdAt: s.createdAt,
|
|
1250
|
+
updatedAt: s.updatedAt
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
return out;
|
|
1254
|
+
}
|
|
1255
|
+
clear(sessionId, owner) {
|
|
1256
|
+
const resolvedOwner = normalizeOwner2(owner);
|
|
1257
|
+
return this.sessions.delete(ownerStorageKey(resolvedOwner, sessionId.trim()));
|
|
1258
|
+
}
|
|
1259
|
+
sizeForOwner(owner) {
|
|
1260
|
+
if (owner === void 0) return this.sessions.size;
|
|
1261
|
+
const resolvedOwner = normalizeOwner2(owner);
|
|
1262
|
+
let count = 0;
|
|
1263
|
+
for (const s of this.sessions.values()) {
|
|
1264
|
+
if (s.owner === resolvedOwner) count += 1;
|
|
1265
|
+
}
|
|
1266
|
+
return count;
|
|
1021
1267
|
}
|
|
1022
1268
|
get size() {
|
|
1023
1269
|
return this.sessions.size;
|
|
@@ -1026,7 +1272,7 @@ var SessionVault = class {
|
|
|
1026
1272
|
|
|
1027
1273
|
// src/server.ts
|
|
1028
1274
|
var SERVER_NAME = "maskera-mcp";
|
|
1029
|
-
var SERVER_VERSION = "
|
|
1275
|
+
var SERVER_VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
1030
1276
|
var SUPPORTED_PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
|
|
1031
1277
|
var PLACEHOLDER_QUERY_RE = /^\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]$/;
|
|
1032
1278
|
var COUNTS_SCHEMA = {
|
|
@@ -1203,14 +1449,14 @@ var TOOLS = [
|
|
|
1203
1449
|
},
|
|
1204
1450
|
session_id: {
|
|
1205
1451
|
type: "string",
|
|
1206
|
-
description: "Session ID
|
|
1452
|
+
description: "Session ID from maskera_read_file or maskera_redact. When omitted, the latest session that knows every placeholder in text is used; ambiguous matches are refused."
|
|
1207
1453
|
},
|
|
1208
1454
|
overwrite: {
|
|
1209
1455
|
type: "boolean",
|
|
1210
1456
|
description: "Allow overwriting an existing file. Default false."
|
|
1211
1457
|
}
|
|
1212
1458
|
},
|
|
1213
|
-
required: ["path", "text"
|
|
1459
|
+
required: ["path", "text"]
|
|
1214
1460
|
},
|
|
1215
1461
|
outputSchema: {
|
|
1216
1462
|
type: "object",
|
|
@@ -1475,6 +1721,35 @@ var TOOLS = [
|
|
|
1475
1721
|
}
|
|
1476
1722
|
];
|
|
1477
1723
|
var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_clear_session"]);
|
|
1724
|
+
var CODE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
1725
|
+
".ts",
|
|
1726
|
+
".tsx",
|
|
1727
|
+
".js",
|
|
1728
|
+
".jsx",
|
|
1729
|
+
".mjs",
|
|
1730
|
+
".cjs",
|
|
1731
|
+
".json",
|
|
1732
|
+
".yaml",
|
|
1733
|
+
".yml",
|
|
1734
|
+
".toml",
|
|
1735
|
+
".lock",
|
|
1736
|
+
".css",
|
|
1737
|
+
".scss",
|
|
1738
|
+
".html",
|
|
1739
|
+
".svg",
|
|
1740
|
+
".map",
|
|
1741
|
+
".py",
|
|
1742
|
+
".rs",
|
|
1743
|
+
".go",
|
|
1744
|
+
".java",
|
|
1745
|
+
".rb",
|
|
1746
|
+
".sh",
|
|
1747
|
+
".sql",
|
|
1748
|
+
".env"
|
|
1749
|
+
]);
|
|
1750
|
+
var PATH_NER_LABELS = /* @__PURE__ */ new Set(["NAMN", "ORG", "PLATS"]);
|
|
1751
|
+
var PATH_NER_PREFIX = "Dokument om ";
|
|
1752
|
+
var MAX_PATH_ALIASES_PER_OWNER = 5e3;
|
|
1478
1753
|
function asObject(value) {
|
|
1479
1754
|
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1480
1755
|
}
|
|
@@ -1514,6 +1789,30 @@ function toolError(message) {
|
|
|
1514
1789
|
content: [{ type: "text", text: message }]
|
|
1515
1790
|
};
|
|
1516
1791
|
}
|
|
1792
|
+
function truncatePreservingPlaceholders(text, maxLength = 500) {
|
|
1793
|
+
if (text.length <= maxLength) return text;
|
|
1794
|
+
let cut = maxLength;
|
|
1795
|
+
const open = text.lastIndexOf("[", cut - 1);
|
|
1796
|
+
if (open >= 0) {
|
|
1797
|
+
const close = text.indexOf("]", open);
|
|
1798
|
+
if (close >= cut) {
|
|
1799
|
+
cut = open;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
return `${text.slice(0, cut)}...`;
|
|
1803
|
+
}
|
|
1804
|
+
function enforceSessionSecretsRedacted(text, sessionMap) {
|
|
1805
|
+
const entries = Object.entries(sessionMap).filter(([, value]) => value.length >= 2).sort((a, b) => b[1].length - a[1].length);
|
|
1806
|
+
let out = text;
|
|
1807
|
+
let extraRedactions = 0;
|
|
1808
|
+
for (const [token, rawValue] of entries) {
|
|
1809
|
+
if (!out.includes(rawValue)) continue;
|
|
1810
|
+
const parts = out.split(rawValue);
|
|
1811
|
+
extraRedactions += parts.length - 1;
|
|
1812
|
+
out = parts.join(token);
|
|
1813
|
+
}
|
|
1814
|
+
return { text: out, extraRedactions };
|
|
1815
|
+
}
|
|
1517
1816
|
function createMaskeraMcpServer(options = {}) {
|
|
1518
1817
|
const engine = options.engine ?? createMaskeraEngine();
|
|
1519
1818
|
const vault = options.vault ?? new SessionVault();
|
|
@@ -1525,11 +1824,155 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1525
1824
|
const requestElicitation = options.requestElicitation;
|
|
1526
1825
|
const onToolCall = options.onToolCall;
|
|
1527
1826
|
let clientSupportsElicitation = false;
|
|
1827
|
+
const ownerPathAliases = /* @__PURE__ */ new Map();
|
|
1828
|
+
function getPathAliasBucket(owner) {
|
|
1829
|
+
let bucket = ownerPathAliases.get(owner);
|
|
1830
|
+
if (!bucket) {
|
|
1831
|
+
bucket = { toAlias: /* @__PURE__ */ new Map(), toReal: /* @__PURE__ */ new Map() };
|
|
1832
|
+
ownerPathAliases.set(owner, bucket);
|
|
1833
|
+
}
|
|
1834
|
+
return bucket;
|
|
1835
|
+
}
|
|
1836
|
+
function registerPathAlias(owner, realPath, aliasPath) {
|
|
1837
|
+
if (realPath === aliasPath) return;
|
|
1838
|
+
const bucket = getPathAliasBucket(owner);
|
|
1839
|
+
if (bucket.toAlias.size >= MAX_PATH_ALIASES_PER_OWNER && !bucket.toAlias.has(realPath)) {
|
|
1840
|
+
const oldestReal = bucket.toAlias.keys().next().value;
|
|
1841
|
+
if (oldestReal !== void 0) {
|
|
1842
|
+
const oldestAlias = bucket.toAlias.get(oldestReal);
|
|
1843
|
+
bucket.toAlias.delete(oldestReal);
|
|
1844
|
+
if (oldestAlias !== void 0) bucket.toReal.delete(oldestAlias);
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
bucket.toAlias.set(realPath, aliasPath);
|
|
1848
|
+
bucket.toReal.set(aliasPath, realPath);
|
|
1849
|
+
}
|
|
1850
|
+
async function redactPathSegment(segment, isFinalSegment, opts) {
|
|
1851
|
+
const ext = isFinalSegment ? extname(segment) : "";
|
|
1852
|
+
const stem = ext ? segment.slice(0, -ext.length) : segment;
|
|
1853
|
+
if (!stem.trim()) return { segment, sessionId: opts.sessionId, changed: false };
|
|
1854
|
+
const rulesProbe = stem.replace(/_/g, " ");
|
|
1855
|
+
const { result: rulesRes } = await engine.redact(rulesProbe, {
|
|
1856
|
+
mode: "rules",
|
|
1857
|
+
profile: opts.profile,
|
|
1858
|
+
customTerms: opts.customTerms
|
|
1859
|
+
});
|
|
1860
|
+
const detections = rulesRes.redactions.map((r) => ({
|
|
1861
|
+
start: r.start,
|
|
1862
|
+
end: r.end,
|
|
1863
|
+
label: r.label,
|
|
1864
|
+
value: stem.slice(r.start, r.end)
|
|
1865
|
+
}));
|
|
1866
|
+
const effectiveMode = opts.mode ?? engine.status().defaultMode;
|
|
1867
|
+
const isCodeFile = ext !== "" && CODE_FILE_EXTENSIONS.has(ext.toLowerCase());
|
|
1868
|
+
if (effectiveMode === "auto" && !isCodeFile) {
|
|
1869
|
+
const alphaWords = stem.match(/[A-Za-zÅÄÖåäöÉé]{2,}/g) ?? [];
|
|
1870
|
+
if (alphaWords.length >= 2) {
|
|
1871
|
+
const titleProbe = stem.replace(/[_-]/g, " ").replace(
|
|
1872
|
+
/(^| )([a-zåäöé])/g,
|
|
1873
|
+
(_m, lead, ch) => `${lead}${ch.toUpperCase()}`
|
|
1874
|
+
);
|
|
1875
|
+
const framed = `${PATH_NER_PREFIX}${titleProbe}`;
|
|
1876
|
+
const { result: nerRes } = await engine.redact(framed, {
|
|
1877
|
+
mode: "auto",
|
|
1878
|
+
profile: opts.profile,
|
|
1879
|
+
customTerms: opts.customTerms
|
|
1880
|
+
});
|
|
1881
|
+
const offset = PATH_NER_PREFIX.length;
|
|
1882
|
+
for (const r of nerRes.redactions) {
|
|
1883
|
+
if (!PATH_NER_LABELS.has(r.label)) continue;
|
|
1884
|
+
const start = r.start - offset;
|
|
1885
|
+
const end = r.end - offset;
|
|
1886
|
+
if (start < 0 || end <= start || end > stem.length) continue;
|
|
1887
|
+
const overlaps = detections.some((d) => d.start < end && d.end > start);
|
|
1888
|
+
if (!overlaps) {
|
|
1889
|
+
detections.push({ start, end, label: r.label, value: stem.slice(start, end) });
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
if (detections.length === 0) {
|
|
1895
|
+
return { segment, sessionId: opts.sessionId, changed: false };
|
|
1896
|
+
}
|
|
1897
|
+
const redactedStem = redactFromDetections(stem, detections);
|
|
1898
|
+
const applied = vault.apply(stem, redactedStem, opts.sessionId, opts.owner);
|
|
1899
|
+
return {
|
|
1900
|
+
segment: `${applied.redacted}${ext}`,
|
|
1901
|
+
sessionId: applied.sessionId,
|
|
1902
|
+
changed: applied.redacted !== stem
|
|
1903
|
+
};
|
|
1904
|
+
}
|
|
1905
|
+
async function redactRelativePath(relPath, opts) {
|
|
1906
|
+
const parts = relPath.split("/");
|
|
1907
|
+
const outParts = [];
|
|
1908
|
+
let activeSession = opts.sessionId;
|
|
1909
|
+
let anyChanged = false;
|
|
1910
|
+
for (let i = 0; i < parts.length; i++) {
|
|
1911
|
+
const part = parts[i] ?? "";
|
|
1912
|
+
const res = await redactPathSegment(part, i === parts.length - 1, {
|
|
1913
|
+
owner: opts.owner,
|
|
1914
|
+
sessionId: activeSession,
|
|
1915
|
+
mode: opts.mode,
|
|
1916
|
+
profile: opts.profile,
|
|
1917
|
+
customTerms: opts.customTerms
|
|
1918
|
+
});
|
|
1919
|
+
activeSession = res.sessionId;
|
|
1920
|
+
if (res.changed) anyChanged = true;
|
|
1921
|
+
outParts.push(res.segment);
|
|
1922
|
+
}
|
|
1923
|
+
const aliasedRel = outParts.join("/");
|
|
1924
|
+
if (anyChanged) {
|
|
1925
|
+
registerPathAlias(opts.owner, relPath, aliasedRel);
|
|
1926
|
+
if (opts.rootBase) {
|
|
1927
|
+
registerPathAlias(opts.owner, join(opts.rootBase, relPath), join(opts.rootBase, aliasedRel));
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
return { path: aliasedRel, sessionId: activeSession, changed: anyChanged };
|
|
1931
|
+
}
|
|
1932
|
+
async function redactResolvedPath(resolvedPath, opts) {
|
|
1933
|
+
const candidates = files.allowedRoots.flatMap(
|
|
1934
|
+
(root) => root.startsWith("/private/") ? [root] : [root, `/private${root}`]
|
|
1935
|
+
);
|
|
1936
|
+
let bestRoot = null;
|
|
1937
|
+
let bestRel = null;
|
|
1938
|
+
for (const root of candidates) {
|
|
1939
|
+
const rel = relative(root, resolvedPath);
|
|
1940
|
+
if (rel && !rel.startsWith("..") && !isAbsolute(rel)) {
|
|
1941
|
+
if (!bestRoot || root.length > bestRoot.length) {
|
|
1942
|
+
bestRoot = root;
|
|
1943
|
+
bestRel = rel.split(sep).join("/");
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
if (!bestRoot || !bestRel) return resolvedPath;
|
|
1948
|
+
const res = await redactRelativePath(bestRel, { ...opts, rootBase: bestRoot });
|
|
1949
|
+
if (!res.changed) return resolvedPath;
|
|
1950
|
+
return join(bestRoot, res.path);
|
|
1951
|
+
}
|
|
1952
|
+
function resolveInputPath(rawPath, owner, sessionId) {
|
|
1953
|
+
const trimmed = rawPath.trim();
|
|
1954
|
+
const bucket = ownerPathAliases.get(owner);
|
|
1955
|
+
const direct = bucket?.toReal.get(trimmed);
|
|
1956
|
+
if (direct) return direct;
|
|
1957
|
+
const normalized = trimmed.split(sep).join("/");
|
|
1958
|
+
const directNorm = bucket?.toReal.get(normalized);
|
|
1959
|
+
if (directNorm) return directNorm;
|
|
1960
|
+
if (trimmed.includes("[") && trimmed.includes("]")) {
|
|
1961
|
+
try {
|
|
1962
|
+
const sid = sessionId?.trim() || vault.resolveSessionFor(trimmed, owner);
|
|
1963
|
+
const { restored } = vault.restore(trimmed, { sessionId: sid, owner });
|
|
1964
|
+
return restored;
|
|
1965
|
+
} catch {
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
return rawPath;
|
|
1969
|
+
}
|
|
1528
1970
|
function resolvePolicy(override) {
|
|
1529
1971
|
return {
|
|
1530
1972
|
allowRawRestore: override?.allowRawRestore ?? options.allowRawRestore ?? true,
|
|
1531
1973
|
readOnly: override?.readOnly ?? options.readOnly ?? false,
|
|
1532
|
-
approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic"
|
|
1974
|
+
approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic",
|
|
1975
|
+
sessionOwner: override?.sessionOwner ?? options.sessionOwner ?? "default"
|
|
1533
1976
|
};
|
|
1534
1977
|
}
|
|
1535
1978
|
function visibleTools(policy) {
|
|
@@ -1552,7 +1995,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1552
1995
|
server: SERVER_NAME,
|
|
1553
1996
|
version: SERVER_VERSION,
|
|
1554
1997
|
engine: engine.status(),
|
|
1555
|
-
active_sessions: vault.
|
|
1998
|
+
active_sessions: vault.sizeForOwner(policy.sessionOwner),
|
|
1556
1999
|
allowed_roots: files.allowedRoots,
|
|
1557
2000
|
policy: {
|
|
1558
2001
|
read_only: policy.readOnly,
|
|
@@ -1607,6 +2050,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1607
2050
|
tool: input.tool,
|
|
1608
2051
|
reason: input.reason,
|
|
1609
2052
|
sessionId: input.sessionId,
|
|
2053
|
+
owner: policy.sessionOwner,
|
|
1610
2054
|
placeholderCount: input.placeholderCount,
|
|
1611
2055
|
execute: input.execute
|
|
1612
2056
|
});
|
|
@@ -1623,6 +2067,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1623
2067
|
async function callTool(name, rawArgs, policy) {
|
|
1624
2068
|
const startedAt = Date.now();
|
|
1625
2069
|
const args = asObject(rawArgs);
|
|
2070
|
+
const owner = policy.sessionOwner;
|
|
1626
2071
|
let telemetrySessionId;
|
|
1627
2072
|
let telemetryRedactions = 0;
|
|
1628
2073
|
let telemetryCounts = {};
|
|
@@ -1659,7 +2104,8 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1659
2104
|
const applied = vault.apply(
|
|
1660
2105
|
args.text,
|
|
1661
2106
|
result,
|
|
1662
|
-
typeof args.session_id === "string" ? args.session_id : void 0
|
|
2107
|
+
typeof args.session_id === "string" ? args.session_id : void 0,
|
|
2108
|
+
owner
|
|
1663
2109
|
);
|
|
1664
2110
|
telemetrySessionId = applied.sessionId;
|
|
1665
2111
|
telemetryRedactions = applied.totalRedactions;
|
|
@@ -1687,6 +2133,13 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1687
2133
|
return finish(toolOk(payload));
|
|
1688
2134
|
}
|
|
1689
2135
|
if (name === "maskera_restore") {
|
|
2136
|
+
if (!policy.allowRawRestore) {
|
|
2137
|
+
return finish(
|
|
2138
|
+
toolError(
|
|
2139
|
+
"Raw PII export is disabled by server policy (--no-raw-restore). Use maskera_write_file to restore directly to disk without exposing raw PII to the model."
|
|
2140
|
+
)
|
|
2141
|
+
);
|
|
2142
|
+
}
|
|
1690
2143
|
if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
|
|
1691
2144
|
const explicitMap = args.map && typeof args.map === "object" && !Array.isArray(args.map) ? Object.fromEntries(
|
|
1692
2145
|
Object.entries(args.map).filter(
|
|
@@ -1697,7 +2150,8 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1697
2150
|
telemetrySessionId = sessionIdArg;
|
|
1698
2151
|
const preview = vault.restore(args.text, {
|
|
1699
2152
|
sessionId: sessionIdArg,
|
|
1700
|
-
map: explicitMap
|
|
2153
|
+
map: explicitMap,
|
|
2154
|
+
owner
|
|
1701
2155
|
});
|
|
1702
2156
|
return finish(
|
|
1703
2157
|
await gateRawPiiExport({
|
|
@@ -1722,7 +2176,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1722
2176
|
return finish(toolError("Missing required non-empty string: request_id"));
|
|
1723
2177
|
}
|
|
1724
2178
|
const requestId = args.request_id.trim();
|
|
1725
|
-
const resumed = await approvals.resume(requestId);
|
|
2179
|
+
const resumed = await approvals.resume(requestId, owner);
|
|
1726
2180
|
if (resumed.status === "not_found") {
|
|
1727
2181
|
return finish(toolError(`Unknown approval request_id "${requestId}".`));
|
|
1728
2182
|
}
|
|
@@ -1744,23 +2198,38 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1744
2198
|
}
|
|
1745
2199
|
if (name === "maskera_read_file") {
|
|
1746
2200
|
if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
|
|
1747
|
-
const
|
|
2201
|
+
const requestedMode = asMode(args.mode);
|
|
2202
|
+
if (engine.status().defaultMode === "auto" && requestedMode === "rules") {
|
|
2203
|
+
return finish(
|
|
2204
|
+
toolError(
|
|
2205
|
+
'Downgrading mode to "rules" is not allowed on maskera_read_file when the server runs in hybrid "auto" mode.'
|
|
2206
|
+
)
|
|
2207
|
+
);
|
|
2208
|
+
}
|
|
2209
|
+
const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
|
|
2210
|
+
const resolvedInputPath = resolveInputPath(args.path, owner, requestedSession);
|
|
2211
|
+
const file = await files.readText(resolvedInputPath);
|
|
2212
|
+
const profile = asProfile(args.profile) ?? defaultProfile;
|
|
2213
|
+
const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
|
|
1748
2214
|
const { result, modeUsed } = await engine.redact(file.content, {
|
|
1749
|
-
mode:
|
|
1750
|
-
profile
|
|
1751
|
-
customTerms
|
|
2215
|
+
mode: requestedMode,
|
|
2216
|
+
profile,
|
|
2217
|
+
customTerms
|
|
2218
|
+
});
|
|
2219
|
+
const applied = vault.apply(file.content, result, requestedSession, owner);
|
|
2220
|
+
const safePath = await redactResolvedPath(file.resolvedPath, {
|
|
2221
|
+
owner,
|
|
2222
|
+
sessionId: applied.sessionId,
|
|
2223
|
+
mode: requestedMode,
|
|
2224
|
+
profile,
|
|
2225
|
+
customTerms
|
|
1752
2226
|
});
|
|
1753
|
-
const applied = vault.apply(
|
|
1754
|
-
file.content,
|
|
1755
|
-
result,
|
|
1756
|
-
typeof args.session_id === "string" ? args.session_id : void 0
|
|
1757
|
-
);
|
|
1758
2227
|
telemetrySessionId = applied.sessionId;
|
|
1759
2228
|
telemetryRedactions = applied.totalRedactions;
|
|
1760
2229
|
telemetryCounts = applied.counts;
|
|
1761
2230
|
return finish(
|
|
1762
2231
|
toolOk({
|
|
1763
|
-
path:
|
|
2232
|
+
path: safePath,
|
|
1764
2233
|
bytes: file.bytes,
|
|
1765
2234
|
redacted: applied.redacted,
|
|
1766
2235
|
session_id: applied.sessionId,
|
|
@@ -1773,20 +2242,25 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1773
2242
|
if (name === "maskera_write_file") {
|
|
1774
2243
|
if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
|
|
1775
2244
|
if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
|
|
1776
|
-
|
|
1777
|
-
return finish(toolError("Missing required non-empty string: session_id"));
|
|
1778
|
-
}
|
|
1779
|
-
const normalizedSessionId = args.session_id.trim();
|
|
2245
|
+
const normalizedSessionId = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : vault.resolveSessionFor(args.text, owner);
|
|
1780
2246
|
telemetrySessionId = normalizedSessionId;
|
|
1781
2247
|
const { restored, knownPlaceholders } = vault.restore(args.text, {
|
|
1782
|
-
sessionId: normalizedSessionId
|
|
2248
|
+
sessionId: normalizedSessionId,
|
|
2249
|
+
owner
|
|
1783
2250
|
});
|
|
1784
|
-
const
|
|
2251
|
+
const resolvedTargetPath = resolveInputPath(args.path, owner, normalizedSessionId);
|
|
2252
|
+
const written = await files.writeText(resolvedTargetPath, restored, {
|
|
1785
2253
|
overwrite: args.overwrite === true
|
|
1786
2254
|
});
|
|
2255
|
+
const safePath = await redactResolvedPath(written.resolvedPath, {
|
|
2256
|
+
owner,
|
|
2257
|
+
sessionId: normalizedSessionId,
|
|
2258
|
+
profile: defaultProfile,
|
|
2259
|
+
customTerms: defaultCustomTerms
|
|
2260
|
+
});
|
|
1787
2261
|
return finish(
|
|
1788
2262
|
toolOk({
|
|
1789
|
-
path:
|
|
2263
|
+
path: safePath,
|
|
1790
2264
|
bytes: written.bytes,
|
|
1791
2265
|
session_id: normalizedSessionId,
|
|
1792
2266
|
known_placeholders: knownPlaceholders
|
|
@@ -1801,11 +2275,25 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1801
2275
|
maxDepth: asOptionalInt(args.max_depth)
|
|
1802
2276
|
}
|
|
1803
2277
|
);
|
|
2278
|
+
let pathSessionId;
|
|
2279
|
+
const safeFiles = [];
|
|
2280
|
+
for (const entry of listed.files) {
|
|
2281
|
+
const safe = await redactRelativePath(entry.path, {
|
|
2282
|
+
owner,
|
|
2283
|
+
sessionId: pathSessionId,
|
|
2284
|
+
profile: defaultProfile,
|
|
2285
|
+
customTerms: defaultCustomTerms,
|
|
2286
|
+
rootBase: listed.root
|
|
2287
|
+
});
|
|
2288
|
+
pathSessionId = safe.sessionId;
|
|
2289
|
+
safeFiles.push({ path: safe.path, bytes: entry.bytes });
|
|
2290
|
+
}
|
|
1804
2291
|
return finish(
|
|
1805
2292
|
toolOk({
|
|
1806
2293
|
root: listed.root,
|
|
1807
|
-
files:
|
|
1808
|
-
truncated: listed.truncated
|
|
2294
|
+
files: safeFiles,
|
|
2295
|
+
truncated: listed.truncated,
|
|
2296
|
+
...pathSessionId ? { session_id: pathSessionId } : {}
|
|
1809
2297
|
})
|
|
1810
2298
|
);
|
|
1811
2299
|
}
|
|
@@ -1813,11 +2301,19 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1813
2301
|
if (typeof args.query !== "string" || !args.query.trim()) {
|
|
1814
2302
|
return finish(toolError("Missing required non-empty string: query"));
|
|
1815
2303
|
}
|
|
2304
|
+
const mode = asMode(args.mode);
|
|
2305
|
+
if (engine.status().defaultMode === "auto" && mode === "rules") {
|
|
2306
|
+
return finish(
|
|
2307
|
+
toolError(
|
|
2308
|
+
'Downgrading mode to "rules" is not allowed on maskera_search_files when the server runs in hybrid "auto" mode.'
|
|
2309
|
+
)
|
|
2310
|
+
);
|
|
2311
|
+
}
|
|
1816
2312
|
const requestedSession = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : void 0;
|
|
2313
|
+
const existingSessionMap = requestedSession ? vault.getMap(requestedSession, owner) : {};
|
|
1817
2314
|
let resolvedQuery = args.query.trim();
|
|
1818
2315
|
if (requestedSession && PLACEHOLDER_QUERY_RE.test(resolvedQuery)) {
|
|
1819
|
-
const
|
|
1820
|
-
const mapped = map[resolvedQuery];
|
|
2316
|
+
const mapped = existingSessionMap[resolvedQuery];
|
|
1821
2317
|
if (mapped) {
|
|
1822
2318
|
resolvedQuery = mapped;
|
|
1823
2319
|
}
|
|
@@ -1827,7 +2323,6 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1827
2323
|
caseSensitive: args.case_sensitive === true,
|
|
1828
2324
|
maxMatches: asOptionalInt(args.max_matches)
|
|
1829
2325
|
});
|
|
1830
|
-
const mode = asMode(args.mode);
|
|
1831
2326
|
const profile = asProfile(args.profile) ?? defaultProfile;
|
|
1832
2327
|
const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
|
|
1833
2328
|
let activeSessionId = requestedSession;
|
|
@@ -1840,22 +2335,35 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1840
2335
|
profile,
|
|
1841
2336
|
customTerms
|
|
1842
2337
|
});
|
|
1843
|
-
const applied = vault.apply(match.lineText, result, activeSessionId);
|
|
2338
|
+
const applied = vault.apply(match.lineText, result, activeSessionId, owner);
|
|
1844
2339
|
activeSessionId = applied.sessionId;
|
|
1845
2340
|
totalRedactions += applied.totalRedactions;
|
|
1846
2341
|
for (const [label, count] of Object.entries(applied.counts)) {
|
|
1847
2342
|
totalCounts[label] = (totalCounts[label] ?? 0) + count;
|
|
1848
2343
|
}
|
|
2344
|
+
const currentMap = vault.getMap(activeSessionId, owner);
|
|
2345
|
+
const safeguarded = enforceSessionSecretsRedacted(applied.redacted, currentMap);
|
|
2346
|
+
totalRedactions += safeguarded.extraRedactions;
|
|
2347
|
+
const safeMatchPath = await redactRelativePath(match.path, {
|
|
2348
|
+
owner,
|
|
2349
|
+
sessionId: activeSessionId,
|
|
2350
|
+
mode,
|
|
2351
|
+
profile,
|
|
2352
|
+
customTerms,
|
|
2353
|
+
rootBase: search.root
|
|
2354
|
+
});
|
|
2355
|
+
activeSessionId = safeMatchPath.sessionId ?? activeSessionId;
|
|
1849
2356
|
redactedMatches.push({
|
|
1850
|
-
path:
|
|
2357
|
+
path: safeMatchPath.path,
|
|
1851
2358
|
line: match.line,
|
|
1852
|
-
redacted_line:
|
|
2359
|
+
redacted_line: truncatePreservingPlaceholders(safeguarded.text, 500)
|
|
1853
2360
|
});
|
|
1854
2361
|
}
|
|
1855
2362
|
const ensuredSessionId = activeSessionId ?? vault.apply(
|
|
1856
2363
|
"",
|
|
1857
2364
|
{ text: "", map: {}, redactions: [], restore: (s) => s },
|
|
1858
|
-
requestedSession
|
|
2365
|
+
requestedSession,
|
|
2366
|
+
owner
|
|
1859
2367
|
).sessionId;
|
|
1860
2368
|
telemetrySessionId = ensuredSessionId;
|
|
1861
2369
|
telemetryRedactions = totalRedactions;
|
|
@@ -1873,7 +2381,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1873
2381
|
);
|
|
1874
2382
|
}
|
|
1875
2383
|
if (name === "maskera_list_sessions") {
|
|
1876
|
-
return finish(toolOk({ sessions: vault.list() }));
|
|
2384
|
+
return finish(toolOk({ sessions: vault.list(owner) }));
|
|
1877
2385
|
}
|
|
1878
2386
|
if (name === "maskera_clear_session") {
|
|
1879
2387
|
if (typeof args.session_id !== "string" || !args.session_id.trim()) {
|
|
@@ -1884,7 +2392,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1884
2392
|
return finish(
|
|
1885
2393
|
toolOk({
|
|
1886
2394
|
session_id: normalizedSessionId,
|
|
1887
|
-
cleared: vault.clear(normalizedSessionId)
|
|
2395
|
+
cleared: vault.clear(normalizedSessionId, owner)
|
|
1888
2396
|
})
|
|
1889
2397
|
);
|
|
1890
2398
|
}
|
|
@@ -1907,7 +2415,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1907
2415
|
};
|
|
1908
2416
|
}
|
|
1909
2417
|
const req = raw;
|
|
1910
|
-
const hasIdProp = Object.
|
|
2418
|
+
const hasIdProp = Object.hasOwn(req, "id");
|
|
1911
2419
|
const validId = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
|
|
1912
2420
|
if (req.jsonrpc !== "2.0" || typeof req.method !== "string" || hasIdProp && validId === void 0) {
|
|
1913
2421
|
return {
|
|
@@ -1924,9 +2432,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1924
2432
|
if (req.method === "initialize") {
|
|
1925
2433
|
const params = asObject(req.params);
|
|
1926
2434
|
const clientCaps = asObject(params.capabilities);
|
|
1927
|
-
|
|
1928
|
-
clientSupportsElicitation = true;
|
|
1929
|
-
}
|
|
2435
|
+
clientSupportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
|
|
1930
2436
|
const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
|
|
1931
2437
|
const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
|
|
1932
2438
|
return {
|
|
@@ -2369,6 +2875,25 @@ async function runGuard(rawInput, engine, options = {}) {
|
|
|
2369
2875
|
}
|
|
2370
2876
|
return out.result.text;
|
|
2371
2877
|
}
|
|
2878
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
2879
|
+
const asText = String(value);
|
|
2880
|
+
if (asText.length >= 7) {
|
|
2881
|
+
const out = await engine.redact(asText, {
|
|
2882
|
+
mode: options.mode,
|
|
2883
|
+
profile: options.profile,
|
|
2884
|
+
customTerms: options.customTerms
|
|
2885
|
+
});
|
|
2886
|
+
if (out.result.redactions.length > 0) {
|
|
2887
|
+
modeUsed2 = out.modeUsed;
|
|
2888
|
+
totalRedactions += out.result.redactions.length;
|
|
2889
|
+
for (const r of out.result.redactions) {
|
|
2890
|
+
counts2[r.label] = (counts2[r.label] ?? 0) + 1;
|
|
2891
|
+
}
|
|
2892
|
+
return out.result.text;
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
return value;
|
|
2896
|
+
}
|
|
2372
2897
|
if (Array.isArray(value)) {
|
|
2373
2898
|
const arr = [];
|
|
2374
2899
|
for (const item of value) arr.push(await redactJson(item));
|
|
@@ -3569,12 +4094,12 @@ function mergeCounts(target, delta) {
|
|
|
3569
4094
|
}
|
|
3570
4095
|
}
|
|
3571
4096
|
function restorePlainText(text, map) {
|
|
3572
|
-
if (!text
|
|
4097
|
+
if (!text?.includes("[") || Object.keys(map).length === 0) return text;
|
|
3573
4098
|
const r = new StreamingRestorer(map);
|
|
3574
4099
|
return r.push(text) + r.flush();
|
|
3575
4100
|
}
|
|
3576
4101
|
function restoreJsonEncodedText(text, map) {
|
|
3577
|
-
if (!text
|
|
4102
|
+
if (!text?.includes("[") || Object.keys(map).length === 0) return text;
|
|
3578
4103
|
try {
|
|
3579
4104
|
const parsed = JSON.parse(text);
|
|
3580
4105
|
const restored = restoreJsonLeaves(parsed, map);
|
|
@@ -3606,14 +4131,127 @@ function shouldSkipToolArgRestore(toolName, argsText) {
|
|
|
3606
4131
|
if (toolName === "execute" && MASKERA_VAULT_CODE_RE.test(argsText)) return true;
|
|
3607
4132
|
return false;
|
|
3608
4133
|
}
|
|
4134
|
+
var SWEDISH_DIACRITIC_RE = /[åäöÅÄÖ]/;
|
|
4135
|
+
var SWEDISH_SIGNAL_WORD_RE = /\b(?:och|inte|ska|eller|enligt|kund|personnummer|svenska|sekretess|arbetsgivare|utbetalning|sammanfatta|skriv|svara|nedan|uppgifter)\b/i;
|
|
4136
|
+
var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
|
|
4137
|
+
"the",
|
|
4138
|
+
"and",
|
|
4139
|
+
"you",
|
|
4140
|
+
"your",
|
|
4141
|
+
"with",
|
|
4142
|
+
"that",
|
|
4143
|
+
"this",
|
|
4144
|
+
"from",
|
|
4145
|
+
"are",
|
|
4146
|
+
"not",
|
|
4147
|
+
"when",
|
|
4148
|
+
"use",
|
|
4149
|
+
"must",
|
|
4150
|
+
"should",
|
|
4151
|
+
"never",
|
|
4152
|
+
"always",
|
|
4153
|
+
"tools",
|
|
4154
|
+
"files",
|
|
4155
|
+
"code",
|
|
4156
|
+
"return",
|
|
4157
|
+
"output",
|
|
4158
|
+
"response",
|
|
4159
|
+
"assistant",
|
|
4160
|
+
"instructions",
|
|
4161
|
+
"command",
|
|
4162
|
+
"user"
|
|
4163
|
+
]);
|
|
4164
|
+
var ASCII_WORD_RE = /\b[a-z]{2,}\b/g;
|
|
4165
|
+
function isLikelyEnglishSystemPrompt(text) {
|
|
4166
|
+
if (text.length < 240) return false;
|
|
4167
|
+
if (SWEDISH_DIACRITIC_RE.test(text)) return false;
|
|
4168
|
+
if (SWEDISH_SIGNAL_WORD_RE.test(text)) return false;
|
|
4169
|
+
const found = /* @__PURE__ */ new Set();
|
|
4170
|
+
const lower = text.toLowerCase();
|
|
4171
|
+
ASCII_WORD_RE.lastIndex = 0;
|
|
4172
|
+
for (let m = ASCII_WORD_RE.exec(lower); m !== null; m = ASCII_WORD_RE.exec(lower)) {
|
|
4173
|
+
const word = m[0];
|
|
4174
|
+
if (word && ENGLISH_BOILERPLATE_WORDS.has(word)) {
|
|
4175
|
+
found.add(word);
|
|
4176
|
+
if (found.size >= 6) return true;
|
|
4177
|
+
}
|
|
4178
|
+
}
|
|
4179
|
+
return false;
|
|
4180
|
+
}
|
|
4181
|
+
function headerFirst(headers, name) {
|
|
4182
|
+
const value = headers[name];
|
|
4183
|
+
if (typeof value === "string") return value.trim();
|
|
4184
|
+
if (Array.isArray(value)) return (value[0] ?? "").trim();
|
|
4185
|
+
return "";
|
|
4186
|
+
}
|
|
4187
|
+
function shortSessionHash(seed) {
|
|
4188
|
+
return `proxy-${createHash("sha256").update(seed).digest("hex").slice(0, 12)}`;
|
|
4189
|
+
}
|
|
4190
|
+
function deriveProxySessionId(headers, body) {
|
|
4191
|
+
const explicit = headerFirst(headers, "x-maskera-session");
|
|
4192
|
+
if (explicit) return explicit;
|
|
4193
|
+
const threadHeader = headerFirst(headers, "x-session-id") || headerFirst(headers, "x-conversation-id") || headerFirst(headers, "openai-conversation-id");
|
|
4194
|
+
if (threadHeader) return shortSessionHash(`hdr:${threadHeader}`);
|
|
4195
|
+
if (body) {
|
|
4196
|
+
if (typeof body.prompt_cache_key === "string" && body.prompt_cache_key.trim()) {
|
|
4197
|
+
return shortSessionHash(`cache:${body.prompt_cache_key.trim()}`);
|
|
4198
|
+
}
|
|
4199
|
+
if (typeof body.conversation === "string" && body.conversation.trim()) {
|
|
4200
|
+
return shortSessionHash(`conv:${body.conversation.trim()}`);
|
|
4201
|
+
}
|
|
4202
|
+
if (isPlainObject(body.conversation) && typeof body.conversation.id === "string" && body.conversation.id.trim()) {
|
|
4203
|
+
return shortSessionHash(`conv:${body.conversation.id.trim()}`);
|
|
4204
|
+
}
|
|
4205
|
+
if (isPlainObject(body.metadata)) {
|
|
4206
|
+
const metaId = typeof body.metadata.session_id === "string" && body.metadata.session_id.trim() || typeof body.metadata.conversation_id === "string" && body.metadata.conversation_id.trim() || typeof body.metadata.user_id === "string" && body.metadata.user_id.trim();
|
|
4207
|
+
if (metaId) return shortSessionHash(`meta:${metaId}`);
|
|
4208
|
+
}
|
|
4209
|
+
}
|
|
4210
|
+
const auth = headerFirst(headers, "authorization") || headerFirst(headers, "x-api-key");
|
|
4211
|
+
if (auth) {
|
|
4212
|
+
const ua = headerFirst(headers, "user-agent");
|
|
4213
|
+
return shortSessionHash(`auth:${auth}\0${ua}`);
|
|
4214
|
+
}
|
|
4215
|
+
return "proxy";
|
|
4216
|
+
}
|
|
4217
|
+
var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
|
|
4218
|
+
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;
|
|
4219
|
+
var DATA_URI_ANY_RE = /^data:([^;,]+);base64,/i;
|
|
4220
|
+
async function redactBase64Utf8(encoded, redactString, kind) {
|
|
4221
|
+
try {
|
|
4222
|
+
const rawBuf = Buffer.from(encoded, "base64");
|
|
4223
|
+
if (rawBuf.includes(0) || rawBuf.byteLength > MAX_BODY_BYTES) return encoded;
|
|
4224
|
+
const decoded = new TextDecoder("utf-8", { fatal: true }).decode(rawBuf);
|
|
4225
|
+
const redacted = await redactString(decoded, kind);
|
|
4226
|
+
if (redacted === decoded) return encoded;
|
|
4227
|
+
return Buffer.from(redacted, "utf8").toString("base64");
|
|
4228
|
+
} catch {
|
|
4229
|
+
return encoded;
|
|
4230
|
+
}
|
|
4231
|
+
}
|
|
3609
4232
|
async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
3610
4233
|
const clone = options.mutate ? body : structuredClone(body);
|
|
4234
|
+
const noteBinary = (kind) => {
|
|
4235
|
+
options.onBinaryAttachment?.(kind);
|
|
4236
|
+
};
|
|
3611
4237
|
async function redactContentBlocks(blocks, kind) {
|
|
3612
4238
|
for (const block of blocks) {
|
|
3613
4239
|
if (!isPlainObject(block)) continue;
|
|
4240
|
+
const blockType = typeof block.type === "string" ? block.type : "";
|
|
4241
|
+
if (blockType === "image" || blockType === "input_image") {
|
|
4242
|
+
const mediaType = isPlainObject(block.source) && typeof block.source.media_type === "string" ? block.source.media_type : blockType;
|
|
4243
|
+
noteBinary(mediaType);
|
|
4244
|
+
} else if (blockType === "image_url" || isPlainObject(block.image_url)) {
|
|
4245
|
+
noteBinary("image_url");
|
|
4246
|
+
} else if (blockType === "input_audio" || isPlainObject(block.input_audio)) {
|
|
4247
|
+
noteBinary("input_audio");
|
|
4248
|
+
}
|
|
3614
4249
|
if (typeof block.text === "string") {
|
|
3615
4250
|
block.text = await redactString(block.text, kind);
|
|
3616
4251
|
}
|
|
4252
|
+
if (typeof block.refusal === "string") {
|
|
4253
|
+
block.refusal = await redactString(block.refusal, kind);
|
|
4254
|
+
}
|
|
3617
4255
|
if (typeof block.thinking === "string") {
|
|
3618
4256
|
const redactedThinking = await redactString(block.thinking, kind);
|
|
3619
4257
|
if (redactedThinking !== block.thinking) {
|
|
@@ -3637,9 +4275,33 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
3637
4275
|
} else if (Array.isArray(block.output)) {
|
|
3638
4276
|
await redactContentBlocks(block.output, kind);
|
|
3639
4277
|
}
|
|
4278
|
+
if (typeof block.file_data === "string") {
|
|
4279
|
+
const match = DATA_URI_TEXT_BASE64_RE.exec(block.file_data);
|
|
4280
|
+
if (match?.[1] && match[2]) {
|
|
4281
|
+
const nextB64 = await redactBase64Utf8(match[2], redactString, kind);
|
|
4282
|
+
block.file_data = `data:${match[1]};base64,${nextB64}`;
|
|
4283
|
+
} else if (block.file_data.startsWith("data:")) {
|
|
4284
|
+
const anyMime = DATA_URI_ANY_RE.exec(block.file_data)?.[1] ?? "application/octet-stream";
|
|
4285
|
+
noteBinary(anyMime);
|
|
4286
|
+
} else {
|
|
4287
|
+
const rawBuf = Buffer.from(block.file_data, "base64");
|
|
4288
|
+
if (rawBuf.includes(0)) {
|
|
4289
|
+
noteBinary("application/octet-stream");
|
|
4290
|
+
} else {
|
|
4291
|
+
block.file_data = await redactBase64Utf8(block.file_data, redactString, kind);
|
|
4292
|
+
}
|
|
4293
|
+
}
|
|
4294
|
+
}
|
|
3640
4295
|
if (isPlainObject(block.source)) {
|
|
3641
4296
|
if (block.source.type === "text" && typeof block.source.data === "string") {
|
|
3642
4297
|
block.source.data = await redactString(block.source.data, kind);
|
|
4298
|
+
} 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)) {
|
|
4299
|
+
block.source.data = await redactBase64Utf8(block.source.data, redactString, kind);
|
|
4300
|
+
} else if (block.source.type === "base64") {
|
|
4301
|
+
const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
|
|
4302
|
+
if (blockType !== "image" && blockType !== "input_image") {
|
|
4303
|
+
noteBinary(mediaType);
|
|
4304
|
+
}
|
|
3643
4305
|
}
|
|
3644
4306
|
if (typeof block.source.content === "string") {
|
|
3645
4307
|
block.source.content = await redactString(block.source.content, kind);
|
|
@@ -3650,13 +4312,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
3650
4312
|
if (typeof block.arguments === "string") {
|
|
3651
4313
|
block.arguments = await redactJsonStringOrText(block.arguments, kind);
|
|
3652
4314
|
}
|
|
3653
|
-
if (
|
|
4315
|
+
if (typeof block.input === "string") {
|
|
4316
|
+
block.input = await redactJsonStringOrText(block.input, kind);
|
|
4317
|
+
} else if (isPlainObject(block.input)) {
|
|
3654
4318
|
block.input = await redactObjectStrings(block.input, kind);
|
|
3655
4319
|
}
|
|
3656
4320
|
}
|
|
3657
4321
|
}
|
|
3658
4322
|
async function redactObjectStrings(value, kind) {
|
|
3659
4323
|
if (typeof value === "string") return redactString(value, kind);
|
|
4324
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && Math.abs(value) >= 1e9) {
|
|
4325
|
+
const asText = String(value);
|
|
4326
|
+
const redacted = await redactString(asText, kind);
|
|
4327
|
+
return redacted !== asText ? redacted : value;
|
|
4328
|
+
}
|
|
3660
4329
|
if (Array.isArray(value)) {
|
|
3661
4330
|
const out = [];
|
|
3662
4331
|
for (const item of value) out.push(await redactObjectStrings(item, kind));
|
|
@@ -3688,6 +4357,31 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
3688
4357
|
if (typeof clone.instructions === "string") {
|
|
3689
4358
|
clone.instructions = await redactString(clone.instructions, "system");
|
|
3690
4359
|
}
|
|
4360
|
+
if (typeof clone.prompt === "string") {
|
|
4361
|
+
clone.prompt = await redactString(clone.prompt, "message");
|
|
4362
|
+
} else if (Array.isArray(clone.prompt)) {
|
|
4363
|
+
for (let i = 0; i < clone.prompt.length; i++) {
|
|
4364
|
+
const entry = clone.prompt[i];
|
|
4365
|
+
if (typeof entry === "string") {
|
|
4366
|
+
clone.prompt[i] = await redactString(entry, "message");
|
|
4367
|
+
}
|
|
4368
|
+
}
|
|
4369
|
+
}
|
|
4370
|
+
if (typeof clone.user === "string") {
|
|
4371
|
+
clone.user = await redactString(clone.user, "tool_description");
|
|
4372
|
+
}
|
|
4373
|
+
if (isPlainObject(clone.metadata)) {
|
|
4374
|
+
clone.metadata = await redactObjectStrings(clone.metadata, "tool_description");
|
|
4375
|
+
}
|
|
4376
|
+
if (Array.isArray(clone.requests)) {
|
|
4377
|
+
for (const batchItem of clone.requests) {
|
|
4378
|
+
if (isPlainObject(batchItem) && isPlainObject(batchItem.params)) {
|
|
4379
|
+
batchItem.params = await redactLlmRequestBody(batchItem.params, redactString, {
|
|
4380
|
+
mutate: true
|
|
4381
|
+
});
|
|
4382
|
+
}
|
|
4383
|
+
}
|
|
4384
|
+
}
|
|
3691
4385
|
async function redactToolEntries(entries) {
|
|
3692
4386
|
for (const tool of entries) {
|
|
3693
4387
|
if (!isPlainObject(tool)) continue;
|
|
@@ -3712,11 +4406,29 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
3712
4406
|
for (const msg of clone.messages) {
|
|
3713
4407
|
if (!isPlainObject(msg)) continue;
|
|
3714
4408
|
const msgKind = msg.role === "system" || msg.role === "developer" ? "system" : "message";
|
|
4409
|
+
if (typeof msg.name === "string") {
|
|
4410
|
+
msg.name = await redactString(msg.name, "tool_description");
|
|
4411
|
+
}
|
|
3715
4412
|
if (typeof msg.content === "string") {
|
|
3716
4413
|
msg.content = await redactString(msg.content, msgKind);
|
|
3717
4414
|
} else if (Array.isArray(msg.content)) {
|
|
3718
4415
|
await redactContentBlocks(msg.content, msgKind);
|
|
3719
4416
|
}
|
|
4417
|
+
if (typeof msg.reasoning_content === "string") {
|
|
4418
|
+
msg.reasoning_content = await redactString(msg.reasoning_content, msgKind);
|
|
4419
|
+
}
|
|
4420
|
+
if (typeof msg.reasoning === "string") {
|
|
4421
|
+
msg.reasoning = await redactString(msg.reasoning, msgKind);
|
|
4422
|
+
}
|
|
4423
|
+
if (typeof msg.refusal === "string") {
|
|
4424
|
+
msg.refusal = await redactString(msg.refusal, msgKind);
|
|
4425
|
+
}
|
|
4426
|
+
if (isPlainObject(msg.function_call) && typeof msg.function_call.arguments === "string") {
|
|
4427
|
+
msg.function_call.arguments = await redactJsonStringOrText(
|
|
4428
|
+
msg.function_call.arguments,
|
|
4429
|
+
msgKind
|
|
4430
|
+
);
|
|
4431
|
+
}
|
|
3720
4432
|
if (Array.isArray(msg.tool_calls)) {
|
|
3721
4433
|
for (const call of msg.tool_calls) {
|
|
3722
4434
|
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
@@ -3751,6 +4463,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
|
3751
4463
|
} else if (Array.isArray(item.output)) {
|
|
3752
4464
|
await redactContentBlocks(item.output, itemKind);
|
|
3753
4465
|
}
|
|
4466
|
+
if (typeof item.input === "string") {
|
|
4467
|
+
item.input = await redactJsonStringOrText(item.input, itemKind);
|
|
4468
|
+
} else if (isPlainObject(item.input)) {
|
|
4469
|
+
item.input = await redactObjectStrings(item.input, itemKind);
|
|
4470
|
+
}
|
|
4471
|
+
if (typeof item.reasoning_content === "string") {
|
|
4472
|
+
item.reasoning_content = await redactString(item.reasoning_content, itemKind);
|
|
4473
|
+
}
|
|
4474
|
+
if (typeof item.reasoning === "string") {
|
|
4475
|
+
item.reasoning = await redactString(item.reasoning, itemKind);
|
|
4476
|
+
}
|
|
4477
|
+
if (typeof item.refusal === "string") {
|
|
4478
|
+
item.refusal = await redactString(item.refusal, itemKind);
|
|
4479
|
+
}
|
|
3754
4480
|
if (Array.isArray(item.summary)) {
|
|
3755
4481
|
await redactContentBlocks(item.summary, itemKind);
|
|
3756
4482
|
}
|
|
@@ -3793,6 +4519,9 @@ function restoreLlmResponseBody(body, map, options = {}) {
|
|
|
3793
4519
|
if (typeof msg.reasoning_content === "string") {
|
|
3794
4520
|
msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
|
|
3795
4521
|
}
|
|
4522
|
+
if (typeof msg.reasoning === "string") {
|
|
4523
|
+
msg.reasoning = restorePlainText(msg.reasoning, map);
|
|
4524
|
+
}
|
|
3796
4525
|
if (Array.isArray(msg.tool_calls)) {
|
|
3797
4526
|
for (const call of msg.tool_calls) {
|
|
3798
4527
|
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
@@ -3817,6 +4546,11 @@ function restoreLlmResponseBody(body, map, options = {}) {
|
|
|
3817
4546
|
if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(item.name, item.arguments)) {
|
|
3818
4547
|
item.arguments = restoreJsonEncodedText(item.arguments, map);
|
|
3819
4548
|
}
|
|
4549
|
+
if (typeof item.input === "string" && !shouldSkipToolArgRestore(item.name, item.input)) {
|
|
4550
|
+
item.input = restorePlainText(item.input, map);
|
|
4551
|
+
} else if (isPlainObject(item.input) && !isMaskeraVaultToolName(item.name)) {
|
|
4552
|
+
item.input = restoreJsonLeaves(item.input, map);
|
|
4553
|
+
}
|
|
3820
4554
|
if (Array.isArray(item.content)) {
|
|
3821
4555
|
for (const part of item.content) {
|
|
3822
4556
|
if (isPlainObject(part) && typeof part.text === "string") {
|
|
@@ -3970,6 +4704,11 @@ data: ${JSON.stringify({
|
|
|
3970
4704
|
events.push(
|
|
3971
4705
|
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
|
|
3972
4706
|
);
|
|
4707
|
+
} else if (key.startsWith("openai_chat_reasoning_plain:")) {
|
|
4708
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
4709
|
+
events.push(
|
|
4710
|
+
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning: tail } }] })}`
|
|
4711
|
+
);
|
|
3973
4712
|
} else if (key.startsWith("resp_reasoning:")) {
|
|
3974
4713
|
const [, outputIdx, summaryIdx] = key.split(":");
|
|
3975
4714
|
events.push(
|
|
@@ -4103,6 +4842,11 @@ data: ${JSON.stringify({
|
|
|
4103
4842
|
delta.reasoning_content
|
|
4104
4843
|
);
|
|
4105
4844
|
}
|
|
4845
|
+
if (typeof delta.reasoning === "string") {
|
|
4846
|
+
delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`).push(
|
|
4847
|
+
delta.reasoning
|
|
4848
|
+
);
|
|
4849
|
+
}
|
|
4106
4850
|
if (Array.isArray(delta.tool_calls)) {
|
|
4107
4851
|
for (const call of delta.tool_calls) {
|
|
4108
4852
|
if (!isPlainObject(call)) continue;
|
|
@@ -4141,6 +4885,12 @@ data: ${JSON.stringify({
|
|
|
4141
4885
|
const d = choice.delta;
|
|
4142
4886
|
d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
|
|
4143
4887
|
}
|
|
4888
|
+
const reasoningPlainTail = flushStream(`openai_chat_reasoning_plain:${cIdx}`);
|
|
4889
|
+
if (reasoningPlainTail) {
|
|
4890
|
+
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
4891
|
+
const d = choice.delta;
|
|
4892
|
+
d.reasoning = (typeof d.reasoning === "string" ? d.reasoning : "") + reasoningPlainTail;
|
|
4893
|
+
}
|
|
4144
4894
|
const toolPrefix = `openai_chat_tool:${cIdx}:`;
|
|
4145
4895
|
for (const key of [...bufferedToolArgs.keys()]) {
|
|
4146
4896
|
if (!key.startsWith(toolPrefix)) continue;
|
|
@@ -4334,10 +5084,10 @@ ${joined}` : joined;
|
|
|
4334
5084
|
sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
4335
5085
|
let out = "";
|
|
4336
5086
|
for (; ; ) {
|
|
4337
|
-
const
|
|
4338
|
-
if (
|
|
4339
|
-
const block = sseBuffer.slice(0,
|
|
4340
|
-
sseBuffer = sseBuffer.slice(
|
|
5087
|
+
const sep3 = sseBuffer.indexOf("\n\n");
|
|
5088
|
+
if (sep3 < 0) break;
|
|
5089
|
+
const block = sseBuffer.slice(0, sep3);
|
|
5090
|
+
sseBuffer = sseBuffer.slice(sep3 + 2);
|
|
4341
5091
|
out += `${processEventBlock(block)}
|
|
4342
5092
|
|
|
4343
5093
|
`;
|
|
@@ -4378,6 +5128,38 @@ var INSPECTOR_SECURITY_HEADERS = {
|
|
|
4378
5128
|
"cache-control": "no-store"
|
|
4379
5129
|
};
|
|
4380
5130
|
var LOOPBACK_HOST_RE = /^(127\.0\.0\.1|localhost|\[::1\])(?::(\d{1,5}))?$/i;
|
|
5131
|
+
var LOOPBACK_BIND_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
5132
|
+
function isLoopbackBindHost(host) {
|
|
5133
|
+
return LOOPBACK_BIND_HOSTS.has(host.trim().toLowerCase());
|
|
5134
|
+
}
|
|
5135
|
+
function isLoopbackRemoteAddress(remoteAddress) {
|
|
5136
|
+
if (!remoteAddress) return false;
|
|
5137
|
+
const normalized = remoteAddress.trim().toLowerCase();
|
|
5138
|
+
return normalized === "127.0.0.1" || normalized === "::1" || normalized === "::ffff:127.0.0.1";
|
|
5139
|
+
}
|
|
5140
|
+
var InvalidRequestPathError = class extends Error {
|
|
5141
|
+
constructor() {
|
|
5142
|
+
super(...arguments);
|
|
5143
|
+
this.statusCode = 400;
|
|
5144
|
+
}
|
|
5145
|
+
};
|
|
5146
|
+
function canonicalizeRequestPath(urlPath) {
|
|
5147
|
+
const rawPathname = urlPath.split("?")[0] ?? urlPath;
|
|
5148
|
+
if (rawPathname.includes("\0")) {
|
|
5149
|
+
throw new InvalidRequestPathError("Request path contains NUL byte.");
|
|
5150
|
+
}
|
|
5151
|
+
let decoded;
|
|
5152
|
+
try {
|
|
5153
|
+
decoded = decodeURIComponent(rawPathname);
|
|
5154
|
+
} catch {
|
|
5155
|
+
throw new InvalidRequestPathError("Malformed percent-encoding in request path.");
|
|
5156
|
+
}
|
|
5157
|
+
if (decoded.includes("\0")) {
|
|
5158
|
+
throw new InvalidRequestPathError("Decoded request path contains NUL byte.");
|
|
5159
|
+
}
|
|
5160
|
+
const normalized = posix.normalize(decoded.replace(/\\+/g, "/"));
|
|
5161
|
+
return normalized.length > 1 ? normalized.replace(/\/+$/, "") : normalized;
|
|
5162
|
+
}
|
|
4381
5163
|
function isLoopbackHost(hostHeader, boundHost, boundPort, requirePresent = false) {
|
|
4382
5164
|
if (!hostHeader) return !requirePresent;
|
|
4383
5165
|
const raw = hostHeader.trim().toLowerCase();
|
|
@@ -4492,8 +5274,8 @@ async function readRequestBody(req) {
|
|
|
4492
5274
|
return Buffer.concat(chunks);
|
|
4493
5275
|
}
|
|
4494
5276
|
function shouldRedactPath(pathname) {
|
|
4495
|
-
const clean = (pathname
|
|
4496
|
-
return clean.endsWith("/messages") || clean.endsWith("/messages/count_tokens") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
|
|
5277
|
+
const clean = canonicalizeRequestPath(pathname).toLowerCase();
|
|
5278
|
+
return clean.endsWith("/messages") || clean.endsWith("/messages/count_tokens") || clean.endsWith("/messages/batches") || clean.endsWith("/chat/completions") || clean.endsWith("/completions") || clean.endsWith("/responses") || clean.endsWith("/responses/input_tokens") || clean.endsWith("/responses/compact") || clean.endsWith("/embeddings") || clean.endsWith("/moderations");
|
|
4497
5279
|
}
|
|
4498
5280
|
var APPROVAL_STRICTNESS = {
|
|
4499
5281
|
automatic: 0,
|
|
@@ -4525,6 +5307,11 @@ function parseScopedMcpPolicy(urlPath, base) {
|
|
|
4525
5307
|
}
|
|
4526
5308
|
async function startMaskeraProxy(options = {}) {
|
|
4527
5309
|
const host = options.host ?? "127.0.0.1";
|
|
5310
|
+
if (!options.allowNonLoopback && !isLoopbackBindHost(host)) {
|
|
5311
|
+
throw new Error(
|
|
5312
|
+
`Refusing to bind maskera-proxy to non-loopback host "${host}". Use 127.0.0.1, localhost, or ::1 (or set allowNonLoopback: true only behind external network isolation).`
|
|
5313
|
+
);
|
|
5314
|
+
}
|
|
4528
5315
|
const requestedPort = options.port ?? 8787;
|
|
4529
5316
|
const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
|
|
4530
5317
|
const vault = options.vault ?? new SessionVault();
|
|
@@ -4548,7 +5335,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
4548
5335
|
const closedMcpSessions = /* @__PURE__ */ new Set();
|
|
4549
5336
|
if (auditLogPath) {
|
|
4550
5337
|
await mkdir(dirname(auditLogPath), { recursive: true });
|
|
4551
|
-
await appendFile(auditLogPath, "", "utf8");
|
|
5338
|
+
await appendFile(auditLogPath, "", { encoding: "utf8", mode: 384 });
|
|
4552
5339
|
}
|
|
4553
5340
|
let totalRequests = 0;
|
|
4554
5341
|
let totalRedactions = 0;
|
|
@@ -4612,11 +5399,13 @@ async function startMaskeraProxy(options = {}) {
|
|
|
4612
5399
|
});
|
|
4613
5400
|
auditChain = auditChain.then(
|
|
4614
5401
|
() => appendFile(auditLogPath, `${auditLine}
|
|
4615
|
-
`, "utf8").catch(
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
|
|
4619
|
-
|
|
5402
|
+
`, { encoding: "utf8", mode: 384 }).catch(
|
|
5403
|
+
(err) => {
|
|
5404
|
+
log(
|
|
5405
|
+
`[maskera-proxy] audit log write error: ${err instanceof Error ? err.message : String(err)}`
|
|
5406
|
+
);
|
|
5407
|
+
}
|
|
5408
|
+
)
|
|
4620
5409
|
);
|
|
4621
5410
|
}
|
|
4622
5411
|
}
|
|
@@ -4628,7 +5417,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
4628
5417
|
const normalizedPath = normalizeInspectorPath(pathname);
|
|
4629
5418
|
const isInspectorRoute = normalizedPath === "/_maskera" || normalizedPath.startsWith("/_maskera/") || normalizedPath.includes("/_maskera/") || normalizedPath.endsWith("/_maskera");
|
|
4630
5419
|
if (isInspectorRoute || pathname === "/healthz") {
|
|
4631
|
-
if (!isLoopbackHost(req.headers.host, host, boundPort)) {
|
|
5420
|
+
if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort)) {
|
|
4632
5421
|
res.writeHead(403, {
|
|
4633
5422
|
...INSPECTOR_SECURITY_HEADERS,
|
|
4634
5423
|
"content-type": "application/json; charset=utf-8"
|
|
@@ -4845,7 +5634,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
4845
5634
|
return;
|
|
4846
5635
|
}
|
|
4847
5636
|
if (normalizedPath === "/mcp" || normalizedPath === "/mcp/") {
|
|
4848
|
-
if (!isLoopbackHost(req.headers.host, host, boundPort, true)) {
|
|
5637
|
+
if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort, true)) {
|
|
4849
5638
|
res.writeHead(403, {
|
|
4850
5639
|
...INSPECTOR_SECURITY_HEADERS,
|
|
4851
5640
|
"content-type": "application/json; charset=utf-8"
|
|
@@ -4868,6 +5657,8 @@ async function startMaskeraProxy(options = {}) {
|
|
|
4868
5657
|
if (incomingSessionId) {
|
|
4869
5658
|
mcpSessions.delete(incomingSessionId);
|
|
4870
5659
|
closedMcpSessions.add(incomingSessionId);
|
|
5660
|
+
vault.clearOwner(`mcp:${incomingSessionId}`);
|
|
5661
|
+
approvals.clearOwner(`mcp:${incomingSessionId}`);
|
|
4871
5662
|
if (closedMcpSessions.size > 500) {
|
|
4872
5663
|
const first = closedMcpSessions.values().next().value;
|
|
4873
5664
|
if (first !== void 0) closedMcpSessions.delete(first);
|
|
@@ -4925,23 +5716,37 @@ async function startMaskeraProxy(options = {}) {
|
|
|
4925
5716
|
);
|
|
4926
5717
|
return;
|
|
4927
5718
|
}
|
|
5719
|
+
const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
|
|
5720
|
+
const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
|
|
5721
|
+
if (!isInit && incomingSessionId && !mcpSessions.has(incomingSessionId)) {
|
|
5722
|
+
res.writeHead(404, {
|
|
5723
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
5724
|
+
"content-type": "application/json; charset=utf-8"
|
|
5725
|
+
});
|
|
5726
|
+
res.end(JSON.stringify({ error: "Unknown MCP session." }));
|
|
5727
|
+
return;
|
|
5728
|
+
}
|
|
4928
5729
|
const sessionBasePolicy = (incomingSessionId ? mcpSessions.get(incomingSessionId) : void 0) ?? baseMcpPolicy;
|
|
4929
5730
|
const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
|
|
4930
5731
|
const mcpServer = getMcpServer();
|
|
4931
|
-
const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
|
|
4932
|
-
const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
|
|
4933
5732
|
let responseSessionId = incomingSessionId;
|
|
4934
5733
|
if (isInit) {
|
|
4935
5734
|
responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
|
|
4936
5735
|
if (mcpSessions.size >= 200) {
|
|
4937
5736
|
const oldest = mcpSessions.keys().next().value;
|
|
4938
|
-
if (oldest !== void 0)
|
|
5737
|
+
if (oldest !== void 0) {
|
|
5738
|
+
mcpSessions.delete(oldest);
|
|
5739
|
+
vault.clearOwner(`mcp:${oldest}`);
|
|
5740
|
+
approvals.clearOwner(`mcp:${oldest}`);
|
|
5741
|
+
}
|
|
4939
5742
|
}
|
|
4940
5743
|
mcpSessions.set(responseSessionId, effectivePolicy);
|
|
4941
5744
|
}
|
|
5745
|
+
const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
|
|
5746
|
+
const scopedPolicy = { ...effectivePolicy, sessionOwner };
|
|
4942
5747
|
const responses = [];
|
|
4943
5748
|
for (const msg of messages) {
|
|
4944
|
-
const reply = await mcpServer.handleMessage(msg,
|
|
5749
|
+
const reply = await mcpServer.handleMessage(msg, scopedPolicy);
|
|
4945
5750
|
if (reply !== null) responses.push(reply);
|
|
4946
5751
|
}
|
|
4947
5752
|
const mcpHeaders = {
|
|
@@ -4977,18 +5782,59 @@ async function startMaskeraProxy(options = {}) {
|
|
|
4977
5782
|
anthropicUpstream,
|
|
4978
5783
|
openaiUpstream
|
|
4979
5784
|
});
|
|
5785
|
+
if (!forwardPath.startsWith("/") || forwardPath.startsWith("//")) {
|
|
5786
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
5787
|
+
res.end(JSON.stringify({ error: { message: "Invalid request path." } }));
|
|
5788
|
+
return;
|
|
5789
|
+
}
|
|
5790
|
+
let needsRedaction;
|
|
5791
|
+
try {
|
|
5792
|
+
needsRedaction = shouldRedactPath(forwardPath);
|
|
5793
|
+
} catch (err) {
|
|
5794
|
+
if (err instanceof InvalidRequestPathError) {
|
|
5795
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
5796
|
+
res.end(JSON.stringify({ error: { message: err.message } }));
|
|
5797
|
+
return;
|
|
5798
|
+
}
|
|
5799
|
+
throw err;
|
|
5800
|
+
}
|
|
4980
5801
|
const upstreamUrl = `${baseUrl}${forwardPath}`;
|
|
5802
|
+
try {
|
|
5803
|
+
if (new URL(upstreamUrl).origin !== new URL(baseUrl).origin) {
|
|
5804
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
5805
|
+
res.end(JSON.stringify({ error: { message: "Upstream origin mismatch." } }));
|
|
5806
|
+
return;
|
|
5807
|
+
}
|
|
5808
|
+
} catch {
|
|
5809
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
5810
|
+
res.end(JSON.stringify({ error: { message: "Invalid upstream URL." } }));
|
|
5811
|
+
return;
|
|
5812
|
+
}
|
|
4981
5813
|
const rawBody = method === "GET" || method === "HEAD" ? void 0 : await readRequestBody(req);
|
|
4982
|
-
|
|
4983
|
-
const
|
|
5814
|
+
let sessionId = deriveProxySessionId(req.headers);
|
|
5815
|
+
const proxyVaultOwner = "proxy";
|
|
5816
|
+
const blockBinary = options.blockBinary === true;
|
|
4984
5817
|
const stats = { redactions: 0, counts: {} };
|
|
4985
5818
|
const redactedPreview = [];
|
|
5819
|
+
const binaryAttachments = /* @__PURE__ */ new Set();
|
|
5820
|
+
let requestWarnings;
|
|
4986
5821
|
let outgoingBody = rawBody;
|
|
4987
5822
|
let rewroteRequestBody = false;
|
|
4988
5823
|
const contentType = String(req.headers["content-type"] ?? "").trim().toLowerCase();
|
|
4989
5824
|
const contentEncoding = typeof req.headers["content-encoding"] === "string" ? req.headers["content-encoding"] : void 0;
|
|
4990
5825
|
const mayBeJson = contentType === "" || contentType.includes("json") || contentType.startsWith("text/plain");
|
|
4991
|
-
if (rawBody && rawBody.byteLength > 0 &&
|
|
5826
|
+
if (rawBody && rawBody.byteLength > 0 && needsRedaction) {
|
|
5827
|
+
if (!mayBeJson) {
|
|
5828
|
+
res.writeHead(415, { "content-type": "application/json; charset=utf-8" });
|
|
5829
|
+
res.end(
|
|
5830
|
+
JSON.stringify({
|
|
5831
|
+
error: {
|
|
5832
|
+
message: `Refusing to forward unredacted content-type "${contentType}" on LLM redaction endpoint (fail-closed).`
|
|
5833
|
+
}
|
|
5834
|
+
})
|
|
5835
|
+
);
|
|
5836
|
+
return;
|
|
5837
|
+
}
|
|
4992
5838
|
let decodedBody;
|
|
4993
5839
|
try {
|
|
4994
5840
|
decodedBody = decodeRequestBody(rawBody, contentEncoding);
|
|
@@ -5010,48 +5856,110 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5010
5856
|
res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
|
|
5011
5857
|
return;
|
|
5012
5858
|
}
|
|
5013
|
-
if (isPlainObject(parsed)) {
|
|
5014
|
-
|
|
5015
|
-
|
|
5016
|
-
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
5021
|
-
|
|
5022
|
-
|
|
5023
|
-
|
|
5024
|
-
|
|
5025
|
-
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5859
|
+
if (!isPlainObject(parsed)) {
|
|
5860
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
5861
|
+
res.end(JSON.stringify({ error: { message: "Expected JSON object request body." } }));
|
|
5862
|
+
return;
|
|
5863
|
+
}
|
|
5864
|
+
sessionId = deriveProxySessionId(req.headers, parsed);
|
|
5865
|
+
let redactedObj;
|
|
5866
|
+
try {
|
|
5867
|
+
const redactChunk = async (chunk, forceRules) => {
|
|
5868
|
+
if (!chunk.trim()) return chunk;
|
|
5869
|
+
const { result } = await engine.redact(chunk, {
|
|
5870
|
+
mode: forceRules ? "rules" : void 0,
|
|
5871
|
+
profile: options.profile,
|
|
5872
|
+
customTerms: options.customTerms
|
|
5873
|
+
});
|
|
5874
|
+
const applied = vault.apply(chunk, result, sessionId, proxyVaultOwner);
|
|
5875
|
+
stats.redactions += applied.totalRedactions;
|
|
5876
|
+
mergeCounts(stats.counts, applied.counts);
|
|
5877
|
+
if (redactedPreview.length < 6) {
|
|
5878
|
+
const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
|
|
5879
|
+
redactedPreview.push(snippet);
|
|
5880
|
+
}
|
|
5881
|
+
return applied.redacted;
|
|
5882
|
+
};
|
|
5883
|
+
redactedObj = await redactLlmRequestBody(
|
|
5884
|
+
parsed,
|
|
5885
|
+
async (text, kind) => {
|
|
5886
|
+
if (!text.trim()) return text;
|
|
5887
|
+
if (kind === "tool_description") {
|
|
5888
|
+
return redactChunk(text, true);
|
|
5889
|
+
}
|
|
5890
|
+
if (kind === "system") {
|
|
5891
|
+
if (text.length >= 600 && text.includes("\n\n")) {
|
|
5892
|
+
const parts = text.split(/(\n{2,})/);
|
|
5893
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
5894
|
+
const para = parts[i] ?? "";
|
|
5895
|
+
if (!para.trim()) continue;
|
|
5896
|
+
parts[i] = await redactChunk(para, isLikelyEnglishSystemPrompt(para));
|
|
5897
|
+
}
|
|
5898
|
+
return parts.join("");
|
|
5031
5899
|
}
|
|
5032
|
-
return
|
|
5033
|
-
}
|
|
5034
|
-
|
|
5035
|
-
|
|
5036
|
-
|
|
5900
|
+
return redactChunk(text, isLikelyEnglishSystemPrompt(text));
|
|
5901
|
+
}
|
|
5902
|
+
return redactChunk(text, false);
|
|
5903
|
+
},
|
|
5904
|
+
{
|
|
5905
|
+
mutate: true,
|
|
5906
|
+
onBinaryAttachment: (kind) => {
|
|
5907
|
+
binaryAttachments.add(kind);
|
|
5908
|
+
}
|
|
5909
|
+
}
|
|
5910
|
+
);
|
|
5911
|
+
} catch (err) {
|
|
5912
|
+
recordAuditAndInspector({
|
|
5913
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5914
|
+
method,
|
|
5915
|
+
path: forwardPath,
|
|
5916
|
+
upstream: baseUrl,
|
|
5917
|
+
sessionId,
|
|
5918
|
+
status: 502,
|
|
5919
|
+
streamed: false,
|
|
5920
|
+
durationMs: Date.now() - startedAt,
|
|
5921
|
+
redactions: stats.redactions,
|
|
5922
|
+
counts: stats.counts,
|
|
5923
|
+
redactedPreview
|
|
5924
|
+
});
|
|
5925
|
+
throw err;
|
|
5926
|
+
}
|
|
5927
|
+
if (binaryAttachments.size > 0) {
|
|
5928
|
+
const kinds = [...binaryAttachments];
|
|
5929
|
+
const warning = `Uninspectable binary attachment(s) without OCR: ${kinds.join(", ")}`;
|
|
5930
|
+
requestWarnings = [warning];
|
|
5931
|
+
log(`[maskera-proxy] warning: ${warning}`);
|
|
5932
|
+
if (blockBinary) {
|
|
5037
5933
|
recordAuditAndInspector({
|
|
5038
5934
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5039
5935
|
method,
|
|
5040
5936
|
path: forwardPath,
|
|
5041
5937
|
upstream: baseUrl,
|
|
5042
5938
|
sessionId,
|
|
5043
|
-
status:
|
|
5939
|
+
status: 415,
|
|
5044
5940
|
streamed: false,
|
|
5045
5941
|
durationMs: Date.now() - startedAt,
|
|
5046
5942
|
redactions: stats.redactions,
|
|
5047
5943
|
counts: stats.counts,
|
|
5048
|
-
redactedPreview
|
|
5944
|
+
redactedPreview,
|
|
5945
|
+
warnings: requestWarnings
|
|
5946
|
+
});
|
|
5947
|
+
res.writeHead(415, {
|
|
5948
|
+
"content-type": "application/json; charset=utf-8",
|
|
5949
|
+
"x-maskera-warning": "uninspectable-binary-attachment"
|
|
5049
5950
|
});
|
|
5050
|
-
|
|
5951
|
+
res.end(
|
|
5952
|
+
JSON.stringify({
|
|
5953
|
+
error: {
|
|
5954
|
+
message: `Refusing to forward uninspectable binary attachment(s) (${kinds.join(", ")}) when --block-binary is enabled.`
|
|
5955
|
+
}
|
|
5956
|
+
})
|
|
5957
|
+
);
|
|
5958
|
+
return;
|
|
5051
5959
|
}
|
|
5052
|
-
outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
|
|
5053
|
-
rewroteRequestBody = true;
|
|
5054
5960
|
}
|
|
5961
|
+
outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
|
|
5962
|
+
rewroteRequestBody = true;
|
|
5055
5963
|
}
|
|
5056
5964
|
const forwardHeaders = new Headers();
|
|
5057
5965
|
for (const [k, v] of Object.entries(req.headers)) {
|
|
@@ -5078,6 +5986,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5078
5986
|
method,
|
|
5079
5987
|
headers: forwardHeaders,
|
|
5080
5988
|
body: outgoingBody ? new Uint8Array(outgoingBody) : void 0,
|
|
5989
|
+
redirect: "manual",
|
|
5081
5990
|
signal: abortController.signal
|
|
5082
5991
|
});
|
|
5083
5992
|
} catch (err) {
|
|
@@ -5107,7 +6016,10 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5107
6016
|
}
|
|
5108
6017
|
});
|
|
5109
6018
|
outHeaders["x-maskera-redacted"] = String(stats.redactions);
|
|
5110
|
-
|
|
6019
|
+
if (requestWarnings) {
|
|
6020
|
+
outHeaders["x-maskera-warning"] = "uninspectable-binary-attachment";
|
|
6021
|
+
}
|
|
6022
|
+
const sessionMap = restoreResponses ? vault.getMap(sessionId, proxyVaultOwner) : {};
|
|
5111
6023
|
const hasMap = Object.keys(sessionMap).length > 0;
|
|
5112
6024
|
const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
|
|
5113
6025
|
const isSse = resContentType.includes("text/event-stream");
|
|
@@ -5158,7 +6070,8 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5158
6070
|
durationMs: durationMs2,
|
|
5159
6071
|
redactions: stats.redactions,
|
|
5160
6072
|
counts: stats.counts,
|
|
5161
|
-
redactedPreview
|
|
6073
|
+
redactedPreview,
|
|
6074
|
+
...requestWarnings ? { warnings: requestWarnings } : {}
|
|
5162
6075
|
});
|
|
5163
6076
|
log(
|
|
5164
6077
|
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${durationMs2}ms`
|
|
@@ -5190,7 +6103,8 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5190
6103
|
durationMs: durationMs2,
|
|
5191
6104
|
redactions: stats.redactions,
|
|
5192
6105
|
counts: stats.counts,
|
|
5193
|
-
redactedPreview
|
|
6106
|
+
redactedPreview,
|
|
6107
|
+
...requestWarnings ? { warnings: requestWarnings } : {}
|
|
5194
6108
|
});
|
|
5195
6109
|
log(
|
|
5196
6110
|
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${durationMs2}ms`
|
|
@@ -5213,7 +6127,8 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5213
6127
|
durationMs,
|
|
5214
6128
|
redactions: stats.redactions,
|
|
5215
6129
|
counts: stats.counts,
|
|
5216
|
-
redactedPreview
|
|
6130
|
+
redactedPreview,
|
|
6131
|
+
...requestWarnings ? { warnings: requestWarnings } : {}
|
|
5217
6132
|
});
|
|
5218
6133
|
log(
|
|
5219
6134
|
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${durationMs}ms`
|
|
@@ -5610,6 +6525,7 @@ async function runWrap(options) {
|
|
|
5610
6525
|
profile: options.profile,
|
|
5611
6526
|
customTerms: options.customTerms,
|
|
5612
6527
|
restoreResponses: options.restoreResponses,
|
|
6528
|
+
blockBinary: options.blockBinary,
|
|
5613
6529
|
auditLogPath: options.auditLogPath
|
|
5614
6530
|
});
|
|
5615
6531
|
let startupReceipt = null;
|
|
@@ -5705,6 +6621,6 @@ async function runWrap(options) {
|
|
|
5705
6621
|
}
|
|
5706
6622
|
}
|
|
5707
6623
|
|
|
5708
|
-
export { ApprovalBroker, LAUNCHD_LABEL, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, ProxyInspector, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, SYSTEMD_UNIT, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createModelProgressLogger, createSseRestorer, detectInstalledClients, extractGuardText, formatDoctorReport, isInstallClient, openUrlInBrowser, redactLlmRequestBody, renderInspectorHtml, renderLaunchdPlist, renderMaskeraPrompt, renderSystemdUnit, restoreLlmResponseBody, runDoctor, runGuard, runGuardViaWarmProxy, runInstall, runService, runWrap, startMaskeraProxy, writeDoctorReceipt };
|
|
6624
|
+
export { ApprovalBroker, LAUNCHD_LABEL, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, ProxyInspector, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, SYSTEMD_UNIT, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createModelProgressLogger, createSseRestorer, deriveProxySessionId, detectInstalledClients, extractGuardText, formatDoctorReport, isInstallClient, isLikelyEnglishSystemPrompt, normalizeMixedScriptHomoglyphs, openUrlInBrowser, redactLlmRequestBody, renderInspectorHtml, renderLaunchdPlist, renderMaskeraPrompt, renderSystemdUnit, restoreLlmResponseBody, runDoctor, runGuard, runGuardViaWarmProxy, runInstall, runService, runWrap, startMaskeraProxy, writeDoctorReceipt };
|
|
5709
6625
|
//# sourceMappingURL=index.js.map
|
|
5710
6626
|
//# sourceMappingURL=index.js.map
|