@maskera/mcp 0.4.1 → 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/dist/index.js CHANGED
@@ -1,9 +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';
4
+ import { dirname, resolve, join, isAbsolute, relative, sep, delimiter, extname, posix } from 'path';
5
5
  import { createRequire } from 'module';
6
- import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
6
+ import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
7
7
  import { spawn, spawnSync } from 'child_process';
8
8
  import { homedir } from 'os';
9
9
  import { createServer } from 'http';
@@ -12,6 +12,11 @@ import * as zlib from 'zlib';
12
12
  // src/approvals.ts
13
13
  var DEFAULT_TTL_MS = 5 * 60 * 1e3;
14
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
+ }
15
20
  var ApprovalBroker = class {
16
21
  constructor(ttlMs = DEFAULT_TTL_MS) {
17
22
  this.records = /* @__PURE__ */ new Map();
@@ -64,6 +69,7 @@ var ApprovalBroker = class {
64
69
  decidedAt: null
65
70
  };
66
71
  this.records.set(id, {
72
+ owner: normalizeOwner(input.owner),
67
73
  summary,
68
74
  expiresAtMs: now + this.ttlMs,
69
75
  execute: input.execute
@@ -88,10 +94,13 @@ var ApprovalBroker = class {
88
94
  this.notify();
89
95
  return { ...record.summary };
90
96
  }
91
- async resume(id) {
97
+ async resume(id, owner) {
92
98
  this.expireStale();
93
99
  const record = this.records.get(id.trim());
94
100
  if (!record) return { status: "not_found" };
101
+ if (owner !== void 0 && record.owner !== normalizeOwner(owner)) {
102
+ return { status: "not_found" };
103
+ }
95
104
  const { status } = record.summary;
96
105
  if (status === "pending" || status === "declined" || status === "expired") {
97
106
  return { status, summary: { ...record.summary } };
@@ -106,6 +115,18 @@ var ApprovalBroker = class {
106
115
  this.notify();
107
116
  return { status: "completed", result, summary: { ...record.summary } };
108
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
+ }
109
130
  clearAll() {
110
131
  this.records.clear();
111
132
  this.notify();
@@ -114,6 +135,119 @@ var ApprovalBroker = class {
114
135
  var WORD_CHAR = /[\p{L}\p{N}_]/u;
115
136
  var DEFAULT_MAX_CACHE_ENTRIES = 512;
116
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
+ }
117
251
  function escapeRegExp(value) {
118
252
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
119
253
  }
@@ -121,7 +255,7 @@ function normalizeCustomTerms(rawTerms) {
121
255
  const unique = /* @__PURE__ */ new Map();
122
256
  for (const raw of rawTerms) {
123
257
  if (typeof raw !== "string") continue;
124
- const trimmed = raw.trim();
258
+ const trimmed = canonicalize(raw.trim()).text.trim();
125
259
  if (trimmed.length < 2 || trimmed.length > 160) continue;
126
260
  const folded = trimmed.toLowerCase();
127
261
  if (!unique.has(folded)) unique.set(folded, trimmed);
@@ -275,12 +409,28 @@ function createMaskeraEngine(options = {}) {
275
409
  }
276
410
  const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
277
411
  if (requestedMode === "rules") {
278
- const result = req.profile === "clinical" ? redactFromDetections(
279
- text,
280
- runDetectors(text, detectors).filter(
281
- (d) => clinicalPrecisionFilter(d, text, "rule")
282
- )
283
- ) : redact(text, { detectors });
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
+ }
284
434
  if (cacheKey) {
285
435
  if (spanCache.size >= maxCacheEntries) {
286
436
  const oldest = spanCache.keys().next().value;
@@ -302,11 +452,36 @@ function createMaskeraEngine(options = {}) {
302
452
  }
303
453
  try {
304
454
  const ner = getRecognizer();
305
- const result = await redactWithNer(text, {
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, {
306
460
  recognizer: ner,
307
461
  detectors,
308
462
  profile: req.profile
309
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
+ );
310
485
  nerLoaded = true;
311
486
  nerError = null;
312
487
  if (cacheKey) {
@@ -598,7 +773,8 @@ function createFileGuard(roots = [process.cwd()]) {
598
773
  }
599
774
  await writeFile(targetReal, content, {
600
775
  encoding: "utf8",
601
- flag: options.overwrite ? "w" : "wx"
776
+ flag: options.overwrite ? "w" : "wx",
777
+ mode: 384
602
778
  }).catch((err) => {
603
779
  if (err.code === "EEXIST") {
604
780
  throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
@@ -674,7 +850,7 @@ function createFileGuard(roots = [process.cwd()]) {
674
850
  matches.push({
675
851
  path: file.relPath,
676
852
  line: i + 1,
677
- lineText: lineText.length > 500 ? `${lineText.slice(0, 500)}...` : lineText
853
+ lineText: lineText.length > 16384 ? lineText.slice(0, 16384) : lineText
678
854
  });
679
855
  if (matches.length >= maxMatches) {
680
856
  truncated = true;
@@ -858,7 +1034,18 @@ ${MASKERA_SKILL_MARKDOWN}`
858
1034
  }
859
1035
  var DEFAULT_MAX_SESSIONS = 100;
860
1036
  var DEFAULT_MAX_ENTITIES_PER_SESSION = 5e3;
1037
+ var DEFAULT_OWNER2 = "default";
861
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
+ }
862
1049
  function valueKey(label, value) {
863
1050
  return `${label.length}:${label}:${value}`;
864
1051
  }
@@ -875,12 +1062,14 @@ var SessionVault = class {
875
1062
  this.maxSessions = Math.max(1, maxSessions);
876
1063
  this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
877
1064
  }
878
- getOrCreate(sessionId) {
1065
+ getOrCreate(sessionId, owner) {
879
1066
  const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
880
- const existing = this.sessions.get(id);
1067
+ const resolvedOwner = normalizeOwner2(owner);
1068
+ const storageKey = ownerStorageKey(resolvedOwner, id);
1069
+ const existing = this.sessions.get(storageKey);
881
1070
  if (existing) {
882
- this.sessions.delete(id);
883
- this.sessions.set(id, existing);
1071
+ this.sessions.delete(storageKey);
1072
+ this.sessions.set(storageKey, existing);
884
1073
  existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
885
1074
  return existing;
886
1075
  }
@@ -891,14 +1080,15 @@ var SessionVault = class {
891
1080
  const now = (/* @__PURE__ */ new Date()).toISOString();
892
1081
  const created = {
893
1082
  id,
1083
+ owner: resolvedOwner,
894
1084
  createdAt: now,
895
1085
  updatedAt: now,
896
1086
  tokenByKey: /* @__PURE__ */ new Map(),
897
- map: {},
1087
+ map: /* @__PURE__ */ Object.create(null),
898
1088
  counters: /* @__PURE__ */ new Map(),
899
1089
  countsByLabel: {}
900
1090
  };
901
- this.sessions.set(id, created);
1091
+ this.sessions.set(storageKey, created);
902
1092
  return created;
903
1093
  }
904
1094
  /**
@@ -906,8 +1096,8 @@ var SessionVault = class {
906
1096
  * the same entity receives the exact same placeholder across multiple calls
907
1097
  * and files in the same session, while avoiding collisions with literal text.
908
1098
  */
909
- apply(originalInput, result, sessionId) {
910
- const session = this.getOrCreate(sessionId);
1099
+ apply(originalInput, result, sessionId, owner) {
1100
+ const session = this.getOrCreate(sessionId, owner);
911
1101
  if (result.redactions.length === 0) {
912
1102
  return {
913
1103
  sessionId: session.id,
@@ -933,7 +1123,7 @@ var SessionVault = class {
933
1123
  for (; ; ) {
934
1124
  next += 1;
935
1125
  const candidate = `[${r.label}_${next}]`;
936
- if (!(candidate in session.map) && !existingTokens?.has(candidate)) {
1126
+ if (!hasOwn(session.map, candidate) && !existingTokens?.has(candidate)) {
937
1127
  token = candidate;
938
1128
  break;
939
1129
  }
@@ -982,7 +1172,8 @@ var SessionVault = class {
982
1172
  if (!normalizedId) {
983
1173
  throw new Error("Provide either session_id or map to restore placeholders.");
984
1174
  }
985
- const session = this.sessions.get(normalizedId);
1175
+ const resolvedOwner = normalizeOwner2(options.owner);
1176
+ const session = this.sessions.get(ownerStorageKey(resolvedOwner, normalizedId));
986
1177
  if (!session) {
987
1178
  throw new Error(`Unknown session_id "${normalizedId}".`);
988
1179
  }
@@ -994,14 +1185,14 @@ var SessionVault = class {
994
1185
  }
995
1186
  /**
996
1187
  * Picks the session that restores `text` when the caller named none.
997
- * A candidate must know every placeholder in the text. When several do and
998
- * would restore it differently, the choice is ambiguous and refused, so a
999
- * missing session_id can never put another document's values into a file.
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.
1000
1190
  */
1001
- resolveSessionFor(text) {
1191
+ resolveSessionFor(text, owner) {
1192
+ const resolvedOwner = normalizeOwner2(owner);
1002
1193
  const tokens = [...new Set(text.match(EXISTING_TOKEN_RE) ?? [])];
1003
1194
  const candidates = [...this.sessions.values()].filter(
1004
- (s) => tokens.every((token) => token in s.map)
1195
+ (s) => s.owner === resolvedOwner && tokens.every((token) => hasOwn(s.map, token))
1005
1196
  );
1006
1197
  if (candidates.length === 0) {
1007
1198
  throw new Error(
@@ -1018,8 +1209,9 @@ var SessionVault = class {
1018
1209
  if (!latest) throw new Error("No local session can restore this text.");
1019
1210
  return latest.id;
1020
1211
  }
1021
- getMap(sessionId) {
1022
- const session = this.sessions.get(sessionId.trim());
1212
+ getMap(sessionId, owner) {
1213
+ const resolvedOwner = normalizeOwner2(owner);
1214
+ const session = this.sessions.get(ownerStorageKey(resolvedOwner, sessionId.trim()));
1023
1215
  return session ? { ...session.map } : {};
1024
1216
  }
1025
1217
  entries() {
@@ -1034,17 +1226,44 @@ var SessionVault = class {
1034
1226
  clearAll() {
1035
1227
  this.sessions.clear();
1036
1228
  }
1037
- list() {
1038
- return [...this.sessions.values()].map((s) => ({
1039
- sessionId: s.id,
1040
- entityCount: Object.keys(s.map).length,
1041
- countsByLabel: { ...s.countsByLabel },
1042
- createdAt: s.createdAt,
1043
- updatedAt: s.updatedAt
1044
- }));
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;
1045
1239
  }
1046
- clear(sessionId) {
1047
- return this.sessions.delete(sessionId.trim());
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;
1048
1267
  }
1049
1268
  get size() {
1050
1269
  return this.sessions.size;
@@ -1502,6 +1721,35 @@ var TOOLS = [
1502
1721
  }
1503
1722
  ];
1504
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;
1505
1753
  function asObject(value) {
1506
1754
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1507
1755
  }
@@ -1541,6 +1789,30 @@ function toolError(message) {
1541
1789
  content: [{ type: "text", text: message }]
1542
1790
  };
1543
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
+ }
1544
1816
  function createMaskeraMcpServer(options = {}) {
1545
1817
  const engine = options.engine ?? createMaskeraEngine();
1546
1818
  const vault = options.vault ?? new SessionVault();
@@ -1552,11 +1824,155 @@ function createMaskeraMcpServer(options = {}) {
1552
1824
  const requestElicitation = options.requestElicitation;
1553
1825
  const onToolCall = options.onToolCall;
1554
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
+ }
1555
1970
  function resolvePolicy(override) {
1556
1971
  return {
1557
1972
  allowRawRestore: override?.allowRawRestore ?? options.allowRawRestore ?? true,
1558
1973
  readOnly: override?.readOnly ?? options.readOnly ?? false,
1559
- approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic"
1974
+ approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic",
1975
+ sessionOwner: override?.sessionOwner ?? options.sessionOwner ?? "default"
1560
1976
  };
1561
1977
  }
1562
1978
  function visibleTools(policy) {
@@ -1579,7 +1995,7 @@ function createMaskeraMcpServer(options = {}) {
1579
1995
  server: SERVER_NAME,
1580
1996
  version: SERVER_VERSION,
1581
1997
  engine: engine.status(),
1582
- active_sessions: vault.size,
1998
+ active_sessions: vault.sizeForOwner(policy.sessionOwner),
1583
1999
  allowed_roots: files.allowedRoots,
1584
2000
  policy: {
1585
2001
  read_only: policy.readOnly,
@@ -1634,6 +2050,7 @@ function createMaskeraMcpServer(options = {}) {
1634
2050
  tool: input.tool,
1635
2051
  reason: input.reason,
1636
2052
  sessionId: input.sessionId,
2053
+ owner: policy.sessionOwner,
1637
2054
  placeholderCount: input.placeholderCount,
1638
2055
  execute: input.execute
1639
2056
  });
@@ -1650,6 +2067,7 @@ function createMaskeraMcpServer(options = {}) {
1650
2067
  async function callTool(name, rawArgs, policy) {
1651
2068
  const startedAt = Date.now();
1652
2069
  const args = asObject(rawArgs);
2070
+ const owner = policy.sessionOwner;
1653
2071
  let telemetrySessionId;
1654
2072
  let telemetryRedactions = 0;
1655
2073
  let telemetryCounts = {};
@@ -1686,7 +2104,8 @@ function createMaskeraMcpServer(options = {}) {
1686
2104
  const applied = vault.apply(
1687
2105
  args.text,
1688
2106
  result,
1689
- typeof args.session_id === "string" ? args.session_id : void 0
2107
+ typeof args.session_id === "string" ? args.session_id : void 0,
2108
+ owner
1690
2109
  );
1691
2110
  telemetrySessionId = applied.sessionId;
1692
2111
  telemetryRedactions = applied.totalRedactions;
@@ -1714,6 +2133,13 @@ function createMaskeraMcpServer(options = {}) {
1714
2133
  return finish(toolOk(payload));
1715
2134
  }
1716
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
+ }
1717
2143
  if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1718
2144
  const explicitMap = args.map && typeof args.map === "object" && !Array.isArray(args.map) ? Object.fromEntries(
1719
2145
  Object.entries(args.map).filter(
@@ -1724,7 +2150,8 @@ function createMaskeraMcpServer(options = {}) {
1724
2150
  telemetrySessionId = sessionIdArg;
1725
2151
  const preview = vault.restore(args.text, {
1726
2152
  sessionId: sessionIdArg,
1727
- map: explicitMap
2153
+ map: explicitMap,
2154
+ owner
1728
2155
  });
1729
2156
  return finish(
1730
2157
  await gateRawPiiExport({
@@ -1749,7 +2176,7 @@ function createMaskeraMcpServer(options = {}) {
1749
2176
  return finish(toolError("Missing required non-empty string: request_id"));
1750
2177
  }
1751
2178
  const requestId = args.request_id.trim();
1752
- const resumed = await approvals.resume(requestId);
2179
+ const resumed = await approvals.resume(requestId, owner);
1753
2180
  if (resumed.status === "not_found") {
1754
2181
  return finish(toolError(`Unknown approval request_id "${requestId}".`));
1755
2182
  }
@@ -1771,23 +2198,38 @@ function createMaskeraMcpServer(options = {}) {
1771
2198
  }
1772
2199
  if (name === "maskera_read_file") {
1773
2200
  if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1774
- const file = await files.readText(args.path);
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));
1775
2214
  const { result, modeUsed } = await engine.redact(file.content, {
1776
- mode: asMode(args.mode),
1777
- profile: asProfile(args.profile) ?? defaultProfile,
1778
- customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
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
1779
2226
  });
1780
- const applied = vault.apply(
1781
- file.content,
1782
- result,
1783
- typeof args.session_id === "string" ? args.session_id : void 0
1784
- );
1785
2227
  telemetrySessionId = applied.sessionId;
1786
2228
  telemetryRedactions = applied.totalRedactions;
1787
2229
  telemetryCounts = applied.counts;
1788
2230
  return finish(
1789
2231
  toolOk({
1790
- path: file.resolvedPath,
2232
+ path: safePath,
1791
2233
  bytes: file.bytes,
1792
2234
  redacted: applied.redacted,
1793
2235
  session_id: applied.sessionId,
@@ -1800,17 +2242,25 @@ function createMaskeraMcpServer(options = {}) {
1800
2242
  if (name === "maskera_write_file") {
1801
2243
  if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1802
2244
  if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1803
- const normalizedSessionId = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : vault.resolveSessionFor(args.text);
2245
+ const normalizedSessionId = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : vault.resolveSessionFor(args.text, owner);
1804
2246
  telemetrySessionId = normalizedSessionId;
1805
2247
  const { restored, knownPlaceholders } = vault.restore(args.text, {
1806
- sessionId: normalizedSessionId
2248
+ sessionId: normalizedSessionId,
2249
+ owner
1807
2250
  });
1808
- const written = await files.writeText(args.path, restored, {
2251
+ const resolvedTargetPath = resolveInputPath(args.path, owner, normalizedSessionId);
2252
+ const written = await files.writeText(resolvedTargetPath, restored, {
1809
2253
  overwrite: args.overwrite === true
1810
2254
  });
2255
+ const safePath = await redactResolvedPath(written.resolvedPath, {
2256
+ owner,
2257
+ sessionId: normalizedSessionId,
2258
+ profile: defaultProfile,
2259
+ customTerms: defaultCustomTerms
2260
+ });
1811
2261
  return finish(
1812
2262
  toolOk({
1813
- path: written.resolvedPath,
2263
+ path: safePath,
1814
2264
  bytes: written.bytes,
1815
2265
  session_id: normalizedSessionId,
1816
2266
  known_placeholders: knownPlaceholders
@@ -1825,11 +2275,25 @@ function createMaskeraMcpServer(options = {}) {
1825
2275
  maxDepth: asOptionalInt(args.max_depth)
1826
2276
  }
1827
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
+ }
1828
2291
  return finish(
1829
2292
  toolOk({
1830
2293
  root: listed.root,
1831
- files: listed.files,
1832
- truncated: listed.truncated
2294
+ files: safeFiles,
2295
+ truncated: listed.truncated,
2296
+ ...pathSessionId ? { session_id: pathSessionId } : {}
1833
2297
  })
1834
2298
  );
1835
2299
  }
@@ -1837,11 +2301,19 @@ function createMaskeraMcpServer(options = {}) {
1837
2301
  if (typeof args.query !== "string" || !args.query.trim()) {
1838
2302
  return finish(toolError("Missing required non-empty string: query"));
1839
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
+ }
1840
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) : {};
1841
2314
  let resolvedQuery = args.query.trim();
1842
2315
  if (requestedSession && PLACEHOLDER_QUERY_RE.test(resolvedQuery)) {
1843
- const map = vault.getMap(requestedSession);
1844
- const mapped = map[resolvedQuery];
2316
+ const mapped = existingSessionMap[resolvedQuery];
1845
2317
  if (mapped) {
1846
2318
  resolvedQuery = mapped;
1847
2319
  }
@@ -1851,7 +2323,6 @@ function createMaskeraMcpServer(options = {}) {
1851
2323
  caseSensitive: args.case_sensitive === true,
1852
2324
  maxMatches: asOptionalInt(args.max_matches)
1853
2325
  });
1854
- const mode = asMode(args.mode);
1855
2326
  const profile = asProfile(args.profile) ?? defaultProfile;
1856
2327
  const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
1857
2328
  let activeSessionId = requestedSession;
@@ -1864,22 +2335,35 @@ function createMaskeraMcpServer(options = {}) {
1864
2335
  profile,
1865
2336
  customTerms
1866
2337
  });
1867
- const applied = vault.apply(match.lineText, result, activeSessionId);
2338
+ const applied = vault.apply(match.lineText, result, activeSessionId, owner);
1868
2339
  activeSessionId = applied.sessionId;
1869
2340
  totalRedactions += applied.totalRedactions;
1870
2341
  for (const [label, count] of Object.entries(applied.counts)) {
1871
2342
  totalCounts[label] = (totalCounts[label] ?? 0) + count;
1872
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;
1873
2356
  redactedMatches.push({
1874
- path: match.path,
2357
+ path: safeMatchPath.path,
1875
2358
  line: match.line,
1876
- redacted_line: applied.redacted
2359
+ redacted_line: truncatePreservingPlaceholders(safeguarded.text, 500)
1877
2360
  });
1878
2361
  }
1879
2362
  const ensuredSessionId = activeSessionId ?? vault.apply(
1880
2363
  "",
1881
2364
  { text: "", map: {}, redactions: [], restore: (s) => s },
1882
- requestedSession
2365
+ requestedSession,
2366
+ owner
1883
2367
  ).sessionId;
1884
2368
  telemetrySessionId = ensuredSessionId;
1885
2369
  telemetryRedactions = totalRedactions;
@@ -1897,7 +2381,7 @@ function createMaskeraMcpServer(options = {}) {
1897
2381
  );
1898
2382
  }
1899
2383
  if (name === "maskera_list_sessions") {
1900
- return finish(toolOk({ sessions: vault.list() }));
2384
+ return finish(toolOk({ sessions: vault.list(owner) }));
1901
2385
  }
1902
2386
  if (name === "maskera_clear_session") {
1903
2387
  if (typeof args.session_id !== "string" || !args.session_id.trim()) {
@@ -1908,7 +2392,7 @@ function createMaskeraMcpServer(options = {}) {
1908
2392
  return finish(
1909
2393
  toolOk({
1910
2394
  session_id: normalizedSessionId,
1911
- cleared: vault.clear(normalizedSessionId)
2395
+ cleared: vault.clear(normalizedSessionId, owner)
1912
2396
  })
1913
2397
  );
1914
2398
  }
@@ -1931,7 +2415,7 @@ function createMaskeraMcpServer(options = {}) {
1931
2415
  };
1932
2416
  }
1933
2417
  const req = raw;
1934
- const hasIdProp = Object.prototype.hasOwnProperty.call(req, "id");
2418
+ const hasIdProp = Object.hasOwn(req, "id");
1935
2419
  const validId = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
1936
2420
  if (req.jsonrpc !== "2.0" || typeof req.method !== "string" || hasIdProp && validId === void 0) {
1937
2421
  return {
@@ -1948,9 +2432,7 @@ function createMaskeraMcpServer(options = {}) {
1948
2432
  if (req.method === "initialize") {
1949
2433
  const params = asObject(req.params);
1950
2434
  const clientCaps = asObject(params.capabilities);
1951
- if ("elicitation" in clientCaps && clientCaps.elicitation) {
1952
- clientSupportsElicitation = true;
1953
- }
2435
+ clientSupportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
1954
2436
  const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
1955
2437
  const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
1956
2438
  return {
@@ -2393,6 +2875,25 @@ async function runGuard(rawInput, engine, options = {}) {
2393
2875
  }
2394
2876
  return out.result.text;
2395
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
+ }
2396
2897
  if (Array.isArray(value)) {
2397
2898
  const arr = [];
2398
2899
  for (const item of value) arr.push(await redactJson(item));
@@ -3593,12 +4094,12 @@ function mergeCounts(target, delta) {
3593
4094
  }
3594
4095
  }
3595
4096
  function restorePlainText(text, map) {
3596
- if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
4097
+ if (!text?.includes("[") || Object.keys(map).length === 0) return text;
3597
4098
  const r = new StreamingRestorer(map);
3598
4099
  return r.push(text) + r.flush();
3599
4100
  }
3600
4101
  function restoreJsonEncodedText(text, map) {
3601
- if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
4102
+ if (!text?.includes("[") || Object.keys(map).length === 0) return text;
3602
4103
  try {
3603
4104
  const parsed = JSON.parse(text);
3604
4105
  const restored = restoreJsonLeaves(parsed, map);
@@ -3630,14 +4131,127 @@ function shouldSkipToolArgRestore(toolName, argsText) {
3630
4131
  if (toolName === "execute" && MASKERA_VAULT_CODE_RE.test(argsText)) return true;
3631
4132
  return false;
3632
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
+ }
3633
4232
  async function redactLlmRequestBody(body, redactString, options = {}) {
3634
4233
  const clone = options.mutate ? body : structuredClone(body);
4234
+ const noteBinary = (kind) => {
4235
+ options.onBinaryAttachment?.(kind);
4236
+ };
3635
4237
  async function redactContentBlocks(blocks, kind) {
3636
4238
  for (const block of blocks) {
3637
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
+ }
3638
4249
  if (typeof block.text === "string") {
3639
4250
  block.text = await redactString(block.text, kind);
3640
4251
  }
4252
+ if (typeof block.refusal === "string") {
4253
+ block.refusal = await redactString(block.refusal, kind);
4254
+ }
3641
4255
  if (typeof block.thinking === "string") {
3642
4256
  const redactedThinking = await redactString(block.thinking, kind);
3643
4257
  if (redactedThinking !== block.thinking) {
@@ -3661,9 +4275,33 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3661
4275
  } else if (Array.isArray(block.output)) {
3662
4276
  await redactContentBlocks(block.output, kind);
3663
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
+ }
3664
4295
  if (isPlainObject(block.source)) {
3665
4296
  if (block.source.type === "text" && typeof block.source.data === "string") {
3666
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
+ }
3667
4305
  }
3668
4306
  if (typeof block.source.content === "string") {
3669
4307
  block.source.content = await redactString(block.source.content, kind);
@@ -3674,13 +4312,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3674
4312
  if (typeof block.arguments === "string") {
3675
4313
  block.arguments = await redactJsonStringOrText(block.arguments, kind);
3676
4314
  }
3677
- if (isPlainObject(block.input)) {
4315
+ if (typeof block.input === "string") {
4316
+ block.input = await redactJsonStringOrText(block.input, kind);
4317
+ } else if (isPlainObject(block.input)) {
3678
4318
  block.input = await redactObjectStrings(block.input, kind);
3679
4319
  }
3680
4320
  }
3681
4321
  }
3682
4322
  async function redactObjectStrings(value, kind) {
3683
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
+ }
3684
4329
  if (Array.isArray(value)) {
3685
4330
  const out = [];
3686
4331
  for (const item of value) out.push(await redactObjectStrings(item, kind));
@@ -3712,6 +4357,31 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3712
4357
  if (typeof clone.instructions === "string") {
3713
4358
  clone.instructions = await redactString(clone.instructions, "system");
3714
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
+ }
3715
4385
  async function redactToolEntries(entries) {
3716
4386
  for (const tool of entries) {
3717
4387
  if (!isPlainObject(tool)) continue;
@@ -3736,11 +4406,29 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3736
4406
  for (const msg of clone.messages) {
3737
4407
  if (!isPlainObject(msg)) continue;
3738
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
+ }
3739
4412
  if (typeof msg.content === "string") {
3740
4413
  msg.content = await redactString(msg.content, msgKind);
3741
4414
  } else if (Array.isArray(msg.content)) {
3742
4415
  await redactContentBlocks(msg.content, msgKind);
3743
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
+ }
3744
4432
  if (Array.isArray(msg.tool_calls)) {
3745
4433
  for (const call of msg.tool_calls) {
3746
4434
  if (isPlainObject(call) && isPlainObject(call.function)) {
@@ -3775,6 +4463,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3775
4463
  } else if (Array.isArray(item.output)) {
3776
4464
  await redactContentBlocks(item.output, itemKind);
3777
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
+ }
3778
4480
  if (Array.isArray(item.summary)) {
3779
4481
  await redactContentBlocks(item.summary, itemKind);
3780
4482
  }
@@ -3817,6 +4519,9 @@ function restoreLlmResponseBody(body, map, options = {}) {
3817
4519
  if (typeof msg.reasoning_content === "string") {
3818
4520
  msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
3819
4521
  }
4522
+ if (typeof msg.reasoning === "string") {
4523
+ msg.reasoning = restorePlainText(msg.reasoning, map);
4524
+ }
3820
4525
  if (Array.isArray(msg.tool_calls)) {
3821
4526
  for (const call of msg.tool_calls) {
3822
4527
  if (isPlainObject(call) && isPlainObject(call.function)) {
@@ -3841,6 +4546,11 @@ function restoreLlmResponseBody(body, map, options = {}) {
3841
4546
  if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(item.name, item.arguments)) {
3842
4547
  item.arguments = restoreJsonEncodedText(item.arguments, map);
3843
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
+ }
3844
4554
  if (Array.isArray(item.content)) {
3845
4555
  for (const part of item.content) {
3846
4556
  if (isPlainObject(part) && typeof part.text === "string") {
@@ -3994,6 +4704,11 @@ data: ${JSON.stringify({
3994
4704
  events.push(
3995
4705
  `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
3996
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
+ );
3997
4712
  } else if (key.startsWith("resp_reasoning:")) {
3998
4713
  const [, outputIdx, summaryIdx] = key.split(":");
3999
4714
  events.push(
@@ -4127,6 +4842,11 @@ data: ${JSON.stringify({
4127
4842
  delta.reasoning_content
4128
4843
  );
4129
4844
  }
4845
+ if (typeof delta.reasoning === "string") {
4846
+ delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`).push(
4847
+ delta.reasoning
4848
+ );
4849
+ }
4130
4850
  if (Array.isArray(delta.tool_calls)) {
4131
4851
  for (const call of delta.tool_calls) {
4132
4852
  if (!isPlainObject(call)) continue;
@@ -4165,6 +4885,12 @@ data: ${JSON.stringify({
4165
4885
  const d = choice.delta;
4166
4886
  d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
4167
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
+ }
4168
4894
  const toolPrefix = `openai_chat_tool:${cIdx}:`;
4169
4895
  for (const key of [...bufferedToolArgs.keys()]) {
4170
4896
  if (!key.startsWith(toolPrefix)) continue;
@@ -4358,10 +5084,10 @@ ${joined}` : joined;
4358
5084
  sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
4359
5085
  let out = "";
4360
5086
  for (; ; ) {
4361
- const sep2 = sseBuffer.indexOf("\n\n");
4362
- if (sep2 < 0) break;
4363
- const block = sseBuffer.slice(0, sep2);
4364
- sseBuffer = sseBuffer.slice(sep2 + 2);
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);
4365
5091
  out += `${processEventBlock(block)}
4366
5092
 
4367
5093
  `;
@@ -4402,6 +5128,38 @@ var INSPECTOR_SECURITY_HEADERS = {
4402
5128
  "cache-control": "no-store"
4403
5129
  };
4404
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
+ }
4405
5163
  function isLoopbackHost(hostHeader, boundHost, boundPort, requirePresent = false) {
4406
5164
  if (!hostHeader) return !requirePresent;
4407
5165
  const raw = hostHeader.trim().toLowerCase();
@@ -4516,8 +5274,8 @@ async function readRequestBody(req) {
4516
5274
  return Buffer.concat(chunks);
4517
5275
  }
4518
5276
  function shouldRedactPath(pathname) {
4519
- const clean = (pathname.split("?")[0] ?? pathname).replace(/\/+$/, "").toLowerCase();
4520
- 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");
4521
5279
  }
4522
5280
  var APPROVAL_STRICTNESS = {
4523
5281
  automatic: 0,
@@ -4549,6 +5307,11 @@ function parseScopedMcpPolicy(urlPath, base) {
4549
5307
  }
4550
5308
  async function startMaskeraProxy(options = {}) {
4551
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
+ }
4552
5315
  const requestedPort = options.port ?? 8787;
4553
5316
  const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
4554
5317
  const vault = options.vault ?? new SessionVault();
@@ -4572,7 +5335,7 @@ async function startMaskeraProxy(options = {}) {
4572
5335
  const closedMcpSessions = /* @__PURE__ */ new Set();
4573
5336
  if (auditLogPath) {
4574
5337
  await mkdir(dirname(auditLogPath), { recursive: true });
4575
- await appendFile(auditLogPath, "", "utf8");
5338
+ await appendFile(auditLogPath, "", { encoding: "utf8", mode: 384 });
4576
5339
  }
4577
5340
  let totalRequests = 0;
4578
5341
  let totalRedactions = 0;
@@ -4636,11 +5399,13 @@ async function startMaskeraProxy(options = {}) {
4636
5399
  });
4637
5400
  auditChain = auditChain.then(
4638
5401
  () => appendFile(auditLogPath, `${auditLine}
4639
- `, "utf8").catch((err) => {
4640
- log(
4641
- `[maskera-proxy] audit log write error: ${err instanceof Error ? err.message : String(err)}`
4642
- );
4643
- })
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
+ )
4644
5409
  );
4645
5410
  }
4646
5411
  }
@@ -4652,7 +5417,7 @@ async function startMaskeraProxy(options = {}) {
4652
5417
  const normalizedPath = normalizeInspectorPath(pathname);
4653
5418
  const isInspectorRoute = normalizedPath === "/_maskera" || normalizedPath.startsWith("/_maskera/") || normalizedPath.includes("/_maskera/") || normalizedPath.endsWith("/_maskera");
4654
5419
  if (isInspectorRoute || pathname === "/healthz") {
4655
- if (!isLoopbackHost(req.headers.host, host, boundPort)) {
5420
+ if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort)) {
4656
5421
  res.writeHead(403, {
4657
5422
  ...INSPECTOR_SECURITY_HEADERS,
4658
5423
  "content-type": "application/json; charset=utf-8"
@@ -4869,7 +5634,7 @@ async function startMaskeraProxy(options = {}) {
4869
5634
  return;
4870
5635
  }
4871
5636
  if (normalizedPath === "/mcp" || normalizedPath === "/mcp/") {
4872
- if (!isLoopbackHost(req.headers.host, host, boundPort, true)) {
5637
+ if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort, true)) {
4873
5638
  res.writeHead(403, {
4874
5639
  ...INSPECTOR_SECURITY_HEADERS,
4875
5640
  "content-type": "application/json; charset=utf-8"
@@ -4892,6 +5657,8 @@ async function startMaskeraProxy(options = {}) {
4892
5657
  if (incomingSessionId) {
4893
5658
  mcpSessions.delete(incomingSessionId);
4894
5659
  closedMcpSessions.add(incomingSessionId);
5660
+ vault.clearOwner(`mcp:${incomingSessionId}`);
5661
+ approvals.clearOwner(`mcp:${incomingSessionId}`);
4895
5662
  if (closedMcpSessions.size > 500) {
4896
5663
  const first = closedMcpSessions.values().next().value;
4897
5664
  if (first !== void 0) closedMcpSessions.delete(first);
@@ -4949,23 +5716,37 @@ async function startMaskeraProxy(options = {}) {
4949
5716
  );
4950
5717
  return;
4951
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
+ }
4952
5729
  const sessionBasePolicy = (incomingSessionId ? mcpSessions.get(incomingSessionId) : void 0) ?? baseMcpPolicy;
4953
5730
  const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
4954
5731
  const mcpServer = getMcpServer();
4955
- const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
4956
- const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
4957
5732
  let responseSessionId = incomingSessionId;
4958
5733
  if (isInit) {
4959
5734
  responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
4960
5735
  if (mcpSessions.size >= 200) {
4961
5736
  const oldest = mcpSessions.keys().next().value;
4962
- if (oldest !== void 0) mcpSessions.delete(oldest);
5737
+ if (oldest !== void 0) {
5738
+ mcpSessions.delete(oldest);
5739
+ vault.clearOwner(`mcp:${oldest}`);
5740
+ approvals.clearOwner(`mcp:${oldest}`);
5741
+ }
4963
5742
  }
4964
5743
  mcpSessions.set(responseSessionId, effectivePolicy);
4965
5744
  }
5745
+ const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
5746
+ const scopedPolicy = { ...effectivePolicy, sessionOwner };
4966
5747
  const responses = [];
4967
5748
  for (const msg of messages) {
4968
- const reply = await mcpServer.handleMessage(msg, effectivePolicy);
5749
+ const reply = await mcpServer.handleMessage(msg, scopedPolicy);
4969
5750
  if (reply !== null) responses.push(reply);
4970
5751
  }
4971
5752
  const mcpHeaders = {
@@ -5001,18 +5782,59 @@ async function startMaskeraProxy(options = {}) {
5001
5782
  anthropicUpstream,
5002
5783
  openaiUpstream
5003
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
+ }
5004
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
+ }
5005
5813
  const rawBody = method === "GET" || method === "HEAD" ? void 0 : await readRequestBody(req);
5006
- const sessionHeader = req.headers["x-maskera-session"];
5007
- const sessionId = typeof sessionHeader === "string" && sessionHeader.trim() ? sessionHeader.trim() : "proxy";
5814
+ let sessionId = deriveProxySessionId(req.headers);
5815
+ const proxyVaultOwner = "proxy";
5816
+ const blockBinary = options.blockBinary === true;
5008
5817
  const stats = { redactions: 0, counts: {} };
5009
5818
  const redactedPreview = [];
5819
+ const binaryAttachments = /* @__PURE__ */ new Set();
5820
+ let requestWarnings;
5010
5821
  let outgoingBody = rawBody;
5011
5822
  let rewroteRequestBody = false;
5012
5823
  const contentType = String(req.headers["content-type"] ?? "").trim().toLowerCase();
5013
5824
  const contentEncoding = typeof req.headers["content-encoding"] === "string" ? req.headers["content-encoding"] : void 0;
5014
5825
  const mayBeJson = contentType === "" || contentType.includes("json") || contentType.startsWith("text/plain");
5015
- if (rawBody && rawBody.byteLength > 0 && shouldRedactPath(forwardPath) && mayBeJson) {
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
+ }
5016
5838
  let decodedBody;
5017
5839
  try {
5018
5840
  decodedBody = decodeRequestBody(rawBody, contentEncoding);
@@ -5034,48 +5856,110 @@ async function startMaskeraProxy(options = {}) {
5034
5856
  res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
5035
5857
  return;
5036
5858
  }
5037
- if (isPlainObject(parsed)) {
5038
- let redactedObj;
5039
- try {
5040
- redactedObj = await redactLlmRequestBody(
5041
- parsed,
5042
- async (text, kind) => {
5043
- if (!text.trim()) return text;
5044
- const { result } = await engine.redact(text, {
5045
- mode: kind === "tool_description" ? "rules" : void 0,
5046
- profile: options.profile,
5047
- customTerms: options.customTerms
5048
- });
5049
- const applied = vault.apply(text, result, sessionId);
5050
- stats.redactions += applied.totalRedactions;
5051
- mergeCounts(stats.counts, applied.counts);
5052
- if (redactedPreview.length < 6) {
5053
- const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
5054
- redactedPreview.push(snippet);
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("");
5055
5899
  }
5056
- return applied.redacted;
5057
- },
5058
- { mutate: true }
5059
- );
5060
- } catch (err) {
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) {
5061
5933
  recordAuditAndInspector({
5062
5934
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5063
5935
  method,
5064
5936
  path: forwardPath,
5065
5937
  upstream: baseUrl,
5066
5938
  sessionId,
5067
- status: 502,
5939
+ status: 415,
5068
5940
  streamed: false,
5069
5941
  durationMs: Date.now() - startedAt,
5070
5942
  redactions: stats.redactions,
5071
5943
  counts: stats.counts,
5072
- 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"
5073
5950
  });
5074
- throw err;
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;
5075
5959
  }
5076
- outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
5077
- rewroteRequestBody = true;
5078
5960
  }
5961
+ outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
5962
+ rewroteRequestBody = true;
5079
5963
  }
5080
5964
  const forwardHeaders = new Headers();
5081
5965
  for (const [k, v] of Object.entries(req.headers)) {
@@ -5102,6 +5986,7 @@ async function startMaskeraProxy(options = {}) {
5102
5986
  method,
5103
5987
  headers: forwardHeaders,
5104
5988
  body: outgoingBody ? new Uint8Array(outgoingBody) : void 0,
5989
+ redirect: "manual",
5105
5990
  signal: abortController.signal
5106
5991
  });
5107
5992
  } catch (err) {
@@ -5131,7 +6016,10 @@ async function startMaskeraProxy(options = {}) {
5131
6016
  }
5132
6017
  });
5133
6018
  outHeaders["x-maskera-redacted"] = String(stats.redactions);
5134
- const sessionMap = restoreResponses ? vault.getMap(sessionId) : {};
6019
+ if (requestWarnings) {
6020
+ outHeaders["x-maskera-warning"] = "uninspectable-binary-attachment";
6021
+ }
6022
+ const sessionMap = restoreResponses ? vault.getMap(sessionId, proxyVaultOwner) : {};
5135
6023
  const hasMap = Object.keys(sessionMap).length > 0;
5136
6024
  const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
5137
6025
  const isSse = resContentType.includes("text/event-stream");
@@ -5182,7 +6070,8 @@ async function startMaskeraProxy(options = {}) {
5182
6070
  durationMs: durationMs2,
5183
6071
  redactions: stats.redactions,
5184
6072
  counts: stats.counts,
5185
- redactedPreview
6073
+ redactedPreview,
6074
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5186
6075
  });
5187
6076
  log(
5188
6077
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${durationMs2}ms`
@@ -5214,7 +6103,8 @@ async function startMaskeraProxy(options = {}) {
5214
6103
  durationMs: durationMs2,
5215
6104
  redactions: stats.redactions,
5216
6105
  counts: stats.counts,
5217
- redactedPreview
6106
+ redactedPreview,
6107
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5218
6108
  });
5219
6109
  log(
5220
6110
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${durationMs2}ms`
@@ -5237,7 +6127,8 @@ async function startMaskeraProxy(options = {}) {
5237
6127
  durationMs,
5238
6128
  redactions: stats.redactions,
5239
6129
  counts: stats.counts,
5240
- redactedPreview
6130
+ redactedPreview,
6131
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5241
6132
  });
5242
6133
  log(
5243
6134
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${durationMs}ms`
@@ -5634,6 +6525,7 @@ async function runWrap(options) {
5634
6525
  profile: options.profile,
5635
6526
  customTerms: options.customTerms,
5636
6527
  restoreResponses: options.restoreResponses,
6528
+ blockBinary: options.blockBinary,
5637
6529
  auditLogPath: options.auditLogPath
5638
6530
  });
5639
6531
  let startupReceipt = null;
@@ -5729,6 +6621,6 @@ async function runWrap(options) {
5729
6621
  }
5730
6622
  }
5731
6623
 
5732
- 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 };
5733
6625
  //# sourceMappingURL=index.js.map
5734
6626
  //# sourceMappingURL=index.js.map