@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/dist/cli.js CHANGED
@@ -1,120 +1,133 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFile, unlink, mkdir, writeFile, stat, access, appendFile, realpath, lstat, readlink, readdir } from 'fs/promises';
3
- import { delimiter, join, dirname, resolve, isAbsolute, relative, sep } from 'path';
3
+ import { delimiter, join, dirname, resolve, isAbsolute, relative, sep, posix, extname } from 'path';
4
4
  import { createInterface } from 'readline';
5
5
  import { format } from 'util';
6
6
  import { constants } from 'fs';
7
+ import { createRequire } from 'module';
8
+ import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
7
9
  import { randomUUID, createHash } from 'crypto';
8
- import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
9
10
  import { spawn, spawnSync } from 'child_process';
10
11
  import { homedir } from 'os';
11
12
  import { createServer } from 'http';
12
13
  import * as zlib from 'zlib';
13
14
 
14
- var DEFAULT_TTL_MS = 5 * 60 * 1e3;
15
- var MAX_RECORDS = 50;
16
- var ApprovalBroker = class {
17
- constructor(ttlMs = DEFAULT_TTL_MS) {
18
- this.records = /* @__PURE__ */ new Map();
19
- this.listeners = /* @__PURE__ */ new Set();
20
- this.ttlMs = Math.max(1e3, ttlMs);
21
- }
22
- expireStale(now = Date.now()) {
23
- let changed = false;
24
- for (const record of this.records.values()) {
25
- if (record.summary.status === "pending" && now >= record.expiresAtMs) {
26
- record.summary.status = "expired";
27
- record.execute = null;
28
- changed = true;
15
+ var WORD_CHAR = /[\p{L}\p{N}_]/u;
16
+ var DEFAULT_MAX_CACHE_ENTRIES = 512;
17
+ var MAX_CUSTOM_DETECTOR_CACHE = 64;
18
+ var CYRILLIC_CONFUSABLES = {
19
+ "\u0410": "A",
20
+ "\u0412": "B",
21
+ "\u0421": "C",
22
+ "\u0415": "E",
23
+ "\u041D": "H",
24
+ "\u0406": "I",
25
+ "\u0408": "J",
26
+ "\u041A": "K",
27
+ "\u041C": "M",
28
+ "\u041E": "O",
29
+ "\u0420": "P",
30
+ "\u0405": "S",
31
+ "\u0422": "T",
32
+ "\u0423": "Y",
33
+ "\u0425": "X",
34
+ "\u0430": "a",
35
+ "\u0432": "b",
36
+ "\u0441": "c",
37
+ "\u0435": "e",
38
+ "\u043D": "h",
39
+ "\u0456": "i",
40
+ "\u0458": "j",
41
+ "\u043A": "k",
42
+ "\u043C": "m",
43
+ "\u043E": "o",
44
+ "\u0440": "p",
45
+ "\u0455": "s",
46
+ "\u0442": "t",
47
+ "\u0443": "y",
48
+ "\u0445": "x"
49
+ };
50
+ var HAS_CYRILLIC_RE = /[\u0400-\u04ff]/;
51
+ var LATIN_LETTER_RE = /[A-Za-z\u00c0-\u024f]/;
52
+ var WORD_TOKEN_RE = new RegExp("\\p{L}+", "gu");
53
+ var SWEDISH_HYPHEN_COMPOUND_RE = /\b([A-ZÅÄÖÉ][a-zåäöé]{2,})-([a-zåäöé]{3,})\b/g;
54
+ var COMPOUND_NER_LABELS = /* @__PURE__ */ new Set(["NAMN", "ORG", "PLATS"]);
55
+ function normalizeMixedScriptHomoglyphs(text) {
56
+ if (!HAS_CYRILLIC_RE.test(text)) return { text, changed: false };
57
+ let latinCount = 0;
58
+ let cyrillicCount = 0;
59
+ for (const ch of text) {
60
+ if (LATIN_LETTER_RE.test(ch)) latinCount += 1;
61
+ else if (HAS_CYRILLIC_RE.test(ch)) cyrillicCount += 1;
62
+ }
63
+ const majorityLatin = latinCount > 0 && latinCount >= cyrillicCount * 2;
64
+ let changed = false;
65
+ const normalized = text.replace(WORD_TOKEN_RE, (word) => {
66
+ if (!HAS_CYRILLIC_RE.test(word)) return word;
67
+ const hasLatin = LATIN_LETTER_RE.test(word);
68
+ if (!hasLatin && !majorityLatin) return word;
69
+ if (!hasLatin) {
70
+ for (const ch of word) {
71
+ if (HAS_CYRILLIC_RE.test(ch) && !(ch in CYRILLIC_CONFUSABLES)) return word;
29
72
  }
30
73
  }
31
- if (changed) this.notify();
32
- }
33
- notify() {
34
- const snapshot = this.list();
35
- for (const listener of this.listeners) {
36
- try {
37
- listener(snapshot);
38
- } catch {
74
+ let out = "";
75
+ let wordChanged = false;
76
+ for (const ch of word) {
77
+ const mapped = CYRILLIC_CONFUSABLES[ch];
78
+ if (mapped !== void 0) {
79
+ out += mapped;
80
+ wordChanged = true;
81
+ } else {
82
+ out += ch;
39
83
  }
40
84
  }
41
- }
42
- onChange(listener) {
43
- this.listeners.add(listener);
44
- return () => {
45
- this.listeners.delete(listener);
46
- };
47
- }
48
- create(input) {
49
- this.expireStale();
50
- if (this.records.size >= MAX_RECORDS) {
51
- const oldestKey = this.records.keys().next().value;
52
- if (oldestKey !== void 0) this.records.delete(oldestKey);
53
- }
54
- const now = Date.now();
55
- const id = `apr_${randomUUID().slice(0, 12)}`;
56
- const summary = {
57
- id,
58
- tool: input.tool,
59
- reason: input.reason,
60
- sessionId: input.sessionId ?? null,
61
- placeholderCount: input.placeholderCount,
62
- status: "pending",
63
- createdAt: new Date(now).toISOString(),
64
- expiresAt: new Date(now + this.ttlMs).toISOString(),
65
- decidedAt: null
66
- };
67
- this.records.set(id, {
68
- summary,
69
- expiresAtMs: now + this.ttlMs,
70
- execute: input.execute
71
- });
72
- this.notify();
73
- return { ...summary };
74
- }
75
- list() {
76
- this.expireStale();
77
- return [...this.records.values()].map((r) => ({ ...r.summary })).reverse();
78
- }
79
- decide(id, decision) {
80
- this.expireStale();
81
- const record = this.records.get(id.trim());
82
- if (!record) return null;
83
- if (record.summary.status !== "pending") return { ...record.summary };
84
- record.summary.status = decision === "approve" ? "approved" : "declined";
85
- record.summary.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
86
- if (decision === "decline") {
87
- record.execute = null;
88
- }
89
- this.notify();
90
- return { ...record.summary };
91
- }
92
- async resume(id) {
93
- this.expireStale();
94
- const record = this.records.get(id.trim());
95
- if (!record) return { status: "not_found" };
96
- const { status } = record.summary;
97
- if (status === "pending" || status === "declined" || status === "expired") {
98
- return { status, summary: { ...record.summary } };
99
- }
100
- if (status === "completed" || !record.execute) {
101
- return { status: "expired", summary: { ...record.summary } };
85
+ if (wordChanged) changed = true;
86
+ return out;
87
+ });
88
+ return { text: normalized, changed };
89
+ }
90
+ async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, existing) {
91
+ const candidates = [];
92
+ SWEDISH_HYPHEN_COMPOUND_RE.lastIndex = 0;
93
+ for (let m = SWEDISH_HYPHEN_COMPOUND_RE.exec(text); m !== null; m = SWEDISH_HYPHEN_COMPOUND_RE.exec(text)) {
94
+ const prefix = m[1];
95
+ if (!prefix) continue;
96
+ const prefixStart = m.index;
97
+ const prefixEnd = prefixStart + prefix.length;
98
+ const alreadyCovered = existing.some((d) => d.start < prefixEnd && d.end > prefixStart);
99
+ if (!alreadyCovered) {
100
+ candidates.push({ prefixStart, prefixEnd, hyphenIndex: prefixEnd });
101
+ }
102
+ }
103
+ if (candidates.length === 0) return [];
104
+ const chars = text.split("");
105
+ for (const c of candidates) {
106
+ chars[c.hyphenIndex] = " ";
107
+ }
108
+ const probeText = chars.join("");
109
+ const probeRes = await redactWithNer(probeText, {
110
+ recognizer: ner,
111
+ detectors: [...detectors],
112
+ profile
113
+ });
114
+ const extra = [];
115
+ for (const r of probeRes.redactions) {
116
+ if (!COMPOUND_NER_LABELS.has(r.label)) continue;
117
+ for (const c of candidates) {
118
+ if (r.start <= c.prefixStart && r.end >= c.prefixEnd && r.end <= c.hyphenIndex) {
119
+ extra.push({
120
+ start: c.prefixStart,
121
+ end: c.prefixEnd,
122
+ label: r.label,
123
+ value: text.slice(c.prefixStart, c.prefixEnd)
124
+ });
125
+ break;
126
+ }
102
127
  }
103
- const run = record.execute;
104
- record.execute = null;
105
- const result = await run();
106
- record.summary.status = "completed";
107
- this.notify();
108
- return { status: "completed", result, summary: { ...record.summary } };
109
128
  }
110
- clearAll() {
111
- this.records.clear();
112
- this.notify();
113
- }
114
- };
115
- var WORD_CHAR = /[\p{L}\p{N}_]/u;
116
- var DEFAULT_MAX_CACHE_ENTRIES = 512;
117
- var MAX_CUSTOM_DETECTOR_CACHE = 64;
129
+ return extra;
130
+ }
118
131
  function escapeRegExp(value) {
119
132
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
120
133
  }
@@ -122,7 +135,7 @@ function normalizeCustomTerms(rawTerms) {
122
135
  const unique = /* @__PURE__ */ new Map();
123
136
  for (const raw of rawTerms) {
124
137
  if (typeof raw !== "string") continue;
125
- const trimmed = raw.trim();
138
+ const trimmed = canonicalize(raw.trim()).text.trim();
126
139
  if (trimmed.length < 2 || trimmed.length > 160) continue;
127
140
  const folded = trimmed.toLowerCase();
128
141
  if (!unique.has(folded)) unique.set(folded, trimmed);
@@ -276,12 +289,28 @@ function createMaskeraEngine(options = {}) {
276
289
  }
277
290
  const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
278
291
  if (requestedMode === "rules") {
279
- const result = req.profile === "clinical" ? redactFromDetections(
280
- text,
281
- runDetectors(text, detectors).filter(
282
- (d) => clinicalPrecisionFilter(d, text, "rule")
283
- )
284
- ) : redact(text, { detectors });
292
+ const canonical = canonicalize(text);
293
+ const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
294
+ let result;
295
+ if (canonical.identity && !homoglyph.changed) {
296
+ result = req.profile === "clinical" ? redactFromDetections(
297
+ text,
298
+ runDetectors(text, detectors).filter(
299
+ (d) => clinicalPrecisionFilter(d, text, "rule")
300
+ )
301
+ ) : redact(text, { detectors });
302
+ } else {
303
+ const detected = runDetectors(homoglyph.text, detectors);
304
+ const filtered = req.profile === "clinical" ? detected.filter((d) => clinicalPrecisionFilter(d, homoglyph.text, "rule")) : detected;
305
+ const mapped = [];
306
+ for (const d of filtered) {
307
+ const [start, end] = canonical.span(d.start, d.end);
308
+ if (end > start) {
309
+ mapped.push({ start, end, label: d.label, value: text.slice(start, end) });
310
+ }
311
+ }
312
+ result = redactFromDetections(text, mapped);
313
+ }
285
314
  if (cacheKey) {
286
315
  if (spanCache.size >= maxCacheEntries) {
287
316
  const oldest = spanCache.keys().next().value;
@@ -303,11 +332,36 @@ function createMaskeraEngine(options = {}) {
303
332
  }
304
333
  try {
305
334
  const ner = getRecognizer();
306
- const result = await redactWithNer(text, {
335
+ const canonical = canonicalize(text);
336
+ const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
337
+ const isIdentity = canonical.identity && !homoglyph.changed;
338
+ const nerInput = isIdentity ? text : homoglyph.text;
339
+ const baseRes = await redactWithNer(nerInput, {
307
340
  recognizer: ner,
308
341
  detectors,
309
342
  profile: req.profile
310
343
  });
344
+ const baseDetections = baseRes.redactions.map((r) => ({
345
+ start: r.start,
346
+ end: r.end,
347
+ label: r.label,
348
+ value: nerInput.slice(r.start, r.end)
349
+ }));
350
+ const compoundExtras = await detectHyphenatedCompoundPrefixes(
351
+ nerInput,
352
+ ner,
353
+ detectors,
354
+ req.profile,
355
+ baseDetections
356
+ );
357
+ const combined = compoundExtras.length > 0 ? [...baseDetections, ...compoundExtras] : baseDetections;
358
+ const result = isIdentity && compoundExtras.length === 0 ? baseRes : redactFromDetections(
359
+ text,
360
+ combined.flatMap((d) => {
361
+ const [start, end] = canonical.span(d.start, d.end);
362
+ return end > start ? [{ start, end, label: d.label, value: text.slice(start, end) }] : [];
363
+ })
364
+ );
311
365
  nerLoaded = true;
312
366
  nerError = null;
313
367
  if (cacheKey) {
@@ -599,7 +653,8 @@ function createFileGuard(roots = [process.cwd()]) {
599
653
  }
600
654
  await writeFile(targetReal, content, {
601
655
  encoding: "utf8",
602
- flag: options.overwrite ? "w" : "wx"
656
+ flag: options.overwrite ? "w" : "wx",
657
+ mode: 384
603
658
  }).catch((err) => {
604
659
  if (err.code === "EEXIST") {
605
660
  throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
@@ -675,7 +730,7 @@ function createFileGuard(roots = [process.cwd()]) {
675
730
  matches.push({
676
731
  path: file.relPath,
677
732
  line: i + 1,
678
- lineText: lineText.length > 500 ? `${lineText.slice(0, 500)}...` : lineText
733
+ lineText: lineText.length > 16384 ? lineText.slice(0, 16384) : lineText
679
734
  });
680
735
  if (matches.length >= maxMatches) {
681
736
  truncated = true;
@@ -859,7 +914,18 @@ ${MASKERA_SKILL_MARKDOWN}`
859
914
  }
860
915
  var DEFAULT_MAX_SESSIONS = 100;
861
916
  var DEFAULT_MAX_ENTITIES_PER_SESSION = 5e3;
917
+ var DEFAULT_OWNER = "default";
862
918
  var EXISTING_TOKEN_RE = /\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]/g;
919
+ function hasOwn(obj, key) {
920
+ return Object.hasOwn(obj, key);
921
+ }
922
+ function ownerStorageKey(owner, id) {
923
+ return `${owner}\0${id}`;
924
+ }
925
+ function normalizeOwner(owner) {
926
+ const trimmed = owner?.trim();
927
+ return trimmed || DEFAULT_OWNER;
928
+ }
863
929
  function valueKey(label, value) {
864
930
  return `${label.length}:${label}:${value}`;
865
931
  }
@@ -876,12 +942,14 @@ var SessionVault = class {
876
942
  this.maxSessions = Math.max(1, maxSessions);
877
943
  this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
878
944
  }
879
- getOrCreate(sessionId) {
945
+ getOrCreate(sessionId, owner) {
880
946
  const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
881
- const existing = this.sessions.get(id);
947
+ const resolvedOwner = normalizeOwner(owner);
948
+ const storageKey = ownerStorageKey(resolvedOwner, id);
949
+ const existing = this.sessions.get(storageKey);
882
950
  if (existing) {
883
- this.sessions.delete(id);
884
- this.sessions.set(id, existing);
951
+ this.sessions.delete(storageKey);
952
+ this.sessions.set(storageKey, existing);
885
953
  existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
886
954
  return existing;
887
955
  }
@@ -892,14 +960,15 @@ var SessionVault = class {
892
960
  const now = (/* @__PURE__ */ new Date()).toISOString();
893
961
  const created = {
894
962
  id,
963
+ owner: resolvedOwner,
895
964
  createdAt: now,
896
965
  updatedAt: now,
897
966
  tokenByKey: /* @__PURE__ */ new Map(),
898
- map: {},
967
+ map: /* @__PURE__ */ Object.create(null),
899
968
  counters: /* @__PURE__ */ new Map(),
900
969
  countsByLabel: {}
901
970
  };
902
- this.sessions.set(id, created);
971
+ this.sessions.set(storageKey, created);
903
972
  return created;
904
973
  }
905
974
  /**
@@ -907,8 +976,8 @@ var SessionVault = class {
907
976
  * the same entity receives the exact same placeholder across multiple calls
908
977
  * and files in the same session, while avoiding collisions with literal text.
909
978
  */
910
- apply(originalInput, result, sessionId) {
911
- const session = this.getOrCreate(sessionId);
979
+ apply(originalInput, result, sessionId, owner) {
980
+ const session = this.getOrCreate(sessionId, owner);
912
981
  if (result.redactions.length === 0) {
913
982
  return {
914
983
  sessionId: session.id,
@@ -934,7 +1003,7 @@ var SessionVault = class {
934
1003
  for (; ; ) {
935
1004
  next += 1;
936
1005
  const candidate = `[${r.label}_${next}]`;
937
- if (!(candidate in session.map) && !existingTokens?.has(candidate)) {
1006
+ if (!hasOwn(session.map, candidate) && !existingTokens?.has(candidate)) {
938
1007
  token = candidate;
939
1008
  break;
940
1009
  }
@@ -983,7 +1052,8 @@ var SessionVault = class {
983
1052
  if (!normalizedId) {
984
1053
  throw new Error("Provide either session_id or map to restore placeholders.");
985
1054
  }
986
- const session = this.sessions.get(normalizedId);
1055
+ const resolvedOwner = normalizeOwner(options.owner);
1056
+ const session = this.sessions.get(ownerStorageKey(resolvedOwner, normalizedId));
987
1057
  if (!session) {
988
1058
  throw new Error(`Unknown session_id "${normalizedId}".`);
989
1059
  }
@@ -993,8 +1063,35 @@ var SessionVault = class {
993
1063
  knownPlaceholders: Object.keys(session.map).length
994
1064
  };
995
1065
  }
996
- getMap(sessionId) {
997
- const session = this.sessions.get(sessionId.trim());
1066
+ /**
1067
+ * Picks the session that restores `text` when the caller named none.
1068
+ * Confined strictly to sessions belonging to `owner` so a missing session_id
1069
+ * can never read another client's or the proxy's vault entries.
1070
+ */
1071
+ resolveSessionFor(text, owner) {
1072
+ const resolvedOwner = normalizeOwner(owner);
1073
+ const tokens = [...new Set(text.match(EXISTING_TOKEN_RE) ?? [])];
1074
+ const candidates = [...this.sessions.values()].filter(
1075
+ (s) => s.owner === resolvedOwner && tokens.every((token) => hasOwn(s.map, token))
1076
+ );
1077
+ if (candidates.length === 0) {
1078
+ throw new Error(
1079
+ 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."
1080
+ );
1081
+ }
1082
+ const restorations = new Set(candidates.map((s) => restore(text, s.map)));
1083
+ if (restorations.size > 1) {
1084
+ throw new Error(
1085
+ `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.`
1086
+ );
1087
+ }
1088
+ const latest = candidates[candidates.length - 1];
1089
+ if (!latest) throw new Error("No local session can restore this text.");
1090
+ return latest.id;
1091
+ }
1092
+ getMap(sessionId, owner) {
1093
+ const resolvedOwner = normalizeOwner(owner);
1094
+ const session = this.sessions.get(ownerStorageKey(resolvedOwner, sessionId.trim()));
998
1095
  return session ? { ...session.map } : {};
999
1096
  }
1000
1097
  entries() {
@@ -1009,17 +1106,44 @@ var SessionVault = class {
1009
1106
  clearAll() {
1010
1107
  this.sessions.clear();
1011
1108
  }
1012
- list() {
1013
- return [...this.sessions.values()].map((s) => ({
1014
- sessionId: s.id,
1015
- entityCount: Object.keys(s.map).length,
1016
- countsByLabel: { ...s.countsByLabel },
1017
- createdAt: s.createdAt,
1018
- updatedAt: s.updatedAt
1019
- }));
1109
+ clearOwner(owner) {
1110
+ const resolvedOwner = normalizeOwner(owner);
1111
+ let removed = 0;
1112
+ for (const [key, entry] of this.sessions.entries()) {
1113
+ if (entry.owner === resolvedOwner) {
1114
+ this.sessions.delete(key);
1115
+ removed += 1;
1116
+ }
1117
+ }
1118
+ return removed;
1020
1119
  }
1021
- clear(sessionId) {
1022
- return this.sessions.delete(sessionId.trim());
1120
+ list(owner) {
1121
+ const resolvedOwner = owner !== void 0 ? normalizeOwner(owner) : void 0;
1122
+ const out = [];
1123
+ for (const s of this.sessions.values()) {
1124
+ if (resolvedOwner !== void 0 && s.owner !== resolvedOwner) continue;
1125
+ out.push({
1126
+ sessionId: s.id,
1127
+ entityCount: Object.keys(s.map).length,
1128
+ countsByLabel: { ...s.countsByLabel },
1129
+ createdAt: s.createdAt,
1130
+ updatedAt: s.updatedAt
1131
+ });
1132
+ }
1133
+ return out;
1134
+ }
1135
+ clear(sessionId, owner) {
1136
+ const resolvedOwner = normalizeOwner(owner);
1137
+ return this.sessions.delete(ownerStorageKey(resolvedOwner, sessionId.trim()));
1138
+ }
1139
+ sizeForOwner(owner) {
1140
+ if (owner === void 0) return this.sessions.size;
1141
+ const resolvedOwner = normalizeOwner(owner);
1142
+ let count = 0;
1143
+ for (const s of this.sessions.values()) {
1144
+ if (s.owner === resolvedOwner) count += 1;
1145
+ }
1146
+ return count;
1023
1147
  }
1024
1148
  get size() {
1025
1149
  return this.sessions.size;
@@ -1028,7 +1152,7 @@ var SessionVault = class {
1028
1152
 
1029
1153
  // src/server.ts
1030
1154
  var SERVER_NAME = "maskera-mcp";
1031
- var SERVER_VERSION = "0.4.0";
1155
+ var SERVER_VERSION = createRequire(import.meta.url)("../package.json").version;
1032
1156
  var SUPPORTED_PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
1033
1157
  var PLACEHOLDER_QUERY_RE = /^\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]$/;
1034
1158
  var COUNTS_SCHEMA = {
@@ -1205,14 +1329,14 @@ var TOOLS = [
1205
1329
  },
1206
1330
  session_id: {
1207
1331
  type: "string",
1208
- description: "Session ID containing the local restore map."
1332
+ 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."
1209
1333
  },
1210
1334
  overwrite: {
1211
1335
  type: "boolean",
1212
1336
  description: "Allow overwriting an existing file. Default false."
1213
1337
  }
1214
1338
  },
1215
- required: ["path", "text", "session_id"]
1339
+ required: ["path", "text"]
1216
1340
  },
1217
1341
  outputSchema: {
1218
1342
  type: "object",
@@ -1477,6 +1601,35 @@ var TOOLS = [
1477
1601
  }
1478
1602
  ];
1479
1603
  var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_clear_session"]);
1604
+ var CODE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1605
+ ".ts",
1606
+ ".tsx",
1607
+ ".js",
1608
+ ".jsx",
1609
+ ".mjs",
1610
+ ".cjs",
1611
+ ".json",
1612
+ ".yaml",
1613
+ ".yml",
1614
+ ".toml",
1615
+ ".lock",
1616
+ ".css",
1617
+ ".scss",
1618
+ ".html",
1619
+ ".svg",
1620
+ ".map",
1621
+ ".py",
1622
+ ".rs",
1623
+ ".go",
1624
+ ".java",
1625
+ ".rb",
1626
+ ".sh",
1627
+ ".sql",
1628
+ ".env"
1629
+ ]);
1630
+ var PATH_NER_LABELS = /* @__PURE__ */ new Set(["NAMN", "ORG", "PLATS"]);
1631
+ var PATH_NER_PREFIX = "Dokument om ";
1632
+ var MAX_PATH_ALIASES_PER_OWNER = 5e3;
1480
1633
  function asObject(value) {
1481
1634
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1482
1635
  }
@@ -1516,6 +1669,30 @@ function toolError(message) {
1516
1669
  content: [{ type: "text", text: message }]
1517
1670
  };
1518
1671
  }
1672
+ function truncatePreservingPlaceholders(text, maxLength = 500) {
1673
+ if (text.length <= maxLength) return text;
1674
+ let cut = maxLength;
1675
+ const open = text.lastIndexOf("[", cut - 1);
1676
+ if (open >= 0) {
1677
+ const close = text.indexOf("]", open);
1678
+ if (close >= cut) {
1679
+ cut = open;
1680
+ }
1681
+ }
1682
+ return `${text.slice(0, cut)}...`;
1683
+ }
1684
+ function enforceSessionSecretsRedacted(text, sessionMap) {
1685
+ const entries = Object.entries(sessionMap).filter(([, value]) => value.length >= 2).sort((a, b) => b[1].length - a[1].length);
1686
+ let out = text;
1687
+ let extraRedactions = 0;
1688
+ for (const [token, rawValue] of entries) {
1689
+ if (!out.includes(rawValue)) continue;
1690
+ const parts = out.split(rawValue);
1691
+ extraRedactions += parts.length - 1;
1692
+ out = parts.join(token);
1693
+ }
1694
+ return { text: out, extraRedactions };
1695
+ }
1519
1696
  function createMaskeraMcpServer(options = {}) {
1520
1697
  const engine = options.engine ?? createMaskeraEngine();
1521
1698
  const vault = options.vault ?? new SessionVault();
@@ -1527,11 +1704,155 @@ function createMaskeraMcpServer(options = {}) {
1527
1704
  const requestElicitation = options.requestElicitation;
1528
1705
  const onToolCall = options.onToolCall;
1529
1706
  let clientSupportsElicitation = false;
1707
+ const ownerPathAliases = /* @__PURE__ */ new Map();
1708
+ function getPathAliasBucket(owner) {
1709
+ let bucket = ownerPathAliases.get(owner);
1710
+ if (!bucket) {
1711
+ bucket = { toAlias: /* @__PURE__ */ new Map(), toReal: /* @__PURE__ */ new Map() };
1712
+ ownerPathAliases.set(owner, bucket);
1713
+ }
1714
+ return bucket;
1715
+ }
1716
+ function registerPathAlias(owner, realPath, aliasPath) {
1717
+ if (realPath === aliasPath) return;
1718
+ const bucket = getPathAliasBucket(owner);
1719
+ if (bucket.toAlias.size >= MAX_PATH_ALIASES_PER_OWNER && !bucket.toAlias.has(realPath)) {
1720
+ const oldestReal = bucket.toAlias.keys().next().value;
1721
+ if (oldestReal !== void 0) {
1722
+ const oldestAlias = bucket.toAlias.get(oldestReal);
1723
+ bucket.toAlias.delete(oldestReal);
1724
+ if (oldestAlias !== void 0) bucket.toReal.delete(oldestAlias);
1725
+ }
1726
+ }
1727
+ bucket.toAlias.set(realPath, aliasPath);
1728
+ bucket.toReal.set(aliasPath, realPath);
1729
+ }
1730
+ async function redactPathSegment(segment, isFinalSegment, opts) {
1731
+ const ext = isFinalSegment ? extname(segment) : "";
1732
+ const stem = ext ? segment.slice(0, -ext.length) : segment;
1733
+ if (!stem.trim()) return { segment, sessionId: opts.sessionId, changed: false };
1734
+ const rulesProbe = stem.replace(/_/g, " ");
1735
+ const { result: rulesRes } = await engine.redact(rulesProbe, {
1736
+ mode: "rules",
1737
+ profile: opts.profile,
1738
+ customTerms: opts.customTerms
1739
+ });
1740
+ const detections = rulesRes.redactions.map((r) => ({
1741
+ start: r.start,
1742
+ end: r.end,
1743
+ label: r.label,
1744
+ value: stem.slice(r.start, r.end)
1745
+ }));
1746
+ const effectiveMode = opts.mode ?? engine.status().defaultMode;
1747
+ const isCodeFile = ext !== "" && CODE_FILE_EXTENSIONS.has(ext.toLowerCase());
1748
+ if (effectiveMode === "auto" && !isCodeFile) {
1749
+ const alphaWords = stem.match(/[A-Za-zÅÄÖåäöÉé]{2,}/g) ?? [];
1750
+ if (alphaWords.length >= 2) {
1751
+ const titleProbe = stem.replace(/[_-]/g, " ").replace(
1752
+ /(^| )([a-zåäöé])/g,
1753
+ (_m, lead, ch) => `${lead}${ch.toUpperCase()}`
1754
+ );
1755
+ const framed = `${PATH_NER_PREFIX}${titleProbe}`;
1756
+ const { result: nerRes } = await engine.redact(framed, {
1757
+ mode: "auto",
1758
+ profile: opts.profile,
1759
+ customTerms: opts.customTerms
1760
+ });
1761
+ const offset = PATH_NER_PREFIX.length;
1762
+ for (const r of nerRes.redactions) {
1763
+ if (!PATH_NER_LABELS.has(r.label)) continue;
1764
+ const start = r.start - offset;
1765
+ const end = r.end - offset;
1766
+ if (start < 0 || end <= start || end > stem.length) continue;
1767
+ const overlaps = detections.some((d) => d.start < end && d.end > start);
1768
+ if (!overlaps) {
1769
+ detections.push({ start, end, label: r.label, value: stem.slice(start, end) });
1770
+ }
1771
+ }
1772
+ }
1773
+ }
1774
+ if (detections.length === 0) {
1775
+ return { segment, sessionId: opts.sessionId, changed: false };
1776
+ }
1777
+ const redactedStem = redactFromDetections(stem, detections);
1778
+ const applied = vault.apply(stem, redactedStem, opts.sessionId, opts.owner);
1779
+ return {
1780
+ segment: `${applied.redacted}${ext}`,
1781
+ sessionId: applied.sessionId,
1782
+ changed: applied.redacted !== stem
1783
+ };
1784
+ }
1785
+ async function redactRelativePath(relPath, opts) {
1786
+ const parts = relPath.split("/");
1787
+ const outParts = [];
1788
+ let activeSession = opts.sessionId;
1789
+ let anyChanged = false;
1790
+ for (let i = 0; i < parts.length; i++) {
1791
+ const part = parts[i] ?? "";
1792
+ const res = await redactPathSegment(part, i === parts.length - 1, {
1793
+ owner: opts.owner,
1794
+ sessionId: activeSession,
1795
+ mode: opts.mode,
1796
+ profile: opts.profile,
1797
+ customTerms: opts.customTerms
1798
+ });
1799
+ activeSession = res.sessionId;
1800
+ if (res.changed) anyChanged = true;
1801
+ outParts.push(res.segment);
1802
+ }
1803
+ const aliasedRel = outParts.join("/");
1804
+ if (anyChanged) {
1805
+ registerPathAlias(opts.owner, relPath, aliasedRel);
1806
+ if (opts.rootBase) {
1807
+ registerPathAlias(opts.owner, join(opts.rootBase, relPath), join(opts.rootBase, aliasedRel));
1808
+ }
1809
+ }
1810
+ return { path: aliasedRel, sessionId: activeSession, changed: anyChanged };
1811
+ }
1812
+ async function redactResolvedPath(resolvedPath, opts) {
1813
+ const candidates = files.allowedRoots.flatMap(
1814
+ (root) => root.startsWith("/private/") ? [root] : [root, `/private${root}`]
1815
+ );
1816
+ let bestRoot = null;
1817
+ let bestRel = null;
1818
+ for (const root of candidates) {
1819
+ const rel = relative(root, resolvedPath);
1820
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) {
1821
+ if (!bestRoot || root.length > bestRoot.length) {
1822
+ bestRoot = root;
1823
+ bestRel = rel.split(sep).join("/");
1824
+ }
1825
+ }
1826
+ }
1827
+ if (!bestRoot || !bestRel) return resolvedPath;
1828
+ const res = await redactRelativePath(bestRel, { ...opts, rootBase: bestRoot });
1829
+ if (!res.changed) return resolvedPath;
1830
+ return join(bestRoot, res.path);
1831
+ }
1832
+ function resolveInputPath(rawPath, owner, sessionId) {
1833
+ const trimmed = rawPath.trim();
1834
+ const bucket = ownerPathAliases.get(owner);
1835
+ const direct = bucket?.toReal.get(trimmed);
1836
+ if (direct) return direct;
1837
+ const normalized = trimmed.split(sep).join("/");
1838
+ const directNorm = bucket?.toReal.get(normalized);
1839
+ if (directNorm) return directNorm;
1840
+ if (trimmed.includes("[") && trimmed.includes("]")) {
1841
+ try {
1842
+ const sid = sessionId?.trim() || vault.resolveSessionFor(trimmed, owner);
1843
+ const { restored } = vault.restore(trimmed, { sessionId: sid, owner });
1844
+ return restored;
1845
+ } catch {
1846
+ }
1847
+ }
1848
+ return rawPath;
1849
+ }
1530
1850
  function resolvePolicy(override) {
1531
1851
  return {
1532
1852
  allowRawRestore: override?.allowRawRestore ?? options.allowRawRestore ?? true,
1533
1853
  readOnly: override?.readOnly ?? options.readOnly ?? false,
1534
- approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic"
1854
+ approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic",
1855
+ sessionOwner: override?.sessionOwner ?? options.sessionOwner ?? "default"
1535
1856
  };
1536
1857
  }
1537
1858
  function visibleTools(policy) {
@@ -1554,7 +1875,7 @@ function createMaskeraMcpServer(options = {}) {
1554
1875
  server: SERVER_NAME,
1555
1876
  version: SERVER_VERSION,
1556
1877
  engine: engine.status(),
1557
- active_sessions: vault.size,
1878
+ active_sessions: vault.sizeForOwner(policy.sessionOwner),
1558
1879
  allowed_roots: files.allowedRoots,
1559
1880
  policy: {
1560
1881
  read_only: policy.readOnly,
@@ -1609,6 +1930,7 @@ function createMaskeraMcpServer(options = {}) {
1609
1930
  tool: input.tool,
1610
1931
  reason: input.reason,
1611
1932
  sessionId: input.sessionId,
1933
+ owner: policy.sessionOwner,
1612
1934
  placeholderCount: input.placeholderCount,
1613
1935
  execute: input.execute
1614
1936
  });
@@ -1625,6 +1947,7 @@ function createMaskeraMcpServer(options = {}) {
1625
1947
  async function callTool(name, rawArgs, policy) {
1626
1948
  const startedAt = Date.now();
1627
1949
  const args = asObject(rawArgs);
1950
+ const owner = policy.sessionOwner;
1628
1951
  let telemetrySessionId;
1629
1952
  let telemetryRedactions = 0;
1630
1953
  let telemetryCounts = {};
@@ -1661,7 +1984,8 @@ function createMaskeraMcpServer(options = {}) {
1661
1984
  const applied = vault.apply(
1662
1985
  args.text,
1663
1986
  result,
1664
- typeof args.session_id === "string" ? args.session_id : void 0
1987
+ typeof args.session_id === "string" ? args.session_id : void 0,
1988
+ owner
1665
1989
  );
1666
1990
  telemetrySessionId = applied.sessionId;
1667
1991
  telemetryRedactions = applied.totalRedactions;
@@ -1689,6 +2013,13 @@ function createMaskeraMcpServer(options = {}) {
1689
2013
  return finish(toolOk(payload));
1690
2014
  }
1691
2015
  if (name === "maskera_restore") {
2016
+ if (!policy.allowRawRestore) {
2017
+ return finish(
2018
+ toolError(
2019
+ "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."
2020
+ )
2021
+ );
2022
+ }
1692
2023
  if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1693
2024
  const explicitMap = args.map && typeof args.map === "object" && !Array.isArray(args.map) ? Object.fromEntries(
1694
2025
  Object.entries(args.map).filter(
@@ -1699,7 +2030,8 @@ function createMaskeraMcpServer(options = {}) {
1699
2030
  telemetrySessionId = sessionIdArg;
1700
2031
  const preview = vault.restore(args.text, {
1701
2032
  sessionId: sessionIdArg,
1702
- map: explicitMap
2033
+ map: explicitMap,
2034
+ owner
1703
2035
  });
1704
2036
  return finish(
1705
2037
  await gateRawPiiExport({
@@ -1724,7 +2056,7 @@ function createMaskeraMcpServer(options = {}) {
1724
2056
  return finish(toolError("Missing required non-empty string: request_id"));
1725
2057
  }
1726
2058
  const requestId = args.request_id.trim();
1727
- const resumed = await approvals.resume(requestId);
2059
+ const resumed = await approvals.resume(requestId, owner);
1728
2060
  if (resumed.status === "not_found") {
1729
2061
  return finish(toolError(`Unknown approval request_id "${requestId}".`));
1730
2062
  }
@@ -1746,23 +2078,38 @@ function createMaskeraMcpServer(options = {}) {
1746
2078
  }
1747
2079
  if (name === "maskera_read_file") {
1748
2080
  if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1749
- const file = await files.readText(args.path);
2081
+ const requestedMode = asMode(args.mode);
2082
+ if (engine.status().defaultMode === "auto" && requestedMode === "rules") {
2083
+ return finish(
2084
+ toolError(
2085
+ 'Downgrading mode to "rules" is not allowed on maskera_read_file when the server runs in hybrid "auto" mode.'
2086
+ )
2087
+ );
2088
+ }
2089
+ const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
2090
+ const resolvedInputPath = resolveInputPath(args.path, owner, requestedSession);
2091
+ const file = await files.readText(resolvedInputPath);
2092
+ const profile = asProfile(args.profile) ?? defaultProfile;
2093
+ const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
1750
2094
  const { result, modeUsed } = await engine.redact(file.content, {
1751
- mode: asMode(args.mode),
1752
- profile: asProfile(args.profile) ?? defaultProfile,
1753
- customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
2095
+ mode: requestedMode,
2096
+ profile,
2097
+ customTerms
2098
+ });
2099
+ const applied = vault.apply(file.content, result, requestedSession, owner);
2100
+ const safePath = await redactResolvedPath(file.resolvedPath, {
2101
+ owner,
2102
+ sessionId: applied.sessionId,
2103
+ mode: requestedMode,
2104
+ profile,
2105
+ customTerms
1754
2106
  });
1755
- const applied = vault.apply(
1756
- file.content,
1757
- result,
1758
- typeof args.session_id === "string" ? args.session_id : void 0
1759
- );
1760
2107
  telemetrySessionId = applied.sessionId;
1761
2108
  telemetryRedactions = applied.totalRedactions;
1762
2109
  telemetryCounts = applied.counts;
1763
2110
  return finish(
1764
2111
  toolOk({
1765
- path: file.resolvedPath,
2112
+ path: safePath,
1766
2113
  bytes: file.bytes,
1767
2114
  redacted: applied.redacted,
1768
2115
  session_id: applied.sessionId,
@@ -1775,20 +2122,25 @@ function createMaskeraMcpServer(options = {}) {
1775
2122
  if (name === "maskera_write_file") {
1776
2123
  if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1777
2124
  if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1778
- if (typeof args.session_id !== "string" || !args.session_id.trim()) {
1779
- return finish(toolError("Missing required non-empty string: session_id"));
1780
- }
1781
- const normalizedSessionId = args.session_id.trim();
2125
+ const normalizedSessionId = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : vault.resolveSessionFor(args.text, owner);
1782
2126
  telemetrySessionId = normalizedSessionId;
1783
2127
  const { restored, knownPlaceholders } = vault.restore(args.text, {
1784
- sessionId: normalizedSessionId
2128
+ sessionId: normalizedSessionId,
2129
+ owner
1785
2130
  });
1786
- const written = await files.writeText(args.path, restored, {
2131
+ const resolvedTargetPath = resolveInputPath(args.path, owner, normalizedSessionId);
2132
+ const written = await files.writeText(resolvedTargetPath, restored, {
1787
2133
  overwrite: args.overwrite === true
1788
2134
  });
2135
+ const safePath = await redactResolvedPath(written.resolvedPath, {
2136
+ owner,
2137
+ sessionId: normalizedSessionId,
2138
+ profile: defaultProfile,
2139
+ customTerms: defaultCustomTerms
2140
+ });
1789
2141
  return finish(
1790
2142
  toolOk({
1791
- path: written.resolvedPath,
2143
+ path: safePath,
1792
2144
  bytes: written.bytes,
1793
2145
  session_id: normalizedSessionId,
1794
2146
  known_placeholders: knownPlaceholders
@@ -1803,11 +2155,25 @@ function createMaskeraMcpServer(options = {}) {
1803
2155
  maxDepth: asOptionalInt(args.max_depth)
1804
2156
  }
1805
2157
  );
2158
+ let pathSessionId;
2159
+ const safeFiles = [];
2160
+ for (const entry of listed.files) {
2161
+ const safe = await redactRelativePath(entry.path, {
2162
+ owner,
2163
+ sessionId: pathSessionId,
2164
+ profile: defaultProfile,
2165
+ customTerms: defaultCustomTerms,
2166
+ rootBase: listed.root
2167
+ });
2168
+ pathSessionId = safe.sessionId;
2169
+ safeFiles.push({ path: safe.path, bytes: entry.bytes });
2170
+ }
1806
2171
  return finish(
1807
2172
  toolOk({
1808
2173
  root: listed.root,
1809
- files: listed.files,
1810
- truncated: listed.truncated
2174
+ files: safeFiles,
2175
+ truncated: listed.truncated,
2176
+ ...pathSessionId ? { session_id: pathSessionId } : {}
1811
2177
  })
1812
2178
  );
1813
2179
  }
@@ -1815,11 +2181,19 @@ function createMaskeraMcpServer(options = {}) {
1815
2181
  if (typeof args.query !== "string" || !args.query.trim()) {
1816
2182
  return finish(toolError("Missing required non-empty string: query"));
1817
2183
  }
2184
+ const mode = asMode(args.mode);
2185
+ if (engine.status().defaultMode === "auto" && mode === "rules") {
2186
+ return finish(
2187
+ toolError(
2188
+ 'Downgrading mode to "rules" is not allowed on maskera_search_files when the server runs in hybrid "auto" mode.'
2189
+ )
2190
+ );
2191
+ }
1818
2192
  const requestedSession = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : void 0;
2193
+ const existingSessionMap = requestedSession ? vault.getMap(requestedSession, owner) : {};
1819
2194
  let resolvedQuery = args.query.trim();
1820
2195
  if (requestedSession && PLACEHOLDER_QUERY_RE.test(resolvedQuery)) {
1821
- const map = vault.getMap(requestedSession);
1822
- const mapped = map[resolvedQuery];
2196
+ const mapped = existingSessionMap[resolvedQuery];
1823
2197
  if (mapped) {
1824
2198
  resolvedQuery = mapped;
1825
2199
  }
@@ -1829,7 +2203,6 @@ function createMaskeraMcpServer(options = {}) {
1829
2203
  caseSensitive: args.case_sensitive === true,
1830
2204
  maxMatches: asOptionalInt(args.max_matches)
1831
2205
  });
1832
- const mode = asMode(args.mode);
1833
2206
  const profile = asProfile(args.profile) ?? defaultProfile;
1834
2207
  const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
1835
2208
  let activeSessionId = requestedSession;
@@ -1842,22 +2215,35 @@ function createMaskeraMcpServer(options = {}) {
1842
2215
  profile,
1843
2216
  customTerms
1844
2217
  });
1845
- const applied = vault.apply(match.lineText, result, activeSessionId);
2218
+ const applied = vault.apply(match.lineText, result, activeSessionId, owner);
1846
2219
  activeSessionId = applied.sessionId;
1847
2220
  totalRedactions += applied.totalRedactions;
1848
2221
  for (const [label, count] of Object.entries(applied.counts)) {
1849
2222
  totalCounts[label] = (totalCounts[label] ?? 0) + count;
1850
2223
  }
2224
+ const currentMap = vault.getMap(activeSessionId, owner);
2225
+ const safeguarded = enforceSessionSecretsRedacted(applied.redacted, currentMap);
2226
+ totalRedactions += safeguarded.extraRedactions;
2227
+ const safeMatchPath = await redactRelativePath(match.path, {
2228
+ owner,
2229
+ sessionId: activeSessionId,
2230
+ mode,
2231
+ profile,
2232
+ customTerms,
2233
+ rootBase: search.root
2234
+ });
2235
+ activeSessionId = safeMatchPath.sessionId ?? activeSessionId;
1851
2236
  redactedMatches.push({
1852
- path: match.path,
2237
+ path: safeMatchPath.path,
1853
2238
  line: match.line,
1854
- redacted_line: applied.redacted
2239
+ redacted_line: truncatePreservingPlaceholders(safeguarded.text, 500)
1855
2240
  });
1856
2241
  }
1857
2242
  const ensuredSessionId = activeSessionId ?? vault.apply(
1858
2243
  "",
1859
2244
  { text: "", map: {}, redactions: [], restore: (s) => s },
1860
- requestedSession
2245
+ requestedSession,
2246
+ owner
1861
2247
  ).sessionId;
1862
2248
  telemetrySessionId = ensuredSessionId;
1863
2249
  telemetryRedactions = totalRedactions;
@@ -1875,7 +2261,7 @@ function createMaskeraMcpServer(options = {}) {
1875
2261
  );
1876
2262
  }
1877
2263
  if (name === "maskera_list_sessions") {
1878
- return finish(toolOk({ sessions: vault.list() }));
2264
+ return finish(toolOk({ sessions: vault.list(owner) }));
1879
2265
  }
1880
2266
  if (name === "maskera_clear_session") {
1881
2267
  if (typeof args.session_id !== "string" || !args.session_id.trim()) {
@@ -1886,7 +2272,7 @@ function createMaskeraMcpServer(options = {}) {
1886
2272
  return finish(
1887
2273
  toolOk({
1888
2274
  session_id: normalizedSessionId,
1889
- cleared: vault.clear(normalizedSessionId)
2275
+ cleared: vault.clear(normalizedSessionId, owner)
1890
2276
  })
1891
2277
  );
1892
2278
  }
@@ -1909,7 +2295,7 @@ function createMaskeraMcpServer(options = {}) {
1909
2295
  };
1910
2296
  }
1911
2297
  const req = raw;
1912
- const hasIdProp = Object.prototype.hasOwnProperty.call(req, "id");
2298
+ const hasIdProp = Object.hasOwn(req, "id");
1913
2299
  const validId = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
1914
2300
  if (req.jsonrpc !== "2.0" || typeof req.method !== "string" || hasIdProp && validId === void 0) {
1915
2301
  return {
@@ -1926,9 +2312,7 @@ function createMaskeraMcpServer(options = {}) {
1926
2312
  if (req.method === "initialize") {
1927
2313
  const params = asObject(req.params);
1928
2314
  const clientCaps = asObject(params.capabilities);
1929
- if ("elicitation" in clientCaps && clientCaps.elicitation) {
1930
- clientSupportsElicitation = true;
1931
- }
2315
+ clientSupportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
1932
2316
  const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
1933
2317
  const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
1934
2318
  return {
@@ -2371,6 +2755,25 @@ async function runGuard(rawInput, engine, options = {}) {
2371
2755
  }
2372
2756
  return out.result.text;
2373
2757
  }
2758
+ if (typeof value === "number" && Number.isFinite(value)) {
2759
+ const asText = String(value);
2760
+ if (asText.length >= 7) {
2761
+ const out = await engine.redact(asText, {
2762
+ mode: options.mode,
2763
+ profile: options.profile,
2764
+ customTerms: options.customTerms
2765
+ });
2766
+ if (out.result.redactions.length > 0) {
2767
+ modeUsed2 = out.modeUsed;
2768
+ totalRedactions += out.result.redactions.length;
2769
+ for (const r of out.result.redactions) {
2770
+ counts2[r.label] = (counts2[r.label] ?? 0) + 1;
2771
+ }
2772
+ return out.result.text;
2773
+ }
2774
+ }
2775
+ return value;
2776
+ }
2374
2777
  if (Array.isArray(value)) {
2375
2778
  const arr = [];
2376
2779
  for (const item of value) arr.push(await redactJson(item));
@@ -2868,6 +3271,128 @@ async function runInstall(options) {
2868
3271
  verifyStep
2869
3272
  };
2870
3273
  }
3274
+ var DEFAULT_TTL_MS = 5 * 60 * 1e3;
3275
+ var MAX_RECORDS = 50;
3276
+ var DEFAULT_OWNER2 = "default";
3277
+ function normalizeOwner2(owner) {
3278
+ const trimmed = owner?.trim();
3279
+ return trimmed || DEFAULT_OWNER2;
3280
+ }
3281
+ var ApprovalBroker = class {
3282
+ constructor(ttlMs = DEFAULT_TTL_MS) {
3283
+ this.records = /* @__PURE__ */ new Map();
3284
+ this.listeners = /* @__PURE__ */ new Set();
3285
+ this.ttlMs = Math.max(1e3, ttlMs);
3286
+ }
3287
+ expireStale(now = Date.now()) {
3288
+ let changed = false;
3289
+ for (const record of this.records.values()) {
3290
+ if (record.summary.status === "pending" && now >= record.expiresAtMs) {
3291
+ record.summary.status = "expired";
3292
+ record.execute = null;
3293
+ changed = true;
3294
+ }
3295
+ }
3296
+ if (changed) this.notify();
3297
+ }
3298
+ notify() {
3299
+ const snapshot = this.list();
3300
+ for (const listener of this.listeners) {
3301
+ try {
3302
+ listener(snapshot);
3303
+ } catch {
3304
+ }
3305
+ }
3306
+ }
3307
+ onChange(listener) {
3308
+ this.listeners.add(listener);
3309
+ return () => {
3310
+ this.listeners.delete(listener);
3311
+ };
3312
+ }
3313
+ create(input) {
3314
+ this.expireStale();
3315
+ if (this.records.size >= MAX_RECORDS) {
3316
+ const oldestKey = this.records.keys().next().value;
3317
+ if (oldestKey !== void 0) this.records.delete(oldestKey);
3318
+ }
3319
+ const now = Date.now();
3320
+ const id = `apr_${randomUUID().slice(0, 12)}`;
3321
+ const summary = {
3322
+ id,
3323
+ tool: input.tool,
3324
+ reason: input.reason,
3325
+ sessionId: input.sessionId ?? null,
3326
+ placeholderCount: input.placeholderCount,
3327
+ status: "pending",
3328
+ createdAt: new Date(now).toISOString(),
3329
+ expiresAt: new Date(now + this.ttlMs).toISOString(),
3330
+ decidedAt: null
3331
+ };
3332
+ this.records.set(id, {
3333
+ owner: normalizeOwner2(input.owner),
3334
+ summary,
3335
+ expiresAtMs: now + this.ttlMs,
3336
+ execute: input.execute
3337
+ });
3338
+ this.notify();
3339
+ return { ...summary };
3340
+ }
3341
+ list() {
3342
+ this.expireStale();
3343
+ return [...this.records.values()].map((r) => ({ ...r.summary })).reverse();
3344
+ }
3345
+ decide(id, decision) {
3346
+ this.expireStale();
3347
+ const record = this.records.get(id.trim());
3348
+ if (!record) return null;
3349
+ if (record.summary.status !== "pending") return { ...record.summary };
3350
+ record.summary.status = decision === "approve" ? "approved" : "declined";
3351
+ record.summary.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
3352
+ if (decision === "decline") {
3353
+ record.execute = null;
3354
+ }
3355
+ this.notify();
3356
+ return { ...record.summary };
3357
+ }
3358
+ async resume(id, owner) {
3359
+ this.expireStale();
3360
+ const record = this.records.get(id.trim());
3361
+ if (!record) return { status: "not_found" };
3362
+ if (owner !== void 0 && record.owner !== normalizeOwner2(owner)) {
3363
+ return { status: "not_found" };
3364
+ }
3365
+ const { status } = record.summary;
3366
+ if (status === "pending" || status === "declined" || status === "expired") {
3367
+ return { status, summary: { ...record.summary } };
3368
+ }
3369
+ if (status === "completed" || !record.execute) {
3370
+ return { status: "expired", summary: { ...record.summary } };
3371
+ }
3372
+ const run = record.execute;
3373
+ record.execute = null;
3374
+ const result = await run();
3375
+ record.summary.status = "completed";
3376
+ this.notify();
3377
+ return { status: "completed", result, summary: { ...record.summary } };
3378
+ }
3379
+ clearOwner(owner) {
3380
+ const resolvedOwner = normalizeOwner2(owner);
3381
+ let changed = false;
3382
+ for (const [id, record] of this.records.entries()) {
3383
+ if (record.owner === resolvedOwner) {
3384
+ record.execute = null;
3385
+ this.records.delete(id);
3386
+ changed = true;
3387
+ }
3388
+ }
3389
+ if (changed) this.notify();
3390
+ }
3391
+ clearAll() {
3392
+ this.records.clear();
3393
+ this.notify();
3394
+ }
3395
+ };
2871
3396
 
2872
3397
  // src/inspector.ts
2873
3398
  var MAX_EVENTS = 100;
@@ -3573,12 +4098,12 @@ function mergeCounts(target, delta) {
3573
4098
  }
3574
4099
  }
3575
4100
  function restorePlainText(text, map) {
3576
- if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
4101
+ if (!text?.includes("[") || Object.keys(map).length === 0) return text;
3577
4102
  const r = new StreamingRestorer(map);
3578
4103
  return r.push(text) + r.flush();
3579
4104
  }
3580
4105
  function restoreJsonEncodedText(text, map) {
3581
- if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
4106
+ if (!text?.includes("[") || Object.keys(map).length === 0) return text;
3582
4107
  try {
3583
4108
  const parsed = JSON.parse(text);
3584
4109
  const restored = restoreJsonLeaves(parsed, map);
@@ -3610,14 +4135,127 @@ function shouldSkipToolArgRestore(toolName, argsText) {
3610
4135
  if (toolName === "execute" && MASKERA_VAULT_CODE_RE.test(argsText)) return true;
3611
4136
  return false;
3612
4137
  }
4138
+ var SWEDISH_DIACRITIC_RE = /[åäöÅÄÖ]/;
4139
+ var SWEDISH_SIGNAL_WORD_RE = /\b(?:och|inte|ska|eller|enligt|kund|personnummer|svenska|sekretess|arbetsgivare|utbetalning|sammanfatta|skriv|svara|nedan|uppgifter)\b/i;
4140
+ var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4141
+ "the",
4142
+ "and",
4143
+ "you",
4144
+ "your",
4145
+ "with",
4146
+ "that",
4147
+ "this",
4148
+ "from",
4149
+ "are",
4150
+ "not",
4151
+ "when",
4152
+ "use",
4153
+ "must",
4154
+ "should",
4155
+ "never",
4156
+ "always",
4157
+ "tools",
4158
+ "files",
4159
+ "code",
4160
+ "return",
4161
+ "output",
4162
+ "response",
4163
+ "assistant",
4164
+ "instructions",
4165
+ "command",
4166
+ "user"
4167
+ ]);
4168
+ var ASCII_WORD_RE = /\b[a-z]{2,}\b/g;
4169
+ function isLikelyEnglishSystemPrompt(text) {
4170
+ if (text.length < 240) return false;
4171
+ if (SWEDISH_DIACRITIC_RE.test(text)) return false;
4172
+ if (SWEDISH_SIGNAL_WORD_RE.test(text)) return false;
4173
+ const found = /* @__PURE__ */ new Set();
4174
+ const lower = text.toLowerCase();
4175
+ ASCII_WORD_RE.lastIndex = 0;
4176
+ for (let m = ASCII_WORD_RE.exec(lower); m !== null; m = ASCII_WORD_RE.exec(lower)) {
4177
+ const word = m[0];
4178
+ if (word && ENGLISH_BOILERPLATE_WORDS.has(word)) {
4179
+ found.add(word);
4180
+ if (found.size >= 6) return true;
4181
+ }
4182
+ }
4183
+ return false;
4184
+ }
4185
+ function headerFirst(headers, name) {
4186
+ const value = headers[name];
4187
+ if (typeof value === "string") return value.trim();
4188
+ if (Array.isArray(value)) return (value[0] ?? "").trim();
4189
+ return "";
4190
+ }
4191
+ function shortSessionHash(seed) {
4192
+ return `proxy-${createHash("sha256").update(seed).digest("hex").slice(0, 12)}`;
4193
+ }
4194
+ function deriveProxySessionId(headers, body) {
4195
+ const explicit = headerFirst(headers, "x-maskera-session");
4196
+ if (explicit) return explicit;
4197
+ const threadHeader = headerFirst(headers, "x-session-id") || headerFirst(headers, "x-conversation-id") || headerFirst(headers, "openai-conversation-id");
4198
+ if (threadHeader) return shortSessionHash(`hdr:${threadHeader}`);
4199
+ if (body) {
4200
+ if (typeof body.prompt_cache_key === "string" && body.prompt_cache_key.trim()) {
4201
+ return shortSessionHash(`cache:${body.prompt_cache_key.trim()}`);
4202
+ }
4203
+ if (typeof body.conversation === "string" && body.conversation.trim()) {
4204
+ return shortSessionHash(`conv:${body.conversation.trim()}`);
4205
+ }
4206
+ if (isPlainObject(body.conversation) && typeof body.conversation.id === "string" && body.conversation.id.trim()) {
4207
+ return shortSessionHash(`conv:${body.conversation.id.trim()}`);
4208
+ }
4209
+ if (isPlainObject(body.metadata)) {
4210
+ 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();
4211
+ if (metaId) return shortSessionHash(`meta:${metaId}`);
4212
+ }
4213
+ }
4214
+ const auth = headerFirst(headers, "authorization") || headerFirst(headers, "x-api-key");
4215
+ if (auth) {
4216
+ const ua = headerFirst(headers, "user-agent");
4217
+ return shortSessionHash(`auth:${auth}\0${ua}`);
4218
+ }
4219
+ return "proxy";
4220
+ }
4221
+ var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
4222
+ 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;
4223
+ var DATA_URI_ANY_RE = /^data:([^;,]+);base64,/i;
4224
+ async function redactBase64Utf8(encoded, redactString, kind) {
4225
+ try {
4226
+ const rawBuf = Buffer.from(encoded, "base64");
4227
+ if (rawBuf.includes(0) || rawBuf.byteLength > MAX_BODY_BYTES) return encoded;
4228
+ const decoded = new TextDecoder("utf-8", { fatal: true }).decode(rawBuf);
4229
+ const redacted = await redactString(decoded, kind);
4230
+ if (redacted === decoded) return encoded;
4231
+ return Buffer.from(redacted, "utf8").toString("base64");
4232
+ } catch {
4233
+ return encoded;
4234
+ }
4235
+ }
3613
4236
  async function redactLlmRequestBody(body, redactString, options = {}) {
3614
4237
  const clone = options.mutate ? body : structuredClone(body);
4238
+ const noteBinary = (kind) => {
4239
+ options.onBinaryAttachment?.(kind);
4240
+ };
3615
4241
  async function redactContentBlocks(blocks, kind) {
3616
4242
  for (const block of blocks) {
3617
4243
  if (!isPlainObject(block)) continue;
4244
+ const blockType = typeof block.type === "string" ? block.type : "";
4245
+ if (blockType === "image" || blockType === "input_image") {
4246
+ const mediaType = isPlainObject(block.source) && typeof block.source.media_type === "string" ? block.source.media_type : blockType;
4247
+ noteBinary(mediaType);
4248
+ } else if (blockType === "image_url" || isPlainObject(block.image_url)) {
4249
+ noteBinary("image_url");
4250
+ } else if (blockType === "input_audio" || isPlainObject(block.input_audio)) {
4251
+ noteBinary("input_audio");
4252
+ }
3618
4253
  if (typeof block.text === "string") {
3619
4254
  block.text = await redactString(block.text, kind);
3620
4255
  }
4256
+ if (typeof block.refusal === "string") {
4257
+ block.refusal = await redactString(block.refusal, kind);
4258
+ }
3621
4259
  if (typeof block.thinking === "string") {
3622
4260
  const redactedThinking = await redactString(block.thinking, kind);
3623
4261
  if (redactedThinking !== block.thinking) {
@@ -3641,9 +4279,33 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3641
4279
  } else if (Array.isArray(block.output)) {
3642
4280
  await redactContentBlocks(block.output, kind);
3643
4281
  }
4282
+ if (typeof block.file_data === "string") {
4283
+ const match = DATA_URI_TEXT_BASE64_RE.exec(block.file_data);
4284
+ if (match?.[1] && match[2]) {
4285
+ const nextB64 = await redactBase64Utf8(match[2], redactString, kind);
4286
+ block.file_data = `data:${match[1]};base64,${nextB64}`;
4287
+ } else if (block.file_data.startsWith("data:")) {
4288
+ const anyMime = DATA_URI_ANY_RE.exec(block.file_data)?.[1] ?? "application/octet-stream";
4289
+ noteBinary(anyMime);
4290
+ } else {
4291
+ const rawBuf = Buffer.from(block.file_data, "base64");
4292
+ if (rawBuf.includes(0)) {
4293
+ noteBinary("application/octet-stream");
4294
+ } else {
4295
+ block.file_data = await redactBase64Utf8(block.file_data, redactString, kind);
4296
+ }
4297
+ }
4298
+ }
3644
4299
  if (isPlainObject(block.source)) {
3645
4300
  if (block.source.type === "text" && typeof block.source.data === "string") {
3646
4301
  block.source.data = await redactString(block.source.data, kind);
4302
+ } 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)) {
4303
+ block.source.data = await redactBase64Utf8(block.source.data, redactString, kind);
4304
+ } else if (block.source.type === "base64") {
4305
+ const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
4306
+ if (blockType !== "image" && blockType !== "input_image") {
4307
+ noteBinary(mediaType);
4308
+ }
3647
4309
  }
3648
4310
  if (typeof block.source.content === "string") {
3649
4311
  block.source.content = await redactString(block.source.content, kind);
@@ -3654,13 +4316,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3654
4316
  if (typeof block.arguments === "string") {
3655
4317
  block.arguments = await redactJsonStringOrText(block.arguments, kind);
3656
4318
  }
3657
- if (isPlainObject(block.input)) {
4319
+ if (typeof block.input === "string") {
4320
+ block.input = await redactJsonStringOrText(block.input, kind);
4321
+ } else if (isPlainObject(block.input)) {
3658
4322
  block.input = await redactObjectStrings(block.input, kind);
3659
4323
  }
3660
4324
  }
3661
4325
  }
3662
4326
  async function redactObjectStrings(value, kind) {
3663
4327
  if (typeof value === "string") return redactString(value, kind);
4328
+ if (typeof value === "number" && Number.isSafeInteger(value) && Math.abs(value) >= 1e9) {
4329
+ const asText = String(value);
4330
+ const redacted = await redactString(asText, kind);
4331
+ return redacted !== asText ? redacted : value;
4332
+ }
3664
4333
  if (Array.isArray(value)) {
3665
4334
  const out = [];
3666
4335
  for (const item of value) out.push(await redactObjectStrings(item, kind));
@@ -3692,6 +4361,31 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3692
4361
  if (typeof clone.instructions === "string") {
3693
4362
  clone.instructions = await redactString(clone.instructions, "system");
3694
4363
  }
4364
+ if (typeof clone.prompt === "string") {
4365
+ clone.prompt = await redactString(clone.prompt, "message");
4366
+ } else if (Array.isArray(clone.prompt)) {
4367
+ for (let i = 0; i < clone.prompt.length; i++) {
4368
+ const entry = clone.prompt[i];
4369
+ if (typeof entry === "string") {
4370
+ clone.prompt[i] = await redactString(entry, "message");
4371
+ }
4372
+ }
4373
+ }
4374
+ if (typeof clone.user === "string") {
4375
+ clone.user = await redactString(clone.user, "tool_description");
4376
+ }
4377
+ if (isPlainObject(clone.metadata)) {
4378
+ clone.metadata = await redactObjectStrings(clone.metadata, "tool_description");
4379
+ }
4380
+ if (Array.isArray(clone.requests)) {
4381
+ for (const batchItem of clone.requests) {
4382
+ if (isPlainObject(batchItem) && isPlainObject(batchItem.params)) {
4383
+ batchItem.params = await redactLlmRequestBody(batchItem.params, redactString, {
4384
+ mutate: true
4385
+ });
4386
+ }
4387
+ }
4388
+ }
3695
4389
  async function redactToolEntries(entries) {
3696
4390
  for (const tool of entries) {
3697
4391
  if (!isPlainObject(tool)) continue;
@@ -3716,11 +4410,29 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3716
4410
  for (const msg of clone.messages) {
3717
4411
  if (!isPlainObject(msg)) continue;
3718
4412
  const msgKind = msg.role === "system" || msg.role === "developer" ? "system" : "message";
4413
+ if (typeof msg.name === "string") {
4414
+ msg.name = await redactString(msg.name, "tool_description");
4415
+ }
3719
4416
  if (typeof msg.content === "string") {
3720
4417
  msg.content = await redactString(msg.content, msgKind);
3721
4418
  } else if (Array.isArray(msg.content)) {
3722
4419
  await redactContentBlocks(msg.content, msgKind);
3723
4420
  }
4421
+ if (typeof msg.reasoning_content === "string") {
4422
+ msg.reasoning_content = await redactString(msg.reasoning_content, msgKind);
4423
+ }
4424
+ if (typeof msg.reasoning === "string") {
4425
+ msg.reasoning = await redactString(msg.reasoning, msgKind);
4426
+ }
4427
+ if (typeof msg.refusal === "string") {
4428
+ msg.refusal = await redactString(msg.refusal, msgKind);
4429
+ }
4430
+ if (isPlainObject(msg.function_call) && typeof msg.function_call.arguments === "string") {
4431
+ msg.function_call.arguments = await redactJsonStringOrText(
4432
+ msg.function_call.arguments,
4433
+ msgKind
4434
+ );
4435
+ }
3724
4436
  if (Array.isArray(msg.tool_calls)) {
3725
4437
  for (const call of msg.tool_calls) {
3726
4438
  if (isPlainObject(call) && isPlainObject(call.function)) {
@@ -3755,6 +4467,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3755
4467
  } else if (Array.isArray(item.output)) {
3756
4468
  await redactContentBlocks(item.output, itemKind);
3757
4469
  }
4470
+ if (typeof item.input === "string") {
4471
+ item.input = await redactJsonStringOrText(item.input, itemKind);
4472
+ } else if (isPlainObject(item.input)) {
4473
+ item.input = await redactObjectStrings(item.input, itemKind);
4474
+ }
4475
+ if (typeof item.reasoning_content === "string") {
4476
+ item.reasoning_content = await redactString(item.reasoning_content, itemKind);
4477
+ }
4478
+ if (typeof item.reasoning === "string") {
4479
+ item.reasoning = await redactString(item.reasoning, itemKind);
4480
+ }
4481
+ if (typeof item.refusal === "string") {
4482
+ item.refusal = await redactString(item.refusal, itemKind);
4483
+ }
3758
4484
  if (Array.isArray(item.summary)) {
3759
4485
  await redactContentBlocks(item.summary, itemKind);
3760
4486
  }
@@ -3797,6 +4523,9 @@ function restoreLlmResponseBody(body, map, options = {}) {
3797
4523
  if (typeof msg.reasoning_content === "string") {
3798
4524
  msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
3799
4525
  }
4526
+ if (typeof msg.reasoning === "string") {
4527
+ msg.reasoning = restorePlainText(msg.reasoning, map);
4528
+ }
3800
4529
  if (Array.isArray(msg.tool_calls)) {
3801
4530
  for (const call of msg.tool_calls) {
3802
4531
  if (isPlainObject(call) && isPlainObject(call.function)) {
@@ -3821,6 +4550,11 @@ function restoreLlmResponseBody(body, map, options = {}) {
3821
4550
  if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(item.name, item.arguments)) {
3822
4551
  item.arguments = restoreJsonEncodedText(item.arguments, map);
3823
4552
  }
4553
+ if (typeof item.input === "string" && !shouldSkipToolArgRestore(item.name, item.input)) {
4554
+ item.input = restorePlainText(item.input, map);
4555
+ } else if (isPlainObject(item.input) && !isMaskeraVaultToolName(item.name)) {
4556
+ item.input = restoreJsonLeaves(item.input, map);
4557
+ }
3824
4558
  if (Array.isArray(item.content)) {
3825
4559
  for (const part of item.content) {
3826
4560
  if (isPlainObject(part) && typeof part.text === "string") {
@@ -3974,6 +4708,11 @@ data: ${JSON.stringify({
3974
4708
  events.push(
3975
4709
  `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
3976
4710
  );
4711
+ } else if (key.startsWith("openai_chat_reasoning_plain:")) {
4712
+ const idx = Number(key.split(":")[1] ?? 0);
4713
+ events.push(
4714
+ `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning: tail } }] })}`
4715
+ );
3977
4716
  } else if (key.startsWith("resp_reasoning:")) {
3978
4717
  const [, outputIdx, summaryIdx] = key.split(":");
3979
4718
  events.push(
@@ -4107,6 +4846,11 @@ data: ${JSON.stringify({
4107
4846
  delta.reasoning_content
4108
4847
  );
4109
4848
  }
4849
+ if (typeof delta.reasoning === "string") {
4850
+ delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`).push(
4851
+ delta.reasoning
4852
+ );
4853
+ }
4110
4854
  if (Array.isArray(delta.tool_calls)) {
4111
4855
  for (const call of delta.tool_calls) {
4112
4856
  if (!isPlainObject(call)) continue;
@@ -4145,6 +4889,12 @@ data: ${JSON.stringify({
4145
4889
  const d = choice.delta;
4146
4890
  d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
4147
4891
  }
4892
+ const reasoningPlainTail = flushStream(`openai_chat_reasoning_plain:${cIdx}`);
4893
+ if (reasoningPlainTail) {
4894
+ if (!isPlainObject(choice.delta)) choice.delta = {};
4895
+ const d = choice.delta;
4896
+ d.reasoning = (typeof d.reasoning === "string" ? d.reasoning : "") + reasoningPlainTail;
4897
+ }
4148
4898
  const toolPrefix = `openai_chat_tool:${cIdx}:`;
4149
4899
  for (const key of [...bufferedToolArgs.keys()]) {
4150
4900
  if (!key.startsWith(toolPrefix)) continue;
@@ -4338,10 +5088,10 @@ ${joined}` : joined;
4338
5088
  sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
4339
5089
  let out = "";
4340
5090
  for (; ; ) {
4341
- const sep2 = sseBuffer.indexOf("\n\n");
4342
- if (sep2 < 0) break;
4343
- const block = sseBuffer.slice(0, sep2);
4344
- sseBuffer = sseBuffer.slice(sep2 + 2);
5091
+ const sep3 = sseBuffer.indexOf("\n\n");
5092
+ if (sep3 < 0) break;
5093
+ const block = sseBuffer.slice(0, sep3);
5094
+ sseBuffer = sseBuffer.slice(sep3 + 2);
4345
5095
  out += `${processEventBlock(block)}
4346
5096
 
4347
5097
  `;
@@ -4382,6 +5132,38 @@ var INSPECTOR_SECURITY_HEADERS = {
4382
5132
  "cache-control": "no-store"
4383
5133
  };
4384
5134
  var LOOPBACK_HOST_RE = /^(127\.0\.0\.1|localhost|\[::1\])(?::(\d{1,5}))?$/i;
5135
+ var LOOPBACK_BIND_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
5136
+ function isLoopbackBindHost(host) {
5137
+ return LOOPBACK_BIND_HOSTS.has(host.trim().toLowerCase());
5138
+ }
5139
+ function isLoopbackRemoteAddress(remoteAddress) {
5140
+ if (!remoteAddress) return false;
5141
+ const normalized = remoteAddress.trim().toLowerCase();
5142
+ return normalized === "127.0.0.1" || normalized === "::1" || normalized === "::ffff:127.0.0.1";
5143
+ }
5144
+ var InvalidRequestPathError = class extends Error {
5145
+ constructor() {
5146
+ super(...arguments);
5147
+ this.statusCode = 400;
5148
+ }
5149
+ };
5150
+ function canonicalizeRequestPath(urlPath) {
5151
+ const rawPathname = urlPath.split("?")[0] ?? urlPath;
5152
+ if (rawPathname.includes("\0")) {
5153
+ throw new InvalidRequestPathError("Request path contains NUL byte.");
5154
+ }
5155
+ let decoded;
5156
+ try {
5157
+ decoded = decodeURIComponent(rawPathname);
5158
+ } catch {
5159
+ throw new InvalidRequestPathError("Malformed percent-encoding in request path.");
5160
+ }
5161
+ if (decoded.includes("\0")) {
5162
+ throw new InvalidRequestPathError("Decoded request path contains NUL byte.");
5163
+ }
5164
+ const normalized = posix.normalize(decoded.replace(/\\+/g, "/"));
5165
+ return normalized.length > 1 ? normalized.replace(/\/+$/, "") : normalized;
5166
+ }
4385
5167
  function isLoopbackHost(hostHeader, boundHost, boundPort, requirePresent = false) {
4386
5168
  if (!hostHeader) return !requirePresent;
4387
5169
  const raw = hostHeader.trim().toLowerCase();
@@ -4496,8 +5278,8 @@ async function readRequestBody(req) {
4496
5278
  return Buffer.concat(chunks);
4497
5279
  }
4498
5280
  function shouldRedactPath(pathname) {
4499
- const clean = (pathname.split("?")[0] ?? pathname).replace(/\/+$/, "").toLowerCase();
4500
- return clean.endsWith("/messages") || clean.endsWith("/messages/count_tokens") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
5281
+ const clean = canonicalizeRequestPath(pathname).toLowerCase();
5282
+ 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");
4501
5283
  }
4502
5284
  var APPROVAL_STRICTNESS = {
4503
5285
  automatic: 0,
@@ -4529,6 +5311,11 @@ function parseScopedMcpPolicy(urlPath, base) {
4529
5311
  }
4530
5312
  async function startMaskeraProxy(options = {}) {
4531
5313
  const host = options.host ?? "127.0.0.1";
5314
+ if (!options.allowNonLoopback && !isLoopbackBindHost(host)) {
5315
+ throw new Error(
5316
+ `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).`
5317
+ );
5318
+ }
4532
5319
  const requestedPort = options.port ?? 8787;
4533
5320
  const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
4534
5321
  const vault = options.vault ?? new SessionVault();
@@ -4552,7 +5339,7 @@ async function startMaskeraProxy(options = {}) {
4552
5339
  const closedMcpSessions = /* @__PURE__ */ new Set();
4553
5340
  if (auditLogPath) {
4554
5341
  await mkdir(dirname(auditLogPath), { recursive: true });
4555
- await appendFile(auditLogPath, "", "utf8");
5342
+ await appendFile(auditLogPath, "", { encoding: "utf8", mode: 384 });
4556
5343
  }
4557
5344
  let totalRequests = 0;
4558
5345
  let totalRedactions = 0;
@@ -4616,11 +5403,13 @@ async function startMaskeraProxy(options = {}) {
4616
5403
  });
4617
5404
  auditChain = auditChain.then(
4618
5405
  () => appendFile(auditLogPath, `${auditLine}
4619
- `, "utf8").catch((err) => {
4620
- log(
4621
- `[maskera-proxy] audit log write error: ${err instanceof Error ? err.message : String(err)}`
4622
- );
4623
- })
5406
+ `, { encoding: "utf8", mode: 384 }).catch(
5407
+ (err) => {
5408
+ log(
5409
+ `[maskera-proxy] audit log write error: ${err instanceof Error ? err.message : String(err)}`
5410
+ );
5411
+ }
5412
+ )
4624
5413
  );
4625
5414
  }
4626
5415
  }
@@ -4632,7 +5421,7 @@ async function startMaskeraProxy(options = {}) {
4632
5421
  const normalizedPath = normalizeInspectorPath(pathname);
4633
5422
  const isInspectorRoute = normalizedPath === "/_maskera" || normalizedPath.startsWith("/_maskera/") || normalizedPath.includes("/_maskera/") || normalizedPath.endsWith("/_maskera");
4634
5423
  if (isInspectorRoute || pathname === "/healthz") {
4635
- if (!isLoopbackHost(req.headers.host, host, boundPort)) {
5424
+ if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort)) {
4636
5425
  res.writeHead(403, {
4637
5426
  ...INSPECTOR_SECURITY_HEADERS,
4638
5427
  "content-type": "application/json; charset=utf-8"
@@ -4849,7 +5638,7 @@ async function startMaskeraProxy(options = {}) {
4849
5638
  return;
4850
5639
  }
4851
5640
  if (normalizedPath === "/mcp" || normalizedPath === "/mcp/") {
4852
- if (!isLoopbackHost(req.headers.host, host, boundPort, true)) {
5641
+ if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort, true)) {
4853
5642
  res.writeHead(403, {
4854
5643
  ...INSPECTOR_SECURITY_HEADERS,
4855
5644
  "content-type": "application/json; charset=utf-8"
@@ -4872,6 +5661,8 @@ async function startMaskeraProxy(options = {}) {
4872
5661
  if (incomingSessionId) {
4873
5662
  mcpSessions.delete(incomingSessionId);
4874
5663
  closedMcpSessions.add(incomingSessionId);
5664
+ vault.clearOwner(`mcp:${incomingSessionId}`);
5665
+ approvals.clearOwner(`mcp:${incomingSessionId}`);
4875
5666
  if (closedMcpSessions.size > 500) {
4876
5667
  const first = closedMcpSessions.values().next().value;
4877
5668
  if (first !== void 0) closedMcpSessions.delete(first);
@@ -4929,23 +5720,37 @@ async function startMaskeraProxy(options = {}) {
4929
5720
  );
4930
5721
  return;
4931
5722
  }
5723
+ const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
5724
+ const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
5725
+ if (!isInit && incomingSessionId && !mcpSessions.has(incomingSessionId)) {
5726
+ res.writeHead(404, {
5727
+ ...INSPECTOR_SECURITY_HEADERS,
5728
+ "content-type": "application/json; charset=utf-8"
5729
+ });
5730
+ res.end(JSON.stringify({ error: "Unknown MCP session." }));
5731
+ return;
5732
+ }
4932
5733
  const sessionBasePolicy = (incomingSessionId ? mcpSessions.get(incomingSessionId) : void 0) ?? baseMcpPolicy;
4933
5734
  const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
4934
5735
  const mcpServer = getMcpServer();
4935
- const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
4936
- const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
4937
5736
  let responseSessionId = incomingSessionId;
4938
5737
  if (isInit) {
4939
5738
  responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
4940
5739
  if (mcpSessions.size >= 200) {
4941
5740
  const oldest = mcpSessions.keys().next().value;
4942
- if (oldest !== void 0) mcpSessions.delete(oldest);
5741
+ if (oldest !== void 0) {
5742
+ mcpSessions.delete(oldest);
5743
+ vault.clearOwner(`mcp:${oldest}`);
5744
+ approvals.clearOwner(`mcp:${oldest}`);
5745
+ }
4943
5746
  }
4944
5747
  mcpSessions.set(responseSessionId, effectivePolicy);
4945
5748
  }
5749
+ const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
5750
+ const scopedPolicy = { ...effectivePolicy, sessionOwner };
4946
5751
  const responses = [];
4947
5752
  for (const msg of messages) {
4948
- const reply = await mcpServer.handleMessage(msg, effectivePolicy);
5753
+ const reply = await mcpServer.handleMessage(msg, scopedPolicy);
4949
5754
  if (reply !== null) responses.push(reply);
4950
5755
  }
4951
5756
  const mcpHeaders = {
@@ -4981,18 +5786,59 @@ async function startMaskeraProxy(options = {}) {
4981
5786
  anthropicUpstream,
4982
5787
  openaiUpstream
4983
5788
  });
5789
+ if (!forwardPath.startsWith("/") || forwardPath.startsWith("//")) {
5790
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
5791
+ res.end(JSON.stringify({ error: { message: "Invalid request path." } }));
5792
+ return;
5793
+ }
5794
+ let needsRedaction;
5795
+ try {
5796
+ needsRedaction = shouldRedactPath(forwardPath);
5797
+ } catch (err) {
5798
+ if (err instanceof InvalidRequestPathError) {
5799
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
5800
+ res.end(JSON.stringify({ error: { message: err.message } }));
5801
+ return;
5802
+ }
5803
+ throw err;
5804
+ }
4984
5805
  const upstreamUrl = `${baseUrl}${forwardPath}`;
5806
+ try {
5807
+ if (new URL(upstreamUrl).origin !== new URL(baseUrl).origin) {
5808
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
5809
+ res.end(JSON.stringify({ error: { message: "Upstream origin mismatch." } }));
5810
+ return;
5811
+ }
5812
+ } catch {
5813
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
5814
+ res.end(JSON.stringify({ error: { message: "Invalid upstream URL." } }));
5815
+ return;
5816
+ }
4985
5817
  const rawBody = method === "GET" || method === "HEAD" ? void 0 : await readRequestBody(req);
4986
- const sessionHeader = req.headers["x-maskera-session"];
4987
- const sessionId = typeof sessionHeader === "string" && sessionHeader.trim() ? sessionHeader.trim() : "proxy";
5818
+ let sessionId = deriveProxySessionId(req.headers);
5819
+ const proxyVaultOwner = "proxy";
5820
+ const blockBinary = options.blockBinary === true;
4988
5821
  const stats = { redactions: 0, counts: {} };
4989
5822
  const redactedPreview = [];
5823
+ const binaryAttachments = /* @__PURE__ */ new Set();
5824
+ let requestWarnings;
4990
5825
  let outgoingBody = rawBody;
4991
5826
  let rewroteRequestBody = false;
4992
5827
  const contentType = String(req.headers["content-type"] ?? "").trim().toLowerCase();
4993
5828
  const contentEncoding = typeof req.headers["content-encoding"] === "string" ? req.headers["content-encoding"] : void 0;
4994
5829
  const mayBeJson = contentType === "" || contentType.includes("json") || contentType.startsWith("text/plain");
4995
- if (rawBody && rawBody.byteLength > 0 && shouldRedactPath(forwardPath) && mayBeJson) {
5830
+ if (rawBody && rawBody.byteLength > 0 && needsRedaction) {
5831
+ if (!mayBeJson) {
5832
+ res.writeHead(415, { "content-type": "application/json; charset=utf-8" });
5833
+ res.end(
5834
+ JSON.stringify({
5835
+ error: {
5836
+ message: `Refusing to forward unredacted content-type "${contentType}" on LLM redaction endpoint (fail-closed).`
5837
+ }
5838
+ })
5839
+ );
5840
+ return;
5841
+ }
4996
5842
  let decodedBody;
4997
5843
  try {
4998
5844
  decodedBody = decodeRequestBody(rawBody, contentEncoding);
@@ -5014,48 +5860,110 @@ async function startMaskeraProxy(options = {}) {
5014
5860
  res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
5015
5861
  return;
5016
5862
  }
5017
- if (isPlainObject(parsed)) {
5018
- let redactedObj;
5019
- try {
5020
- redactedObj = await redactLlmRequestBody(
5021
- parsed,
5022
- async (text, kind) => {
5023
- if (!text.trim()) return text;
5024
- const { result } = await engine.redact(text, {
5025
- mode: kind === "tool_description" ? "rules" : void 0,
5026
- profile: options.profile,
5027
- customTerms: options.customTerms
5028
- });
5029
- const applied = vault.apply(text, result, sessionId);
5030
- stats.redactions += applied.totalRedactions;
5031
- mergeCounts(stats.counts, applied.counts);
5032
- if (redactedPreview.length < 6) {
5033
- const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
5034
- redactedPreview.push(snippet);
5863
+ if (!isPlainObject(parsed)) {
5864
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
5865
+ res.end(JSON.stringify({ error: { message: "Expected JSON object request body." } }));
5866
+ return;
5867
+ }
5868
+ sessionId = deriveProxySessionId(req.headers, parsed);
5869
+ let redactedObj;
5870
+ try {
5871
+ const redactChunk = async (chunk, forceRules) => {
5872
+ if (!chunk.trim()) return chunk;
5873
+ const { result } = await engine.redact(chunk, {
5874
+ mode: forceRules ? "rules" : void 0,
5875
+ profile: options.profile,
5876
+ customTerms: options.customTerms
5877
+ });
5878
+ const applied = vault.apply(chunk, result, sessionId, proxyVaultOwner);
5879
+ stats.redactions += applied.totalRedactions;
5880
+ mergeCounts(stats.counts, applied.counts);
5881
+ if (redactedPreview.length < 6) {
5882
+ const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
5883
+ redactedPreview.push(snippet);
5884
+ }
5885
+ return applied.redacted;
5886
+ };
5887
+ redactedObj = await redactLlmRequestBody(
5888
+ parsed,
5889
+ async (text, kind) => {
5890
+ if (!text.trim()) return text;
5891
+ if (kind === "tool_description") {
5892
+ return redactChunk(text, true);
5893
+ }
5894
+ if (kind === "system") {
5895
+ if (text.length >= 600 && text.includes("\n\n")) {
5896
+ const parts = text.split(/(\n{2,})/);
5897
+ for (let i = 0; i < parts.length; i += 2) {
5898
+ const para = parts[i] ?? "";
5899
+ if (!para.trim()) continue;
5900
+ parts[i] = await redactChunk(para, isLikelyEnglishSystemPrompt(para));
5901
+ }
5902
+ return parts.join("");
5035
5903
  }
5036
- return applied.redacted;
5037
- },
5038
- { mutate: true }
5039
- );
5040
- } catch (err) {
5904
+ return redactChunk(text, isLikelyEnglishSystemPrompt(text));
5905
+ }
5906
+ return redactChunk(text, false);
5907
+ },
5908
+ {
5909
+ mutate: true,
5910
+ onBinaryAttachment: (kind) => {
5911
+ binaryAttachments.add(kind);
5912
+ }
5913
+ }
5914
+ );
5915
+ } catch (err) {
5916
+ recordAuditAndInspector({
5917
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5918
+ method,
5919
+ path: forwardPath,
5920
+ upstream: baseUrl,
5921
+ sessionId,
5922
+ status: 502,
5923
+ streamed: false,
5924
+ durationMs: Date.now() - startedAt,
5925
+ redactions: stats.redactions,
5926
+ counts: stats.counts,
5927
+ redactedPreview
5928
+ });
5929
+ throw err;
5930
+ }
5931
+ if (binaryAttachments.size > 0) {
5932
+ const kinds = [...binaryAttachments];
5933
+ const warning = `Uninspectable binary attachment(s) without OCR: ${kinds.join(", ")}`;
5934
+ requestWarnings = [warning];
5935
+ log(`[maskera-proxy] warning: ${warning}`);
5936
+ if (blockBinary) {
5041
5937
  recordAuditAndInspector({
5042
5938
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5043
5939
  method,
5044
5940
  path: forwardPath,
5045
5941
  upstream: baseUrl,
5046
5942
  sessionId,
5047
- status: 502,
5943
+ status: 415,
5048
5944
  streamed: false,
5049
5945
  durationMs: Date.now() - startedAt,
5050
5946
  redactions: stats.redactions,
5051
5947
  counts: stats.counts,
5052
- redactedPreview
5948
+ redactedPreview,
5949
+ warnings: requestWarnings
5053
5950
  });
5054
- throw err;
5951
+ res.writeHead(415, {
5952
+ "content-type": "application/json; charset=utf-8",
5953
+ "x-maskera-warning": "uninspectable-binary-attachment"
5954
+ });
5955
+ res.end(
5956
+ JSON.stringify({
5957
+ error: {
5958
+ message: `Refusing to forward uninspectable binary attachment(s) (${kinds.join(", ")}) when --block-binary is enabled.`
5959
+ }
5960
+ })
5961
+ );
5962
+ return;
5055
5963
  }
5056
- outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
5057
- rewroteRequestBody = true;
5058
5964
  }
5965
+ outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
5966
+ rewroteRequestBody = true;
5059
5967
  }
5060
5968
  const forwardHeaders = new Headers();
5061
5969
  for (const [k, v] of Object.entries(req.headers)) {
@@ -5082,6 +5990,7 @@ async function startMaskeraProxy(options = {}) {
5082
5990
  method,
5083
5991
  headers: forwardHeaders,
5084
5992
  body: outgoingBody ? new Uint8Array(outgoingBody) : void 0,
5993
+ redirect: "manual",
5085
5994
  signal: abortController.signal
5086
5995
  });
5087
5996
  } catch (err) {
@@ -5111,7 +6020,10 @@ async function startMaskeraProxy(options = {}) {
5111
6020
  }
5112
6021
  });
5113
6022
  outHeaders["x-maskera-redacted"] = String(stats.redactions);
5114
- const sessionMap = restoreResponses ? vault.getMap(sessionId) : {};
6023
+ if (requestWarnings) {
6024
+ outHeaders["x-maskera-warning"] = "uninspectable-binary-attachment";
6025
+ }
6026
+ const sessionMap = restoreResponses ? vault.getMap(sessionId, proxyVaultOwner) : {};
5115
6027
  const hasMap = Object.keys(sessionMap).length > 0;
5116
6028
  const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
5117
6029
  const isSse = resContentType.includes("text/event-stream");
@@ -5162,7 +6074,8 @@ async function startMaskeraProxy(options = {}) {
5162
6074
  durationMs: durationMs2,
5163
6075
  redactions: stats.redactions,
5164
6076
  counts: stats.counts,
5165
- redactedPreview
6077
+ redactedPreview,
6078
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5166
6079
  });
5167
6080
  log(
5168
6081
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${durationMs2}ms`
@@ -5194,7 +6107,8 @@ async function startMaskeraProxy(options = {}) {
5194
6107
  durationMs: durationMs2,
5195
6108
  redactions: stats.redactions,
5196
6109
  counts: stats.counts,
5197
- redactedPreview
6110
+ redactedPreview,
6111
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5198
6112
  });
5199
6113
  log(
5200
6114
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${durationMs2}ms`
@@ -5217,7 +6131,8 @@ async function startMaskeraProxy(options = {}) {
5217
6131
  durationMs,
5218
6132
  redactions: stats.redactions,
5219
6133
  counts: stats.counts,
5220
- redactedPreview
6134
+ redactedPreview,
6135
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5221
6136
  });
5222
6137
  log(
5223
6138
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${durationMs}ms`
@@ -5614,6 +6529,7 @@ async function runWrap(options) {
5614
6529
  profile: options.profile,
5615
6530
  customTerms: options.customTerms,
5616
6531
  restoreResponses: options.restoreResponses,
6532
+ blockBinary: options.blockBinary,
5617
6533
  auditLogPath: options.auditLogPath
5618
6534
  });
5619
6535
  let startupReceipt = null;
@@ -5741,6 +6657,7 @@ function parseArgs(argv) {
5741
6657
  let anthropicUpstream = process.env.MASKERA_ANTHROPIC_UPSTREAM || void 0;
5742
6658
  let openaiUpstream = process.env.MASKERA_OPENAI_UPSTREAM || void 0;
5743
6659
  let restoreResponses = true;
6660
+ let blockBinary = process.env.MASKERA_PROXY_BLOCK_BINARY === "1";
5744
6661
  let auditLogPath = process.env.MASKERA_AUDIT_LOG || void 0;
5745
6662
  let openInspector = false;
5746
6663
  let wrapCommand;
@@ -5813,6 +6730,8 @@ function parseArgs(argv) {
5813
6730
  approvalMode = parseApprovalMode(value);
5814
6731
  } else if (flag === "--no-restore") {
5815
6732
  restoreResponses = false;
6733
+ } else if (flag === "--block-binary") {
6734
+ blockBinary = true;
5816
6735
  } else if (flag === "--open") {
5817
6736
  openInspector = true;
5818
6737
  } else if (flag === "--redact") {
@@ -5943,6 +6862,7 @@ function parseArgs(argv) {
5943
6862
  anthropicUpstream,
5944
6863
  openaiUpstream,
5945
6864
  restoreResponses,
6865
+ blockBinary,
5946
6866
  auditLogPath,
5947
6867
  openInspector,
5948
6868
  wrapCommand,
@@ -5973,7 +6893,7 @@ function printHelp() {
5973
6893
  "",
5974
6894
  "Usage:",
5975
6895
  " maskera-mcp [mcp] [--root <dir>] [--no-raw-restore] [--read-only] [--approval-mode automatic|native] [--rules-only]",
5976
- " maskera-mcp proxy [--port 8787] [--host 127.0.0.1] [--root <dir>] [--open] [--upstream <url>] [--audit-log <file.jsonl>] [--no-raw-restore] [--read-only] [--approval-mode automatic|browser] [--rules-only] [--no-restore]",
6896
+ " maskera-mcp proxy [--port 8787] [--host 127.0.0.1] [--root <dir>] [--open] [--upstream <url>] [--audit-log <file.jsonl>] [--no-raw-restore] [--read-only] [--approval-mode automatic|browser] [--rules-only] [--no-restore] [--block-binary]",
5977
6897
  " maskera-mcp wrap [flags] -- <cmd> [args...] Start local proxy, verify, inject ANTHROPIC_BASE_URL/OPENAI_BASE_URL, and run <cmd>",
5978
6898
  " maskera-mcp guard [--redact] [--file <path>] [--proxy-url <url>] [--no-proxy] [--rules-only]",
5979
6899
  ` maskera-mcp install [client|all] [--transport stdio|http] [--url <http://127.0.0.1:8787/mcp>] [--root <dir>] [--apply] [--project] [--with-hook] [--no-raw-restore] [--read-only] [--config <path>] [--receipt <file.json>] [--no-verify] [--dry-run]`,
@@ -5996,6 +6916,7 @@ function printHelp() {
5996
6916
  " --no-raw-restore Block maskera_restore and include_map=true (allow maskera_write_file only)",
5997
6917
  " --read-only Hide and block maskera_write_file and maskera_clear_session",
5998
6918
  " --approval-mode <m> Raw PII export gate: 'automatic' (default), 'browser', or 'native'",
6919
+ " --block-binary Block uninspectable binary attachments (images/PDFs) in proxy with HTTP 415",
5999
6920
  " --open Open local live inspector (/_maskera) in the browser (proxy/wrap)",
6000
6921
  " -v, --version Print version",
6001
6922
  " -h, --help Print this help",
@@ -6029,10 +6950,17 @@ function buildEngine(args) {
6029
6950
  }
6030
6951
  });
6031
6952
  }
6032
- async function readStdinAll() {
6953
+ var MAX_GUARD_INPUT_BYTES = 16 * 1024 * 1024;
6954
+ async function readStdinAll(maxBytes = MAX_GUARD_INPUT_BYTES) {
6033
6955
  const chunks = [];
6956
+ let total = 0;
6034
6957
  for await (const chunk of process.stdin) {
6035
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
6958
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
6959
+ total += buf.byteLength;
6960
+ if (total > maxBytes) {
6961
+ throw new Error(`Input exceeds max allowed size (${maxBytes} bytes).`);
6962
+ }
6963
+ chunks.push(buf);
6036
6964
  }
6037
6965
  return Buffer.concat(chunks).toString("utf8");
6038
6966
  }
@@ -6248,6 +7176,11 @@ Verify: ${primary.verifyStep}
6248
7176
  let raw;
6249
7177
  if (args.file) {
6250
7178
  const buf = await readFile(args.file);
7179
+ if (buf.byteLength > MAX_GUARD_INPUT_BYTES) {
7180
+ throw new Error(
7181
+ `"${args.file}" is ${buf.byteLength} bytes (max ${MAX_GUARD_INPUT_BYTES} bytes for guard).`
7182
+ );
7183
+ }
6251
7184
  if (buf.includes(0)) {
6252
7185
  throw new Error(`"${args.file}" appears to be a binary file; only UTF-8 text is supported.`);
6253
7186
  }
@@ -6312,6 +7245,7 @@ Verify: ${primary.verifyStep}
6312
7245
  profile: args.profile,
6313
7246
  customTerms: args.customTerms.length > 0 ? args.customTerms : void 0,
6314
7247
  restoreResponses: args.restoreResponses,
7248
+ blockBinary: args.blockBinary,
6315
7249
  auditLogPath: args.auditLogPath,
6316
7250
  verify: args.verify,
6317
7251
  receiptPath: args.receiptPath,
@@ -6358,6 +7292,7 @@ Verify: ${primary.verifyStep}
6358
7292
  profile: args.profile,
6359
7293
  customTerms: args.customTerms.length > 0 ? args.customTerms : void 0,
6360
7294
  restoreResponses: args.restoreResponses,
7295
+ blockBinary: args.blockBinary,
6361
7296
  auditLogPath: args.auditLogPath,
6362
7297
  onLog: (line) => process.stderr.write(`${line}
6363
7298
  `)