@maskera/mcp 0.4.1 → 0.4.3

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,121 +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
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';
8
9
  import { randomUUID, createHash } from 'crypto';
9
- import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
10
10
  import { spawn, spawnSync } from 'child_process';
11
11
  import { homedir } from 'os';
12
12
  import { createServer } from 'http';
13
13
  import * as zlib from 'zlib';
14
14
 
15
- var DEFAULT_TTL_MS = 5 * 60 * 1e3;
16
- var MAX_RECORDS = 50;
17
- var ApprovalBroker = class {
18
- constructor(ttlMs = DEFAULT_TTL_MS) {
19
- this.records = /* @__PURE__ */ new Map();
20
- this.listeners = /* @__PURE__ */ new Set();
21
- this.ttlMs = Math.max(1e3, ttlMs);
22
- }
23
- expireStale(now = Date.now()) {
24
- let changed = false;
25
- for (const record of this.records.values()) {
26
- if (record.summary.status === "pending" && now >= record.expiresAtMs) {
27
- record.summary.status = "expired";
28
- record.execute = null;
29
- 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;
30
72
  }
31
73
  }
32
- if (changed) this.notify();
33
- }
34
- notify() {
35
- const snapshot = this.list();
36
- for (const listener of this.listeners) {
37
- try {
38
- listener(snapshot);
39
- } 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;
40
83
  }
41
84
  }
42
- }
43
- onChange(listener) {
44
- this.listeners.add(listener);
45
- return () => {
46
- this.listeners.delete(listener);
47
- };
48
- }
49
- create(input) {
50
- this.expireStale();
51
- if (this.records.size >= MAX_RECORDS) {
52
- const oldestKey = this.records.keys().next().value;
53
- if (oldestKey !== void 0) this.records.delete(oldestKey);
54
- }
55
- const now = Date.now();
56
- const id = `apr_${randomUUID().slice(0, 12)}`;
57
- const summary = {
58
- id,
59
- tool: input.tool,
60
- reason: input.reason,
61
- sessionId: input.sessionId ?? null,
62
- placeholderCount: input.placeholderCount,
63
- status: "pending",
64
- createdAt: new Date(now).toISOString(),
65
- expiresAt: new Date(now + this.ttlMs).toISOString(),
66
- decidedAt: null
67
- };
68
- this.records.set(id, {
69
- summary,
70
- expiresAtMs: now + this.ttlMs,
71
- execute: input.execute
72
- });
73
- this.notify();
74
- return { ...summary };
75
- }
76
- list() {
77
- this.expireStale();
78
- return [...this.records.values()].map((r) => ({ ...r.summary })).reverse();
79
- }
80
- decide(id, decision) {
81
- this.expireStale();
82
- const record = this.records.get(id.trim());
83
- if (!record) return null;
84
- if (record.summary.status !== "pending") return { ...record.summary };
85
- record.summary.status = decision === "approve" ? "approved" : "declined";
86
- record.summary.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
87
- if (decision === "decline") {
88
- record.execute = null;
89
- }
90
- this.notify();
91
- return { ...record.summary };
92
- }
93
- async resume(id) {
94
- this.expireStale();
95
- const record = this.records.get(id.trim());
96
- if (!record) return { status: "not_found" };
97
- const { status } = record.summary;
98
- if (status === "pending" || status === "declined" || status === "expired") {
99
- return { status, summary: { ...record.summary } };
100
- }
101
- if (status === "completed" || !record.execute) {
102
- 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
+ }
103
127
  }
104
- const run = record.execute;
105
- record.execute = null;
106
- const result = await run();
107
- record.summary.status = "completed";
108
- this.notify();
109
- return { status: "completed", result, summary: { ...record.summary } };
110
- }
111
- clearAll() {
112
- this.records.clear();
113
- this.notify();
114
128
  }
115
- };
116
- var WORD_CHAR = /[\p{L}\p{N}_]/u;
117
- var DEFAULT_MAX_CACHE_ENTRIES = 512;
118
- var MAX_CUSTOM_DETECTOR_CACHE = 64;
129
+ return extra;
130
+ }
119
131
  function escapeRegExp(value) {
120
132
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
121
133
  }
@@ -123,7 +135,7 @@ function normalizeCustomTerms(rawTerms) {
123
135
  const unique = /* @__PURE__ */ new Map();
124
136
  for (const raw of rawTerms) {
125
137
  if (typeof raw !== "string") continue;
126
- const trimmed = raw.trim();
138
+ const trimmed = canonicalize(raw.trim()).text.trim();
127
139
  if (trimmed.length < 2 || trimmed.length > 160) continue;
128
140
  const folded = trimmed.toLowerCase();
129
141
  if (!unique.has(folded)) unique.set(folded, trimmed);
@@ -277,12 +289,28 @@ function createMaskeraEngine(options = {}) {
277
289
  }
278
290
  const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
279
291
  if (requestedMode === "rules") {
280
- const result = req.profile === "clinical" ? redactFromDetections(
281
- text,
282
- runDetectors(text, detectors).filter(
283
- (d) => clinicalPrecisionFilter(d, text, "rule")
284
- )
285
- ) : 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
+ }
286
314
  if (cacheKey) {
287
315
  if (spanCache.size >= maxCacheEntries) {
288
316
  const oldest = spanCache.keys().next().value;
@@ -304,11 +332,36 @@ function createMaskeraEngine(options = {}) {
304
332
  }
305
333
  try {
306
334
  const ner = getRecognizer();
307
- 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, {
308
340
  recognizer: ner,
309
341
  detectors,
310
342
  profile: req.profile
311
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
+ );
312
365
  nerLoaded = true;
313
366
  nerError = null;
314
367
  if (cacheKey) {
@@ -600,7 +653,8 @@ function createFileGuard(roots = [process.cwd()]) {
600
653
  }
601
654
  await writeFile(targetReal, content, {
602
655
  encoding: "utf8",
603
- flag: options.overwrite ? "w" : "wx"
656
+ flag: options.overwrite ? "w" : "wx",
657
+ mode: 384
604
658
  }).catch((err) => {
605
659
  if (err.code === "EEXIST") {
606
660
  throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
@@ -676,7 +730,7 @@ function createFileGuard(roots = [process.cwd()]) {
676
730
  matches.push({
677
731
  path: file.relPath,
678
732
  line: i + 1,
679
- lineText: lineText.length > 500 ? `${lineText.slice(0, 500)}...` : lineText
733
+ lineText: lineText.length > 16384 ? lineText.slice(0, 16384) : lineText
680
734
  });
681
735
  if (matches.length >= maxMatches) {
682
736
  truncated = true;
@@ -860,7 +914,18 @@ ${MASKERA_SKILL_MARKDOWN}`
860
914
  }
861
915
  var DEFAULT_MAX_SESSIONS = 100;
862
916
  var DEFAULT_MAX_ENTITIES_PER_SESSION = 5e3;
917
+ var DEFAULT_OWNER = "default";
863
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
+ }
864
929
  function valueKey(label, value) {
865
930
  return `${label.length}:${label}:${value}`;
866
931
  }
@@ -877,12 +942,14 @@ var SessionVault = class {
877
942
  this.maxSessions = Math.max(1, maxSessions);
878
943
  this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
879
944
  }
880
- getOrCreate(sessionId) {
945
+ getOrCreate(sessionId, owner) {
881
946
  const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
882
- const existing = this.sessions.get(id);
947
+ const resolvedOwner = normalizeOwner(owner);
948
+ const storageKey = ownerStorageKey(resolvedOwner, id);
949
+ const existing = this.sessions.get(storageKey);
883
950
  if (existing) {
884
- this.sessions.delete(id);
885
- this.sessions.set(id, existing);
951
+ this.sessions.delete(storageKey);
952
+ this.sessions.set(storageKey, existing);
886
953
  existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
887
954
  return existing;
888
955
  }
@@ -893,14 +960,15 @@ var SessionVault = class {
893
960
  const now = (/* @__PURE__ */ new Date()).toISOString();
894
961
  const created = {
895
962
  id,
963
+ owner: resolvedOwner,
896
964
  createdAt: now,
897
965
  updatedAt: now,
898
966
  tokenByKey: /* @__PURE__ */ new Map(),
899
- map: {},
967
+ map: /* @__PURE__ */ Object.create(null),
900
968
  counters: /* @__PURE__ */ new Map(),
901
969
  countsByLabel: {}
902
970
  };
903
- this.sessions.set(id, created);
971
+ this.sessions.set(storageKey, created);
904
972
  return created;
905
973
  }
906
974
  /**
@@ -908,8 +976,8 @@ var SessionVault = class {
908
976
  * the same entity receives the exact same placeholder across multiple calls
909
977
  * and files in the same session, while avoiding collisions with literal text.
910
978
  */
911
- apply(originalInput, result, sessionId) {
912
- const session = this.getOrCreate(sessionId);
979
+ apply(originalInput, result, sessionId, owner) {
980
+ const session = this.getOrCreate(sessionId, owner);
913
981
  if (result.redactions.length === 0) {
914
982
  return {
915
983
  sessionId: session.id,
@@ -935,7 +1003,7 @@ var SessionVault = class {
935
1003
  for (; ; ) {
936
1004
  next += 1;
937
1005
  const candidate = `[${r.label}_${next}]`;
938
- if (!(candidate in session.map) && !existingTokens?.has(candidate)) {
1006
+ if (!hasOwn(session.map, candidate) && !existingTokens?.has(candidate)) {
939
1007
  token = candidate;
940
1008
  break;
941
1009
  }
@@ -984,7 +1052,8 @@ var SessionVault = class {
984
1052
  if (!normalizedId) {
985
1053
  throw new Error("Provide either session_id or map to restore placeholders.");
986
1054
  }
987
- const session = this.sessions.get(normalizedId);
1055
+ const resolvedOwner = normalizeOwner(options.owner);
1056
+ const session = this.sessions.get(ownerStorageKey(resolvedOwner, normalizedId));
988
1057
  if (!session) {
989
1058
  throw new Error(`Unknown session_id "${normalizedId}".`);
990
1059
  }
@@ -996,14 +1065,14 @@ var SessionVault = class {
996
1065
  }
997
1066
  /**
998
1067
  * Picks the session that restores `text` when the caller named none.
999
- * A candidate must know every placeholder in the text. When several do and
1000
- * would restore it differently, the choice is ambiguous and refused, so a
1001
- * missing session_id can never put another document's values into a file.
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.
1002
1070
  */
1003
- resolveSessionFor(text) {
1071
+ resolveSessionFor(text, owner) {
1072
+ const resolvedOwner = normalizeOwner(owner);
1004
1073
  const tokens = [...new Set(text.match(EXISTING_TOKEN_RE) ?? [])];
1005
1074
  const candidates = [...this.sessions.values()].filter(
1006
- (s) => tokens.every((token) => token in s.map)
1075
+ (s) => s.owner === resolvedOwner && tokens.every((token) => hasOwn(s.map, token))
1007
1076
  );
1008
1077
  if (candidates.length === 0) {
1009
1078
  throw new Error(
@@ -1020,8 +1089,9 @@ var SessionVault = class {
1020
1089
  if (!latest) throw new Error("No local session can restore this text.");
1021
1090
  return latest.id;
1022
1091
  }
1023
- getMap(sessionId) {
1024
- const session = this.sessions.get(sessionId.trim());
1092
+ getMap(sessionId, owner) {
1093
+ const resolvedOwner = normalizeOwner(owner);
1094
+ const session = this.sessions.get(ownerStorageKey(resolvedOwner, sessionId.trim()));
1025
1095
  return session ? { ...session.map } : {};
1026
1096
  }
1027
1097
  entries() {
@@ -1036,17 +1106,44 @@ var SessionVault = class {
1036
1106
  clearAll() {
1037
1107
  this.sessions.clear();
1038
1108
  }
1039
- list() {
1040
- return [...this.sessions.values()].map((s) => ({
1041
- sessionId: s.id,
1042
- entityCount: Object.keys(s.map).length,
1043
- countsByLabel: { ...s.countsByLabel },
1044
- createdAt: s.createdAt,
1045
- updatedAt: s.updatedAt
1046
- }));
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;
1119
+ }
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;
1047
1134
  }
1048
- clear(sessionId) {
1049
- return this.sessions.delete(sessionId.trim());
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;
1050
1147
  }
1051
1148
  get size() {
1052
1149
  return this.sessions.size;
@@ -1504,6 +1601,35 @@ var TOOLS = [
1504
1601
  }
1505
1602
  ];
1506
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;
1507
1633
  function asObject(value) {
1508
1634
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1509
1635
  }
@@ -1543,6 +1669,30 @@ function toolError(message) {
1543
1669
  content: [{ type: "text", text: message }]
1544
1670
  };
1545
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
+ }
1546
1696
  function createMaskeraMcpServer(options = {}) {
1547
1697
  const engine = options.engine ?? createMaskeraEngine();
1548
1698
  const vault = options.vault ?? new SessionVault();
@@ -1554,11 +1704,155 @@ function createMaskeraMcpServer(options = {}) {
1554
1704
  const requestElicitation = options.requestElicitation;
1555
1705
  const onToolCall = options.onToolCall;
1556
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
+ }
1557
1850
  function resolvePolicy(override) {
1558
1851
  return {
1559
1852
  allowRawRestore: override?.allowRawRestore ?? options.allowRawRestore ?? true,
1560
1853
  readOnly: override?.readOnly ?? options.readOnly ?? false,
1561
- approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic"
1854
+ approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic",
1855
+ sessionOwner: override?.sessionOwner ?? options.sessionOwner ?? "default"
1562
1856
  };
1563
1857
  }
1564
1858
  function visibleTools(policy) {
@@ -1581,7 +1875,7 @@ function createMaskeraMcpServer(options = {}) {
1581
1875
  server: SERVER_NAME,
1582
1876
  version: SERVER_VERSION,
1583
1877
  engine: engine.status(),
1584
- active_sessions: vault.size,
1878
+ active_sessions: vault.sizeForOwner(policy.sessionOwner),
1585
1879
  allowed_roots: files.allowedRoots,
1586
1880
  policy: {
1587
1881
  read_only: policy.readOnly,
@@ -1636,6 +1930,7 @@ function createMaskeraMcpServer(options = {}) {
1636
1930
  tool: input.tool,
1637
1931
  reason: input.reason,
1638
1932
  sessionId: input.sessionId,
1933
+ owner: policy.sessionOwner,
1639
1934
  placeholderCount: input.placeholderCount,
1640
1935
  execute: input.execute
1641
1936
  });
@@ -1652,6 +1947,7 @@ function createMaskeraMcpServer(options = {}) {
1652
1947
  async function callTool(name, rawArgs, policy) {
1653
1948
  const startedAt = Date.now();
1654
1949
  const args = asObject(rawArgs);
1950
+ const owner = policy.sessionOwner;
1655
1951
  let telemetrySessionId;
1656
1952
  let telemetryRedactions = 0;
1657
1953
  let telemetryCounts = {};
@@ -1688,7 +1984,8 @@ function createMaskeraMcpServer(options = {}) {
1688
1984
  const applied = vault.apply(
1689
1985
  args.text,
1690
1986
  result,
1691
- typeof args.session_id === "string" ? args.session_id : void 0
1987
+ typeof args.session_id === "string" ? args.session_id : void 0,
1988
+ owner
1692
1989
  );
1693
1990
  telemetrySessionId = applied.sessionId;
1694
1991
  telemetryRedactions = applied.totalRedactions;
@@ -1716,6 +2013,13 @@ function createMaskeraMcpServer(options = {}) {
1716
2013
  return finish(toolOk(payload));
1717
2014
  }
1718
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
+ }
1719
2023
  if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1720
2024
  const explicitMap = args.map && typeof args.map === "object" && !Array.isArray(args.map) ? Object.fromEntries(
1721
2025
  Object.entries(args.map).filter(
@@ -1726,7 +2030,8 @@ function createMaskeraMcpServer(options = {}) {
1726
2030
  telemetrySessionId = sessionIdArg;
1727
2031
  const preview = vault.restore(args.text, {
1728
2032
  sessionId: sessionIdArg,
1729
- map: explicitMap
2033
+ map: explicitMap,
2034
+ owner
1730
2035
  });
1731
2036
  return finish(
1732
2037
  await gateRawPiiExport({
@@ -1751,7 +2056,7 @@ function createMaskeraMcpServer(options = {}) {
1751
2056
  return finish(toolError("Missing required non-empty string: request_id"));
1752
2057
  }
1753
2058
  const requestId = args.request_id.trim();
1754
- const resumed = await approvals.resume(requestId);
2059
+ const resumed = await approvals.resume(requestId, owner);
1755
2060
  if (resumed.status === "not_found") {
1756
2061
  return finish(toolError(`Unknown approval request_id "${requestId}".`));
1757
2062
  }
@@ -1773,23 +2078,38 @@ function createMaskeraMcpServer(options = {}) {
1773
2078
  }
1774
2079
  if (name === "maskera_read_file") {
1775
2080
  if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1776
- 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));
1777
2094
  const { result, modeUsed } = await engine.redact(file.content, {
1778
- mode: asMode(args.mode),
1779
- profile: asProfile(args.profile) ?? defaultProfile,
1780
- 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
1781
2106
  });
1782
- const applied = vault.apply(
1783
- file.content,
1784
- result,
1785
- typeof args.session_id === "string" ? args.session_id : void 0
1786
- );
1787
2107
  telemetrySessionId = applied.sessionId;
1788
2108
  telemetryRedactions = applied.totalRedactions;
1789
2109
  telemetryCounts = applied.counts;
1790
2110
  return finish(
1791
2111
  toolOk({
1792
- path: file.resolvedPath,
2112
+ path: safePath,
1793
2113
  bytes: file.bytes,
1794
2114
  redacted: applied.redacted,
1795
2115
  session_id: applied.sessionId,
@@ -1802,17 +2122,25 @@ function createMaskeraMcpServer(options = {}) {
1802
2122
  if (name === "maskera_write_file") {
1803
2123
  if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1804
2124
  if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1805
- const normalizedSessionId = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : vault.resolveSessionFor(args.text);
2125
+ const normalizedSessionId = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : vault.resolveSessionFor(args.text, owner);
1806
2126
  telemetrySessionId = normalizedSessionId;
1807
2127
  const { restored, knownPlaceholders } = vault.restore(args.text, {
1808
- sessionId: normalizedSessionId
2128
+ sessionId: normalizedSessionId,
2129
+ owner
1809
2130
  });
1810
- const written = await files.writeText(args.path, restored, {
2131
+ const resolvedTargetPath = resolveInputPath(args.path, owner, normalizedSessionId);
2132
+ const written = await files.writeText(resolvedTargetPath, restored, {
1811
2133
  overwrite: args.overwrite === true
1812
2134
  });
2135
+ const safePath = await redactResolvedPath(written.resolvedPath, {
2136
+ owner,
2137
+ sessionId: normalizedSessionId,
2138
+ profile: defaultProfile,
2139
+ customTerms: defaultCustomTerms
2140
+ });
1813
2141
  return finish(
1814
2142
  toolOk({
1815
- path: written.resolvedPath,
2143
+ path: safePath,
1816
2144
  bytes: written.bytes,
1817
2145
  session_id: normalizedSessionId,
1818
2146
  known_placeholders: knownPlaceholders
@@ -1827,11 +2155,25 @@ function createMaskeraMcpServer(options = {}) {
1827
2155
  maxDepth: asOptionalInt(args.max_depth)
1828
2156
  }
1829
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
+ }
1830
2171
  return finish(
1831
2172
  toolOk({
1832
2173
  root: listed.root,
1833
- files: listed.files,
1834
- truncated: listed.truncated
2174
+ files: safeFiles,
2175
+ truncated: listed.truncated,
2176
+ ...pathSessionId ? { session_id: pathSessionId } : {}
1835
2177
  })
1836
2178
  );
1837
2179
  }
@@ -1839,11 +2181,19 @@ function createMaskeraMcpServer(options = {}) {
1839
2181
  if (typeof args.query !== "string" || !args.query.trim()) {
1840
2182
  return finish(toolError("Missing required non-empty string: query"));
1841
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
+ }
1842
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) : {};
1843
2194
  let resolvedQuery = args.query.trim();
1844
2195
  if (requestedSession && PLACEHOLDER_QUERY_RE.test(resolvedQuery)) {
1845
- const map = vault.getMap(requestedSession);
1846
- const mapped = map[resolvedQuery];
2196
+ const mapped = existingSessionMap[resolvedQuery];
1847
2197
  if (mapped) {
1848
2198
  resolvedQuery = mapped;
1849
2199
  }
@@ -1853,7 +2203,6 @@ function createMaskeraMcpServer(options = {}) {
1853
2203
  caseSensitive: args.case_sensitive === true,
1854
2204
  maxMatches: asOptionalInt(args.max_matches)
1855
2205
  });
1856
- const mode = asMode(args.mode);
1857
2206
  const profile = asProfile(args.profile) ?? defaultProfile;
1858
2207
  const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
1859
2208
  let activeSessionId = requestedSession;
@@ -1866,22 +2215,35 @@ function createMaskeraMcpServer(options = {}) {
1866
2215
  profile,
1867
2216
  customTerms
1868
2217
  });
1869
- const applied = vault.apply(match.lineText, result, activeSessionId);
2218
+ const applied = vault.apply(match.lineText, result, activeSessionId, owner);
1870
2219
  activeSessionId = applied.sessionId;
1871
2220
  totalRedactions += applied.totalRedactions;
1872
2221
  for (const [label, count] of Object.entries(applied.counts)) {
1873
2222
  totalCounts[label] = (totalCounts[label] ?? 0) + count;
1874
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;
1875
2236
  redactedMatches.push({
1876
- path: match.path,
2237
+ path: safeMatchPath.path,
1877
2238
  line: match.line,
1878
- redacted_line: applied.redacted
2239
+ redacted_line: truncatePreservingPlaceholders(safeguarded.text, 500)
1879
2240
  });
1880
2241
  }
1881
2242
  const ensuredSessionId = activeSessionId ?? vault.apply(
1882
2243
  "",
1883
2244
  { text: "", map: {}, redactions: [], restore: (s) => s },
1884
- requestedSession
2245
+ requestedSession,
2246
+ owner
1885
2247
  ).sessionId;
1886
2248
  telemetrySessionId = ensuredSessionId;
1887
2249
  telemetryRedactions = totalRedactions;
@@ -1899,7 +2261,7 @@ function createMaskeraMcpServer(options = {}) {
1899
2261
  );
1900
2262
  }
1901
2263
  if (name === "maskera_list_sessions") {
1902
- return finish(toolOk({ sessions: vault.list() }));
2264
+ return finish(toolOk({ sessions: vault.list(owner) }));
1903
2265
  }
1904
2266
  if (name === "maskera_clear_session") {
1905
2267
  if (typeof args.session_id !== "string" || !args.session_id.trim()) {
@@ -1910,7 +2272,7 @@ function createMaskeraMcpServer(options = {}) {
1910
2272
  return finish(
1911
2273
  toolOk({
1912
2274
  session_id: normalizedSessionId,
1913
- cleared: vault.clear(normalizedSessionId)
2275
+ cleared: vault.clear(normalizedSessionId, owner)
1914
2276
  })
1915
2277
  );
1916
2278
  }
@@ -1933,7 +2295,7 @@ function createMaskeraMcpServer(options = {}) {
1933
2295
  };
1934
2296
  }
1935
2297
  const req = raw;
1936
- const hasIdProp = Object.prototype.hasOwnProperty.call(req, "id");
2298
+ const hasIdProp = Object.hasOwn(req, "id");
1937
2299
  const validId = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
1938
2300
  if (req.jsonrpc !== "2.0" || typeof req.method !== "string" || hasIdProp && validId === void 0) {
1939
2301
  return {
@@ -1950,9 +2312,7 @@ function createMaskeraMcpServer(options = {}) {
1950
2312
  if (req.method === "initialize") {
1951
2313
  const params = asObject(req.params);
1952
2314
  const clientCaps = asObject(params.capabilities);
1953
- if ("elicitation" in clientCaps && clientCaps.elicitation) {
1954
- clientSupportsElicitation = true;
1955
- }
2315
+ clientSupportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
1956
2316
  const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
1957
2317
  const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
1958
2318
  return {
@@ -2395,6 +2755,25 @@ async function runGuard(rawInput, engine, options = {}) {
2395
2755
  }
2396
2756
  return out.result.text;
2397
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
+ }
2398
2777
  if (Array.isArray(value)) {
2399
2778
  const arr = [];
2400
2779
  for (const item of value) arr.push(await redactJson(item));
@@ -2892,6 +3271,128 @@ async function runInstall(options) {
2892
3271
  verifyStep
2893
3272
  };
2894
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
+ };
2895
3396
 
2896
3397
  // src/inspector.ts
2897
3398
  var MAX_EVENTS = 100;
@@ -3597,12 +4098,12 @@ function mergeCounts(target, delta) {
3597
4098
  }
3598
4099
  }
3599
4100
  function restorePlainText(text, map) {
3600
- if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
4101
+ if (!text?.includes("[") || Object.keys(map).length === 0) return text;
3601
4102
  const r = new StreamingRestorer(map);
3602
4103
  return r.push(text) + r.flush();
3603
4104
  }
3604
4105
  function restoreJsonEncodedText(text, map) {
3605
- if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
4106
+ if (!text?.includes("[") || Object.keys(map).length === 0) return text;
3606
4107
  try {
3607
4108
  const parsed = JSON.parse(text);
3608
4109
  const restored = restoreJsonLeaves(parsed, map);
@@ -3634,14 +4135,127 @@ function shouldSkipToolArgRestore(toolName, argsText) {
3634
4135
  if (toolName === "execute" && MASKERA_VAULT_CODE_RE.test(argsText)) return true;
3635
4136
  return false;
3636
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
+ }
3637
4236
  async function redactLlmRequestBody(body, redactString, options = {}) {
3638
4237
  const clone = options.mutate ? body : structuredClone(body);
4238
+ const noteBinary = (kind) => {
4239
+ options.onBinaryAttachment?.(kind);
4240
+ };
3639
4241
  async function redactContentBlocks(blocks, kind) {
3640
4242
  for (const block of blocks) {
3641
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
+ }
3642
4253
  if (typeof block.text === "string") {
3643
4254
  block.text = await redactString(block.text, kind);
3644
4255
  }
4256
+ if (typeof block.refusal === "string") {
4257
+ block.refusal = await redactString(block.refusal, kind);
4258
+ }
3645
4259
  if (typeof block.thinking === "string") {
3646
4260
  const redactedThinking = await redactString(block.thinking, kind);
3647
4261
  if (redactedThinking !== block.thinking) {
@@ -3665,9 +4279,33 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3665
4279
  } else if (Array.isArray(block.output)) {
3666
4280
  await redactContentBlocks(block.output, kind);
3667
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
+ }
3668
4299
  if (isPlainObject(block.source)) {
3669
4300
  if (block.source.type === "text" && typeof block.source.data === "string") {
3670
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
+ }
3671
4309
  }
3672
4310
  if (typeof block.source.content === "string") {
3673
4311
  block.source.content = await redactString(block.source.content, kind);
@@ -3678,13 +4316,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3678
4316
  if (typeof block.arguments === "string") {
3679
4317
  block.arguments = await redactJsonStringOrText(block.arguments, kind);
3680
4318
  }
3681
- if (isPlainObject(block.input)) {
4319
+ if (typeof block.input === "string") {
4320
+ block.input = await redactJsonStringOrText(block.input, kind);
4321
+ } else if (isPlainObject(block.input)) {
3682
4322
  block.input = await redactObjectStrings(block.input, kind);
3683
4323
  }
3684
4324
  }
3685
4325
  }
3686
4326
  async function redactObjectStrings(value, kind) {
3687
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
+ }
3688
4333
  if (Array.isArray(value)) {
3689
4334
  const out = [];
3690
4335
  for (const item of value) out.push(await redactObjectStrings(item, kind));
@@ -3716,6 +4361,31 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3716
4361
  if (typeof clone.instructions === "string") {
3717
4362
  clone.instructions = await redactString(clone.instructions, "system");
3718
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
+ }
3719
4389
  async function redactToolEntries(entries) {
3720
4390
  for (const tool of entries) {
3721
4391
  if (!isPlainObject(tool)) continue;
@@ -3740,11 +4410,29 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3740
4410
  for (const msg of clone.messages) {
3741
4411
  if (!isPlainObject(msg)) continue;
3742
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
+ }
3743
4416
  if (typeof msg.content === "string") {
3744
4417
  msg.content = await redactString(msg.content, msgKind);
3745
4418
  } else if (Array.isArray(msg.content)) {
3746
4419
  await redactContentBlocks(msg.content, msgKind);
3747
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
+ }
3748
4436
  if (Array.isArray(msg.tool_calls)) {
3749
4437
  for (const call of msg.tool_calls) {
3750
4438
  if (isPlainObject(call) && isPlainObject(call.function)) {
@@ -3779,6 +4467,20 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
3779
4467
  } else if (Array.isArray(item.output)) {
3780
4468
  await redactContentBlocks(item.output, itemKind);
3781
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
+ }
3782
4484
  if (Array.isArray(item.summary)) {
3783
4485
  await redactContentBlocks(item.summary, itemKind);
3784
4486
  }
@@ -3821,6 +4523,9 @@ function restoreLlmResponseBody(body, map, options = {}) {
3821
4523
  if (typeof msg.reasoning_content === "string") {
3822
4524
  msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
3823
4525
  }
4526
+ if (typeof msg.reasoning === "string") {
4527
+ msg.reasoning = restorePlainText(msg.reasoning, map);
4528
+ }
3824
4529
  if (Array.isArray(msg.tool_calls)) {
3825
4530
  for (const call of msg.tool_calls) {
3826
4531
  if (isPlainObject(call) && isPlainObject(call.function)) {
@@ -3845,6 +4550,11 @@ function restoreLlmResponseBody(body, map, options = {}) {
3845
4550
  if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(item.name, item.arguments)) {
3846
4551
  item.arguments = restoreJsonEncodedText(item.arguments, map);
3847
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
+ }
3848
4558
  if (Array.isArray(item.content)) {
3849
4559
  for (const part of item.content) {
3850
4560
  if (isPlainObject(part) && typeof part.text === "string") {
@@ -3998,6 +4708,11 @@ data: ${JSON.stringify({
3998
4708
  events.push(
3999
4709
  `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
4000
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
+ );
4001
4716
  } else if (key.startsWith("resp_reasoning:")) {
4002
4717
  const [, outputIdx, summaryIdx] = key.split(":");
4003
4718
  events.push(
@@ -4131,6 +4846,11 @@ data: ${JSON.stringify({
4131
4846
  delta.reasoning_content
4132
4847
  );
4133
4848
  }
4849
+ if (typeof delta.reasoning === "string") {
4850
+ delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`).push(
4851
+ delta.reasoning
4852
+ );
4853
+ }
4134
4854
  if (Array.isArray(delta.tool_calls)) {
4135
4855
  for (const call of delta.tool_calls) {
4136
4856
  if (!isPlainObject(call)) continue;
@@ -4169,6 +4889,12 @@ data: ${JSON.stringify({
4169
4889
  const d = choice.delta;
4170
4890
  d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
4171
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
+ }
4172
4898
  const toolPrefix = `openai_chat_tool:${cIdx}:`;
4173
4899
  for (const key of [...bufferedToolArgs.keys()]) {
4174
4900
  if (!key.startsWith(toolPrefix)) continue;
@@ -4362,10 +5088,10 @@ ${joined}` : joined;
4362
5088
  sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
4363
5089
  let out = "";
4364
5090
  for (; ; ) {
4365
- const sep2 = sseBuffer.indexOf("\n\n");
4366
- if (sep2 < 0) break;
4367
- const block = sseBuffer.slice(0, sep2);
4368
- 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);
4369
5095
  out += `${processEventBlock(block)}
4370
5096
 
4371
5097
  `;
@@ -4406,6 +5132,38 @@ var INSPECTOR_SECURITY_HEADERS = {
4406
5132
  "cache-control": "no-store"
4407
5133
  };
4408
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
+ }
4409
5167
  function isLoopbackHost(hostHeader, boundHost, boundPort, requirePresent = false) {
4410
5168
  if (!hostHeader) return !requirePresent;
4411
5169
  const raw = hostHeader.trim().toLowerCase();
@@ -4520,8 +5278,8 @@ async function readRequestBody(req) {
4520
5278
  return Buffer.concat(chunks);
4521
5279
  }
4522
5280
  function shouldRedactPath(pathname) {
4523
- const clean = (pathname.split("?")[0] ?? pathname).replace(/\/+$/, "").toLowerCase();
4524
- 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");
4525
5283
  }
4526
5284
  var APPROVAL_STRICTNESS = {
4527
5285
  automatic: 0,
@@ -4553,6 +5311,11 @@ function parseScopedMcpPolicy(urlPath, base) {
4553
5311
  }
4554
5312
  async function startMaskeraProxy(options = {}) {
4555
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
+ }
4556
5319
  const requestedPort = options.port ?? 8787;
4557
5320
  const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
4558
5321
  const vault = options.vault ?? new SessionVault();
@@ -4576,7 +5339,7 @@ async function startMaskeraProxy(options = {}) {
4576
5339
  const closedMcpSessions = /* @__PURE__ */ new Set();
4577
5340
  if (auditLogPath) {
4578
5341
  await mkdir(dirname(auditLogPath), { recursive: true });
4579
- await appendFile(auditLogPath, "", "utf8");
5342
+ await appendFile(auditLogPath, "", { encoding: "utf8", mode: 384 });
4580
5343
  }
4581
5344
  let totalRequests = 0;
4582
5345
  let totalRedactions = 0;
@@ -4640,11 +5403,13 @@ async function startMaskeraProxy(options = {}) {
4640
5403
  });
4641
5404
  auditChain = auditChain.then(
4642
5405
  () => appendFile(auditLogPath, `${auditLine}
4643
- `, "utf8").catch((err) => {
4644
- log(
4645
- `[maskera-proxy] audit log write error: ${err instanceof Error ? err.message : String(err)}`
4646
- );
4647
- })
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
+ )
4648
5413
  );
4649
5414
  }
4650
5415
  }
@@ -4656,7 +5421,7 @@ async function startMaskeraProxy(options = {}) {
4656
5421
  const normalizedPath = normalizeInspectorPath(pathname);
4657
5422
  const isInspectorRoute = normalizedPath === "/_maskera" || normalizedPath.startsWith("/_maskera/") || normalizedPath.includes("/_maskera/") || normalizedPath.endsWith("/_maskera");
4658
5423
  if (isInspectorRoute || pathname === "/healthz") {
4659
- if (!isLoopbackHost(req.headers.host, host, boundPort)) {
5424
+ if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort)) {
4660
5425
  res.writeHead(403, {
4661
5426
  ...INSPECTOR_SECURITY_HEADERS,
4662
5427
  "content-type": "application/json; charset=utf-8"
@@ -4873,7 +5638,7 @@ async function startMaskeraProxy(options = {}) {
4873
5638
  return;
4874
5639
  }
4875
5640
  if (normalizedPath === "/mcp" || normalizedPath === "/mcp/") {
4876
- if (!isLoopbackHost(req.headers.host, host, boundPort, true)) {
5641
+ if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort, true)) {
4877
5642
  res.writeHead(403, {
4878
5643
  ...INSPECTOR_SECURITY_HEADERS,
4879
5644
  "content-type": "application/json; charset=utf-8"
@@ -4896,6 +5661,8 @@ async function startMaskeraProxy(options = {}) {
4896
5661
  if (incomingSessionId) {
4897
5662
  mcpSessions.delete(incomingSessionId);
4898
5663
  closedMcpSessions.add(incomingSessionId);
5664
+ vault.clearOwner(`mcp:${incomingSessionId}`);
5665
+ approvals.clearOwner(`mcp:${incomingSessionId}`);
4899
5666
  if (closedMcpSessions.size > 500) {
4900
5667
  const first = closedMcpSessions.values().next().value;
4901
5668
  if (first !== void 0) closedMcpSessions.delete(first);
@@ -4953,23 +5720,37 @@ async function startMaskeraProxy(options = {}) {
4953
5720
  );
4954
5721
  return;
4955
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
+ }
4956
5733
  const sessionBasePolicy = (incomingSessionId ? mcpSessions.get(incomingSessionId) : void 0) ?? baseMcpPolicy;
4957
5734
  const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
4958
5735
  const mcpServer = getMcpServer();
4959
- const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
4960
- const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
4961
5736
  let responseSessionId = incomingSessionId;
4962
5737
  if (isInit) {
4963
5738
  responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
4964
5739
  if (mcpSessions.size >= 200) {
4965
5740
  const oldest = mcpSessions.keys().next().value;
4966
- 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
+ }
4967
5746
  }
4968
5747
  mcpSessions.set(responseSessionId, effectivePolicy);
4969
5748
  }
5749
+ const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
5750
+ const scopedPolicy = { ...effectivePolicy, sessionOwner };
4970
5751
  const responses = [];
4971
5752
  for (const msg of messages) {
4972
- const reply = await mcpServer.handleMessage(msg, effectivePolicy);
5753
+ const reply = await mcpServer.handleMessage(msg, scopedPolicy);
4973
5754
  if (reply !== null) responses.push(reply);
4974
5755
  }
4975
5756
  const mcpHeaders = {
@@ -5005,18 +5786,59 @@ async function startMaskeraProxy(options = {}) {
5005
5786
  anthropicUpstream,
5006
5787
  openaiUpstream
5007
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
+ }
5008
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
+ }
5009
5817
  const rawBody = method === "GET" || method === "HEAD" ? void 0 : await readRequestBody(req);
5010
- const sessionHeader = req.headers["x-maskera-session"];
5011
- 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;
5012
5821
  const stats = { redactions: 0, counts: {} };
5013
5822
  const redactedPreview = [];
5823
+ const binaryAttachments = /* @__PURE__ */ new Set();
5824
+ let requestWarnings;
5014
5825
  let outgoingBody = rawBody;
5015
5826
  let rewroteRequestBody = false;
5016
5827
  const contentType = String(req.headers["content-type"] ?? "").trim().toLowerCase();
5017
5828
  const contentEncoding = typeof req.headers["content-encoding"] === "string" ? req.headers["content-encoding"] : void 0;
5018
5829
  const mayBeJson = contentType === "" || contentType.includes("json") || contentType.startsWith("text/plain");
5019
- 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
+ }
5020
5842
  let decodedBody;
5021
5843
  try {
5022
5844
  decodedBody = decodeRequestBody(rawBody, contentEncoding);
@@ -5038,48 +5860,110 @@ async function startMaskeraProxy(options = {}) {
5038
5860
  res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
5039
5861
  return;
5040
5862
  }
5041
- if (isPlainObject(parsed)) {
5042
- let redactedObj;
5043
- try {
5044
- redactedObj = await redactLlmRequestBody(
5045
- parsed,
5046
- async (text, kind) => {
5047
- if (!text.trim()) return text;
5048
- const { result } = await engine.redact(text, {
5049
- mode: kind === "tool_description" ? "rules" : void 0,
5050
- profile: options.profile,
5051
- customTerms: options.customTerms
5052
- });
5053
- const applied = vault.apply(text, result, sessionId);
5054
- stats.redactions += applied.totalRedactions;
5055
- mergeCounts(stats.counts, applied.counts);
5056
- if (redactedPreview.length < 6) {
5057
- const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
5058
- 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("");
5059
5903
  }
5060
- return applied.redacted;
5061
- },
5062
- { mutate: true }
5063
- );
5064
- } 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) {
5065
5937
  recordAuditAndInspector({
5066
5938
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5067
5939
  method,
5068
5940
  path: forwardPath,
5069
5941
  upstream: baseUrl,
5070
5942
  sessionId,
5071
- status: 502,
5943
+ status: 415,
5072
5944
  streamed: false,
5073
5945
  durationMs: Date.now() - startedAt,
5074
5946
  redactions: stats.redactions,
5075
5947
  counts: stats.counts,
5076
- redactedPreview
5948
+ redactedPreview,
5949
+ warnings: requestWarnings
5077
5950
  });
5078
- 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;
5079
5963
  }
5080
- outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
5081
- rewroteRequestBody = true;
5082
5964
  }
5965
+ outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
5966
+ rewroteRequestBody = true;
5083
5967
  }
5084
5968
  const forwardHeaders = new Headers();
5085
5969
  for (const [k, v] of Object.entries(req.headers)) {
@@ -5106,6 +5990,7 @@ async function startMaskeraProxy(options = {}) {
5106
5990
  method,
5107
5991
  headers: forwardHeaders,
5108
5992
  body: outgoingBody ? new Uint8Array(outgoingBody) : void 0,
5993
+ redirect: "manual",
5109
5994
  signal: abortController.signal
5110
5995
  });
5111
5996
  } catch (err) {
@@ -5135,7 +6020,10 @@ async function startMaskeraProxy(options = {}) {
5135
6020
  }
5136
6021
  });
5137
6022
  outHeaders["x-maskera-redacted"] = String(stats.redactions);
5138
- 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) : {};
5139
6027
  const hasMap = Object.keys(sessionMap).length > 0;
5140
6028
  const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
5141
6029
  const isSse = resContentType.includes("text/event-stream");
@@ -5186,7 +6074,8 @@ async function startMaskeraProxy(options = {}) {
5186
6074
  durationMs: durationMs2,
5187
6075
  redactions: stats.redactions,
5188
6076
  counts: stats.counts,
5189
- redactedPreview
6077
+ redactedPreview,
6078
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5190
6079
  });
5191
6080
  log(
5192
6081
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${durationMs2}ms`
@@ -5218,7 +6107,8 @@ async function startMaskeraProxy(options = {}) {
5218
6107
  durationMs: durationMs2,
5219
6108
  redactions: stats.redactions,
5220
6109
  counts: stats.counts,
5221
- redactedPreview
6110
+ redactedPreview,
6111
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5222
6112
  });
5223
6113
  log(
5224
6114
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${durationMs2}ms`
@@ -5241,7 +6131,8 @@ async function startMaskeraProxy(options = {}) {
5241
6131
  durationMs,
5242
6132
  redactions: stats.redactions,
5243
6133
  counts: stats.counts,
5244
- redactedPreview
6134
+ redactedPreview,
6135
+ ...requestWarnings ? { warnings: requestWarnings } : {}
5245
6136
  });
5246
6137
  log(
5247
6138
  `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${durationMs}ms`
@@ -5638,6 +6529,7 @@ async function runWrap(options) {
5638
6529
  profile: options.profile,
5639
6530
  customTerms: options.customTerms,
5640
6531
  restoreResponses: options.restoreResponses,
6532
+ blockBinary: options.blockBinary,
5641
6533
  auditLogPath: options.auditLogPath
5642
6534
  });
5643
6535
  let startupReceipt = null;
@@ -5765,6 +6657,7 @@ function parseArgs(argv) {
5765
6657
  let anthropicUpstream = process.env.MASKERA_ANTHROPIC_UPSTREAM || void 0;
5766
6658
  let openaiUpstream = process.env.MASKERA_OPENAI_UPSTREAM || void 0;
5767
6659
  let restoreResponses = true;
6660
+ let blockBinary = process.env.MASKERA_PROXY_BLOCK_BINARY === "1";
5768
6661
  let auditLogPath = process.env.MASKERA_AUDIT_LOG || void 0;
5769
6662
  let openInspector = false;
5770
6663
  let wrapCommand;
@@ -5837,6 +6730,8 @@ function parseArgs(argv) {
5837
6730
  approvalMode = parseApprovalMode(value);
5838
6731
  } else if (flag === "--no-restore") {
5839
6732
  restoreResponses = false;
6733
+ } else if (flag === "--block-binary") {
6734
+ blockBinary = true;
5840
6735
  } else if (flag === "--open") {
5841
6736
  openInspector = true;
5842
6737
  } else if (flag === "--redact") {
@@ -5967,6 +6862,7 @@ function parseArgs(argv) {
5967
6862
  anthropicUpstream,
5968
6863
  openaiUpstream,
5969
6864
  restoreResponses,
6865
+ blockBinary,
5970
6866
  auditLogPath,
5971
6867
  openInspector,
5972
6868
  wrapCommand,
@@ -5997,7 +6893,7 @@ function printHelp() {
5997
6893
  "",
5998
6894
  "Usage:",
5999
6895
  " maskera-mcp [mcp] [--root <dir>] [--no-raw-restore] [--read-only] [--approval-mode automatic|native] [--rules-only]",
6000
- " 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]",
6001
6897
  " maskera-mcp wrap [flags] -- <cmd> [args...] Start local proxy, verify, inject ANTHROPIC_BASE_URL/OPENAI_BASE_URL, and run <cmd>",
6002
6898
  " maskera-mcp guard [--redact] [--file <path>] [--proxy-url <url>] [--no-proxy] [--rules-only]",
6003
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]`,
@@ -6020,6 +6916,7 @@ function printHelp() {
6020
6916
  " --no-raw-restore Block maskera_restore and include_map=true (allow maskera_write_file only)",
6021
6917
  " --read-only Hide and block maskera_write_file and maskera_clear_session",
6022
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",
6023
6920
  " --open Open local live inspector (/_maskera) in the browser (proxy/wrap)",
6024
6921
  " -v, --version Print version",
6025
6922
  " -h, --help Print this help",
@@ -6053,10 +6950,17 @@ function buildEngine(args) {
6053
6950
  }
6054
6951
  });
6055
6952
  }
6056
- async function readStdinAll() {
6953
+ var MAX_GUARD_INPUT_BYTES = 16 * 1024 * 1024;
6954
+ async function readStdinAll(maxBytes = MAX_GUARD_INPUT_BYTES) {
6057
6955
  const chunks = [];
6956
+ let total = 0;
6058
6957
  for await (const chunk of process.stdin) {
6059
- 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);
6060
6964
  }
6061
6965
  return Buffer.concat(chunks).toString("utf8");
6062
6966
  }
@@ -6272,6 +7176,11 @@ Verify: ${primary.verifyStep}
6272
7176
  let raw;
6273
7177
  if (args.file) {
6274
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
+ }
6275
7184
  if (buf.includes(0)) {
6276
7185
  throw new Error(`"${args.file}" appears to be a binary file; only UTF-8 text is supported.`);
6277
7186
  }
@@ -6336,6 +7245,7 @@ Verify: ${primary.verifyStep}
6336
7245
  profile: args.profile,
6337
7246
  customTerms: args.customTerms.length > 0 ? args.customTerms : void 0,
6338
7247
  restoreResponses: args.restoreResponses,
7248
+ blockBinary: args.blockBinary,
6339
7249
  auditLogPath: args.auditLogPath,
6340
7250
  verify: args.verify,
6341
7251
  receiptPath: args.receiptPath,
@@ -6382,6 +7292,7 @@ Verify: ${primary.verifyStep}
6382
7292
  profile: args.profile,
6383
7293
  customTerms: args.customTerms.length > 0 ? args.customTerms : void 0,
6384
7294
  restoreResponses: args.restoreResponses,
7295
+ blockBinary: args.blockBinary,
6385
7296
  auditLogPath: args.auditLogPath,
6386
7297
  onLog: (line) => process.stderr.write(`${line}
6387
7298
  `)