@maskera/mcp 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -4
- package/dist/cli.js +1821 -241
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +80 -8
- package/dist/index.js +1702 -198
- package/dist/index.js.map +1 -1
- package/package.json +6 -2
package/dist/index.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { randomUUID, createHash } from 'crypto';
|
|
2
|
+
import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
|
|
3
|
+
import { mkdir, realpath, writeFile, stat, readFile, appendFile, lstat, readlink } from 'fs/promises';
|
|
4
|
+
import { dirname, resolve, isAbsolute, relative, sep } from 'path';
|
|
4
5
|
import { createServer } from 'http';
|
|
5
|
-
import
|
|
6
|
+
import * as zlib from 'zlib';
|
|
6
7
|
|
|
7
8
|
// src/engine.ts
|
|
8
9
|
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
10
|
+
var DEFAULT_MAX_CACHE_ENTRIES = 512;
|
|
11
|
+
var MAX_CUSTOM_DETECTOR_CACHE = 64;
|
|
9
12
|
function escapeRegExp(value) {
|
|
10
13
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
11
14
|
}
|
|
12
|
-
function
|
|
15
|
+
function normalizeCustomTerms(rawTerms) {
|
|
13
16
|
const unique = /* @__PURE__ */ new Map();
|
|
14
17
|
for (const raw of rawTerms) {
|
|
15
18
|
if (typeof raw !== "string") continue;
|
|
@@ -19,9 +22,20 @@ function buildCustomTermsDetector(rawTerms) {
|
|
|
19
22
|
if (!unique.has(folded)) unique.set(folded, trimmed);
|
|
20
23
|
if (unique.size >= 200) break;
|
|
21
24
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
return [...unique.values()].sort((a, b) => b.length - a.length);
|
|
26
|
+
}
|
|
27
|
+
function buildCustomTermsDetector(rawTerms) {
|
|
28
|
+
const sorted = normalizeCustomTerms(rawTerms);
|
|
29
|
+
if (sorted.length === 0) return null;
|
|
30
|
+
const pattern = new RegExp(
|
|
31
|
+
sorted.map((term) => {
|
|
32
|
+
const escaped = escapeRegExp(term);
|
|
33
|
+
const startGuard = WORD_CHAR.test(term[0] ?? "") ? "(?<![\\p{L}\\p{N}_])" : "";
|
|
34
|
+
const endGuard = WORD_CHAR.test(term[term.length - 1] ?? "") ? "(?![\\p{L}\\p{N}_])" : "";
|
|
35
|
+
return `${startGuard}${escaped}${endGuard}`;
|
|
36
|
+
}).join("|"),
|
|
37
|
+
"giu"
|
|
38
|
+
);
|
|
25
39
|
return {
|
|
26
40
|
label: "EGENT",
|
|
27
41
|
detect(text) {
|
|
@@ -30,13 +44,11 @@ function buildCustomTermsDetector(rawTerms) {
|
|
|
30
44
|
for (let m = pattern.exec(text); m !== null; m = pattern.exec(text)) {
|
|
31
45
|
const start = m.index;
|
|
32
46
|
const value = m[0];
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const after = end < text.length ? text[end] ?? "" : "";
|
|
36
|
-
if (WORD_CHAR.test(value[0] ?? "") && WORD_CHAR.test(before) || WORD_CHAR.test(value[value.length - 1] ?? "") && WORD_CHAR.test(after)) {
|
|
47
|
+
if (!value) {
|
|
48
|
+
pattern.lastIndex += 1;
|
|
37
49
|
continue;
|
|
38
50
|
}
|
|
39
|
-
out.push({ start, end, value });
|
|
51
|
+
out.push({ start, end: start + value.length, value });
|
|
40
52
|
}
|
|
41
53
|
return out;
|
|
42
54
|
}
|
|
@@ -46,23 +58,93 @@ function createMaskeraEngine(options = {}) {
|
|
|
46
58
|
const defaultMode = options.defaultMode ?? "auto";
|
|
47
59
|
const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
|
|
48
60
|
const revision = options.nerOptions?.revision ?? (model === MASKERA_SV_NER_MODEL ? MASKERA_SV_NER_REVISION : void 0);
|
|
61
|
+
const maxCacheEntries = Math.max(0, options.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES);
|
|
49
62
|
let recognizer = options.recognizer ?? null;
|
|
50
63
|
let nerLoaded = false;
|
|
51
64
|
let nerError = null;
|
|
65
|
+
let warmupStarted = false;
|
|
66
|
+
const spanCache = /* @__PURE__ */ new Map();
|
|
67
|
+
const customDetectorCache = /* @__PURE__ */ new Map();
|
|
68
|
+
let cacheHits = 0;
|
|
69
|
+
let cacheMisses = 0;
|
|
52
70
|
function getRecognizer() {
|
|
53
71
|
if (!recognizer) {
|
|
72
|
+
const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
|
|
54
73
|
recognizer = createNerRecognizer({
|
|
55
74
|
...options.nerOptions,
|
|
56
75
|
model,
|
|
57
|
-
revision
|
|
76
|
+
revision,
|
|
77
|
+
dtype
|
|
58
78
|
});
|
|
59
79
|
}
|
|
60
80
|
return recognizer;
|
|
61
81
|
}
|
|
82
|
+
function getCustomDetector(rawTerms) {
|
|
83
|
+
if (!rawTerms || rawTerms.length === 0) return { detector: null, termsKey: "" };
|
|
84
|
+
const sorted = normalizeCustomTerms(rawTerms);
|
|
85
|
+
if (sorted.length === 0) return { detector: null, termsKey: "" };
|
|
86
|
+
const termsKey = sorted.map((t) => `${t.length}:${t.toLowerCase()}`).join("|");
|
|
87
|
+
if (customDetectorCache.has(termsKey)) {
|
|
88
|
+
const hit = customDetectorCache.get(termsKey) ?? null;
|
|
89
|
+
customDetectorCache.delete(termsKey);
|
|
90
|
+
customDetectorCache.set(termsKey, hit);
|
|
91
|
+
return { detector: hit, termsKey };
|
|
92
|
+
}
|
|
93
|
+
const detector = buildCustomTermsDetector(sorted);
|
|
94
|
+
if (customDetectorCache.size >= MAX_CUSTOM_DETECTOR_CACHE) {
|
|
95
|
+
const oldest = customDetectorCache.keys().next().value;
|
|
96
|
+
if (oldest !== void 0) customDetectorCache.delete(oldest);
|
|
97
|
+
}
|
|
98
|
+
customDetectorCache.set(termsKey, detector);
|
|
99
|
+
return { detector, termsKey };
|
|
100
|
+
}
|
|
101
|
+
function makeCacheKey(mode, profile, termsKey, text) {
|
|
102
|
+
return createHash("sha256").update(mode).update("\0").update(profile ?? "").update("\0").update(termsKey).update("\0").update(text).digest("base64url");
|
|
103
|
+
}
|
|
62
104
|
return {
|
|
105
|
+
warmup() {
|
|
106
|
+
if (defaultMode !== "auto" || warmupStarted || nerLoaded) return;
|
|
107
|
+
warmupStarted = true;
|
|
108
|
+
const ner = getRecognizer();
|
|
109
|
+
void ner.ready.then(
|
|
110
|
+
() => {
|
|
111
|
+
nerLoaded = true;
|
|
112
|
+
nerError = null;
|
|
113
|
+
},
|
|
114
|
+
(err) => {
|
|
115
|
+
warmupStarted = false;
|
|
116
|
+
nerError = err instanceof Error ? err.message : String(err);
|
|
117
|
+
}
|
|
118
|
+
);
|
|
119
|
+
},
|
|
120
|
+
clearCache() {
|
|
121
|
+
spanCache.clear();
|
|
122
|
+
cacheHits = 0;
|
|
123
|
+
cacheMisses = 0;
|
|
124
|
+
},
|
|
63
125
|
async redact(text, req = {}) {
|
|
64
126
|
const requestedMode = req.mode ?? defaultMode;
|
|
65
|
-
const customDetector
|
|
127
|
+
const { detector: customDetector, termsKey } = getCustomDetector(req.customTerms);
|
|
128
|
+
const cacheKey = maxCacheEntries > 0 && text.length > 0 ? makeCacheKey(requestedMode, req.profile, termsKey, text) : null;
|
|
129
|
+
if (cacheKey) {
|
|
130
|
+
const cached = spanCache.get(cacheKey);
|
|
131
|
+
if (cached) {
|
|
132
|
+
spanCache.delete(cacheKey);
|
|
133
|
+
spanCache.set(cacheKey, cached);
|
|
134
|
+
cacheHits += 1;
|
|
135
|
+
const result = cached.spans.length === 0 ? redactFromDetections(text, []) : redactFromDetections(
|
|
136
|
+
text,
|
|
137
|
+
cached.spans.map((s) => ({
|
|
138
|
+
start: s.start,
|
|
139
|
+
end: s.end,
|
|
140
|
+
label: s.label,
|
|
141
|
+
value: text.slice(s.start, s.end)
|
|
142
|
+
}))
|
|
143
|
+
);
|
|
144
|
+
return { result, modeUsed: cached.modeUsed };
|
|
145
|
+
}
|
|
146
|
+
cacheMisses += 1;
|
|
147
|
+
}
|
|
66
148
|
const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
|
|
67
149
|
if (requestedMode === "rules") {
|
|
68
150
|
const result = req.profile === "clinical" ? redactFromDetections(
|
|
@@ -71,6 +153,20 @@ function createMaskeraEngine(options = {}) {
|
|
|
71
153
|
(d) => clinicalPrecisionFilter(d, text, "rule")
|
|
72
154
|
)
|
|
73
155
|
) : redact(text, { detectors });
|
|
156
|
+
if (cacheKey) {
|
|
157
|
+
if (spanCache.size >= maxCacheEntries) {
|
|
158
|
+
const oldest = spanCache.keys().next().value;
|
|
159
|
+
if (oldest !== void 0) spanCache.delete(oldest);
|
|
160
|
+
}
|
|
161
|
+
spanCache.set(cacheKey, {
|
|
162
|
+
spans: result.redactions.map((r) => ({
|
|
163
|
+
start: r.start,
|
|
164
|
+
end: r.end,
|
|
165
|
+
label: r.label
|
|
166
|
+
})),
|
|
167
|
+
modeUsed: "rules"
|
|
168
|
+
});
|
|
169
|
+
}
|
|
74
170
|
return {
|
|
75
171
|
result,
|
|
76
172
|
modeUsed: "rules"
|
|
@@ -85,6 +181,20 @@ function createMaskeraEngine(options = {}) {
|
|
|
85
181
|
});
|
|
86
182
|
nerLoaded = true;
|
|
87
183
|
nerError = null;
|
|
184
|
+
if (cacheKey) {
|
|
185
|
+
if (spanCache.size >= maxCacheEntries) {
|
|
186
|
+
const oldest = spanCache.keys().next().value;
|
|
187
|
+
if (oldest !== void 0) spanCache.delete(oldest);
|
|
188
|
+
}
|
|
189
|
+
spanCache.set(cacheKey, {
|
|
190
|
+
spans: result.redactions.map((r) => ({
|
|
191
|
+
start: r.start,
|
|
192
|
+
end: r.end,
|
|
193
|
+
label: r.label
|
|
194
|
+
})),
|
|
195
|
+
modeUsed: "hybrid"
|
|
196
|
+
});
|
|
197
|
+
}
|
|
88
198
|
return { result, modeUsed: "hybrid" };
|
|
89
199
|
} catch (err) {
|
|
90
200
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -100,15 +210,20 @@ function createMaskeraEngine(options = {}) {
|
|
|
100
210
|
model,
|
|
101
211
|
revision: revision ?? "local",
|
|
102
212
|
nerLoaded,
|
|
103
|
-
nerError
|
|
213
|
+
nerError,
|
|
214
|
+
cacheSize: spanCache.size,
|
|
215
|
+
cacheHits,
|
|
216
|
+
cacheMisses
|
|
104
217
|
};
|
|
105
218
|
}
|
|
106
219
|
};
|
|
107
220
|
}
|
|
108
221
|
var MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
222
|
+
var MAX_SYMLINK_HOPS = 40;
|
|
223
|
+
var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
|
|
109
224
|
function isWithinRoot(root, target) {
|
|
110
225
|
const rel = relative(root, target);
|
|
111
|
-
return rel === "" || !rel.startsWith(
|
|
226
|
+
return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
112
227
|
}
|
|
113
228
|
async function resolveExistingAncestor(target) {
|
|
114
229
|
let current = resolve(target);
|
|
@@ -116,7 +231,7 @@ async function resolveExistingAncestor(target) {
|
|
|
116
231
|
for (; ; ) {
|
|
117
232
|
try {
|
|
118
233
|
const real = await realpath(current);
|
|
119
|
-
return { ancestor: real, tail: segments.reverse().join(
|
|
234
|
+
return { ancestor: real, tail: segments.reverse().join(sep) };
|
|
120
235
|
} catch {
|
|
121
236
|
const parent = dirname(current);
|
|
122
237
|
if (parent === current) {
|
|
@@ -127,6 +242,27 @@ async function resolveExistingAncestor(target) {
|
|
|
127
242
|
}
|
|
128
243
|
}
|
|
129
244
|
}
|
|
245
|
+
async function resolveCanonicalTarget(target) {
|
|
246
|
+
let current = resolve(target);
|
|
247
|
+
for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {
|
|
248
|
+
const { ancestor, tail } = await resolveExistingAncestor(current);
|
|
249
|
+
const candidate = tail ? resolve(ancestor, tail) : ancestor;
|
|
250
|
+
try {
|
|
251
|
+
const info = await lstat(candidate);
|
|
252
|
+
if (!info.isSymbolicLink()) {
|
|
253
|
+
return candidate;
|
|
254
|
+
}
|
|
255
|
+
const linkTarget = await readlink(candidate);
|
|
256
|
+
current = resolve(dirname(candidate), linkTarget);
|
|
257
|
+
} catch (err) {
|
|
258
|
+
if (err.code === "ENOENT") {
|
|
259
|
+
return candidate;
|
|
260
|
+
}
|
|
261
|
+
throw err;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
throw new Error(`Too many symlink hops while resolving "${target}".`);
|
|
265
|
+
}
|
|
130
266
|
function createFileGuard(roots = [process.cwd()]) {
|
|
131
267
|
const rawRoots = roots.length > 0 ? roots : [process.cwd()];
|
|
132
268
|
let canonicalRootsPromise = null;
|
|
@@ -138,7 +274,12 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
138
274
|
try {
|
|
139
275
|
return await realpath(abs);
|
|
140
276
|
} catch {
|
|
141
|
-
|
|
277
|
+
try {
|
|
278
|
+
const { ancestor, tail } = await resolveExistingAncestor(abs);
|
|
279
|
+
return tail ? resolve(ancestor, tail) : ancestor;
|
|
280
|
+
} catch {
|
|
281
|
+
return abs;
|
|
282
|
+
}
|
|
142
283
|
}
|
|
143
284
|
})
|
|
144
285
|
);
|
|
@@ -183,17 +324,24 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
183
324
|
if (buffer.includes(0)) {
|
|
184
325
|
throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
|
|
185
326
|
}
|
|
327
|
+
let content;
|
|
328
|
+
try {
|
|
329
|
+
content = UTF8_DECODER.decode(buffer);
|
|
330
|
+
} catch {
|
|
331
|
+
throw new Error(
|
|
332
|
+
`"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
|
|
333
|
+
);
|
|
334
|
+
}
|
|
186
335
|
return {
|
|
187
336
|
resolvedPath: real,
|
|
188
|
-
content
|
|
337
|
+
content,
|
|
189
338
|
bytes: buffer.byteLength
|
|
190
339
|
};
|
|
191
340
|
},
|
|
192
341
|
async writeText(filePath, content, options = {}) {
|
|
193
342
|
const rootsList = await getCanonicalRoots();
|
|
194
343
|
const candidate = resolveAgainstBase(filePath);
|
|
195
|
-
const
|
|
196
|
-
const targetReal = tail ? resolve(ancestor, tail) : ancestor;
|
|
344
|
+
const targetReal = await resolveCanonicalTarget(candidate);
|
|
197
345
|
if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
|
|
198
346
|
throw new Error(
|
|
199
347
|
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
@@ -204,6 +352,12 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
204
352
|
throw new Error(`Output exceeds max allowed size (${MAX_FILE_BYTES} bytes).`);
|
|
205
353
|
}
|
|
206
354
|
await mkdir(dirname(targetReal), { recursive: true });
|
|
355
|
+
const parentReal = await realpath(dirname(targetReal));
|
|
356
|
+
if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
|
|
357
|
+
throw new Error(
|
|
358
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
359
|
+
);
|
|
360
|
+
}
|
|
207
361
|
await writeFile(targetReal, content, {
|
|
208
362
|
encoding: "utf8",
|
|
209
363
|
flag: options.overwrite ? "w" : "wx"
|
|
@@ -219,26 +373,47 @@ function createFileGuard(roots = [process.cwd()]) {
|
|
|
219
373
|
}
|
|
220
374
|
|
|
221
375
|
// src/guard.ts
|
|
376
|
+
var HOOK_PAYLOAD_KEYS = [
|
|
377
|
+
"prompt",
|
|
378
|
+
"user_prompt",
|
|
379
|
+
"tool_input",
|
|
380
|
+
"tool_response",
|
|
381
|
+
"tool_output",
|
|
382
|
+
"command",
|
|
383
|
+
"content",
|
|
384
|
+
"edits",
|
|
385
|
+
"attachments"
|
|
386
|
+
];
|
|
387
|
+
var HOOK_META_SKIP_KEYS = /* @__PURE__ */ new Set([
|
|
388
|
+
"hook_event_name",
|
|
389
|
+
"tool_name",
|
|
390
|
+
"permission_mode",
|
|
391
|
+
"session_id"
|
|
392
|
+
]);
|
|
393
|
+
function collectScalars(value, parts, skipKey) {
|
|
394
|
+
if (skipKey && HOOK_META_SKIP_KEYS.has(skipKey)) return;
|
|
395
|
+
if (typeof value === "string") {
|
|
396
|
+
if (value.trim()) parts.push(value);
|
|
397
|
+
} else if (typeof value === "number" && Number.isFinite(value)) {
|
|
398
|
+
parts.push(String(value));
|
|
399
|
+
} else if (Array.isArray(value)) {
|
|
400
|
+
for (const item of value) collectScalars(item, parts);
|
|
401
|
+
} else if (value && typeof value === "object") {
|
|
402
|
+
for (const [k, v] of Object.entries(value)) collectScalars(v, parts, k);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
222
405
|
function extractGuardText(rawInput) {
|
|
223
406
|
const trimmed = rawInput.trim();
|
|
224
407
|
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
225
408
|
try {
|
|
226
409
|
const parsed = JSON.parse(trimmed);
|
|
227
|
-
if (typeof parsed
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
const parts = [];
|
|
235
|
-
const walk = (v) => {
|
|
236
|
-
if (typeof v === "string") parts.push(v);
|
|
237
|
-
else if (Array.isArray(v)) v.forEach(walk);
|
|
238
|
-
else if (v && typeof v === "object") Object.values(v).forEach(walk);
|
|
239
|
-
};
|
|
240
|
-
walk(parsed.tool_input);
|
|
241
|
-
return { text: parts.join("\n"), isHookEnvelope: true };
|
|
410
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
411
|
+
const isHookEnvelope = HOOK_PAYLOAD_KEYS.some((key) => key in parsed);
|
|
412
|
+
if (isHookEnvelope) {
|
|
413
|
+
const parts = [];
|
|
414
|
+
collectScalars(parsed, parts);
|
|
415
|
+
return { text: parts.join("\n"), isHookEnvelope: true };
|
|
416
|
+
}
|
|
242
417
|
}
|
|
243
418
|
} catch {
|
|
244
419
|
}
|
|
@@ -246,6 +421,56 @@ function extractGuardText(rawInput) {
|
|
|
246
421
|
return { text: rawInput, isHookEnvelope: false };
|
|
247
422
|
}
|
|
248
423
|
async function runGuard(rawInput, engine, options = {}) {
|
|
424
|
+
const trimmed = rawInput.trim();
|
|
425
|
+
if (options.preserveJsonStructure && trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
426
|
+
try {
|
|
427
|
+
const parsed = JSON.parse(trimmed);
|
|
428
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
429
|
+
const counts2 = {};
|
|
430
|
+
let totalRedactions = 0;
|
|
431
|
+
let modeUsed2 = options.mode === "rules" ? "rules" : "hybrid";
|
|
432
|
+
const redactJson = async (value, key) => {
|
|
433
|
+
if (key && HOOK_META_SKIP_KEYS.has(key)) return value;
|
|
434
|
+
if (typeof value === "string") {
|
|
435
|
+
if (!value.trim()) return value;
|
|
436
|
+
const out = await engine.redact(value, {
|
|
437
|
+
mode: options.mode,
|
|
438
|
+
profile: options.profile,
|
|
439
|
+
customTerms: options.customTerms
|
|
440
|
+
});
|
|
441
|
+
modeUsed2 = out.modeUsed;
|
|
442
|
+
totalRedactions += out.result.redactions.length;
|
|
443
|
+
for (const r of out.result.redactions) {
|
|
444
|
+
counts2[r.label] = (counts2[r.label] ?? 0) + 1;
|
|
445
|
+
}
|
|
446
|
+
return out.result.text;
|
|
447
|
+
}
|
|
448
|
+
if (Array.isArray(value)) {
|
|
449
|
+
const arr = [];
|
|
450
|
+
for (const item of value) arr.push(await redactJson(item));
|
|
451
|
+
return arr;
|
|
452
|
+
}
|
|
453
|
+
if (value && typeof value === "object") {
|
|
454
|
+
const obj = {};
|
|
455
|
+
for (const [k, v] of Object.entries(value)) {
|
|
456
|
+
obj[k] = await redactJson(v, k);
|
|
457
|
+
}
|
|
458
|
+
return obj;
|
|
459
|
+
}
|
|
460
|
+
return value;
|
|
461
|
+
};
|
|
462
|
+
const redactedObj = await redactJson(parsed);
|
|
463
|
+
return {
|
|
464
|
+
blocked: totalRedactions > 0,
|
|
465
|
+
totalRedactions,
|
|
466
|
+
counts: counts2,
|
|
467
|
+
redacted: JSON.stringify(redactedObj),
|
|
468
|
+
modeUsed: modeUsed2
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
} catch {
|
|
472
|
+
}
|
|
473
|
+
}
|
|
249
474
|
const { text } = extractGuardText(rawInput);
|
|
250
475
|
if (!text.trim()) {
|
|
251
476
|
return {
|
|
@@ -273,14 +498,429 @@ async function runGuard(rawInput, engine, options = {}) {
|
|
|
273
498
|
modeUsed
|
|
274
499
|
};
|
|
275
500
|
}
|
|
501
|
+
|
|
502
|
+
// src/inspector.ts
|
|
503
|
+
var MAX_EVENTS = 100;
|
|
504
|
+
var ProxyInspector = class {
|
|
505
|
+
constructor() {
|
|
506
|
+
this.items = [];
|
|
507
|
+
this.subscribers = /* @__PURE__ */ new Set();
|
|
508
|
+
this.seq = 0;
|
|
509
|
+
}
|
|
510
|
+
record(entry) {
|
|
511
|
+
this.seq += 1;
|
|
512
|
+
const item = { id: `req_${this.seq}`, ...entry };
|
|
513
|
+
this.items.unshift(item);
|
|
514
|
+
if (this.items.length > MAX_EVENTS) this.items.length = MAX_EVENTS;
|
|
515
|
+
const payload = `event: request
|
|
516
|
+
data: ${JSON.stringify(item)}
|
|
517
|
+
|
|
518
|
+
`;
|
|
519
|
+
for (const res of [...this.subscribers]) {
|
|
520
|
+
if (res.writableEnded || res.destroyed) {
|
|
521
|
+
this.subscribers.delete(res);
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
res.write(payload);
|
|
525
|
+
}
|
|
526
|
+
return item;
|
|
527
|
+
}
|
|
528
|
+
list() {
|
|
529
|
+
return this.items;
|
|
530
|
+
}
|
|
531
|
+
clear() {
|
|
532
|
+
this.items.length = 0;
|
|
533
|
+
const payload = `event: cleared
|
|
534
|
+
data: {}
|
|
535
|
+
|
|
536
|
+
`;
|
|
537
|
+
for (const res of [...this.subscribers]) {
|
|
538
|
+
if (res.writableEnded || res.destroyed) {
|
|
539
|
+
this.subscribers.delete(res);
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
res.write(payload);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
subscribe(res, extraHeaders = {}) {
|
|
546
|
+
res.writeHead(200, {
|
|
547
|
+
...extraHeaders,
|
|
548
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
549
|
+
"cache-control": "no-cache, no-transform",
|
|
550
|
+
connection: "keep-alive"
|
|
551
|
+
});
|
|
552
|
+
res.write(`event: init
|
|
553
|
+
data: ${JSON.stringify({ items: this.items })}
|
|
554
|
+
|
|
555
|
+
`);
|
|
556
|
+
this.subscribers.add(res);
|
|
557
|
+
res.on("close", () => {
|
|
558
|
+
this.subscribers.delete(res);
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
closeAll() {
|
|
562
|
+
for (const res of [...this.subscribers]) {
|
|
563
|
+
try {
|
|
564
|
+
res.end();
|
|
565
|
+
} catch {
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
this.subscribers.clear();
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
function renderInspectorHtml(info) {
|
|
572
|
+
const safeUrl = info.url.replace(/[<>&"']/g, "");
|
|
573
|
+
return `<!doctype html>
|
|
574
|
+
<html lang="sv">
|
|
575
|
+
<head>
|
|
576
|
+
<meta charset="utf-8" />
|
|
577
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
578
|
+
<title>Maskera Proxy Inspector</title>
|
|
579
|
+
<style>
|
|
580
|
+
:root {
|
|
581
|
+
--bg: #ffffff;
|
|
582
|
+
--bg-subtle: #f7f7f8;
|
|
583
|
+
--fg: #111113;
|
|
584
|
+
--muted: #666670;
|
|
585
|
+
--border: #e4e4e7;
|
|
586
|
+
--ok: #15803d;
|
|
587
|
+
--ok-bg: #f0fdf4;
|
|
588
|
+
--err: #b91c1c;
|
|
589
|
+
--err-bg: #fef2f2;
|
|
590
|
+
--tok-bg: #eff6ff;
|
|
591
|
+
--tok-fg: #1d4ed8;
|
|
592
|
+
--tok-border: #bfdbfe;
|
|
593
|
+
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
594
|
+
--sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
595
|
+
}
|
|
596
|
+
@media (prefers-color-scheme: dark) {
|
|
597
|
+
:root {
|
|
598
|
+
--bg: #0c0c0e;
|
|
599
|
+
--bg-subtle: #16161a;
|
|
600
|
+
--fg: #f4f4f5;
|
|
601
|
+
--muted: #a1a1aa;
|
|
602
|
+
--border: #27272a;
|
|
603
|
+
--ok: #4ade80;
|
|
604
|
+
--ok-bg: #052e16;
|
|
605
|
+
--err: #f87171;
|
|
606
|
+
--err-bg: #450a0a;
|
|
607
|
+
--tok-bg: #172554;
|
|
608
|
+
--tok-fg: #93c5fd;
|
|
609
|
+
--tok-border: #1e3a8a;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
* { box-sizing: border-box; }
|
|
613
|
+
body {
|
|
614
|
+
margin: 0;
|
|
615
|
+
font-family: var(--sans);
|
|
616
|
+
background: var(--bg);
|
|
617
|
+
color: var(--fg);
|
|
618
|
+
line-height: 1.5;
|
|
619
|
+
}
|
|
620
|
+
.wrap { max-width: 960px; margin: 0 auto; padding: 24px 20px 64px; }
|
|
621
|
+
header {
|
|
622
|
+
display: flex;
|
|
623
|
+
align-items: flex-start;
|
|
624
|
+
justify-content: space-between;
|
|
625
|
+
gap: 16px;
|
|
626
|
+
flex-wrap: wrap;
|
|
627
|
+
padding-bottom: 18px;
|
|
628
|
+
border-bottom: 1px solid var(--border);
|
|
629
|
+
}
|
|
630
|
+
h1 { margin: 0; font-size: 18px; font-weight: 650; letter-spacing: -0.02em; }
|
|
631
|
+
.sub { margin: 4px 0 0; font-size: 13px; color: var(--muted); }
|
|
632
|
+
.dot {
|
|
633
|
+
display: inline-block; width: 8px; height: 8px; border-radius: 50%;
|
|
634
|
+
background: var(--ok); margin-right: 6px; vertical-align: middle;
|
|
635
|
+
}
|
|
636
|
+
.actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
|
637
|
+
button {
|
|
638
|
+
font-family: var(--sans);
|
|
639
|
+
font-weight: 500;
|
|
640
|
+
font-size: 12.5px;
|
|
641
|
+
padding: 7px 12px;
|
|
642
|
+
border-radius: 7px;
|
|
643
|
+
border: 1px solid var(--border);
|
|
644
|
+
background: var(--bg);
|
|
645
|
+
color: var(--fg);
|
|
646
|
+
cursor: pointer;
|
|
647
|
+
}
|
|
648
|
+
button:hover { background: var(--bg-subtle); }
|
|
649
|
+
button.active { background: var(--fg); color: var(--bg); border-color: var(--fg); }
|
|
650
|
+
.stats {
|
|
651
|
+
display: grid;
|
|
652
|
+
grid-template-columns: repeat(4, minmax(0, 1fr));
|
|
653
|
+
gap: 10px;
|
|
654
|
+
margin: 18px 0 22px;
|
|
655
|
+
}
|
|
656
|
+
@media (max-width: 640px) { .stats { grid-template-columns: repeat(2, 1fr); } }
|
|
657
|
+
.stat {
|
|
658
|
+
border: 1px solid var(--border);
|
|
659
|
+
border-radius: 8px;
|
|
660
|
+
padding: 12px 14px;
|
|
661
|
+
background: var(--bg-subtle);
|
|
662
|
+
}
|
|
663
|
+
.stat-k { font-size: 11.5px; color: var(--muted); }
|
|
664
|
+
.stat-v { font-size: 20px; font-weight: 650; margin-top: 2px; font-variant-numeric: tabular-nums; }
|
|
665
|
+
.empty {
|
|
666
|
+
border: 1px dashed var(--border);
|
|
667
|
+
border-radius: 8px;
|
|
668
|
+
padding: 28px 20px;
|
|
669
|
+
text-align: center;
|
|
670
|
+
color: var(--muted);
|
|
671
|
+
font-size: 13.5px;
|
|
672
|
+
}
|
|
673
|
+
.empty code {
|
|
674
|
+
display: block; margin: 10px auto 0; max-width: 560px; padding: 10px 12px;
|
|
675
|
+
background: var(--bg-subtle); border: 1px solid var(--border); border-radius: 6px;
|
|
676
|
+
font: 12px/1.6 var(--mono); color: var(--fg); text-align: left; white-space: pre-wrap;
|
|
677
|
+
}
|
|
678
|
+
.list { display: flex; flex-direction: column; gap: 8px; }
|
|
679
|
+
details.item {
|
|
680
|
+
border: 1px solid var(--border);
|
|
681
|
+
border-radius: 8px;
|
|
682
|
+
background: var(--bg);
|
|
683
|
+
overflow: hidden;
|
|
684
|
+
}
|
|
685
|
+
summary {
|
|
686
|
+
list-style: none;
|
|
687
|
+
cursor: pointer;
|
|
688
|
+
display: flex;
|
|
689
|
+
align-items: center;
|
|
690
|
+
justify-content: space-between;
|
|
691
|
+
gap: 10px;
|
|
692
|
+
flex-wrap: wrap;
|
|
693
|
+
padding: 11px 14px;
|
|
694
|
+
font-size: 13px;
|
|
695
|
+
}
|
|
696
|
+
summary::-webkit-details-marker { display: none; }
|
|
697
|
+
summary:hover { background: var(--bg-subtle); }
|
|
698
|
+
.left { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
|
699
|
+
.right { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
|
700
|
+
.badge {
|
|
701
|
+
font-family: var(--mono);
|
|
702
|
+
font-weight: 600;
|
|
703
|
+
font-size: 11px;
|
|
704
|
+
padding: 2px 6px;
|
|
705
|
+
border-radius: 5px;
|
|
706
|
+
}
|
|
707
|
+
.badge.ok { background: var(--ok-bg); color: var(--ok); }
|
|
708
|
+
.badge.err { background: var(--err-bg); color: var(--err); }
|
|
709
|
+
.path { font-family: var(--mono); font-weight: 500; font-size: 12.5px; }
|
|
710
|
+
.pill {
|
|
711
|
+
font-family: var(--mono);
|
|
712
|
+
font-weight: 500;
|
|
713
|
+
font-size: 11px;
|
|
714
|
+
padding: 2px 6px;
|
|
715
|
+
border-radius: 5px;
|
|
716
|
+
background: var(--tok-bg);
|
|
717
|
+
color: var(--tok-fg);
|
|
718
|
+
border: 1px solid var(--tok-border);
|
|
719
|
+
}
|
|
720
|
+
.body {
|
|
721
|
+
border-top: 1px solid var(--border);
|
|
722
|
+
padding: 12px 14px;
|
|
723
|
+
background: var(--bg-subtle);
|
|
724
|
+
}
|
|
725
|
+
.body-label { font-size: 11.5px; color: var(--muted); margin: 0 0 8px; }
|
|
726
|
+
.preview {
|
|
727
|
+
margin: 0 0 8px;
|
|
728
|
+
padding: 10px 12px;
|
|
729
|
+
border: 1px solid var(--border);
|
|
730
|
+
border-radius: 6px;
|
|
731
|
+
background: var(--bg);
|
|
732
|
+
font: 12.5px/1.6 var(--mono);
|
|
733
|
+
white-space: pre-wrap;
|
|
734
|
+
word-break: break-word;
|
|
735
|
+
}
|
|
736
|
+
.tok {
|
|
737
|
+
display: inline-block;
|
|
738
|
+
padding: 0 4px;
|
|
739
|
+
border-radius: 4px;
|
|
740
|
+
background: var(--tok-bg);
|
|
741
|
+
color: var(--tok-fg);
|
|
742
|
+
border: 1px solid var(--tok-border);
|
|
743
|
+
font-weight: 600;
|
|
744
|
+
}
|
|
745
|
+
.vault-box {
|
|
746
|
+
margin-top: 24px;
|
|
747
|
+
border: 1px solid var(--border);
|
|
748
|
+
border-radius: 8px;
|
|
749
|
+
padding: 14px 16px;
|
|
750
|
+
background: var(--bg-subtle);
|
|
751
|
+
}
|
|
752
|
+
.vault-box h2 { margin: 0 0 6px; font-size: 14px; }
|
|
753
|
+
.vault-box p { margin: 0 0 10px; font-size: 12.5px; color: var(--muted); }
|
|
754
|
+
table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
|
755
|
+
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--border); font-family: var(--mono); }
|
|
756
|
+
th { font-family: var(--sans); font-size: 11.5px; color: var(--muted); }
|
|
757
|
+
</style>
|
|
758
|
+
</head>
|
|
759
|
+
<body>
|
|
760
|
+
<div class="wrap">
|
|
761
|
+
<header>
|
|
762
|
+
<div>
|
|
763
|
+
<h1><span class="dot"></span>Maskera lokal proxy-inspekt\xF6r</h1>
|
|
764
|
+
<p class="sub">K\xF6rs enbart p\xE5 ${safeUrl} \xB7 l\xE4ge: ${info.defaultMode} \xB7 \xE5terst\xE4llning: ${info.restoreResponses ? "p\xE5" : "av"} \xB7 allt lagras bara i lokalt RAM</p>
|
|
765
|
+
</div>
|
|
766
|
+
<div class="actions">
|
|
767
|
+
<button id="reveal-btn" type="button">Visa originalv\xE4rden lokalt</button>
|
|
768
|
+
<button id="clear-btn" type="button">Rensa minne</button>
|
|
769
|
+
</div>
|
|
770
|
+
</header>
|
|
771
|
+
|
|
772
|
+
<section class="stats">
|
|
773
|
+
<div class="stat"><div class="stat-k">Anrop</div><div class="stat-v" id="st-req">0</div></div>
|
|
774
|
+
<div class="stat"><div class="stat-k">Maskerade uppgifter</div><div class="stat-v" id="st-red">0</div></div>
|
|
775
|
+
<div class="stat"><div class="stat-k">Unika i sessionsvalvet</div><div class="stat-v" id="st-uniq">0</div></div>
|
|
776
|
+
<div class="stat"><div class="stat-k">AI-modell</div><div class="stat-v" id="st-model">Redo</div></div>
|
|
777
|
+
</section>
|
|
778
|
+
|
|
779
|
+
<div id="feed"></div>
|
|
780
|
+
<div id="vault-root"></div>
|
|
781
|
+
</div>
|
|
782
|
+
<script>
|
|
783
|
+
(() => {
|
|
784
|
+
const feedEl = document.getElementById("feed");
|
|
785
|
+
const vaultRoot = document.getElementById("vault-root");
|
|
786
|
+
const revealBtn = document.getElementById("reveal-btn");
|
|
787
|
+
const clearBtn = document.getElementById("clear-btn");
|
|
788
|
+
const stReq = document.getElementById("st-req");
|
|
789
|
+
const stRed = document.getElementById("st-red");
|
|
790
|
+
const stUniq = document.getElementById("st-uniq");
|
|
791
|
+
const stModel = document.getElementById("st-model");
|
|
792
|
+
let items = [];
|
|
793
|
+
let reveal = false;
|
|
794
|
+
let userToggled = false;
|
|
795
|
+
const openIds = new Set();
|
|
796
|
+
const seenIds = new Set();
|
|
797
|
+
|
|
798
|
+
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&":"&","<":"<",">":">",'"':""","'":"'" }[c]));
|
|
799
|
+
const highlightTokens = (s) => esc(s).replace(/\\[[A-Z\xC5\xC4\xD6][A-Z\xC5\xC4\xD60-9_]*_\\d+\\]/g, (m) => '<span class="tok">' + m + "</span>");
|
|
800
|
+
|
|
801
|
+
async function refreshStatus() {
|
|
802
|
+
try {
|
|
803
|
+
const r = await fetch("/_maskera/status");
|
|
804
|
+
const d = await r.json();
|
|
805
|
+
stReq.textContent = String(d.requests_proxied ?? 0);
|
|
806
|
+
stRed.textContent = String(d.total_redactions ?? 0);
|
|
807
|
+
const uniq = (d.sessions || []).reduce((sum, s) => sum + (s.entityCount || 0), 0);
|
|
808
|
+
stUniq.textContent = String(uniq);
|
|
809
|
+
stModel.textContent = d.engine?.defaultMode === "rules"
|
|
810
|
+
? "Regler"
|
|
811
|
+
: (d.engine?.nerError ? "Fel" : (d.engine?.nerLoaded ? "ONNX aktiv" : "V\xE4ntar"));
|
|
812
|
+
} catch {}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async function refreshVault() {
|
|
816
|
+
if (!reveal) { vaultRoot.innerHTML = ""; return; }
|
|
817
|
+
try {
|
|
818
|
+
const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
|
|
819
|
+
const d = await r.json();
|
|
820
|
+
const rows = (d.entries || []).map((e) => "<tr><td>" + esc(e.sessionId) + "</td><td><span class=\\"tok\\">" + esc(e.token) + "</span></td><td>" + esc(e.value) + "</td></tr>").join("");
|
|
821
|
+
vaultRoot.innerHTML = '<section class="vault-box"><h2>Lokal \xE5terst\xE4llningsnyckel (stannar i RAM)</h2><p>D\xF6lj den h\xE4r vyn innan du delar sk\xE4rm.</p>' +
|
|
822
|
+
(rows ? "<table><thead><tr><th>Session</th><th>Platsh\xE5llare</th><th>Originalv\xE4rde</th></tr></thead><tbody>" + rows + "</tbody></table>" : "<p>Inga lagrade v\xE4rden \xE4n.</p>") +
|
|
823
|
+
"</section>";
|
|
824
|
+
} catch {}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
function render() {
|
|
828
|
+
if (!items.length) {
|
|
829
|
+
feedEl.innerHTML = '<div class="empty">Inga proxade AI-anrop \xE4nnu. Peka din agent hit f\xF6r att se maskeringen i realtid:<code>ANTHROPIC_BASE_URL=${safeUrl} claude\\nOPENAI_BASE_URL=${safeUrl}/v1 codex</code></div>';
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
if (seenIds.size === 0 && items[0]?.id) {
|
|
833
|
+
openIds.add(items[0].id);
|
|
834
|
+
}
|
|
835
|
+
for (const it of items) seenIds.add(it.id);
|
|
836
|
+
feedEl.innerHTML = '<div class="list">' + items.map((it) => {
|
|
837
|
+
const time = (it.timestamp || "").slice(11, 19);
|
|
838
|
+
const pills = Object.entries(it.counts || {}).map(([k, v]) => '<span class="pill">' + esc(k) + " \xD7" + v + "</span>").join("");
|
|
839
|
+
const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
|
|
840
|
+
const statusCls = it.status >= 200 && it.status < 400 ? "ok" : "err";
|
|
841
|
+
const isOpen = openIds.has(it.id);
|
|
842
|
+
return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
|
|
843
|
+
'<summary><span class="left"><span class="badge ' + statusCls + '">' + it.status + '</span><span class="path">' + esc(it.method + " " + it.path) + '</span>' + pills + (it.redactions === 0 ? '<span style="color:var(--muted);font-size:12px">0 PII</span>' : "") + '</span>' +
|
|
844
|
+
'<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
|
|
845
|
+
'<div class="body"><p class="body-label">Vad som skickades vidare till molnet (0 r\xE5 PII):</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
|
|
846
|
+
}).join("") + "</div>";
|
|
847
|
+
for (const det of feedEl.querySelectorAll("details.item")) {
|
|
848
|
+
det.addEventListener("toggle", () => {
|
|
849
|
+
const id = det.getAttribute("data-id");
|
|
850
|
+
if (!id) return;
|
|
851
|
+
userToggled = true;
|
|
852
|
+
if (det.open) openIds.add(id);
|
|
853
|
+
else openIds.delete(id);
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
revealBtn.addEventListener("click", () => {
|
|
859
|
+
reveal = !reveal;
|
|
860
|
+
revealBtn.classList.toggle("active", reveal);
|
|
861
|
+
revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden lokalt";
|
|
862
|
+
void refreshVault();
|
|
863
|
+
});
|
|
864
|
+
|
|
865
|
+
clearBtn.addEventListener("click", async () => {
|
|
866
|
+
await fetch("/_maskera/clear", { method: "POST", headers: { "x-maskera-action": "clear" } });
|
|
867
|
+
items = [];
|
|
868
|
+
userToggled = false;
|
|
869
|
+
openIds.clear();
|
|
870
|
+
seenIds.clear();
|
|
871
|
+
render();
|
|
872
|
+
await refreshStatus();
|
|
873
|
+
await refreshVault();
|
|
874
|
+
});
|
|
875
|
+
|
|
876
|
+
const es = new EventSource("/_maskera/events");
|
|
877
|
+
es.addEventListener("init", (ev) => {
|
|
878
|
+
items = JSON.parse(ev.data).items || [];
|
|
879
|
+
render();
|
|
880
|
+
void refreshStatus();
|
|
881
|
+
});
|
|
882
|
+
es.addEventListener("request", (ev) => {
|
|
883
|
+
const next = JSON.parse(ev.data);
|
|
884
|
+
items.unshift(next);
|
|
885
|
+
if (items.length > 100) items.length = 100;
|
|
886
|
+
if (!userToggled && openIds.size === 0 && next?.id) openIds.add(next.id);
|
|
887
|
+
render();
|
|
888
|
+
void refreshStatus();
|
|
889
|
+
if (reveal) void refreshVault();
|
|
890
|
+
});
|
|
891
|
+
es.addEventListener("cleared", () => {
|
|
892
|
+
items = [];
|
|
893
|
+
userToggled = false;
|
|
894
|
+
openIds.clear();
|
|
895
|
+
seenIds.clear();
|
|
896
|
+
render();
|
|
897
|
+
void refreshStatus();
|
|
898
|
+
void refreshVault();
|
|
899
|
+
});
|
|
900
|
+
void refreshStatus();
|
|
901
|
+
})();
|
|
902
|
+
</script>
|
|
903
|
+
</body>
|
|
904
|
+
</html>`;
|
|
905
|
+
}
|
|
276
906
|
var DEFAULT_MAX_SESSIONS = 100;
|
|
907
|
+
var DEFAULT_MAX_ENTITIES_PER_SESSION = 5e3;
|
|
908
|
+
var EXISTING_TOKEN_RE = /\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]/g;
|
|
277
909
|
function valueKey(label, value) {
|
|
278
910
|
return `${label.length}:${label}:${value}`;
|
|
279
911
|
}
|
|
912
|
+
function labelFromKey(key) {
|
|
913
|
+
const firstColon = key.indexOf(":");
|
|
914
|
+
if (firstColon < 1) return null;
|
|
915
|
+
const len = Number(key.slice(0, firstColon));
|
|
916
|
+
if (!Number.isInteger(len) || len <= 0) return null;
|
|
917
|
+
return key.slice(firstColon + 1, firstColon + 1 + len);
|
|
918
|
+
}
|
|
280
919
|
var SessionVault = class {
|
|
281
|
-
constructor(maxSessions = DEFAULT_MAX_SESSIONS) {
|
|
920
|
+
constructor(maxSessions = DEFAULT_MAX_SESSIONS, maxEntitiesPerSession = DEFAULT_MAX_ENTITIES_PER_SESSION) {
|
|
282
921
|
this.sessions = /* @__PURE__ */ new Map();
|
|
283
922
|
this.maxSessions = Math.max(1, maxSessions);
|
|
923
|
+
this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
|
|
284
924
|
}
|
|
285
925
|
getOrCreate(sessionId) {
|
|
286
926
|
const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
|
|
@@ -315,23 +955,49 @@ var SessionVault = class {
|
|
|
315
955
|
*/
|
|
316
956
|
apply(originalInput, result, sessionId) {
|
|
317
957
|
const session = this.getOrCreate(sessionId);
|
|
958
|
+
if (result.redactions.length === 0) {
|
|
959
|
+
return {
|
|
960
|
+
sessionId: session.id,
|
|
961
|
+
redacted: originalInput,
|
|
962
|
+
counts: {},
|
|
963
|
+
totalRedactions: 0,
|
|
964
|
+
map: {}
|
|
965
|
+
};
|
|
966
|
+
}
|
|
318
967
|
const counts = {};
|
|
319
968
|
const localMap = {};
|
|
969
|
+
const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
|
|
320
970
|
let redacted = "";
|
|
321
971
|
let cursor = 0;
|
|
322
972
|
for (const r of result.redactions) {
|
|
323
973
|
const key = valueKey(r.label, r.value);
|
|
324
974
|
let token = session.tokenByKey.get(key);
|
|
325
|
-
if (
|
|
975
|
+
if (token) {
|
|
976
|
+
session.tokenByKey.delete(key);
|
|
977
|
+
session.tokenByKey.set(key, token);
|
|
978
|
+
} else {
|
|
326
979
|
let next = session.counters.get(r.label) ?? 0;
|
|
327
980
|
for (; ; ) {
|
|
328
981
|
next += 1;
|
|
329
982
|
const candidate = `[${r.label}_${next}]`;
|
|
330
|
-
if (!(candidate in session.map) && !
|
|
983
|
+
if (!(candidate in session.map) && !existingTokens?.has(candidate)) {
|
|
331
984
|
token = candidate;
|
|
332
985
|
break;
|
|
333
986
|
}
|
|
334
987
|
}
|
|
988
|
+
if (session.tokenByKey.size >= this.maxEntitiesPerSession) {
|
|
989
|
+
const oldestEntry = session.tokenByKey.entries().next().value;
|
|
990
|
+
if (oldestEntry) {
|
|
991
|
+
const [oldestKey, oldestToken] = oldestEntry;
|
|
992
|
+
session.tokenByKey.delete(oldestKey);
|
|
993
|
+
delete session.map[oldestToken];
|
|
994
|
+
const oldLabel = labelFromKey(oldestKey);
|
|
995
|
+
if (oldLabel && session.countsByLabel[oldLabel]) {
|
|
996
|
+
session.countsByLabel[oldLabel] -= 1;
|
|
997
|
+
if (session.countsByLabel[oldLabel] <= 0) delete session.countsByLabel[oldLabel];
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
335
1001
|
session.counters.set(r.label, next);
|
|
336
1002
|
session.tokenByKey.set(key, token);
|
|
337
1003
|
session.map[token] = r.value;
|
|
@@ -352,19 +1018,20 @@ var SessionVault = class {
|
|
|
352
1018
|
};
|
|
353
1019
|
}
|
|
354
1020
|
restore(text, options) {
|
|
1021
|
+
const normalizedId = options.sessionId?.trim() || void 0;
|
|
355
1022
|
if (options.map && Object.keys(options.map).length > 0) {
|
|
356
1023
|
return {
|
|
357
1024
|
restored: restore(text, options.map),
|
|
358
|
-
sessionId:
|
|
1025
|
+
sessionId: normalizedId ?? null,
|
|
359
1026
|
knownPlaceholders: Object.keys(options.map).length
|
|
360
1027
|
};
|
|
361
1028
|
}
|
|
362
|
-
if (!
|
|
1029
|
+
if (!normalizedId) {
|
|
363
1030
|
throw new Error("Provide either session_id or map to restore placeholders.");
|
|
364
1031
|
}
|
|
365
|
-
const session = this.sessions.get(
|
|
1032
|
+
const session = this.sessions.get(normalizedId);
|
|
366
1033
|
if (!session) {
|
|
367
|
-
throw new Error(`Unknown session_id "${
|
|
1034
|
+
throw new Error(`Unknown session_id "${normalizedId}".`);
|
|
368
1035
|
}
|
|
369
1036
|
return {
|
|
370
1037
|
restored: restore(text, session.map),
|
|
@@ -373,9 +1040,21 @@ var SessionVault = class {
|
|
|
373
1040
|
};
|
|
374
1041
|
}
|
|
375
1042
|
getMap(sessionId) {
|
|
376
|
-
const session = this.sessions.get(sessionId);
|
|
1043
|
+
const session = this.sessions.get(sessionId.trim());
|
|
377
1044
|
return session ? { ...session.map } : {};
|
|
378
1045
|
}
|
|
1046
|
+
entries() {
|
|
1047
|
+
const out = [];
|
|
1048
|
+
for (const s of this.sessions.values()) {
|
|
1049
|
+
for (const [token, value] of Object.entries(s.map)) {
|
|
1050
|
+
out.push({ sessionId: s.id, token, value });
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
return out;
|
|
1054
|
+
}
|
|
1055
|
+
clearAll() {
|
|
1056
|
+
this.sessions.clear();
|
|
1057
|
+
}
|
|
379
1058
|
list() {
|
|
380
1059
|
return [...this.sessions.values()].map((s) => ({
|
|
381
1060
|
sessionId: s.id,
|
|
@@ -386,7 +1065,7 @@ var SessionVault = class {
|
|
|
386
1065
|
}));
|
|
387
1066
|
}
|
|
388
1067
|
clear(sessionId) {
|
|
389
|
-
return this.sessions.delete(sessionId);
|
|
1068
|
+
return this.sessions.delete(sessionId.trim());
|
|
390
1069
|
}
|
|
391
1070
|
get size() {
|
|
392
1071
|
return this.sessions.size;
|
|
@@ -436,6 +1115,7 @@ var StreamingRestorer = class {
|
|
|
436
1115
|
}
|
|
437
1116
|
push(chunk) {
|
|
438
1117
|
if (!chunk || this.tokens.length === 0) return chunk;
|
|
1118
|
+
if (!this.buffer && !chunk.includes("[")) return chunk;
|
|
439
1119
|
this.buffer += chunk;
|
|
440
1120
|
return this.drain(false);
|
|
441
1121
|
}
|
|
@@ -493,12 +1173,12 @@ function mergeCounts(target, delta) {
|
|
|
493
1173
|
}
|
|
494
1174
|
}
|
|
495
1175
|
function restorePlainText(text, map) {
|
|
496
|
-
if (!text || Object.keys(map).length === 0) return text;
|
|
1176
|
+
if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
|
|
497
1177
|
const r = new StreamingRestorer(map);
|
|
498
1178
|
return r.push(text) + r.flush();
|
|
499
1179
|
}
|
|
500
1180
|
function restoreJsonEncodedText(text, map) {
|
|
501
|
-
if (!text || Object.keys(map).length === 0) return text;
|
|
1181
|
+
if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
|
|
502
1182
|
try {
|
|
503
1183
|
const parsed = JSON.parse(text);
|
|
504
1184
|
const restored = restoreJsonLeaves(parsed, map);
|
|
@@ -520,76 +1200,135 @@ function restoreJsonLeaves(value, map) {
|
|
|
520
1200
|
}
|
|
521
1201
|
return value;
|
|
522
1202
|
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
1203
|
+
var MASKERA_VAULT_TOOL_RE = /(?:^|__)maskera_(?:write_file|restore|clear_session)$/;
|
|
1204
|
+
var MASKERA_VAULT_CODE_RE = /\bmaskera_(?:write_file|restore)\b/;
|
|
1205
|
+
function isMaskeraVaultToolName(name) {
|
|
1206
|
+
return typeof name === "string" && MASKERA_VAULT_TOOL_RE.test(name);
|
|
1207
|
+
}
|
|
1208
|
+
function shouldSkipToolArgRestore(toolName, argsText) {
|
|
1209
|
+
if (isMaskeraVaultToolName(toolName)) return true;
|
|
1210
|
+
if (toolName === "execute" && MASKERA_VAULT_CODE_RE.test(argsText)) return true;
|
|
1211
|
+
return false;
|
|
1212
|
+
}
|
|
1213
|
+
async function redactLlmRequestBody(body, redactString, options = {}) {
|
|
1214
|
+
const clone = options.mutate ? body : structuredClone(body);
|
|
1215
|
+
async function redactContentBlocks(blocks, kind) {
|
|
526
1216
|
for (const block of blocks) {
|
|
527
1217
|
if (!isPlainObject(block)) continue;
|
|
528
1218
|
if (typeof block.text === "string") {
|
|
529
|
-
block.text = await redactString(block.text);
|
|
1219
|
+
block.text = await redactString(block.text, kind);
|
|
1220
|
+
}
|
|
1221
|
+
if (typeof block.thinking === "string") {
|
|
1222
|
+
const redactedThinking = await redactString(block.thinking, kind);
|
|
1223
|
+
if (redactedThinking !== block.thinking) {
|
|
1224
|
+
block.thinking = redactedThinking;
|
|
1225
|
+
delete block.signature;
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
if (typeof block.title === "string") {
|
|
1229
|
+
block.title = await redactString(block.title, kind);
|
|
1230
|
+
}
|
|
1231
|
+
if (typeof block.context === "string") {
|
|
1232
|
+
block.context = await redactString(block.context, kind);
|
|
530
1233
|
}
|
|
531
1234
|
if (typeof block.content === "string") {
|
|
532
|
-
block.content = await redactString(block.content);
|
|
1235
|
+
block.content = await redactString(block.content, kind);
|
|
533
1236
|
} else if (Array.isArray(block.content)) {
|
|
534
|
-
await redactContentBlocks(block.content);
|
|
1237
|
+
await redactContentBlocks(block.content, kind);
|
|
535
1238
|
}
|
|
536
1239
|
if (typeof block.output === "string") {
|
|
537
|
-
block.output = await redactString(block.output);
|
|
1240
|
+
block.output = await redactString(block.output, kind);
|
|
1241
|
+
} else if (Array.isArray(block.output)) {
|
|
1242
|
+
await redactContentBlocks(block.output, kind);
|
|
1243
|
+
}
|
|
1244
|
+
if (isPlainObject(block.source)) {
|
|
1245
|
+
if (block.source.type === "text" && typeof block.source.data === "string") {
|
|
1246
|
+
block.source.data = await redactString(block.source.data, kind);
|
|
1247
|
+
}
|
|
1248
|
+
if (typeof block.source.content === "string") {
|
|
1249
|
+
block.source.content = await redactString(block.source.content, kind);
|
|
1250
|
+
} else if (Array.isArray(block.source.content)) {
|
|
1251
|
+
await redactContentBlocks(block.source.content, kind);
|
|
1252
|
+
}
|
|
538
1253
|
}
|
|
539
1254
|
if (typeof block.arguments === "string") {
|
|
540
|
-
block.arguments = await redactJsonStringOrText(block.arguments);
|
|
1255
|
+
block.arguments = await redactJsonStringOrText(block.arguments, kind);
|
|
541
1256
|
}
|
|
542
1257
|
if (isPlainObject(block.input)) {
|
|
543
|
-
block.input = await redactObjectStrings(block.input);
|
|
1258
|
+
block.input = await redactObjectStrings(block.input, kind);
|
|
544
1259
|
}
|
|
545
1260
|
}
|
|
546
1261
|
}
|
|
547
|
-
async function redactObjectStrings(value) {
|
|
548
|
-
if (typeof value === "string") return redactString(value);
|
|
1262
|
+
async function redactObjectStrings(value, kind) {
|
|
1263
|
+
if (typeof value === "string") return redactString(value, kind);
|
|
549
1264
|
if (Array.isArray(value)) {
|
|
550
1265
|
const out = [];
|
|
551
|
-
for (const item of value) out.push(await redactObjectStrings(item));
|
|
1266
|
+
for (const item of value) out.push(await redactObjectStrings(item, kind));
|
|
552
1267
|
return out;
|
|
553
1268
|
}
|
|
554
1269
|
if (isPlainObject(value)) {
|
|
555
1270
|
const out = {};
|
|
556
1271
|
for (const [k, v] of Object.entries(value)) {
|
|
557
|
-
out[k] = await redactObjectStrings(v);
|
|
1272
|
+
out[k] = await redactObjectStrings(v, kind);
|
|
558
1273
|
}
|
|
559
1274
|
return out;
|
|
560
1275
|
}
|
|
561
1276
|
return value;
|
|
562
1277
|
}
|
|
563
|
-
async function redactJsonStringOrText(raw) {
|
|
1278
|
+
async function redactJsonStringOrText(raw, kind) {
|
|
564
1279
|
try {
|
|
565
1280
|
const parsed = JSON.parse(raw);
|
|
566
|
-
const redacted = await redactObjectStrings(parsed);
|
|
1281
|
+
const redacted = await redactObjectStrings(parsed, kind);
|
|
567
1282
|
return JSON.stringify(redacted);
|
|
568
1283
|
} catch {
|
|
569
|
-
return redactString(raw);
|
|
1284
|
+
return redactString(raw, kind);
|
|
570
1285
|
}
|
|
571
1286
|
}
|
|
572
1287
|
if (typeof clone.system === "string") {
|
|
573
|
-
clone.system = await redactString(clone.system);
|
|
1288
|
+
clone.system = await redactString(clone.system, "system");
|
|
574
1289
|
} else if (Array.isArray(clone.system)) {
|
|
575
|
-
await redactContentBlocks(clone.system);
|
|
1290
|
+
await redactContentBlocks(clone.system, "system");
|
|
576
1291
|
}
|
|
577
1292
|
if (typeof clone.instructions === "string") {
|
|
578
|
-
clone.instructions = await redactString(clone.instructions);
|
|
1293
|
+
clone.instructions = await redactString(clone.instructions, "system");
|
|
1294
|
+
}
|
|
1295
|
+
async function redactToolEntries(entries) {
|
|
1296
|
+
for (const tool of entries) {
|
|
1297
|
+
if (!isPlainObject(tool)) continue;
|
|
1298
|
+
if (typeof tool.description === "string") {
|
|
1299
|
+
tool.description = await redactString(tool.description, "tool_description");
|
|
1300
|
+
}
|
|
1301
|
+
if (isPlainObject(tool.function) && typeof tool.function.description === "string") {
|
|
1302
|
+
tool.function.description = await redactString(
|
|
1303
|
+
tool.function.description,
|
|
1304
|
+
"tool_description"
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
if (Array.isArray(tool.tools)) {
|
|
1308
|
+
await redactToolEntries(tool.tools);
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
if (Array.isArray(clone.tools)) {
|
|
1313
|
+
await redactToolEntries(clone.tools);
|
|
579
1314
|
}
|
|
580
1315
|
if (Array.isArray(clone.messages)) {
|
|
581
1316
|
for (const msg of clone.messages) {
|
|
582
1317
|
if (!isPlainObject(msg)) continue;
|
|
1318
|
+
const msgKind = msg.role === "system" || msg.role === "developer" ? "system" : "message";
|
|
583
1319
|
if (typeof msg.content === "string") {
|
|
584
|
-
msg.content = await redactString(msg.content);
|
|
1320
|
+
msg.content = await redactString(msg.content, msgKind);
|
|
585
1321
|
} else if (Array.isArray(msg.content)) {
|
|
586
|
-
await redactContentBlocks(msg.content);
|
|
1322
|
+
await redactContentBlocks(msg.content, msgKind);
|
|
587
1323
|
}
|
|
588
1324
|
if (Array.isArray(msg.tool_calls)) {
|
|
589
1325
|
for (const call of msg.tool_calls) {
|
|
590
1326
|
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
591
1327
|
if (typeof call.function.arguments === "string") {
|
|
592
|
-
call.function.arguments = await redactJsonStringOrText(
|
|
1328
|
+
call.function.arguments = await redactJsonStringOrText(
|
|
1329
|
+
call.function.arguments,
|
|
1330
|
+
msgKind
|
|
1331
|
+
);
|
|
593
1332
|
}
|
|
594
1333
|
}
|
|
595
1334
|
}
|
|
@@ -597,44 +1336,53 @@ async function redactLlmRequestBody(body, redactString) {
|
|
|
597
1336
|
}
|
|
598
1337
|
}
|
|
599
1338
|
if (typeof clone.input === "string") {
|
|
600
|
-
clone.input = await redactString(clone.input);
|
|
1339
|
+
clone.input = await redactString(clone.input, "message");
|
|
601
1340
|
} else if (Array.isArray(clone.input)) {
|
|
602
1341
|
for (let i = 0; i < clone.input.length; i++) {
|
|
603
1342
|
const item = clone.input[i];
|
|
604
1343
|
if (typeof item === "string") {
|
|
605
|
-
clone.input[i] = await redactString(item);
|
|
1344
|
+
clone.input[i] = await redactString(item, "message");
|
|
606
1345
|
} else if (isPlainObject(item)) {
|
|
607
|
-
|
|
1346
|
+
const itemKind = item.role === "system" || item.role === "developer" ? "system" : "message";
|
|
1347
|
+
if (typeof item.text === "string") item.text = await redactString(item.text, itemKind);
|
|
608
1348
|
if (typeof item.content === "string") {
|
|
609
|
-
item.content = await redactString(item.content);
|
|
1349
|
+
item.content = await redactString(item.content, itemKind);
|
|
610
1350
|
} else if (Array.isArray(item.content)) {
|
|
611
|
-
await redactContentBlocks(item.content);
|
|
1351
|
+
await redactContentBlocks(item.content, itemKind);
|
|
612
1352
|
}
|
|
613
1353
|
if (typeof item.output === "string") {
|
|
614
|
-
item.output = await redactString(item.output);
|
|
1354
|
+
item.output = await redactString(item.output, itemKind);
|
|
1355
|
+
} else if (Array.isArray(item.output)) {
|
|
1356
|
+
await redactContentBlocks(item.output, itemKind);
|
|
1357
|
+
}
|
|
1358
|
+
if (Array.isArray(item.summary)) {
|
|
1359
|
+
await redactContentBlocks(item.summary, itemKind);
|
|
615
1360
|
}
|
|
616
1361
|
if (typeof item.arguments === "string") {
|
|
617
|
-
item.arguments = await redactJsonStringOrText(item.arguments);
|
|
1362
|
+
item.arguments = await redactJsonStringOrText(item.arguments, itemKind);
|
|
618
1363
|
}
|
|
619
1364
|
}
|
|
620
1365
|
}
|
|
621
1366
|
}
|
|
622
1367
|
return clone;
|
|
623
1368
|
}
|
|
624
|
-
function restoreLlmResponseBody(body, map) {
|
|
1369
|
+
function restoreLlmResponseBody(body, map, options = {}) {
|
|
625
1370
|
if (!isPlainObject(body) || Object.keys(map).length === 0) return body;
|
|
626
|
-
const clone = structuredClone(body);
|
|
1371
|
+
const clone = options.mutate ? body : structuredClone(body);
|
|
627
1372
|
if (Array.isArray(clone.content)) {
|
|
628
1373
|
for (const block of clone.content) {
|
|
629
1374
|
if (!isPlainObject(block)) continue;
|
|
630
1375
|
if (typeof block.text === "string") {
|
|
631
1376
|
block.text = restorePlainText(block.text, map);
|
|
632
1377
|
}
|
|
633
|
-
if (typeof block.thinking === "string") {
|
|
1378
|
+
if (typeof block.thinking === "string" && typeof block.signature !== "string") {
|
|
634
1379
|
block.thinking = restorePlainText(block.thinking, map);
|
|
635
1380
|
}
|
|
636
1381
|
if (isPlainObject(block.input)) {
|
|
637
|
-
block.input
|
|
1382
|
+
const skipRestore = isMaskeraVaultToolName(block.name) || block.name === "execute" && typeof block.input.code === "string" && MASKERA_VAULT_CODE_RE.test(block.input.code);
|
|
1383
|
+
if (!skipRestore) {
|
|
1384
|
+
block.input = restoreJsonLeaves(block.input, map);
|
|
1385
|
+
}
|
|
638
1386
|
}
|
|
639
1387
|
}
|
|
640
1388
|
}
|
|
@@ -646,10 +1394,13 @@ function restoreLlmResponseBody(body, map) {
|
|
|
646
1394
|
if (typeof msg.content === "string") {
|
|
647
1395
|
msg.content = restorePlainText(msg.content, map);
|
|
648
1396
|
}
|
|
1397
|
+
if (typeof msg.reasoning_content === "string") {
|
|
1398
|
+
msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
|
|
1399
|
+
}
|
|
649
1400
|
if (Array.isArray(msg.tool_calls)) {
|
|
650
1401
|
for (const call of msg.tool_calls) {
|
|
651
1402
|
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
652
|
-
if (typeof call.function.arguments === "string") {
|
|
1403
|
+
if (typeof call.function.arguments === "string" && !shouldSkipToolArgRestore(call.function.name, call.function.arguments)) {
|
|
653
1404
|
call.function.arguments = restoreJsonEncodedText(call.function.arguments, map);
|
|
654
1405
|
}
|
|
655
1406
|
}
|
|
@@ -667,7 +1418,7 @@ function restoreLlmResponseBody(body, map) {
|
|
|
667
1418
|
if (Array.isArray(clone.output)) {
|
|
668
1419
|
for (const item of clone.output) {
|
|
669
1420
|
if (!isPlainObject(item)) continue;
|
|
670
|
-
if (typeof item.arguments === "string") {
|
|
1421
|
+
if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(item.name, item.arguments)) {
|
|
671
1422
|
item.arguments = restoreJsonEncodedText(item.arguments, map);
|
|
672
1423
|
}
|
|
673
1424
|
if (Array.isArray(item.content)) {
|
|
@@ -677,12 +1428,21 @@ function restoreLlmResponseBody(body, map) {
|
|
|
677
1428
|
}
|
|
678
1429
|
}
|
|
679
1430
|
}
|
|
1431
|
+
if (Array.isArray(item.summary)) {
|
|
1432
|
+
for (const part of item.summary) {
|
|
1433
|
+
if (isPlainObject(part) && typeof part.text === "string") {
|
|
1434
|
+
part.text = restorePlainText(part.text, map);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
680
1438
|
}
|
|
681
1439
|
}
|
|
682
1440
|
return clone;
|
|
683
1441
|
}
|
|
684
1442
|
function createSseRestorer(map) {
|
|
685
1443
|
const streams = /* @__PURE__ */ new Map();
|
|
1444
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
1445
|
+
const bufferedToolArgs = /* @__PURE__ */ new Map();
|
|
686
1446
|
const getStream = (key, escapeForJsonString = false) => {
|
|
687
1447
|
let r = streams.get(key);
|
|
688
1448
|
if (!r) {
|
|
@@ -697,6 +1457,148 @@ function createSseRestorer(map) {
|
|
|
697
1457
|
streams.delete(key);
|
|
698
1458
|
return r.flush();
|
|
699
1459
|
}
|
|
1460
|
+
function flushBufferedToolArgs(key) {
|
|
1461
|
+
const raw = bufferedToolArgs.get(key);
|
|
1462
|
+
if (raw === void 0) return "";
|
|
1463
|
+
bufferedToolArgs.delete(key);
|
|
1464
|
+
const name = toolNames.get(key);
|
|
1465
|
+
if (shouldSkipToolArgRestore(name, raw)) return raw;
|
|
1466
|
+
return restoreJsonEncodedText(raw, map);
|
|
1467
|
+
}
|
|
1468
|
+
function drainRemainingStreams() {
|
|
1469
|
+
const events = [];
|
|
1470
|
+
for (const key of [...bufferedToolArgs.keys()]) {
|
|
1471
|
+
const full = flushBufferedToolArgs(key);
|
|
1472
|
+
if (!full) continue;
|
|
1473
|
+
if (key.startsWith("openai_chat_tool:")) {
|
|
1474
|
+
const [, cIdx, tIdx] = key.split(":");
|
|
1475
|
+
events.push(
|
|
1476
|
+
`data: ${JSON.stringify({
|
|
1477
|
+
choices: [
|
|
1478
|
+
{
|
|
1479
|
+
index: Number(cIdx ?? 0),
|
|
1480
|
+
delta: {
|
|
1481
|
+
tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: full } }]
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
]
|
|
1485
|
+
})}`
|
|
1486
|
+
);
|
|
1487
|
+
} else if (key.startsWith("anth_json:")) {
|
|
1488
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
1489
|
+
events.push(
|
|
1490
|
+
`event: content_block_delta
|
|
1491
|
+
data: ${JSON.stringify({
|
|
1492
|
+
type: "content_block_delta",
|
|
1493
|
+
index: idx,
|
|
1494
|
+
delta: { type: "input_json_delta", partial_json: full }
|
|
1495
|
+
})}`
|
|
1496
|
+
);
|
|
1497
|
+
} else if (key.startsWith("resp_args:")) {
|
|
1498
|
+
const outputIdx = Number(key.split(":")[1] ?? 0);
|
|
1499
|
+
events.push(
|
|
1500
|
+
`event: response.function_call_arguments.delta
|
|
1501
|
+
data: ${JSON.stringify({
|
|
1502
|
+
type: "response.function_call_arguments.delta",
|
|
1503
|
+
output_index: outputIdx,
|
|
1504
|
+
delta: full
|
|
1505
|
+
})}`
|
|
1506
|
+
);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
for (const key of [...streams.keys()]) {
|
|
1510
|
+
const tail = flushStream(key);
|
|
1511
|
+
if (!tail) continue;
|
|
1512
|
+
if (key.startsWith("openai_chat_text:")) {
|
|
1513
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
1514
|
+
events.push(
|
|
1515
|
+
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { content: tail } }] })}`
|
|
1516
|
+
);
|
|
1517
|
+
} else if (key.startsWith("openai_chat_tool:")) {
|
|
1518
|
+
const [, cIdx, tIdx] = key.split(":");
|
|
1519
|
+
events.push(
|
|
1520
|
+
`data: ${JSON.stringify({
|
|
1521
|
+
choices: [
|
|
1522
|
+
{
|
|
1523
|
+
index: Number(cIdx ?? 0),
|
|
1524
|
+
delta: {
|
|
1525
|
+
tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
]
|
|
1529
|
+
})}`
|
|
1530
|
+
);
|
|
1531
|
+
} else if (key.startsWith("anth_text:")) {
|
|
1532
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
1533
|
+
events.push(
|
|
1534
|
+
`event: content_block_delta
|
|
1535
|
+
data: ${JSON.stringify({
|
|
1536
|
+
type: "content_block_delta",
|
|
1537
|
+
index: idx,
|
|
1538
|
+
delta: { type: "text_delta", text: tail }
|
|
1539
|
+
})}`
|
|
1540
|
+
);
|
|
1541
|
+
} else if (key.startsWith("anth_thinking:")) {
|
|
1542
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
1543
|
+
events.push(
|
|
1544
|
+
`event: content_block_delta
|
|
1545
|
+
data: ${JSON.stringify({
|
|
1546
|
+
type: "content_block_delta",
|
|
1547
|
+
index: idx,
|
|
1548
|
+
delta: { type: "thinking_delta", thinking: tail }
|
|
1549
|
+
})}`
|
|
1550
|
+
);
|
|
1551
|
+
} else if (key.startsWith("anth_json:")) {
|
|
1552
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
1553
|
+
events.push(
|
|
1554
|
+
`event: content_block_delta
|
|
1555
|
+
data: ${JSON.stringify({
|
|
1556
|
+
type: "content_block_delta",
|
|
1557
|
+
index: idx,
|
|
1558
|
+
delta: { type: "input_json_delta", partial_json: tail }
|
|
1559
|
+
})}`
|
|
1560
|
+
);
|
|
1561
|
+
} else if (key.startsWith("resp_text:")) {
|
|
1562
|
+
const [, outputIdx, contentIdx] = key.split(":");
|
|
1563
|
+
events.push(
|
|
1564
|
+
`event: response.output_text.delta
|
|
1565
|
+
data: ${JSON.stringify({
|
|
1566
|
+
type: "response.output_text.delta",
|
|
1567
|
+
output_index: Number(outputIdx ?? 0),
|
|
1568
|
+
content_index: Number(contentIdx ?? 0),
|
|
1569
|
+
delta: tail
|
|
1570
|
+
})}`
|
|
1571
|
+
);
|
|
1572
|
+
} else if (key.startsWith("openai_chat_reasoning:")) {
|
|
1573
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
1574
|
+
events.push(
|
|
1575
|
+
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
|
|
1576
|
+
);
|
|
1577
|
+
} else if (key.startsWith("resp_reasoning:")) {
|
|
1578
|
+
const [, outputIdx, summaryIdx] = key.split(":");
|
|
1579
|
+
events.push(
|
|
1580
|
+
`event: response.reasoning_summary_text.delta
|
|
1581
|
+
data: ${JSON.stringify({
|
|
1582
|
+
type: "response.reasoning_summary_text.delta",
|
|
1583
|
+
output_index: Number(outputIdx ?? 0),
|
|
1584
|
+
summary_index: Number(summaryIdx ?? 0),
|
|
1585
|
+
delta: tail
|
|
1586
|
+
})}`
|
|
1587
|
+
);
|
|
1588
|
+
} else if (key.startsWith("resp_args:")) {
|
|
1589
|
+
const outputIdx = Number(key.split(":")[1] ?? 0);
|
|
1590
|
+
events.push(
|
|
1591
|
+
`event: response.function_call_arguments.delta
|
|
1592
|
+
data: ${JSON.stringify({
|
|
1593
|
+
type: "response.function_call_arguments.delta",
|
|
1594
|
+
output_index: outputIdx,
|
|
1595
|
+
delta: tail
|
|
1596
|
+
})}`
|
|
1597
|
+
);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
return events;
|
|
1601
|
+
}
|
|
700
1602
|
let sseBuffer = "";
|
|
701
1603
|
function processEventBlock(block) {
|
|
702
1604
|
const lines = block.split("\n");
|
|
@@ -709,30 +1611,7 @@ function createSseRestorer(map) {
|
|
|
709
1611
|
}
|
|
710
1612
|
const rawData = line.slice("data:".length).trimStart();
|
|
711
1613
|
if (!rawData || rawData === "[DONE]") {
|
|
712
|
-
|
|
713
|
-
const tail = flushStream(key);
|
|
714
|
-
if (!tail) continue;
|
|
715
|
-
if (key.startsWith("openai_chat_text:")) {
|
|
716
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
717
|
-
extraEvents.push(
|
|
718
|
-
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { content: tail } }] })}`
|
|
719
|
-
);
|
|
720
|
-
} else if (key.startsWith("openai_chat_tool:")) {
|
|
721
|
-
const [, cIdx, tIdx] = key.split(":");
|
|
722
|
-
extraEvents.push(
|
|
723
|
-
`data: ${JSON.stringify({
|
|
724
|
-
choices: [
|
|
725
|
-
{
|
|
726
|
-
index: Number(cIdx ?? 0),
|
|
727
|
-
delta: {
|
|
728
|
-
tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
]
|
|
732
|
-
})}`
|
|
733
|
-
);
|
|
734
|
-
}
|
|
735
|
-
}
|
|
1614
|
+
extraEvents.push(...drainRemainingStreams());
|
|
736
1615
|
outLines.push(line);
|
|
737
1616
|
continue;
|
|
738
1617
|
}
|
|
@@ -747,14 +1626,29 @@ function createSseRestorer(map) {
|
|
|
747
1626
|
outLines.push(line);
|
|
748
1627
|
continue;
|
|
749
1628
|
}
|
|
1629
|
+
if (parsed.type === "content_block_start" && isPlainObject(parsed.content_block)) {
|
|
1630
|
+
const idx = typeof parsed.index === "number" ? parsed.index : 0;
|
|
1631
|
+
if (parsed.content_block.type === "tool_use" && typeof parsed.content_block.name === "string") {
|
|
1632
|
+
toolNames.set(`anth_json:${idx}`, parsed.content_block.name);
|
|
1633
|
+
}
|
|
1634
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1635
|
+
continue;
|
|
1636
|
+
}
|
|
750
1637
|
if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
|
|
751
1638
|
const idx = typeof parsed.index === "number" ? parsed.index : 0;
|
|
752
1639
|
if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
|
|
753
1640
|
parsed.delta.text = getStream(`anth_text:${idx}`).push(parsed.delta.text);
|
|
1641
|
+
} else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
|
|
1642
|
+
parsed.delta.thinking = getStream(`anth_thinking:${idx}`).push(parsed.delta.thinking);
|
|
754
1643
|
} else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
);
|
|
1644
|
+
const key = `anth_json:${idx}`;
|
|
1645
|
+
const name = toolNames.get(key);
|
|
1646
|
+
if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
|
|
1647
|
+
bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta.partial_json);
|
|
1648
|
+
parsed.delta.partial_json = "";
|
|
1649
|
+
} else {
|
|
1650
|
+
parsed.delta.partial_json = getStream(key, true).push(parsed.delta.partial_json);
|
|
1651
|
+
}
|
|
758
1652
|
}
|
|
759
1653
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
760
1654
|
continue;
|
|
@@ -772,7 +1666,20 @@ data: ${JSON.stringify({
|
|
|
772
1666
|
})}`
|
|
773
1667
|
);
|
|
774
1668
|
}
|
|
775
|
-
const
|
|
1669
|
+
const thinkingTail = flushStream(`anth_thinking:${idx}`);
|
|
1670
|
+
if (thinkingTail) {
|
|
1671
|
+
extraEvents.push(
|
|
1672
|
+
`event: content_block_delta
|
|
1673
|
+
data: ${JSON.stringify({
|
|
1674
|
+
type: "content_block_delta",
|
|
1675
|
+
index: idx,
|
|
1676
|
+
delta: { type: "thinking_delta", thinking: thinkingTail }
|
|
1677
|
+
})}`
|
|
1678
|
+
);
|
|
1679
|
+
}
|
|
1680
|
+
const jsonKey = `anth_json:${idx}`;
|
|
1681
|
+
const jsonTail = flushBufferedToolArgs(jsonKey) || flushStream(jsonKey);
|
|
1682
|
+
toolNames.delete(jsonKey);
|
|
776
1683
|
if (jsonTail) {
|
|
777
1684
|
extraEvents.push(
|
|
778
1685
|
`event: content_block_delta
|
|
@@ -795,15 +1702,32 @@ data: ${JSON.stringify({
|
|
|
795
1702
|
if (typeof delta.content === "string") {
|
|
796
1703
|
delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
|
|
797
1704
|
}
|
|
1705
|
+
if (typeof delta.reasoning_content === "string") {
|
|
1706
|
+
delta.reasoning_content = getStream(`openai_chat_reasoning:${cIdx}`).push(
|
|
1707
|
+
delta.reasoning_content
|
|
1708
|
+
);
|
|
1709
|
+
}
|
|
798
1710
|
if (Array.isArray(delta.tool_calls)) {
|
|
799
1711
|
for (const call of delta.tool_calls) {
|
|
800
1712
|
if (!isPlainObject(call)) continue;
|
|
801
1713
|
const tIdx = typeof call.index === "number" ? call.index : 0;
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
1714
|
+
const key = `openai_chat_tool:${cIdx}:${tIdx}`;
|
|
1715
|
+
if (isPlainObject(call.function)) {
|
|
1716
|
+
if (typeof call.function.name === "string" && call.function.name) {
|
|
1717
|
+
toolNames.set(key, call.function.name);
|
|
1718
|
+
}
|
|
1719
|
+
if (typeof call.function.arguments === "string") {
|
|
1720
|
+
const name = toolNames.get(key);
|
|
1721
|
+
if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
|
|
1722
|
+
bufferedToolArgs.set(
|
|
1723
|
+
key,
|
|
1724
|
+
(bufferedToolArgs.get(key) ?? "") + call.function.arguments
|
|
1725
|
+
);
|
|
1726
|
+
call.function.arguments = "";
|
|
1727
|
+
} else {
|
|
1728
|
+
call.function.arguments = getStream(key, true).push(call.function.arguments);
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
807
1731
|
}
|
|
808
1732
|
}
|
|
809
1733
|
}
|
|
@@ -815,11 +1739,63 @@ data: ${JSON.stringify({
|
|
|
815
1739
|
const d = choice.delta;
|
|
816
1740
|
d.content = (typeof d.content === "string" ? d.content : "") + textTail;
|
|
817
1741
|
}
|
|
1742
|
+
const reasoningTail = flushStream(`openai_chat_reasoning:${cIdx}`);
|
|
1743
|
+
if (reasoningTail) {
|
|
1744
|
+
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
1745
|
+
const d = choice.delta;
|
|
1746
|
+
d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
|
|
1747
|
+
}
|
|
1748
|
+
const toolPrefix = `openai_chat_tool:${cIdx}:`;
|
|
1749
|
+
for (const key of [...bufferedToolArgs.keys()]) {
|
|
1750
|
+
if (!key.startsWith(toolPrefix)) continue;
|
|
1751
|
+
const tIdx = Number(key.slice(toolPrefix.length) || 0);
|
|
1752
|
+
const fullArgs = flushBufferedToolArgs(key);
|
|
1753
|
+
toolNames.delete(key);
|
|
1754
|
+
if (!fullArgs) continue;
|
|
1755
|
+
extraEvents.push(
|
|
1756
|
+
`data: ${JSON.stringify({
|
|
1757
|
+
choices: [
|
|
1758
|
+
{
|
|
1759
|
+
index: cIdx,
|
|
1760
|
+
delta: {
|
|
1761
|
+
tool_calls: [{ index: tIdx, function: { arguments: fullArgs } }]
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
]
|
|
1765
|
+
})}`
|
|
1766
|
+
);
|
|
1767
|
+
}
|
|
1768
|
+
for (const key of [...streams.keys()]) {
|
|
1769
|
+
if (!key.startsWith(toolPrefix)) continue;
|
|
1770
|
+
const tIdx = Number(key.slice(toolPrefix.length) || 0);
|
|
1771
|
+
const toolTail = flushStream(key);
|
|
1772
|
+
toolNames.delete(key);
|
|
1773
|
+
if (!toolTail) continue;
|
|
1774
|
+
extraEvents.push(
|
|
1775
|
+
`data: ${JSON.stringify({
|
|
1776
|
+
choices: [
|
|
1777
|
+
{
|
|
1778
|
+
index: cIdx,
|
|
1779
|
+
delta: {
|
|
1780
|
+
tool_calls: [{ index: tIdx, function: { arguments: toolTail } }]
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
]
|
|
1784
|
+
})}`
|
|
1785
|
+
);
|
|
1786
|
+
}
|
|
818
1787
|
}
|
|
819
1788
|
}
|
|
820
1789
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
821
1790
|
continue;
|
|
822
1791
|
}
|
|
1792
|
+
if (parsed.type === "response.output_item.added" && isPlainObject(parsed.item)) {
|
|
1793
|
+
if (parsed.item.type === "function_call" && typeof parsed.item.name === "string") {
|
|
1794
|
+
toolNames.set(`resp_args:${String(parsed.output_index ?? 0)}`, parsed.item.name);
|
|
1795
|
+
}
|
|
1796
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
823
1799
|
if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
|
|
824
1800
|
const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
|
|
825
1801
|
parsed.delta = getStream(key).push(parsed.delta);
|
|
@@ -846,15 +1822,48 @@ data: ${JSON.stringify({
|
|
|
846
1822
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
847
1823
|
continue;
|
|
848
1824
|
}
|
|
1825
|
+
if (parsed.type === "response.reasoning_summary_text.delta" && typeof parsed.delta === "string") {
|
|
1826
|
+
const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
|
|
1827
|
+
parsed.delta = getStream(key).push(parsed.delta);
|
|
1828
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1829
|
+
continue;
|
|
1830
|
+
}
|
|
1831
|
+
if (parsed.type === "response.reasoning_summary_text.done") {
|
|
1832
|
+
const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
|
|
1833
|
+
const tail = flushStream(key);
|
|
1834
|
+
if (tail) {
|
|
1835
|
+
extraEvents.push(
|
|
1836
|
+
`event: response.reasoning_summary_text.delta
|
|
1837
|
+
data: ${JSON.stringify({
|
|
1838
|
+
type: "response.reasoning_summary_text.delta",
|
|
1839
|
+
output_index: parsed.output_index ?? 0,
|
|
1840
|
+
summary_index: parsed.summary_index ?? 0,
|
|
1841
|
+
delta: tail
|
|
1842
|
+
})}`
|
|
1843
|
+
);
|
|
1844
|
+
}
|
|
1845
|
+
if (typeof parsed.text === "string") {
|
|
1846
|
+
parsed.text = restorePlainText(parsed.text, map);
|
|
1847
|
+
}
|
|
1848
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1849
|
+
continue;
|
|
1850
|
+
}
|
|
849
1851
|
if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
|
|
850
1852
|
const key = `resp_args:${String(parsed.output_index ?? 0)}`;
|
|
851
|
-
|
|
1853
|
+
const name = toolNames.get(key);
|
|
1854
|
+
if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
|
|
1855
|
+
bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta);
|
|
1856
|
+
parsed.delta = "";
|
|
1857
|
+
} else {
|
|
1858
|
+
parsed.delta = getStream(key, true).push(parsed.delta);
|
|
1859
|
+
}
|
|
852
1860
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
853
1861
|
continue;
|
|
854
1862
|
}
|
|
855
1863
|
if (parsed.type === "response.function_call_arguments.done") {
|
|
856
1864
|
const key = `resp_args:${String(parsed.output_index ?? 0)}`;
|
|
857
|
-
const
|
|
1865
|
+
const name = toolNames.get(key);
|
|
1866
|
+
const tail = flushBufferedToolArgs(key) || flushStream(key);
|
|
858
1867
|
if (tail) {
|
|
859
1868
|
extraEvents.push(
|
|
860
1869
|
`event: response.function_call_arguments.delta
|
|
@@ -865,13 +1874,50 @@ data: ${JSON.stringify({
|
|
|
865
1874
|
})}`
|
|
866
1875
|
);
|
|
867
1876
|
}
|
|
868
|
-
if (typeof parsed.arguments === "string") {
|
|
1877
|
+
if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(name, parsed.arguments)) {
|
|
869
1878
|
parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
|
|
870
1879
|
}
|
|
871
1880
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
872
1881
|
continue;
|
|
873
1882
|
}
|
|
874
|
-
if (parsed.type === "
|
|
1883
|
+
if (parsed.type === "error") {
|
|
1884
|
+
extraEvents.push(...drainRemainingStreams());
|
|
1885
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1886
|
+
continue;
|
|
1887
|
+
}
|
|
1888
|
+
if (parsed.type === "response.content_part.done" && isPlainObject(parsed.part)) {
|
|
1889
|
+
if (typeof parsed.part.text === "string") {
|
|
1890
|
+
parsed.part.text = restorePlainText(parsed.part.text, map);
|
|
1891
|
+
}
|
|
1892
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1893
|
+
continue;
|
|
1894
|
+
}
|
|
1895
|
+
if (parsed.type === "response.output_item.done" && isPlainObject(parsed.item)) {
|
|
1896
|
+
const item = parsed.item;
|
|
1897
|
+
const key = `resp_args:${String(parsed.output_index ?? 0)}`;
|
|
1898
|
+
const name = typeof item.name === "string" ? item.name : toolNames.get(key);
|
|
1899
|
+
toolNames.delete(key);
|
|
1900
|
+
if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(name, item.arguments)) {
|
|
1901
|
+
item.arguments = restoreJsonEncodedText(item.arguments, map);
|
|
1902
|
+
}
|
|
1903
|
+
if (Array.isArray(item.content)) {
|
|
1904
|
+
for (const part of item.content) {
|
|
1905
|
+
if (isPlainObject(part) && typeof part.text === "string") {
|
|
1906
|
+
part.text = restorePlainText(part.text, map);
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
if (Array.isArray(item.summary)) {
|
|
1911
|
+
for (const part of item.summary) {
|
|
1912
|
+
if (isPlainObject(part) && typeof part.text === "string") {
|
|
1913
|
+
part.text = restorePlainText(part.text, map);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1918
|
+
continue;
|
|
1919
|
+
}
|
|
1920
|
+
if ((parsed.type === "response.completed" || parsed.type === "response.incomplete") && isPlainObject(parsed.response)) {
|
|
875
1921
|
parsed.response = restoreLlmResponseBody(parsed.response, map);
|
|
876
1922
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
877
1923
|
continue;
|
|
@@ -883,15 +1929,19 @@ data: ${JSON.stringify({
|
|
|
883
1929
|
|
|
884
1930
|
${joined}` : joined;
|
|
885
1931
|
}
|
|
1932
|
+
let pendingCr = false;
|
|
886
1933
|
return {
|
|
887
1934
|
push(chunk) {
|
|
888
|
-
|
|
1935
|
+
let text = pendingCr ? `\r${chunk}` : chunk;
|
|
1936
|
+
pendingCr = text.endsWith("\r");
|
|
1937
|
+
if (pendingCr) text = text.slice(0, -1);
|
|
1938
|
+
sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
889
1939
|
let out = "";
|
|
890
1940
|
for (; ; ) {
|
|
891
|
-
const
|
|
892
|
-
if (
|
|
893
|
-
const block = sseBuffer.slice(0,
|
|
894
|
-
sseBuffer = sseBuffer.slice(
|
|
1941
|
+
const sep2 = sseBuffer.indexOf("\n\n");
|
|
1942
|
+
if (sep2 < 0) break;
|
|
1943
|
+
const block = sseBuffer.slice(0, sep2);
|
|
1944
|
+
sseBuffer = sseBuffer.slice(sep2 + 2);
|
|
895
1945
|
out += `${processEventBlock(block)}
|
|
896
1946
|
|
|
897
1947
|
`;
|
|
@@ -899,13 +1949,113 @@ ${joined}` : joined;
|
|
|
899
1949
|
return out;
|
|
900
1950
|
},
|
|
901
1951
|
flush() {
|
|
902
|
-
if (
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
1952
|
+
if (pendingCr) {
|
|
1953
|
+
sseBuffer += "\n";
|
|
1954
|
+
pendingCr = false;
|
|
1955
|
+
}
|
|
1956
|
+
const parts = [];
|
|
1957
|
+
if (sseBuffer) {
|
|
1958
|
+
parts.push(processEventBlock(sseBuffer));
|
|
1959
|
+
sseBuffer = "";
|
|
1960
|
+
}
|
|
1961
|
+
const drained = drainRemainingStreams();
|
|
1962
|
+
if (drained.length > 0) {
|
|
1963
|
+
parts.push(`${drained.join("\n\n")}
|
|
1964
|
+
|
|
1965
|
+
`);
|
|
1966
|
+
}
|
|
1967
|
+
return parts.join("");
|
|
906
1968
|
}
|
|
907
1969
|
};
|
|
908
1970
|
}
|
|
1971
|
+
var PayloadTooLargeError = class extends Error {
|
|
1972
|
+
constructor() {
|
|
1973
|
+
super(...arguments);
|
|
1974
|
+
this.statusCode = 413;
|
|
1975
|
+
}
|
|
1976
|
+
};
|
|
1977
|
+
var INSPECTOR_SECURITY_HEADERS = {
|
|
1978
|
+
"x-frame-options": "DENY",
|
|
1979
|
+
"content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'",
|
|
1980
|
+
"x-content-type-options": "nosniff",
|
|
1981
|
+
"referrer-policy": "no-referrer",
|
|
1982
|
+
"cache-control": "no-store"
|
|
1983
|
+
};
|
|
1984
|
+
var LOOPBACK_HOST_RE = /^(127\.0\.0\.1|localhost|\[::1\])(?::(\d{1,5}))?$/i;
|
|
1985
|
+
function isLoopbackHost(hostHeader, boundHost, boundPort, requirePresent = false) {
|
|
1986
|
+
if (!hostHeader) return !requirePresent;
|
|
1987
|
+
const raw = hostHeader.trim().toLowerCase();
|
|
1988
|
+
const match = LOOPBACK_HOST_RE.exec(raw);
|
|
1989
|
+
if (match) {
|
|
1990
|
+
const portStr = match[2];
|
|
1991
|
+
if (portStr !== void 0) {
|
|
1992
|
+
const p = Number(portStr);
|
|
1993
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) return false;
|
|
1994
|
+
if (boundPort > 0 && p !== boundPort) return false;
|
|
1995
|
+
}
|
|
1996
|
+
return true;
|
|
1997
|
+
}
|
|
1998
|
+
const boundLower = boundHost.toLowerCase();
|
|
1999
|
+
if (raw === boundLower || boundPort > 0 && raw === `${boundLower}:${boundPort}`) {
|
|
2000
|
+
return true;
|
|
2001
|
+
}
|
|
2002
|
+
return false;
|
|
2003
|
+
}
|
|
2004
|
+
function isSameOriginLoopbackRequest(req, boundHost, boundPort) {
|
|
2005
|
+
if (!isLoopbackHost(req.headers.host, boundHost, boundPort, true)) {
|
|
2006
|
+
return false;
|
|
2007
|
+
}
|
|
2008
|
+
const secFetchSite = String(req.headers["sec-fetch-site"] ?? "").toLowerCase();
|
|
2009
|
+
if (secFetchSite && secFetchSite !== "same-origin" && secFetchSite !== "none") {
|
|
2010
|
+
return false;
|
|
2011
|
+
}
|
|
2012
|
+
const origin = req.headers.origin;
|
|
2013
|
+
if (typeof origin === "string" && origin.trim()) {
|
|
2014
|
+
try {
|
|
2015
|
+
const parsed = new URL(origin);
|
|
2016
|
+
if (!isLoopbackHost(parsed.host, boundHost, boundPort, true)) return false;
|
|
2017
|
+
if (boundPort > 0 && parsed.port !== String(boundPort)) return false;
|
|
2018
|
+
if (req.headers.host && parsed.host.toLowerCase() !== req.headers.host.trim().toLowerCase()) {
|
|
2019
|
+
return false;
|
|
2020
|
+
}
|
|
2021
|
+
} catch {
|
|
2022
|
+
return false;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
return true;
|
|
2026
|
+
}
|
|
2027
|
+
function normalizeInspectorPath(rawPathname) {
|
|
2028
|
+
let decoded = rawPathname;
|
|
2029
|
+
try {
|
|
2030
|
+
decoded = decodeURIComponent(rawPathname);
|
|
2031
|
+
} catch {
|
|
2032
|
+
}
|
|
2033
|
+
return decoded.replace(/\/{2,}/g, "/").toLowerCase();
|
|
2034
|
+
}
|
|
2035
|
+
var UnsupportedContentEncodingError = class extends Error {
|
|
2036
|
+
constructor() {
|
|
2037
|
+
super(...arguments);
|
|
2038
|
+
this.statusCode = 415;
|
|
2039
|
+
}
|
|
2040
|
+
};
|
|
2041
|
+
var zstdDecompressSync2 = zlib.zstdDecompressSync;
|
|
2042
|
+
function decodeRequestBody(rawBody, encodingHeader) {
|
|
2043
|
+
const enc = (encodingHeader ?? "").trim().toLowerCase();
|
|
2044
|
+
if (!enc || enc === "identity") return rawBody;
|
|
2045
|
+
if (enc === "gzip") {
|
|
2046
|
+
return zlib.gunzipSync(rawBody, { maxOutputLength: MAX_BODY_BYTES });
|
|
2047
|
+
}
|
|
2048
|
+
if (enc === "deflate") {
|
|
2049
|
+
return zlib.inflateSync(rawBody, { maxOutputLength: MAX_BODY_BYTES });
|
|
2050
|
+
}
|
|
2051
|
+
if (enc === "br") {
|
|
2052
|
+
return zlib.brotliDecompressSync(rawBody, { maxOutputLength: MAX_BODY_BYTES });
|
|
2053
|
+
}
|
|
2054
|
+
if (enc === "zstd" && typeof zstdDecompressSync2 === "function") {
|
|
2055
|
+
return zstdDecompressSync2(rawBody, { maxOutputLength: MAX_BODY_BYTES });
|
|
2056
|
+
}
|
|
2057
|
+
throw new UnsupportedContentEncodingError(`Unsupported content-encoding: "${enc}".`);
|
|
2058
|
+
}
|
|
909
2059
|
function resolveUpstreamTarget(urlPath, headers, options) {
|
|
910
2060
|
if (urlPath.startsWith("/anthropic/")) {
|
|
911
2061
|
return {
|
|
@@ -925,7 +2075,7 @@ function resolveUpstreamTarget(urlPath, headers, options) {
|
|
|
925
2075
|
forwardPath: urlPath
|
|
926
2076
|
};
|
|
927
2077
|
}
|
|
928
|
-
const isAnthropic = urlPath.startsWith("/v1/messages") || typeof headers["anthropic-version"] === "string" || typeof headers["x-api-key"] === "string";
|
|
2078
|
+
const isAnthropic = urlPath.startsWith("/v1/messages") || urlPath.startsWith("/api/") || typeof headers["anthropic-version"] === "string" || typeof headers["anthropic-beta"] === "string" || typeof headers["x-api-key"] === "string";
|
|
929
2079
|
return {
|
|
930
2080
|
baseUrl: (isAnthropic ? options.anthropicUpstream : options.openaiUpstream).replace(/\/$/, ""),
|
|
931
2081
|
forwardPath: urlPath
|
|
@@ -938,44 +2088,176 @@ async function readRequestBody(req) {
|
|
|
938
2088
|
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
939
2089
|
total += buf.byteLength;
|
|
940
2090
|
if (total > MAX_BODY_BYTES) {
|
|
941
|
-
|
|
2091
|
+
req.resume();
|
|
2092
|
+
throw new PayloadTooLargeError(`Request body exceeds ${MAX_BODY_BYTES} bytes.`);
|
|
942
2093
|
}
|
|
943
2094
|
chunks.push(buf);
|
|
944
2095
|
}
|
|
945
2096
|
return Buffer.concat(chunks);
|
|
946
2097
|
}
|
|
947
2098
|
function shouldRedactPath(pathname) {
|
|
948
|
-
const clean = pathname.split("?")[0] ?? pathname;
|
|
949
|
-
return clean.endsWith("/messages") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
|
|
2099
|
+
const clean = (pathname.split("?")[0] ?? pathname).replace(/\/+$/, "").toLowerCase();
|
|
2100
|
+
return clean.endsWith("/messages") || clean.endsWith("/messages/count_tokens") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
|
|
950
2101
|
}
|
|
951
2102
|
async function startMaskeraProxy(options = {}) {
|
|
952
2103
|
const host = options.host ?? "127.0.0.1";
|
|
953
2104
|
const requestedPort = options.port ?? 8787;
|
|
954
2105
|
const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
|
|
955
2106
|
const vault = options.vault ?? new SessionVault();
|
|
2107
|
+
const inspector = new ProxyInspector();
|
|
956
2108
|
const restoreResponses = options.restoreResponses !== false;
|
|
957
2109
|
const anthropicUpstream = options.anthropicUpstream ?? DEFAULT_ANTHROPIC_UPSTREAM;
|
|
958
2110
|
const openaiUpstream = options.openaiUpstream ?? DEFAULT_OPENAI_UPSTREAM;
|
|
2111
|
+
const auditLogPath = options.auditLogPath;
|
|
959
2112
|
const log = options.onLog ?? (() => {
|
|
960
2113
|
});
|
|
2114
|
+
if (auditLogPath) {
|
|
2115
|
+
await mkdir(dirname(auditLogPath), { recursive: true });
|
|
2116
|
+
await appendFile(auditLogPath, "", "utf8");
|
|
2117
|
+
}
|
|
961
2118
|
let totalRequests = 0;
|
|
962
2119
|
let totalRedactions = 0;
|
|
2120
|
+
let boundPort = requestedPort;
|
|
2121
|
+
let boundUrl = `http://${host}:${requestedPort}`;
|
|
2122
|
+
let auditChain = Promise.resolve();
|
|
2123
|
+
function recordAuditAndInspector(entry) {
|
|
2124
|
+
totalRequests += 1;
|
|
2125
|
+
totalRedactions += entry.redactions;
|
|
2126
|
+
inspector.record(entry);
|
|
2127
|
+
if (auditLogPath) {
|
|
2128
|
+
const auditLine = JSON.stringify({
|
|
2129
|
+
timestamp: entry.timestamp,
|
|
2130
|
+
method: entry.method,
|
|
2131
|
+
path: entry.path,
|
|
2132
|
+
upstream: entry.upstream,
|
|
2133
|
+
status: entry.status,
|
|
2134
|
+
streamed: entry.streamed,
|
|
2135
|
+
durationMs: entry.durationMs,
|
|
2136
|
+
redactions: entry.redactions,
|
|
2137
|
+
counts: entry.counts
|
|
2138
|
+
});
|
|
2139
|
+
auditChain = auditChain.then(
|
|
2140
|
+
() => appendFile(auditLogPath, `${auditLine}
|
|
2141
|
+
`, "utf8").catch((err) => {
|
|
2142
|
+
log(
|
|
2143
|
+
`[maskera-proxy] audit log write error: ${err instanceof Error ? err.message : String(err)}`
|
|
2144
|
+
);
|
|
2145
|
+
})
|
|
2146
|
+
);
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
963
2149
|
async function handleRequest(req, res) {
|
|
964
2150
|
const startedAt = Date.now();
|
|
965
2151
|
const method = req.method ?? "GET";
|
|
966
2152
|
const urlPath = req.url ?? "/";
|
|
967
|
-
|
|
2153
|
+
const pathname = urlPath.split("?")[0] ?? urlPath;
|
|
2154
|
+
const normalizedPath = normalizeInspectorPath(pathname);
|
|
2155
|
+
const isInspectorRoute = normalizedPath === "/_maskera" || normalizedPath.startsWith("/_maskera/") || normalizedPath.includes("/_maskera/") || normalizedPath.endsWith("/_maskera");
|
|
2156
|
+
if (isInspectorRoute || pathname === "/healthz") {
|
|
2157
|
+
if (!isLoopbackHost(req.headers.host, host, boundPort)) {
|
|
2158
|
+
res.writeHead(403, {
|
|
2159
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2160
|
+
"content-type": "application/json; charset=utf-8"
|
|
2161
|
+
});
|
|
2162
|
+
res.end(JSON.stringify({ error: "Forbidden host header for local inspector route." }));
|
|
2163
|
+
return;
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
if (method === "GET" && (pathname === "/_maskera" || pathname === "/_maskera/")) {
|
|
2167
|
+
res.writeHead(200, {
|
|
2168
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2169
|
+
"content-type": "text/html; charset=utf-8"
|
|
2170
|
+
});
|
|
2171
|
+
res.end(
|
|
2172
|
+
renderInspectorHtml({
|
|
2173
|
+
url: boundUrl,
|
|
2174
|
+
defaultMode: engine.status().defaultMode,
|
|
2175
|
+
restoreResponses
|
|
2176
|
+
})
|
|
2177
|
+
);
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
if (method === "GET" && pathname === "/_maskera/events") {
|
|
2181
|
+
inspector.subscribe(res, INSPECTOR_SECURITY_HEADERS);
|
|
2182
|
+
return;
|
|
2183
|
+
}
|
|
2184
|
+
if (method === "GET" && pathname === "/_maskera/vault") {
|
|
2185
|
+
if (req.headers["x-maskera-reveal"] !== "1" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
|
|
2186
|
+
res.writeHead(403, {
|
|
2187
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2188
|
+
"content-type": "application/json; charset=utf-8"
|
|
2189
|
+
});
|
|
2190
|
+
res.end(JSON.stringify({ error: "Pass x-maskera-reveal: 1 to read local vault values." }));
|
|
2191
|
+
return;
|
|
2192
|
+
}
|
|
2193
|
+
res.writeHead(200, {
|
|
2194
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2195
|
+
"content-type": "application/json; charset=utf-8"
|
|
2196
|
+
});
|
|
2197
|
+
res.end(JSON.stringify({ entries: vault.entries() }));
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
if (method === "POST" && pathname === "/_maskera/clear") {
|
|
2201
|
+
if (req.headers["x-maskera-action"] !== "clear" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
|
|
2202
|
+
res.writeHead(403, {
|
|
2203
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2204
|
+
"content-type": "application/json; charset=utf-8"
|
|
2205
|
+
});
|
|
2206
|
+
res.end(
|
|
2207
|
+
JSON.stringify({ error: "Pass x-maskera-action: clear from same-origin loopback." })
|
|
2208
|
+
);
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
vault.clearAll();
|
|
2212
|
+
engine.clearCache();
|
|
2213
|
+
inspector.clear();
|
|
2214
|
+
totalRequests = 0;
|
|
2215
|
+
totalRedactions = 0;
|
|
2216
|
+
res.writeHead(200, {
|
|
2217
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2218
|
+
"content-type": "application/json; charset=utf-8"
|
|
2219
|
+
});
|
|
2220
|
+
res.end(JSON.stringify({ cleared: true }));
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
if (method === "GET" && (pathname === "/healthz" || pathname === "/_maskera/status")) {
|
|
968
2224
|
const payload = {
|
|
969
2225
|
status: "ok",
|
|
2226
|
+
inspector_url: `${boundUrl}/_maskera`,
|
|
970
2227
|
engine: engine.status(),
|
|
971
2228
|
requests_proxied: totalRequests,
|
|
972
2229
|
total_redactions: totalRedactions,
|
|
973
2230
|
sessions: vault.list()
|
|
974
2231
|
};
|
|
975
|
-
res.writeHead(200, {
|
|
2232
|
+
res.writeHead(200, {
|
|
2233
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2234
|
+
"content-type": "application/json; charset=utf-8"
|
|
2235
|
+
});
|
|
976
2236
|
res.end(JSON.stringify(payload, null, 2));
|
|
977
2237
|
return;
|
|
978
2238
|
}
|
|
2239
|
+
if (isInspectorRoute) {
|
|
2240
|
+
res.writeHead(404, {
|
|
2241
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2242
|
+
"content-type": "application/json; charset=utf-8"
|
|
2243
|
+
});
|
|
2244
|
+
res.end(JSON.stringify({ error: "Unknown inspector route." }));
|
|
2245
|
+
return;
|
|
2246
|
+
}
|
|
2247
|
+
if (String(req.headers.upgrade ?? "").toLowerCase() === "websocket") {
|
|
2248
|
+
res.writeHead(426, {
|
|
2249
|
+
"content-type": "application/json; charset=utf-8",
|
|
2250
|
+
connection: "close"
|
|
2251
|
+
});
|
|
2252
|
+
res.end(
|
|
2253
|
+
JSON.stringify({
|
|
2254
|
+
error: {
|
|
2255
|
+
message: "WebSocket transport is not supported by maskera-proxy; retry over HTTP SSE."
|
|
2256
|
+
}
|
|
2257
|
+
})
|
|
2258
|
+
);
|
|
2259
|
+
return;
|
|
2260
|
+
}
|
|
979
2261
|
const { baseUrl, forwardPath } = resolveUpstreamTarget(urlPath, req.headers, {
|
|
980
2262
|
explicitUpstream: options.upstream,
|
|
981
2263
|
anthropicUpstream,
|
|
@@ -986,39 +2268,84 @@ async function startMaskeraProxy(options = {}) {
|
|
|
986
2268
|
const sessionHeader = req.headers["x-maskera-session"];
|
|
987
2269
|
const sessionId = typeof sessionHeader === "string" && sessionHeader.trim() ? sessionHeader.trim() : "proxy";
|
|
988
2270
|
const stats = { redactions: 0, counts: {} };
|
|
2271
|
+
const redactedPreview = [];
|
|
989
2272
|
let outgoingBody = rawBody;
|
|
990
|
-
|
|
991
|
-
|
|
2273
|
+
let rewroteRequestBody = false;
|
|
2274
|
+
const contentType = String(req.headers["content-type"] ?? "").trim().toLowerCase();
|
|
2275
|
+
const contentEncoding = typeof req.headers["content-encoding"] === "string" ? req.headers["content-encoding"] : void 0;
|
|
2276
|
+
const mayBeJson = contentType === "" || contentType.includes("json") || contentType.startsWith("text/plain");
|
|
2277
|
+
if (rawBody && rawBody.byteLength > 0 && shouldRedactPath(forwardPath) && mayBeJson) {
|
|
2278
|
+
let decodedBody;
|
|
2279
|
+
try {
|
|
2280
|
+
decodedBody = decodeRequestBody(rawBody, contentEncoding);
|
|
2281
|
+
} catch (err) {
|
|
2282
|
+
if (err instanceof UnsupportedContentEncodingError) {
|
|
2283
|
+
res.writeHead(415, { "content-type": "application/json; charset=utf-8" });
|
|
2284
|
+
res.end(JSON.stringify({ error: { message: err.message } }));
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
2288
|
+
res.end(JSON.stringify({ error: { message: "Invalid compressed request body." } }));
|
|
2289
|
+
return;
|
|
2290
|
+
}
|
|
992
2291
|
let parsed;
|
|
993
2292
|
try {
|
|
994
|
-
parsed = JSON.parse(
|
|
2293
|
+
parsed = JSON.parse(decodedBody.toString("utf8"));
|
|
995
2294
|
} catch {
|
|
996
2295
|
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
997
2296
|
res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
|
|
998
2297
|
return;
|
|
999
2298
|
}
|
|
1000
2299
|
if (isPlainObject(parsed)) {
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
2300
|
+
let redactedObj;
|
|
2301
|
+
try {
|
|
2302
|
+
redactedObj = await redactLlmRequestBody(
|
|
2303
|
+
parsed,
|
|
2304
|
+
async (text, kind) => {
|
|
2305
|
+
if (!text.trim()) return text;
|
|
2306
|
+
const { result } = await engine.redact(text, {
|
|
2307
|
+
mode: kind === "tool_description" ? "rules" : void 0,
|
|
2308
|
+
profile: options.profile,
|
|
2309
|
+
customTerms: options.customTerms
|
|
2310
|
+
});
|
|
2311
|
+
const applied = vault.apply(text, result, sessionId);
|
|
2312
|
+
stats.redactions += applied.totalRedactions;
|
|
2313
|
+
mergeCounts(stats.counts, applied.counts);
|
|
2314
|
+
if (redactedPreview.length < 6) {
|
|
2315
|
+
const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
|
|
2316
|
+
redactedPreview.push(snippet);
|
|
2317
|
+
}
|
|
2318
|
+
return applied.redacted;
|
|
2319
|
+
},
|
|
2320
|
+
{ mutate: true }
|
|
2321
|
+
);
|
|
2322
|
+
} catch (err) {
|
|
2323
|
+
recordAuditAndInspector({
|
|
2324
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2325
|
+
method,
|
|
2326
|
+
path: forwardPath,
|
|
2327
|
+
upstream: baseUrl,
|
|
2328
|
+
sessionId,
|
|
2329
|
+
status: 502,
|
|
2330
|
+
streamed: false,
|
|
2331
|
+
durationMs: Date.now() - startedAt,
|
|
2332
|
+
redactions: stats.redactions,
|
|
2333
|
+
counts: stats.counts,
|
|
2334
|
+
redactedPreview
|
|
1006
2335
|
});
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
mergeCounts(stats.counts, applied.counts);
|
|
1010
|
-
return applied.redacted;
|
|
1011
|
-
});
|
|
2336
|
+
throw err;
|
|
2337
|
+
}
|
|
1012
2338
|
outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
|
|
2339
|
+
rewroteRequestBody = true;
|
|
1013
2340
|
}
|
|
1014
2341
|
}
|
|
1015
|
-
totalRequests += 1;
|
|
1016
|
-
totalRedactions += stats.redactions;
|
|
1017
2342
|
const forwardHeaders = new Headers();
|
|
1018
2343
|
for (const [k, v] of Object.entries(req.headers)) {
|
|
1019
2344
|
if (v === void 0) continue;
|
|
1020
2345
|
const lower = k.toLowerCase();
|
|
1021
|
-
if (HOP_BY_HOP_REQUEST_HEADERS.has(lower) || lower === "x-maskera-session")
|
|
2346
|
+
if (HOP_BY_HOP_REQUEST_HEADERS.has(lower) || lower === "x-maskera-session" || rewroteRequestBody && lower === "content-encoding") {
|
|
2347
|
+
continue;
|
|
2348
|
+
}
|
|
1022
2349
|
if (Array.isArray(v)) {
|
|
1023
2350
|
for (const item of v) forwardHeaders.append(k, item);
|
|
1024
2351
|
} else {
|
|
@@ -1026,11 +2353,39 @@ async function startMaskeraProxy(options = {}) {
|
|
|
1026
2353
|
}
|
|
1027
2354
|
}
|
|
1028
2355
|
forwardHeaders.set("accept-encoding", "identity");
|
|
1029
|
-
const
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
2356
|
+
const abortController = new AbortController();
|
|
2357
|
+
const onClientClose = () => {
|
|
2358
|
+
if (!res.writableEnded) abortController.abort();
|
|
2359
|
+
};
|
|
2360
|
+
res.on("close", onClientClose);
|
|
2361
|
+
let upstreamRes;
|
|
2362
|
+
try {
|
|
2363
|
+
upstreamRes = await fetch(upstreamUrl, {
|
|
2364
|
+
method,
|
|
2365
|
+
headers: forwardHeaders,
|
|
2366
|
+
body: outgoingBody ? new Uint8Array(outgoingBody) : void 0,
|
|
2367
|
+
signal: abortController.signal
|
|
2368
|
+
});
|
|
2369
|
+
} catch (err) {
|
|
2370
|
+
res.off("close", onClientClose);
|
|
2371
|
+
if (!abortController.signal.aborted) {
|
|
2372
|
+
const durationMs2 = Date.now() - startedAt;
|
|
2373
|
+
recordAuditAndInspector({
|
|
2374
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2375
|
+
method,
|
|
2376
|
+
path: forwardPath,
|
|
2377
|
+
upstream: baseUrl,
|
|
2378
|
+
sessionId,
|
|
2379
|
+
status: 502,
|
|
2380
|
+
streamed: false,
|
|
2381
|
+
durationMs: durationMs2,
|
|
2382
|
+
redactions: stats.redactions,
|
|
2383
|
+
counts: stats.counts,
|
|
2384
|
+
redactedPreview
|
|
2385
|
+
});
|
|
2386
|
+
}
|
|
2387
|
+
throw err;
|
|
2388
|
+
}
|
|
1034
2389
|
const outHeaders = {};
|
|
1035
2390
|
upstreamRes.headers.forEach((value, key) => {
|
|
1036
2391
|
if (!HOP_BY_HOP_RESPONSE_HEADERS.has(key.toLowerCase())) {
|
|
@@ -1040,42 +2395,91 @@ async function startMaskeraProxy(options = {}) {
|
|
|
1040
2395
|
outHeaders["x-maskera-redacted"] = String(stats.redactions);
|
|
1041
2396
|
const sessionMap = restoreResponses ? vault.getMap(sessionId) : {};
|
|
1042
2397
|
const hasMap = Object.keys(sessionMap).length > 0;
|
|
1043
|
-
const resContentType = upstreamRes.headers.get("content-type") ?? "";
|
|
1044
|
-
|
|
2398
|
+
const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
|
|
2399
|
+
const isSse = resContentType.includes("text/event-stream");
|
|
2400
|
+
if (isSse && upstreamRes.body) {
|
|
1045
2401
|
res.writeHead(upstreamRes.status, outHeaders);
|
|
1046
|
-
const sse = createSseRestorer(sessionMap);
|
|
1047
|
-
const decoder = new TextDecoder();
|
|
2402
|
+
const sse = hasMap ? createSseRestorer(sessionMap) : null;
|
|
2403
|
+
const decoder = sse ? new TextDecoder() : null;
|
|
1048
2404
|
const reader = upstreamRes.body.getReader();
|
|
2405
|
+
const onStreamAbort = () => {
|
|
2406
|
+
void reader.cancel().catch(() => {
|
|
2407
|
+
});
|
|
2408
|
+
};
|
|
2409
|
+
abortController.signal.addEventListener("abort", onStreamAbort, { once: true });
|
|
1049
2410
|
try {
|
|
1050
2411
|
for (; ; ) {
|
|
1051
2412
|
const { done, value } = await reader.read();
|
|
1052
2413
|
if (done) break;
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
2414
|
+
if (sse && decoder) {
|
|
2415
|
+
const chunkText = decoder.decode(value, { stream: true });
|
|
2416
|
+
const transformed = sse.push(chunkText);
|
|
2417
|
+
if (transformed) res.write(transformed);
|
|
2418
|
+
} else if (value) {
|
|
2419
|
+
res.write(value);
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
if (sse && decoder) {
|
|
2423
|
+
const finalText = decoder.decode();
|
|
2424
|
+
const tail = (finalText ? sse.push(finalText) : "") + sse.flush();
|
|
2425
|
+
if (tail) res.write(tail);
|
|
1056
2426
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
if (tail) res.write(tail);
|
|
2427
|
+
} catch (err) {
|
|
2428
|
+
if (!abortController.signal.aborted) throw err;
|
|
1060
2429
|
} finally {
|
|
2430
|
+
abortController.signal.removeEventListener("abort", onStreamAbort);
|
|
2431
|
+
res.off("close", onClientClose);
|
|
1061
2432
|
reader.releaseLock();
|
|
1062
|
-
res.end();
|
|
1063
|
-
}
|
|
2433
|
+
if (!res.writableEnded) res.end();
|
|
2434
|
+
}
|
|
2435
|
+
const durationMs2 = Date.now() - startedAt;
|
|
2436
|
+
recordAuditAndInspector({
|
|
2437
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2438
|
+
method,
|
|
2439
|
+
path: forwardPath,
|
|
2440
|
+
upstream: baseUrl,
|
|
2441
|
+
sessionId,
|
|
2442
|
+
status: upstreamRes.status,
|
|
2443
|
+
streamed: true,
|
|
2444
|
+
durationMs: durationMs2,
|
|
2445
|
+
redactions: stats.redactions,
|
|
2446
|
+
counts: stats.counts,
|
|
2447
|
+
redactedPreview
|
|
2448
|
+
});
|
|
1064
2449
|
log(
|
|
1065
|
-
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${
|
|
2450
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${durationMs2}ms`
|
|
1066
2451
|
);
|
|
1067
2452
|
return;
|
|
1068
2453
|
}
|
|
1069
|
-
|
|
2454
|
+
let resBuf;
|
|
2455
|
+
try {
|
|
2456
|
+
resBuf = Buffer.from(await upstreamRes.arrayBuffer());
|
|
2457
|
+
} finally {
|
|
2458
|
+
res.off("close", onClientClose);
|
|
2459
|
+
}
|
|
1070
2460
|
if (hasMap && resContentType.includes("application/json")) {
|
|
1071
2461
|
try {
|
|
1072
2462
|
const parsed = JSON.parse(resBuf.toString("utf8"));
|
|
1073
|
-
const restored = restoreLlmResponseBody(parsed, sessionMap);
|
|
2463
|
+
const restored = restoreLlmResponseBody(parsed, sessionMap, { mutate: true });
|
|
1074
2464
|
const restoredBuf = Buffer.from(JSON.stringify(restored), "utf8");
|
|
1075
2465
|
res.writeHead(upstreamRes.status, outHeaders);
|
|
1076
2466
|
res.end(restoredBuf);
|
|
2467
|
+
const durationMs2 = Date.now() - startedAt;
|
|
2468
|
+
recordAuditAndInspector({
|
|
2469
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2470
|
+
method,
|
|
2471
|
+
path: forwardPath,
|
|
2472
|
+
upstream: baseUrl,
|
|
2473
|
+
sessionId,
|
|
2474
|
+
status: upstreamRes.status,
|
|
2475
|
+
streamed: false,
|
|
2476
|
+
durationMs: durationMs2,
|
|
2477
|
+
redactions: stats.redactions,
|
|
2478
|
+
counts: stats.counts,
|
|
2479
|
+
redactedPreview
|
|
2480
|
+
});
|
|
1077
2481
|
log(
|
|
1078
|
-
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${
|
|
2482
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${durationMs2}ms`
|
|
1079
2483
|
);
|
|
1080
2484
|
return;
|
|
1081
2485
|
} catch {
|
|
@@ -1083,22 +2487,55 @@ async function startMaskeraProxy(options = {}) {
|
|
|
1083
2487
|
}
|
|
1084
2488
|
res.writeHead(upstreamRes.status, outHeaders);
|
|
1085
2489
|
res.end(resBuf);
|
|
2490
|
+
const durationMs = Date.now() - startedAt;
|
|
2491
|
+
recordAuditAndInspector({
|
|
2492
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2493
|
+
method,
|
|
2494
|
+
path: forwardPath,
|
|
2495
|
+
upstream: baseUrl,
|
|
2496
|
+
sessionId,
|
|
2497
|
+
status: upstreamRes.status,
|
|
2498
|
+
streamed: isSse,
|
|
2499
|
+
durationMs,
|
|
2500
|
+
redactions: stats.redactions,
|
|
2501
|
+
counts: stats.counts,
|
|
2502
|
+
redactedPreview
|
|
2503
|
+
});
|
|
1086
2504
|
log(
|
|
1087
|
-
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${
|
|
2505
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${durationMs}ms`
|
|
1088
2506
|
);
|
|
1089
2507
|
}
|
|
1090
2508
|
const server = createServer((req, res) => {
|
|
1091
2509
|
void handleRequest(req, res).catch((err) => {
|
|
2510
|
+
if (res.destroyed || req.aborted) return;
|
|
2511
|
+
const statusCode = err instanceof PayloadTooLargeError ? err.statusCode : 502;
|
|
1092
2512
|
const message = err instanceof Error ? err.message : String(err);
|
|
1093
2513
|
log(`[maskera-proxy] error: ${message}`);
|
|
1094
2514
|
if (!res.headersSent) {
|
|
1095
|
-
res.writeHead(
|
|
2515
|
+
res.writeHead(statusCode, { "content-type": "application/json; charset=utf-8" });
|
|
1096
2516
|
res.end(JSON.stringify({ error: { message: `maskera-proxy error: ${message}` } }));
|
|
1097
|
-
} else {
|
|
2517
|
+
} else if (!res.writableEnded) {
|
|
1098
2518
|
res.end();
|
|
1099
2519
|
}
|
|
1100
2520
|
});
|
|
1101
2521
|
});
|
|
2522
|
+
server.on("upgrade", (req, socket) => {
|
|
2523
|
+
const body = JSON.stringify({
|
|
2524
|
+
error: {
|
|
2525
|
+
message: "WebSocket transport is not supported by maskera-proxy; retry over HTTP SSE."
|
|
2526
|
+
}
|
|
2527
|
+
});
|
|
2528
|
+
socket.write(
|
|
2529
|
+
`HTTP/1.1 426 Upgrade Required\r
|
|
2530
|
+
Content-Type: application/json; charset=utf-8\r
|
|
2531
|
+
Connection: close\r
|
|
2532
|
+
Content-Length: ${Buffer.byteLength(body)}\r
|
|
2533
|
+
\r
|
|
2534
|
+
${body}`
|
|
2535
|
+
);
|
|
2536
|
+
socket.end();
|
|
2537
|
+
log(`[maskera-proxy] UPGRADE ${req.url ?? "/"} 426 (HTTP SSE fallback)`);
|
|
2538
|
+
});
|
|
1102
2539
|
await new Promise((resolveListen, rejectListen) => {
|
|
1103
2540
|
server.once("error", rejectListen);
|
|
1104
2541
|
server.listen(requestedPort, host, () => {
|
|
@@ -1108,26 +2545,41 @@ async function startMaskeraProxy(options = {}) {
|
|
|
1108
2545
|
});
|
|
1109
2546
|
const addr = server.address();
|
|
1110
2547
|
const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
|
|
2548
|
+
boundPort = actualPort;
|
|
2549
|
+
boundUrl = `http://${host}:${actualPort}`;
|
|
1111
2550
|
return {
|
|
1112
2551
|
host,
|
|
1113
2552
|
port: actualPort,
|
|
1114
|
-
url:
|
|
2553
|
+
url: boundUrl,
|
|
2554
|
+
inspectorUrl: `${boundUrl}/_maskera`,
|
|
1115
2555
|
server,
|
|
1116
2556
|
vault,
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
2557
|
+
inspector,
|
|
2558
|
+
close: async () => {
|
|
2559
|
+
inspector.closeAll();
|
|
2560
|
+
await new Promise((resolveClose, rejectClose) => {
|
|
2561
|
+
server.close((err) => err ? rejectClose(err) : resolveClose());
|
|
2562
|
+
});
|
|
2563
|
+
await auditChain;
|
|
2564
|
+
}
|
|
1120
2565
|
};
|
|
1121
2566
|
}
|
|
1122
2567
|
|
|
1123
2568
|
// src/server.ts
|
|
1124
2569
|
var SERVER_NAME = "maskera-mcp";
|
|
1125
|
-
var SERVER_VERSION = "0.
|
|
1126
|
-
var SUPPORTED_PROTOCOLS = ["2025-03-26", "2024-11-05"];
|
|
2570
|
+
var SERVER_VERSION = "0.2.0";
|
|
2571
|
+
var SUPPORTED_PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
|
|
1127
2572
|
var TOOLS = [
|
|
1128
2573
|
{
|
|
1129
2574
|
name: "maskera_redact",
|
|
1130
2575
|
description: "Redact Swedish PII (names, personnummer, addresses, emails, phones, IBAN, etc.) locally on-device using Maskera's 43 MB Swedish NER model and deterministic rules. Stores the restore map locally under session_id so placeholders stay consistent across calls and can be restored later without exposing raw PII to the LLM.",
|
|
2576
|
+
annotations: {
|
|
2577
|
+
title: "Redact Swedish PII locally",
|
|
2578
|
+
readOnlyHint: true,
|
|
2579
|
+
destructiveHint: false,
|
|
2580
|
+
idempotentHint: false,
|
|
2581
|
+
openWorldHint: false
|
|
2582
|
+
},
|
|
1131
2583
|
inputSchema: {
|
|
1132
2584
|
type: "object",
|
|
1133
2585
|
properties: {
|
|
@@ -1162,6 +2614,13 @@ var TOOLS = [
|
|
|
1162
2614
|
{
|
|
1163
2615
|
name: "maskera_restore",
|
|
1164
2616
|
description: "Restore Maskera placeholders (e.g. [NAMN_1], [PERSONNUMMER_1]) in text using a locally stored session_id or an explicit map.",
|
|
2617
|
+
annotations: {
|
|
2618
|
+
title: "Restore Maskera placeholders",
|
|
2619
|
+
readOnlyHint: true,
|
|
2620
|
+
destructiveHint: false,
|
|
2621
|
+
idempotentHint: true,
|
|
2622
|
+
openWorldHint: false
|
|
2623
|
+
},
|
|
1165
2624
|
inputSchema: {
|
|
1166
2625
|
type: "object",
|
|
1167
2626
|
properties: {
|
|
@@ -1182,6 +2641,13 @@ var TOOLS = [
|
|
|
1182
2641
|
{
|
|
1183
2642
|
name: "maskera_read_file",
|
|
1184
2643
|
description: "Read a local UTF-8 text file and redact Swedish PII BEFORE returning its contents to the model. Keeps raw PII strictly in local memory under session_id so the cloud LLM never sees real names or personal IDs.",
|
|
2644
|
+
annotations: {
|
|
2645
|
+
title: "Read local file with PII redaction",
|
|
2646
|
+
readOnlyHint: true,
|
|
2647
|
+
destructiveHint: false,
|
|
2648
|
+
idempotentHint: false,
|
|
2649
|
+
openWorldHint: false
|
|
2650
|
+
},
|
|
1185
2651
|
inputSchema: {
|
|
1186
2652
|
type: "object",
|
|
1187
2653
|
properties: {
|
|
@@ -1215,6 +2681,13 @@ var TOOLS = [
|
|
|
1215
2681
|
{
|
|
1216
2682
|
name: "maskera_write_file",
|
|
1217
2683
|
description: "Restore Maskera placeholders from a local session_id and write the restored text directly to a local file without echoing raw PII back into the LLM context.",
|
|
2684
|
+
annotations: {
|
|
2685
|
+
title: "Restore placeholders and write local file",
|
|
2686
|
+
readOnlyHint: false,
|
|
2687
|
+
destructiveHint: false,
|
|
2688
|
+
idempotentHint: false,
|
|
2689
|
+
openWorldHint: false
|
|
2690
|
+
},
|
|
1218
2691
|
inputSchema: {
|
|
1219
2692
|
type: "object",
|
|
1220
2693
|
properties: {
|
|
@@ -1241,11 +2714,25 @@ var TOOLS = [
|
|
|
1241
2714
|
{
|
|
1242
2715
|
name: "maskera_list_sessions",
|
|
1243
2716
|
description: "List active local redaction sessions and entity counts (never returns raw PII values).",
|
|
2717
|
+
annotations: {
|
|
2718
|
+
title: "List active Maskera sessions",
|
|
2719
|
+
readOnlyHint: true,
|
|
2720
|
+
destructiveHint: false,
|
|
2721
|
+
idempotentHint: true,
|
|
2722
|
+
openWorldHint: false
|
|
2723
|
+
},
|
|
1244
2724
|
inputSchema: { type: "object", properties: {} }
|
|
1245
2725
|
},
|
|
1246
2726
|
{
|
|
1247
2727
|
name: "maskera_clear_session",
|
|
1248
2728
|
description: "Erase a session's local in-memory restore map immediately.",
|
|
2729
|
+
annotations: {
|
|
2730
|
+
title: "Clear Maskera session vault",
|
|
2731
|
+
readOnlyHint: false,
|
|
2732
|
+
destructiveHint: true,
|
|
2733
|
+
idempotentHint: true,
|
|
2734
|
+
openWorldHint: false
|
|
2735
|
+
},
|
|
1249
2736
|
inputSchema: {
|
|
1250
2737
|
type: "object",
|
|
1251
2738
|
properties: {
|
|
@@ -1257,6 +2744,13 @@ var TOOLS = [
|
|
|
1257
2744
|
{
|
|
1258
2745
|
name: "maskera_status",
|
|
1259
2746
|
description: "Report local Maskera MCP server status: model pin, readiness, active sessions, and allowed file roots.",
|
|
2747
|
+
annotations: {
|
|
2748
|
+
title: "Maskera MCP server status",
|
|
2749
|
+
readOnlyHint: true,
|
|
2750
|
+
destructiveHint: false,
|
|
2751
|
+
idempotentHint: true,
|
|
2752
|
+
openWorldHint: false
|
|
2753
|
+
},
|
|
1260
2754
|
inputSchema: { type: "object", properties: {} }
|
|
1261
2755
|
}
|
|
1262
2756
|
];
|
|
@@ -1296,6 +2790,13 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1296
2790
|
const engine = options.engine ?? createMaskeraEngine();
|
|
1297
2791
|
const vault = options.vault ?? new SessionVault();
|
|
1298
2792
|
const files = options.files ?? createFileGuard(options.allowedRoots);
|
|
2793
|
+
const defaultProfile = options.defaultProfile;
|
|
2794
|
+
const defaultCustomTerms = options.defaultCustomTerms;
|
|
2795
|
+
function mergeCustomTerms(callTerms) {
|
|
2796
|
+
if (!defaultCustomTerms?.length) return callTerms;
|
|
2797
|
+
if (!callTerms?.length) return defaultCustomTerms;
|
|
2798
|
+
return [...defaultCustomTerms, ...callTerms];
|
|
2799
|
+
}
|
|
1299
2800
|
async function callTool(name, rawArgs) {
|
|
1300
2801
|
const args = asObject(rawArgs);
|
|
1301
2802
|
try {
|
|
@@ -1303,8 +2804,8 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1303
2804
|
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
1304
2805
|
const { result, modeUsed } = await engine.redact(args.text, {
|
|
1305
2806
|
mode: asMode(args.mode),
|
|
1306
|
-
profile: asProfile(args.profile),
|
|
1307
|
-
customTerms: asStringArray(args.custom_terms)
|
|
2807
|
+
profile: asProfile(args.profile) ?? defaultProfile,
|
|
2808
|
+
customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
|
|
1308
2809
|
});
|
|
1309
2810
|
const applied = vault.apply(
|
|
1310
2811
|
args.text,
|
|
@@ -1343,8 +2844,8 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1343
2844
|
const file = await files.readText(args.path);
|
|
1344
2845
|
const { result, modeUsed } = await engine.redact(file.content, {
|
|
1345
2846
|
mode: asMode(args.mode),
|
|
1346
|
-
profile: asProfile(args.profile),
|
|
1347
|
-
customTerms: asStringArray(args.custom_terms)
|
|
2847
|
+
profile: asProfile(args.profile) ?? defaultProfile,
|
|
2848
|
+
customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
|
|
1348
2849
|
});
|
|
1349
2850
|
const applied = vault.apply(
|
|
1350
2851
|
file.content,
|
|
@@ -1364,11 +2865,12 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1364
2865
|
if (name === "maskera_write_file") {
|
|
1365
2866
|
if (typeof args.path !== "string") return toolError("Missing required string: path");
|
|
1366
2867
|
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
1367
|
-
if (typeof args.session_id !== "string") {
|
|
1368
|
-
return toolError("Missing required string: session_id");
|
|
2868
|
+
if (typeof args.session_id !== "string" || !args.session_id.trim()) {
|
|
2869
|
+
return toolError("Missing required non-empty string: session_id");
|
|
1369
2870
|
}
|
|
2871
|
+
const normalizedSessionId = args.session_id.trim();
|
|
1370
2872
|
const { restored, knownPlaceholders } = vault.restore(args.text, {
|
|
1371
|
-
sessionId:
|
|
2873
|
+
sessionId: normalizedSessionId
|
|
1372
2874
|
});
|
|
1373
2875
|
const written = await files.writeText(args.path, restored, {
|
|
1374
2876
|
overwrite: args.overwrite === true
|
|
@@ -1376,7 +2878,7 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1376
2878
|
return toolOk({
|
|
1377
2879
|
path: written.resolvedPath,
|
|
1378
2880
|
bytes: written.bytes,
|
|
1379
|
-
session_id:
|
|
2881
|
+
session_id: normalizedSessionId,
|
|
1380
2882
|
known_placeholders: knownPlaceholders
|
|
1381
2883
|
});
|
|
1382
2884
|
}
|
|
@@ -1384,12 +2886,13 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1384
2886
|
return toolOk({ sessions: vault.list() });
|
|
1385
2887
|
}
|
|
1386
2888
|
if (name === "maskera_clear_session") {
|
|
1387
|
-
if (typeof args.session_id !== "string") {
|
|
1388
|
-
return toolError("Missing required string: session_id");
|
|
2889
|
+
if (typeof args.session_id !== "string" || !args.session_id.trim()) {
|
|
2890
|
+
return toolError("Missing required non-empty string: session_id");
|
|
1389
2891
|
}
|
|
2892
|
+
const normalizedSessionId = args.session_id.trim();
|
|
1390
2893
|
return toolOk({
|
|
1391
|
-
session_id:
|
|
1392
|
-
cleared: vault.clear(
|
|
2894
|
+
session_id: normalizedSessionId,
|
|
2895
|
+
cleared: vault.clear(normalizedSessionId)
|
|
1393
2896
|
});
|
|
1394
2897
|
}
|
|
1395
2898
|
if (name === "maskera_status") {
|
|
@@ -1417,15 +2920,16 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1417
2920
|
};
|
|
1418
2921
|
}
|
|
1419
2922
|
const req = raw;
|
|
1420
|
-
const
|
|
1421
|
-
|
|
1422
|
-
|
|
2923
|
+
const hasIdProp = Object.prototype.hasOwnProperty.call(req, "id");
|
|
2924
|
+
const validId = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
|
|
2925
|
+
if (req.jsonrpc !== "2.0" || typeof req.method !== "string" || hasIdProp && validId === void 0) {
|
|
1423
2926
|
return {
|
|
1424
2927
|
jsonrpc: "2.0",
|
|
1425
|
-
id,
|
|
2928
|
+
id: validId ?? null,
|
|
1426
2929
|
error: { code: -32600, message: "Invalid Request" }
|
|
1427
2930
|
};
|
|
1428
2931
|
}
|
|
2932
|
+
const id = validId;
|
|
1429
2933
|
if (id === void 0) {
|
|
1430
2934
|
return null;
|
|
1431
2935
|
}
|
|
@@ -1471,6 +2975,6 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1471
2975
|
};
|
|
1472
2976
|
}
|
|
1473
2977
|
|
|
1474
|
-
export { SERVER_NAME, SERVER_VERSION, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createSseRestorer, extractGuardText, redactLlmRequestBody, restoreLlmResponseBody, runGuard, startMaskeraProxy };
|
|
2978
|
+
export { ProxyInspector, SERVER_NAME, SERVER_VERSION, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createSseRestorer, extractGuardText, redactLlmRequestBody, renderInspectorHtml, restoreLlmResponseBody, runGuard, startMaskeraProxy };
|
|
1475
2979
|
//# sourceMappingURL=index.js.map
|
|
1476
2980
|
//# sourceMappingURL=index.js.map
|