@maskera/mcp 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +106 -2
- package/dist/cli.js +3312 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +309 -0
- package/dist/index.js +2980 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2980 @@
|
|
|
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';
|
|
5
|
+
import { createServer } from 'http';
|
|
6
|
+
import * as zlib from 'zlib';
|
|
7
|
+
|
|
8
|
+
// src/engine.ts
|
|
9
|
+
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
10
|
+
var DEFAULT_MAX_CACHE_ENTRIES = 512;
|
|
11
|
+
var MAX_CUSTOM_DETECTOR_CACHE = 64;
|
|
12
|
+
function escapeRegExp(value) {
|
|
13
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
14
|
+
}
|
|
15
|
+
function normalizeCustomTerms(rawTerms) {
|
|
16
|
+
const unique = /* @__PURE__ */ new Map();
|
|
17
|
+
for (const raw of rawTerms) {
|
|
18
|
+
if (typeof raw !== "string") continue;
|
|
19
|
+
const trimmed = raw.trim();
|
|
20
|
+
if (trimmed.length < 2 || trimmed.length > 160) continue;
|
|
21
|
+
const folded = trimmed.toLowerCase();
|
|
22
|
+
if (!unique.has(folded)) unique.set(folded, trimmed);
|
|
23
|
+
if (unique.size >= 200) break;
|
|
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
|
+
);
|
|
39
|
+
return {
|
|
40
|
+
label: "EGENT",
|
|
41
|
+
detect(text) {
|
|
42
|
+
const out = [];
|
|
43
|
+
pattern.lastIndex = 0;
|
|
44
|
+
for (let m = pattern.exec(text); m !== null; m = pattern.exec(text)) {
|
|
45
|
+
const start = m.index;
|
|
46
|
+
const value = m[0];
|
|
47
|
+
if (!value) {
|
|
48
|
+
pattern.lastIndex += 1;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
out.push({ start, end: start + value.length, value });
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function createMaskeraEngine(options = {}) {
|
|
58
|
+
const defaultMode = options.defaultMode ?? "auto";
|
|
59
|
+
const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
|
|
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);
|
|
62
|
+
let recognizer = options.recognizer ?? null;
|
|
63
|
+
let nerLoaded = false;
|
|
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;
|
|
70
|
+
function getRecognizer() {
|
|
71
|
+
if (!recognizer) {
|
|
72
|
+
const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
|
|
73
|
+
recognizer = createNerRecognizer({
|
|
74
|
+
...options.nerOptions,
|
|
75
|
+
model,
|
|
76
|
+
revision,
|
|
77
|
+
dtype
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
return recognizer;
|
|
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
|
+
}
|
|
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
|
+
},
|
|
125
|
+
async redact(text, req = {}) {
|
|
126
|
+
const requestedMode = req.mode ?? defaultMode;
|
|
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
|
+
}
|
|
148
|
+
const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
|
|
149
|
+
if (requestedMode === "rules") {
|
|
150
|
+
const result = req.profile === "clinical" ? redactFromDetections(
|
|
151
|
+
text,
|
|
152
|
+
runDetectors(text, detectors).filter(
|
|
153
|
+
(d) => clinicalPrecisionFilter(d, text, "rule")
|
|
154
|
+
)
|
|
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
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
result,
|
|
172
|
+
modeUsed: "rules"
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
const ner = getRecognizer();
|
|
177
|
+
const result = await redactWithNer(text, {
|
|
178
|
+
recognizer: ner,
|
|
179
|
+
detectors,
|
|
180
|
+
profile: req.profile
|
|
181
|
+
});
|
|
182
|
+
nerLoaded = true;
|
|
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
|
+
}
|
|
198
|
+
return { result, modeUsed: "hybrid" };
|
|
199
|
+
} catch (err) {
|
|
200
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
201
|
+
nerError = message;
|
|
202
|
+
throw new Error(
|
|
203
|
+
`Hybrid NER failed to run (${message}). Pass mode="rules" explicitly if you only want deterministic structured redaction.`
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
status() {
|
|
208
|
+
return {
|
|
209
|
+
defaultMode,
|
|
210
|
+
model,
|
|
211
|
+
revision: revision ?? "local",
|
|
212
|
+
nerLoaded,
|
|
213
|
+
nerError,
|
|
214
|
+
cacheSize: spanCache.size,
|
|
215
|
+
cacheHits,
|
|
216
|
+
cacheMisses
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
var MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
222
|
+
var MAX_SYMLINK_HOPS = 40;
|
|
223
|
+
var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
|
|
224
|
+
function isWithinRoot(root, target) {
|
|
225
|
+
const rel = relative(root, target);
|
|
226
|
+
return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
227
|
+
}
|
|
228
|
+
async function resolveExistingAncestor(target) {
|
|
229
|
+
let current = resolve(target);
|
|
230
|
+
const segments = [];
|
|
231
|
+
for (; ; ) {
|
|
232
|
+
try {
|
|
233
|
+
const real = await realpath(current);
|
|
234
|
+
return { ancestor: real, tail: segments.reverse().join(sep) };
|
|
235
|
+
} catch {
|
|
236
|
+
const parent = dirname(current);
|
|
237
|
+
if (parent === current) {
|
|
238
|
+
throw new Error(`Cannot resolve path "${target}".`);
|
|
239
|
+
}
|
|
240
|
+
segments.push(relative(parent, current));
|
|
241
|
+
current = parent;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
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
|
+
}
|
|
266
|
+
function createFileGuard(roots = [process.cwd()]) {
|
|
267
|
+
const rawRoots = roots.length > 0 ? roots : [process.cwd()];
|
|
268
|
+
let canonicalRootsPromise = null;
|
|
269
|
+
function getCanonicalRoots() {
|
|
270
|
+
if (!canonicalRootsPromise) {
|
|
271
|
+
canonicalRootsPromise = Promise.all(
|
|
272
|
+
rawRoots.map(async (root) => {
|
|
273
|
+
const abs = resolve(root);
|
|
274
|
+
try {
|
|
275
|
+
return await realpath(abs);
|
|
276
|
+
} catch {
|
|
277
|
+
try {
|
|
278
|
+
const { ancestor, tail } = await resolveExistingAncestor(abs);
|
|
279
|
+
return tail ? resolve(ancestor, tail) : ancestor;
|
|
280
|
+
} catch {
|
|
281
|
+
return abs;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
})
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
return canonicalRootsPromise;
|
|
288
|
+
}
|
|
289
|
+
function resolveAgainstBase(filePath) {
|
|
290
|
+
const trimmed = filePath.trim();
|
|
291
|
+
if (!trimmed) throw new Error("Path must not be empty.");
|
|
292
|
+
return isAbsolute(trimmed) ? resolve(trimmed) : resolve(rawRoots[0] ?? process.cwd(), trimmed);
|
|
293
|
+
}
|
|
294
|
+
return {
|
|
295
|
+
allowedRoots: rawRoots.map((r) => resolve(r)),
|
|
296
|
+
async readText(filePath) {
|
|
297
|
+
const rootsList = await getCanonicalRoots();
|
|
298
|
+
const candidate = resolveAgainstBase(filePath);
|
|
299
|
+
const { ancestor, tail } = await resolveExistingAncestor(candidate);
|
|
300
|
+
const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
|
|
301
|
+
if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
|
|
302
|
+
throw new Error(
|
|
303
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
const real = await realpath(candidate).catch(() => {
|
|
307
|
+
throw new Error(`File not found: "${filePath}".`);
|
|
308
|
+
});
|
|
309
|
+
if (!rootsList.some((root) => isWithinRoot(root, real))) {
|
|
310
|
+
throw new Error(
|
|
311
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
const info = await stat(real);
|
|
315
|
+
if (!info.isFile()) {
|
|
316
|
+
throw new Error(`"${filePath}" is not a regular file.`);
|
|
317
|
+
}
|
|
318
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
319
|
+
throw new Error(
|
|
320
|
+
`File "${filePath}" is ${info.size} bytes (max ${MAX_FILE_BYTES} bytes for local redaction).`
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
const buffer = await readFile(real);
|
|
324
|
+
if (buffer.includes(0)) {
|
|
325
|
+
throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
|
|
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
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
resolvedPath: real,
|
|
337
|
+
content,
|
|
338
|
+
bytes: buffer.byteLength
|
|
339
|
+
};
|
|
340
|
+
},
|
|
341
|
+
async writeText(filePath, content, options = {}) {
|
|
342
|
+
const rootsList = await getCanonicalRoots();
|
|
343
|
+
const candidate = resolveAgainstBase(filePath);
|
|
344
|
+
const targetReal = await resolveCanonicalTarget(candidate);
|
|
345
|
+
if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
|
|
346
|
+
throw new Error(
|
|
347
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
const bytes = Buffer.byteLength(content, "utf8");
|
|
351
|
+
if (bytes > MAX_FILE_BYTES) {
|
|
352
|
+
throw new Error(`Output exceeds max allowed size (${MAX_FILE_BYTES} bytes).`);
|
|
353
|
+
}
|
|
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
|
+
}
|
|
361
|
+
await writeFile(targetReal, content, {
|
|
362
|
+
encoding: "utf8",
|
|
363
|
+
flag: options.overwrite ? "w" : "wx"
|
|
364
|
+
}).catch((err) => {
|
|
365
|
+
if (err.code === "EEXIST") {
|
|
366
|
+
throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
|
|
367
|
+
}
|
|
368
|
+
throw err;
|
|
369
|
+
});
|
|
370
|
+
return { resolvedPath: targetReal, bytes };
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
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
|
+
}
|
|
405
|
+
function extractGuardText(rawInput) {
|
|
406
|
+
const trimmed = rawInput.trim();
|
|
407
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
408
|
+
try {
|
|
409
|
+
const parsed = JSON.parse(trimmed);
|
|
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
|
+
}
|
|
417
|
+
}
|
|
418
|
+
} catch {
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return { text: rawInput, isHookEnvelope: false };
|
|
422
|
+
}
|
|
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
|
+
}
|
|
474
|
+
const { text } = extractGuardText(rawInput);
|
|
475
|
+
if (!text.trim()) {
|
|
476
|
+
return {
|
|
477
|
+
blocked: false,
|
|
478
|
+
totalRedactions: 0,
|
|
479
|
+
counts: {},
|
|
480
|
+
redacted: text,
|
|
481
|
+
modeUsed: options.mode === "rules" ? "rules" : "hybrid"
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
const { result, modeUsed } = await engine.redact(text, {
|
|
485
|
+
mode: options.mode,
|
|
486
|
+
profile: options.profile,
|
|
487
|
+
customTerms: options.customTerms
|
|
488
|
+
});
|
|
489
|
+
const counts = {};
|
|
490
|
+
for (const r of result.redactions) {
|
|
491
|
+
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
492
|
+
}
|
|
493
|
+
return {
|
|
494
|
+
blocked: result.redactions.length > 0,
|
|
495
|
+
totalRedactions: result.redactions.length,
|
|
496
|
+
counts,
|
|
497
|
+
redacted: result.text,
|
|
498
|
+
modeUsed
|
|
499
|
+
};
|
|
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
|
+
}
|
|
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;
|
|
909
|
+
function valueKey(label, value) {
|
|
910
|
+
return `${label.length}:${label}:${value}`;
|
|
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
|
+
}
|
|
919
|
+
var SessionVault = class {
|
|
920
|
+
constructor(maxSessions = DEFAULT_MAX_SESSIONS, maxEntitiesPerSession = DEFAULT_MAX_ENTITIES_PER_SESSION) {
|
|
921
|
+
this.sessions = /* @__PURE__ */ new Map();
|
|
922
|
+
this.maxSessions = Math.max(1, maxSessions);
|
|
923
|
+
this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
|
|
924
|
+
}
|
|
925
|
+
getOrCreate(sessionId) {
|
|
926
|
+
const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
|
|
927
|
+
const existing = this.sessions.get(id);
|
|
928
|
+
if (existing) {
|
|
929
|
+
this.sessions.delete(id);
|
|
930
|
+
this.sessions.set(id, existing);
|
|
931
|
+
existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
932
|
+
return existing;
|
|
933
|
+
}
|
|
934
|
+
if (this.sessions.size >= this.maxSessions) {
|
|
935
|
+
const oldestKey = this.sessions.keys().next().value;
|
|
936
|
+
if (oldestKey !== void 0) this.sessions.delete(oldestKey);
|
|
937
|
+
}
|
|
938
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
939
|
+
const created = {
|
|
940
|
+
id,
|
|
941
|
+
createdAt: now,
|
|
942
|
+
updatedAt: now,
|
|
943
|
+
tokenByKey: /* @__PURE__ */ new Map(),
|
|
944
|
+
map: {},
|
|
945
|
+
counters: /* @__PURE__ */ new Map(),
|
|
946
|
+
countsByLabel: {}
|
|
947
|
+
};
|
|
948
|
+
this.sessions.set(id, created);
|
|
949
|
+
return created;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Re-number a RedactResult's replacements into a persistent session so that
|
|
953
|
+
* the same entity receives the exact same placeholder across multiple calls
|
|
954
|
+
* and files in the same session, while avoiding collisions with literal text.
|
|
955
|
+
*/
|
|
956
|
+
apply(originalInput, result, sessionId) {
|
|
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
|
+
}
|
|
967
|
+
const counts = {};
|
|
968
|
+
const localMap = {};
|
|
969
|
+
const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
|
|
970
|
+
let redacted = "";
|
|
971
|
+
let cursor = 0;
|
|
972
|
+
for (const r of result.redactions) {
|
|
973
|
+
const key = valueKey(r.label, r.value);
|
|
974
|
+
let token = session.tokenByKey.get(key);
|
|
975
|
+
if (token) {
|
|
976
|
+
session.tokenByKey.delete(key);
|
|
977
|
+
session.tokenByKey.set(key, token);
|
|
978
|
+
} else {
|
|
979
|
+
let next = session.counters.get(r.label) ?? 0;
|
|
980
|
+
for (; ; ) {
|
|
981
|
+
next += 1;
|
|
982
|
+
const candidate = `[${r.label}_${next}]`;
|
|
983
|
+
if (!(candidate in session.map) && !existingTokens?.has(candidate)) {
|
|
984
|
+
token = candidate;
|
|
985
|
+
break;
|
|
986
|
+
}
|
|
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
|
+
}
|
|
1001
|
+
session.counters.set(r.label, next);
|
|
1002
|
+
session.tokenByKey.set(key, token);
|
|
1003
|
+
session.map[token] = r.value;
|
|
1004
|
+
session.countsByLabel[r.label] = (session.countsByLabel[r.label] ?? 0) + 1;
|
|
1005
|
+
}
|
|
1006
|
+
localMap[token] = r.value;
|
|
1007
|
+
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
1008
|
+
redacted += originalInput.slice(cursor, r.start) + token;
|
|
1009
|
+
cursor = r.end;
|
|
1010
|
+
}
|
|
1011
|
+
redacted += originalInput.slice(cursor);
|
|
1012
|
+
return {
|
|
1013
|
+
sessionId: session.id,
|
|
1014
|
+
redacted,
|
|
1015
|
+
counts,
|
|
1016
|
+
totalRedactions: result.redactions.length,
|
|
1017
|
+
map: localMap
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
restore(text, options) {
|
|
1021
|
+
const normalizedId = options.sessionId?.trim() || void 0;
|
|
1022
|
+
if (options.map && Object.keys(options.map).length > 0) {
|
|
1023
|
+
return {
|
|
1024
|
+
restored: restore(text, options.map),
|
|
1025
|
+
sessionId: normalizedId ?? null,
|
|
1026
|
+
knownPlaceholders: Object.keys(options.map).length
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
if (!normalizedId) {
|
|
1030
|
+
throw new Error("Provide either session_id or map to restore placeholders.");
|
|
1031
|
+
}
|
|
1032
|
+
const session = this.sessions.get(normalizedId);
|
|
1033
|
+
if (!session) {
|
|
1034
|
+
throw new Error(`Unknown session_id "${normalizedId}".`);
|
|
1035
|
+
}
|
|
1036
|
+
return {
|
|
1037
|
+
restored: restore(text, session.map),
|
|
1038
|
+
sessionId: session.id,
|
|
1039
|
+
knownPlaceholders: Object.keys(session.map).length
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
getMap(sessionId) {
|
|
1043
|
+
const session = this.sessions.get(sessionId.trim());
|
|
1044
|
+
return session ? { ...session.map } : {};
|
|
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
|
+
}
|
|
1058
|
+
list() {
|
|
1059
|
+
return [...this.sessions.values()].map((s) => ({
|
|
1060
|
+
sessionId: s.id,
|
|
1061
|
+
entityCount: Object.keys(s.map).length,
|
|
1062
|
+
countsByLabel: { ...s.countsByLabel },
|
|
1063
|
+
createdAt: s.createdAt,
|
|
1064
|
+
updatedAt: s.updatedAt
|
|
1065
|
+
}));
|
|
1066
|
+
}
|
|
1067
|
+
clear(sessionId) {
|
|
1068
|
+
return this.sessions.delete(sessionId.trim());
|
|
1069
|
+
}
|
|
1070
|
+
get size() {
|
|
1071
|
+
return this.sessions.size;
|
|
1072
|
+
}
|
|
1073
|
+
};
|
|
1074
|
+
|
|
1075
|
+
// src/proxy.ts
|
|
1076
|
+
var DEFAULT_ANTHROPIC_UPSTREAM = "https://api.anthropic.com";
|
|
1077
|
+
var DEFAULT_OPENAI_UPSTREAM = "https://api.openai.com";
|
|
1078
|
+
var MAX_BODY_BYTES = 16 * 1024 * 1024;
|
|
1079
|
+
var HOP_BY_HOP_REQUEST_HEADERS = /* @__PURE__ */ new Set([
|
|
1080
|
+
"connection",
|
|
1081
|
+
"keep-alive",
|
|
1082
|
+
"proxy-authenticate",
|
|
1083
|
+
"proxy-authorization",
|
|
1084
|
+
"te",
|
|
1085
|
+
"trailers",
|
|
1086
|
+
"transfer-encoding",
|
|
1087
|
+
"upgrade",
|
|
1088
|
+
"host",
|
|
1089
|
+
"content-length",
|
|
1090
|
+
"accept-encoding"
|
|
1091
|
+
]);
|
|
1092
|
+
var HOP_BY_HOP_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
|
|
1093
|
+
"connection",
|
|
1094
|
+
"keep-alive",
|
|
1095
|
+
"proxy-authenticate",
|
|
1096
|
+
"proxy-authorization",
|
|
1097
|
+
"te",
|
|
1098
|
+
"trailers",
|
|
1099
|
+
"transfer-encoding",
|
|
1100
|
+
"upgrade",
|
|
1101
|
+
"content-length",
|
|
1102
|
+
"content-encoding"
|
|
1103
|
+
]);
|
|
1104
|
+
var StreamingRestorer = class {
|
|
1105
|
+
constructor(map, options = {}) {
|
|
1106
|
+
this.buffer = "";
|
|
1107
|
+
this.map = map;
|
|
1108
|
+
this.tokens = Object.keys(map).sort((a, b) => b.length - a.length);
|
|
1109
|
+
this.maxTokenLength = this.tokens.reduce((max, t) => Math.max(max, t.length), 0);
|
|
1110
|
+
this.escapeForJsonString = options.escapeForJsonString === true;
|
|
1111
|
+
}
|
|
1112
|
+
formatReplacement(value) {
|
|
1113
|
+
if (!this.escapeForJsonString) return value;
|
|
1114
|
+
return JSON.stringify(value).slice(1, -1);
|
|
1115
|
+
}
|
|
1116
|
+
push(chunk) {
|
|
1117
|
+
if (!chunk || this.tokens.length === 0) return chunk;
|
|
1118
|
+
if (!this.buffer && !chunk.includes("[")) return chunk;
|
|
1119
|
+
this.buffer += chunk;
|
|
1120
|
+
return this.drain(false);
|
|
1121
|
+
}
|
|
1122
|
+
flush() {
|
|
1123
|
+
if (!this.buffer) return "";
|
|
1124
|
+
return this.drain(true);
|
|
1125
|
+
}
|
|
1126
|
+
drain(final) {
|
|
1127
|
+
let out = "";
|
|
1128
|
+
let cursor = 0;
|
|
1129
|
+
const buf = this.buffer;
|
|
1130
|
+
while (cursor < buf.length) {
|
|
1131
|
+
const bracket = buf.indexOf("[", cursor);
|
|
1132
|
+
if (bracket < 0) {
|
|
1133
|
+
out += buf.slice(cursor);
|
|
1134
|
+
cursor = buf.length;
|
|
1135
|
+
break;
|
|
1136
|
+
}
|
|
1137
|
+
if (bracket > cursor) {
|
|
1138
|
+
out += buf.slice(cursor, bracket);
|
|
1139
|
+
cursor = bracket;
|
|
1140
|
+
}
|
|
1141
|
+
const remaining = buf.slice(cursor);
|
|
1142
|
+
let matchedToken = null;
|
|
1143
|
+
for (const token of this.tokens) {
|
|
1144
|
+
if (remaining.startsWith(token)) {
|
|
1145
|
+
matchedToken = token;
|
|
1146
|
+
break;
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
if (matchedToken) {
|
|
1150
|
+
out += this.formatReplacement(this.map[matchedToken] ?? matchedToken);
|
|
1151
|
+
cursor += matchedToken.length;
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
if (!final && remaining.length < this.maxTokenLength) {
|
|
1155
|
+
const couldMatch = this.tokens.some((token) => token.startsWith(remaining));
|
|
1156
|
+
if (couldMatch) {
|
|
1157
|
+
break;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
out += "[";
|
|
1161
|
+
cursor += 1;
|
|
1162
|
+
}
|
|
1163
|
+
this.buffer = buf.slice(cursor);
|
|
1164
|
+
return out;
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
function isPlainObject(value) {
|
|
1168
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
1169
|
+
}
|
|
1170
|
+
function mergeCounts(target, delta) {
|
|
1171
|
+
for (const [k, v] of Object.entries(delta)) {
|
|
1172
|
+
target[k] = (target[k] ?? 0) + v;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
function restorePlainText(text, map) {
|
|
1176
|
+
if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
|
|
1177
|
+
const r = new StreamingRestorer(map);
|
|
1178
|
+
return r.push(text) + r.flush();
|
|
1179
|
+
}
|
|
1180
|
+
function restoreJsonEncodedText(text, map) {
|
|
1181
|
+
if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
|
|
1182
|
+
try {
|
|
1183
|
+
const parsed = JSON.parse(text);
|
|
1184
|
+
const restored = restoreJsonLeaves(parsed, map);
|
|
1185
|
+
return JSON.stringify(restored);
|
|
1186
|
+
} catch {
|
|
1187
|
+
const r = new StreamingRestorer(map, { escapeForJsonString: true });
|
|
1188
|
+
return r.push(text) + r.flush();
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
function restoreJsonLeaves(value, map) {
|
|
1192
|
+
if (typeof value === "string") return restorePlainText(value, map);
|
|
1193
|
+
if (Array.isArray(value)) return value.map((item) => restoreJsonLeaves(item, map));
|
|
1194
|
+
if (isPlainObject(value)) {
|
|
1195
|
+
const out = {};
|
|
1196
|
+
for (const [k, v] of Object.entries(value)) {
|
|
1197
|
+
out[k] = restoreJsonLeaves(v, map);
|
|
1198
|
+
}
|
|
1199
|
+
return out;
|
|
1200
|
+
}
|
|
1201
|
+
return value;
|
|
1202
|
+
}
|
|
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) {
|
|
1216
|
+
for (const block of blocks) {
|
|
1217
|
+
if (!isPlainObject(block)) continue;
|
|
1218
|
+
if (typeof block.text === "string") {
|
|
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);
|
|
1233
|
+
}
|
|
1234
|
+
if (typeof block.content === "string") {
|
|
1235
|
+
block.content = await redactString(block.content, kind);
|
|
1236
|
+
} else if (Array.isArray(block.content)) {
|
|
1237
|
+
await redactContentBlocks(block.content, kind);
|
|
1238
|
+
}
|
|
1239
|
+
if (typeof block.output === "string") {
|
|
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
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
if (typeof block.arguments === "string") {
|
|
1255
|
+
block.arguments = await redactJsonStringOrText(block.arguments, kind);
|
|
1256
|
+
}
|
|
1257
|
+
if (isPlainObject(block.input)) {
|
|
1258
|
+
block.input = await redactObjectStrings(block.input, kind);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
async function redactObjectStrings(value, kind) {
|
|
1263
|
+
if (typeof value === "string") return redactString(value, kind);
|
|
1264
|
+
if (Array.isArray(value)) {
|
|
1265
|
+
const out = [];
|
|
1266
|
+
for (const item of value) out.push(await redactObjectStrings(item, kind));
|
|
1267
|
+
return out;
|
|
1268
|
+
}
|
|
1269
|
+
if (isPlainObject(value)) {
|
|
1270
|
+
const out = {};
|
|
1271
|
+
for (const [k, v] of Object.entries(value)) {
|
|
1272
|
+
out[k] = await redactObjectStrings(v, kind);
|
|
1273
|
+
}
|
|
1274
|
+
return out;
|
|
1275
|
+
}
|
|
1276
|
+
return value;
|
|
1277
|
+
}
|
|
1278
|
+
async function redactJsonStringOrText(raw, kind) {
|
|
1279
|
+
try {
|
|
1280
|
+
const parsed = JSON.parse(raw);
|
|
1281
|
+
const redacted = await redactObjectStrings(parsed, kind);
|
|
1282
|
+
return JSON.stringify(redacted);
|
|
1283
|
+
} catch {
|
|
1284
|
+
return redactString(raw, kind);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
if (typeof clone.system === "string") {
|
|
1288
|
+
clone.system = await redactString(clone.system, "system");
|
|
1289
|
+
} else if (Array.isArray(clone.system)) {
|
|
1290
|
+
await redactContentBlocks(clone.system, "system");
|
|
1291
|
+
}
|
|
1292
|
+
if (typeof clone.instructions === "string") {
|
|
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);
|
|
1314
|
+
}
|
|
1315
|
+
if (Array.isArray(clone.messages)) {
|
|
1316
|
+
for (const msg of clone.messages) {
|
|
1317
|
+
if (!isPlainObject(msg)) continue;
|
|
1318
|
+
const msgKind = msg.role === "system" || msg.role === "developer" ? "system" : "message";
|
|
1319
|
+
if (typeof msg.content === "string") {
|
|
1320
|
+
msg.content = await redactString(msg.content, msgKind);
|
|
1321
|
+
} else if (Array.isArray(msg.content)) {
|
|
1322
|
+
await redactContentBlocks(msg.content, msgKind);
|
|
1323
|
+
}
|
|
1324
|
+
if (Array.isArray(msg.tool_calls)) {
|
|
1325
|
+
for (const call of msg.tool_calls) {
|
|
1326
|
+
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
1327
|
+
if (typeof call.function.arguments === "string") {
|
|
1328
|
+
call.function.arguments = await redactJsonStringOrText(
|
|
1329
|
+
call.function.arguments,
|
|
1330
|
+
msgKind
|
|
1331
|
+
);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
if (typeof clone.input === "string") {
|
|
1339
|
+
clone.input = await redactString(clone.input, "message");
|
|
1340
|
+
} else if (Array.isArray(clone.input)) {
|
|
1341
|
+
for (let i = 0; i < clone.input.length; i++) {
|
|
1342
|
+
const item = clone.input[i];
|
|
1343
|
+
if (typeof item === "string") {
|
|
1344
|
+
clone.input[i] = await redactString(item, "message");
|
|
1345
|
+
} else if (isPlainObject(item)) {
|
|
1346
|
+
const itemKind = item.role === "system" || item.role === "developer" ? "system" : "message";
|
|
1347
|
+
if (typeof item.text === "string") item.text = await redactString(item.text, itemKind);
|
|
1348
|
+
if (typeof item.content === "string") {
|
|
1349
|
+
item.content = await redactString(item.content, itemKind);
|
|
1350
|
+
} else if (Array.isArray(item.content)) {
|
|
1351
|
+
await redactContentBlocks(item.content, itemKind);
|
|
1352
|
+
}
|
|
1353
|
+
if (typeof item.output === "string") {
|
|
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);
|
|
1360
|
+
}
|
|
1361
|
+
if (typeof item.arguments === "string") {
|
|
1362
|
+
item.arguments = await redactJsonStringOrText(item.arguments, itemKind);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
return clone;
|
|
1368
|
+
}
|
|
1369
|
+
function restoreLlmResponseBody(body, map, options = {}) {
|
|
1370
|
+
if (!isPlainObject(body) || Object.keys(map).length === 0) return body;
|
|
1371
|
+
const clone = options.mutate ? body : structuredClone(body);
|
|
1372
|
+
if (Array.isArray(clone.content)) {
|
|
1373
|
+
for (const block of clone.content) {
|
|
1374
|
+
if (!isPlainObject(block)) continue;
|
|
1375
|
+
if (typeof block.text === "string") {
|
|
1376
|
+
block.text = restorePlainText(block.text, map);
|
|
1377
|
+
}
|
|
1378
|
+
if (typeof block.thinking === "string" && typeof block.signature !== "string") {
|
|
1379
|
+
block.thinking = restorePlainText(block.thinking, map);
|
|
1380
|
+
}
|
|
1381
|
+
if (isPlainObject(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
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
if (Array.isArray(clone.choices)) {
|
|
1390
|
+
for (const choice of clone.choices) {
|
|
1391
|
+
if (!isPlainObject(choice)) continue;
|
|
1392
|
+
const msg = choice.message;
|
|
1393
|
+
if (isPlainObject(msg)) {
|
|
1394
|
+
if (typeof msg.content === "string") {
|
|
1395
|
+
msg.content = restorePlainText(msg.content, map);
|
|
1396
|
+
}
|
|
1397
|
+
if (typeof msg.reasoning_content === "string") {
|
|
1398
|
+
msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
|
|
1399
|
+
}
|
|
1400
|
+
if (Array.isArray(msg.tool_calls)) {
|
|
1401
|
+
for (const call of msg.tool_calls) {
|
|
1402
|
+
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
1403
|
+
if (typeof call.function.arguments === "string" && !shouldSkipToolArgRestore(call.function.name, call.function.arguments)) {
|
|
1404
|
+
call.function.arguments = restoreJsonEncodedText(call.function.arguments, map);
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
if (typeof choice.text === "string") {
|
|
1411
|
+
choice.text = restorePlainText(choice.text, map);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
if (typeof clone.output_text === "string") {
|
|
1416
|
+
clone.output_text = restorePlainText(clone.output_text, map);
|
|
1417
|
+
}
|
|
1418
|
+
if (Array.isArray(clone.output)) {
|
|
1419
|
+
for (const item of clone.output) {
|
|
1420
|
+
if (!isPlainObject(item)) continue;
|
|
1421
|
+
if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(item.name, item.arguments)) {
|
|
1422
|
+
item.arguments = restoreJsonEncodedText(item.arguments, map);
|
|
1423
|
+
}
|
|
1424
|
+
if (Array.isArray(item.content)) {
|
|
1425
|
+
for (const part of item.content) {
|
|
1426
|
+
if (isPlainObject(part) && typeof part.text === "string") {
|
|
1427
|
+
part.text = restorePlainText(part.text, map);
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
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
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
return clone;
|
|
1441
|
+
}
|
|
1442
|
+
function createSseRestorer(map) {
|
|
1443
|
+
const streams = /* @__PURE__ */ new Map();
|
|
1444
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
1445
|
+
const bufferedToolArgs = /* @__PURE__ */ new Map();
|
|
1446
|
+
const getStream = (key, escapeForJsonString = false) => {
|
|
1447
|
+
let r = streams.get(key);
|
|
1448
|
+
if (!r) {
|
|
1449
|
+
r = new StreamingRestorer(map, { escapeForJsonString });
|
|
1450
|
+
streams.set(key, r);
|
|
1451
|
+
}
|
|
1452
|
+
return r;
|
|
1453
|
+
};
|
|
1454
|
+
function flushStream(key) {
|
|
1455
|
+
const r = streams.get(key);
|
|
1456
|
+
if (!r) return "";
|
|
1457
|
+
streams.delete(key);
|
|
1458
|
+
return r.flush();
|
|
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
|
+
}
|
|
1602
|
+
let sseBuffer = "";
|
|
1603
|
+
function processEventBlock(block) {
|
|
1604
|
+
const lines = block.split("\n");
|
|
1605
|
+
const outLines = [];
|
|
1606
|
+
const extraEvents = [];
|
|
1607
|
+
for (const line of lines) {
|
|
1608
|
+
if (!line.startsWith("data:")) {
|
|
1609
|
+
outLines.push(line);
|
|
1610
|
+
continue;
|
|
1611
|
+
}
|
|
1612
|
+
const rawData = line.slice("data:".length).trimStart();
|
|
1613
|
+
if (!rawData || rawData === "[DONE]") {
|
|
1614
|
+
extraEvents.push(...drainRemainingStreams());
|
|
1615
|
+
outLines.push(line);
|
|
1616
|
+
continue;
|
|
1617
|
+
}
|
|
1618
|
+
let parsed;
|
|
1619
|
+
try {
|
|
1620
|
+
parsed = JSON.parse(rawData);
|
|
1621
|
+
} catch {
|
|
1622
|
+
outLines.push(line);
|
|
1623
|
+
continue;
|
|
1624
|
+
}
|
|
1625
|
+
if (!isPlainObject(parsed)) {
|
|
1626
|
+
outLines.push(line);
|
|
1627
|
+
continue;
|
|
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
|
+
}
|
|
1637
|
+
if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
|
|
1638
|
+
const idx = typeof parsed.index === "number" ? parsed.index : 0;
|
|
1639
|
+
if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
|
|
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);
|
|
1643
|
+
} else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
|
|
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
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1654
|
+
continue;
|
|
1655
|
+
}
|
|
1656
|
+
if (parsed.type === "content_block_stop") {
|
|
1657
|
+
const idx = typeof parsed.index === "number" ? parsed.index : 0;
|
|
1658
|
+
const textTail = flushStream(`anth_text:${idx}`);
|
|
1659
|
+
if (textTail) {
|
|
1660
|
+
extraEvents.push(
|
|
1661
|
+
`event: content_block_delta
|
|
1662
|
+
data: ${JSON.stringify({
|
|
1663
|
+
type: "content_block_delta",
|
|
1664
|
+
index: idx,
|
|
1665
|
+
delta: { type: "text_delta", text: textTail }
|
|
1666
|
+
})}`
|
|
1667
|
+
);
|
|
1668
|
+
}
|
|
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);
|
|
1683
|
+
if (jsonTail) {
|
|
1684
|
+
extraEvents.push(
|
|
1685
|
+
`event: content_block_delta
|
|
1686
|
+
data: ${JSON.stringify({
|
|
1687
|
+
type: "content_block_delta",
|
|
1688
|
+
index: idx,
|
|
1689
|
+
delta: { type: "input_json_delta", partial_json: jsonTail }
|
|
1690
|
+
})}`
|
|
1691
|
+
);
|
|
1692
|
+
}
|
|
1693
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1694
|
+
continue;
|
|
1695
|
+
}
|
|
1696
|
+
if (Array.isArray(parsed.choices)) {
|
|
1697
|
+
for (const choice of parsed.choices) {
|
|
1698
|
+
if (!isPlainObject(choice)) continue;
|
|
1699
|
+
const cIdx = typeof choice.index === "number" ? choice.index : 0;
|
|
1700
|
+
const delta = choice.delta;
|
|
1701
|
+
if (isPlainObject(delta)) {
|
|
1702
|
+
if (typeof delta.content === "string") {
|
|
1703
|
+
delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
|
|
1704
|
+
}
|
|
1705
|
+
if (typeof delta.reasoning_content === "string") {
|
|
1706
|
+
delta.reasoning_content = getStream(`openai_chat_reasoning:${cIdx}`).push(
|
|
1707
|
+
delta.reasoning_content
|
|
1708
|
+
);
|
|
1709
|
+
}
|
|
1710
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
1711
|
+
for (const call of delta.tool_calls) {
|
|
1712
|
+
if (!isPlainObject(call)) continue;
|
|
1713
|
+
const tIdx = typeof call.index === "number" ? call.index : 0;
|
|
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
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
if (choice.finish_reason !== null && choice.finish_reason !== void 0) {
|
|
1736
|
+
const textTail = flushStream(`openai_chat_text:${cIdx}`);
|
|
1737
|
+
if (textTail) {
|
|
1738
|
+
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
1739
|
+
const d = choice.delta;
|
|
1740
|
+
d.content = (typeof d.content === "string" ? d.content : "") + textTail;
|
|
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
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1790
|
+
continue;
|
|
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
|
+
}
|
|
1799
|
+
if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
|
|
1800
|
+
const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
|
|
1801
|
+
parsed.delta = getStream(key).push(parsed.delta);
|
|
1802
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1803
|
+
continue;
|
|
1804
|
+
}
|
|
1805
|
+
if (parsed.type === "response.output_text.done") {
|
|
1806
|
+
const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
|
|
1807
|
+
const tail = flushStream(key);
|
|
1808
|
+
if (tail) {
|
|
1809
|
+
extraEvents.push(
|
|
1810
|
+
`event: response.output_text.delta
|
|
1811
|
+
data: ${JSON.stringify({
|
|
1812
|
+
type: "response.output_text.delta",
|
|
1813
|
+
output_index: parsed.output_index ?? 0,
|
|
1814
|
+
content_index: parsed.content_index ?? 0,
|
|
1815
|
+
delta: tail
|
|
1816
|
+
})}`
|
|
1817
|
+
);
|
|
1818
|
+
}
|
|
1819
|
+
if (typeof parsed.text === "string") {
|
|
1820
|
+
parsed.text = restorePlainText(parsed.text, map);
|
|
1821
|
+
}
|
|
1822
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1823
|
+
continue;
|
|
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
|
+
}
|
|
1851
|
+
if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
|
|
1852
|
+
const key = `resp_args:${String(parsed.output_index ?? 0)}`;
|
|
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
|
+
}
|
|
1860
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1861
|
+
continue;
|
|
1862
|
+
}
|
|
1863
|
+
if (parsed.type === "response.function_call_arguments.done") {
|
|
1864
|
+
const key = `resp_args:${String(parsed.output_index ?? 0)}`;
|
|
1865
|
+
const name = toolNames.get(key);
|
|
1866
|
+
const tail = flushBufferedToolArgs(key) || flushStream(key);
|
|
1867
|
+
if (tail) {
|
|
1868
|
+
extraEvents.push(
|
|
1869
|
+
`event: response.function_call_arguments.delta
|
|
1870
|
+
data: ${JSON.stringify({
|
|
1871
|
+
type: "response.function_call_arguments.delta",
|
|
1872
|
+
output_index: parsed.output_index ?? 0,
|
|
1873
|
+
delta: tail
|
|
1874
|
+
})}`
|
|
1875
|
+
);
|
|
1876
|
+
}
|
|
1877
|
+
if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(name, parsed.arguments)) {
|
|
1878
|
+
parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
|
|
1879
|
+
}
|
|
1880
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1881
|
+
continue;
|
|
1882
|
+
}
|
|
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)) {
|
|
1921
|
+
parsed.response = restoreLlmResponseBody(parsed.response, map);
|
|
1922
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1923
|
+
continue;
|
|
1924
|
+
}
|
|
1925
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
1926
|
+
}
|
|
1927
|
+
const joined = outLines.join("\n");
|
|
1928
|
+
return extraEvents.length > 0 ? `${extraEvents.join("\n\n")}
|
|
1929
|
+
|
|
1930
|
+
${joined}` : joined;
|
|
1931
|
+
}
|
|
1932
|
+
let pendingCr = false;
|
|
1933
|
+
return {
|
|
1934
|
+
push(chunk) {
|
|
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");
|
|
1939
|
+
let out = "";
|
|
1940
|
+
for (; ; ) {
|
|
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);
|
|
1945
|
+
out += `${processEventBlock(block)}
|
|
1946
|
+
|
|
1947
|
+
`;
|
|
1948
|
+
}
|
|
1949
|
+
return out;
|
|
1950
|
+
},
|
|
1951
|
+
flush() {
|
|
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("");
|
|
1968
|
+
}
|
|
1969
|
+
};
|
|
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
|
+
}
|
|
2059
|
+
function resolveUpstreamTarget(urlPath, headers, options) {
|
|
2060
|
+
if (urlPath.startsWith("/anthropic/")) {
|
|
2061
|
+
return {
|
|
2062
|
+
baseUrl: options.anthropicUpstream.replace(/\/$/, ""),
|
|
2063
|
+
forwardPath: urlPath.slice("/anthropic".length)
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
if (urlPath.startsWith("/openai/")) {
|
|
2067
|
+
return {
|
|
2068
|
+
baseUrl: options.openaiUpstream.replace(/\/$/, ""),
|
|
2069
|
+
forwardPath: urlPath.slice("/openai".length)
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
if (options.explicitUpstream) {
|
|
2073
|
+
return {
|
|
2074
|
+
baseUrl: options.explicitUpstream.replace(/\/$/, ""),
|
|
2075
|
+
forwardPath: urlPath
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
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";
|
|
2079
|
+
return {
|
|
2080
|
+
baseUrl: (isAnthropic ? options.anthropicUpstream : options.openaiUpstream).replace(/\/$/, ""),
|
|
2081
|
+
forwardPath: urlPath
|
|
2082
|
+
};
|
|
2083
|
+
}
|
|
2084
|
+
async function readRequestBody(req) {
|
|
2085
|
+
const chunks = [];
|
|
2086
|
+
let total = 0;
|
|
2087
|
+
for await (const chunk of req) {
|
|
2088
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
2089
|
+
total += buf.byteLength;
|
|
2090
|
+
if (total > MAX_BODY_BYTES) {
|
|
2091
|
+
req.resume();
|
|
2092
|
+
throw new PayloadTooLargeError(`Request body exceeds ${MAX_BODY_BYTES} bytes.`);
|
|
2093
|
+
}
|
|
2094
|
+
chunks.push(buf);
|
|
2095
|
+
}
|
|
2096
|
+
return Buffer.concat(chunks);
|
|
2097
|
+
}
|
|
2098
|
+
function shouldRedactPath(pathname) {
|
|
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");
|
|
2101
|
+
}
|
|
2102
|
+
async function startMaskeraProxy(options = {}) {
|
|
2103
|
+
const host = options.host ?? "127.0.0.1";
|
|
2104
|
+
const requestedPort = options.port ?? 8787;
|
|
2105
|
+
const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
|
|
2106
|
+
const vault = options.vault ?? new SessionVault();
|
|
2107
|
+
const inspector = new ProxyInspector();
|
|
2108
|
+
const restoreResponses = options.restoreResponses !== false;
|
|
2109
|
+
const anthropicUpstream = options.anthropicUpstream ?? DEFAULT_ANTHROPIC_UPSTREAM;
|
|
2110
|
+
const openaiUpstream = options.openaiUpstream ?? DEFAULT_OPENAI_UPSTREAM;
|
|
2111
|
+
const auditLogPath = options.auditLogPath;
|
|
2112
|
+
const log = options.onLog ?? (() => {
|
|
2113
|
+
});
|
|
2114
|
+
if (auditLogPath) {
|
|
2115
|
+
await mkdir(dirname(auditLogPath), { recursive: true });
|
|
2116
|
+
await appendFile(auditLogPath, "", "utf8");
|
|
2117
|
+
}
|
|
2118
|
+
let totalRequests = 0;
|
|
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
|
+
}
|
|
2149
|
+
async function handleRequest(req, res) {
|
|
2150
|
+
const startedAt = Date.now();
|
|
2151
|
+
const method = req.method ?? "GET";
|
|
2152
|
+
const urlPath = req.url ?? "/";
|
|
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")) {
|
|
2224
|
+
const payload = {
|
|
2225
|
+
status: "ok",
|
|
2226
|
+
inspector_url: `${boundUrl}/_maskera`,
|
|
2227
|
+
engine: engine.status(),
|
|
2228
|
+
requests_proxied: totalRequests,
|
|
2229
|
+
total_redactions: totalRedactions,
|
|
2230
|
+
sessions: vault.list()
|
|
2231
|
+
};
|
|
2232
|
+
res.writeHead(200, {
|
|
2233
|
+
...INSPECTOR_SECURITY_HEADERS,
|
|
2234
|
+
"content-type": "application/json; charset=utf-8"
|
|
2235
|
+
});
|
|
2236
|
+
res.end(JSON.stringify(payload, null, 2));
|
|
2237
|
+
return;
|
|
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
|
+
}
|
|
2261
|
+
const { baseUrl, forwardPath } = resolveUpstreamTarget(urlPath, req.headers, {
|
|
2262
|
+
explicitUpstream: options.upstream,
|
|
2263
|
+
anthropicUpstream,
|
|
2264
|
+
openaiUpstream
|
|
2265
|
+
});
|
|
2266
|
+
const upstreamUrl = `${baseUrl}${forwardPath}`;
|
|
2267
|
+
const rawBody = method === "GET" || method === "HEAD" ? void 0 : await readRequestBody(req);
|
|
2268
|
+
const sessionHeader = req.headers["x-maskera-session"];
|
|
2269
|
+
const sessionId = typeof sessionHeader === "string" && sessionHeader.trim() ? sessionHeader.trim() : "proxy";
|
|
2270
|
+
const stats = { redactions: 0, counts: {} };
|
|
2271
|
+
const redactedPreview = [];
|
|
2272
|
+
let outgoingBody = rawBody;
|
|
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
|
+
}
|
|
2291
|
+
let parsed;
|
|
2292
|
+
try {
|
|
2293
|
+
parsed = JSON.parse(decodedBody.toString("utf8"));
|
|
2294
|
+
} catch {
|
|
2295
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
2296
|
+
res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
if (isPlainObject(parsed)) {
|
|
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
|
|
2335
|
+
});
|
|
2336
|
+
throw err;
|
|
2337
|
+
}
|
|
2338
|
+
outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
|
|
2339
|
+
rewroteRequestBody = true;
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
const forwardHeaders = new Headers();
|
|
2343
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
2344
|
+
if (v === void 0) continue;
|
|
2345
|
+
const lower = k.toLowerCase();
|
|
2346
|
+
if (HOP_BY_HOP_REQUEST_HEADERS.has(lower) || lower === "x-maskera-session" || rewroteRequestBody && lower === "content-encoding") {
|
|
2347
|
+
continue;
|
|
2348
|
+
}
|
|
2349
|
+
if (Array.isArray(v)) {
|
|
2350
|
+
for (const item of v) forwardHeaders.append(k, item);
|
|
2351
|
+
} else {
|
|
2352
|
+
forwardHeaders.set(k, v);
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
forwardHeaders.set("accept-encoding", "identity");
|
|
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
|
+
}
|
|
2389
|
+
const outHeaders = {};
|
|
2390
|
+
upstreamRes.headers.forEach((value, key) => {
|
|
2391
|
+
if (!HOP_BY_HOP_RESPONSE_HEADERS.has(key.toLowerCase())) {
|
|
2392
|
+
outHeaders[key] = value;
|
|
2393
|
+
}
|
|
2394
|
+
});
|
|
2395
|
+
outHeaders["x-maskera-redacted"] = String(stats.redactions);
|
|
2396
|
+
const sessionMap = restoreResponses ? vault.getMap(sessionId) : {};
|
|
2397
|
+
const hasMap = Object.keys(sessionMap).length > 0;
|
|
2398
|
+
const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
|
|
2399
|
+
const isSse = resContentType.includes("text/event-stream");
|
|
2400
|
+
if (isSse && upstreamRes.body) {
|
|
2401
|
+
res.writeHead(upstreamRes.status, outHeaders);
|
|
2402
|
+
const sse = hasMap ? createSseRestorer(sessionMap) : null;
|
|
2403
|
+
const decoder = sse ? new TextDecoder() : null;
|
|
2404
|
+
const reader = upstreamRes.body.getReader();
|
|
2405
|
+
const onStreamAbort = () => {
|
|
2406
|
+
void reader.cancel().catch(() => {
|
|
2407
|
+
});
|
|
2408
|
+
};
|
|
2409
|
+
abortController.signal.addEventListener("abort", onStreamAbort, { once: true });
|
|
2410
|
+
try {
|
|
2411
|
+
for (; ; ) {
|
|
2412
|
+
const { done, value } = await reader.read();
|
|
2413
|
+
if (done) break;
|
|
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);
|
|
2426
|
+
}
|
|
2427
|
+
} catch (err) {
|
|
2428
|
+
if (!abortController.signal.aborted) throw err;
|
|
2429
|
+
} finally {
|
|
2430
|
+
abortController.signal.removeEventListener("abort", onStreamAbort);
|
|
2431
|
+
res.off("close", onClientClose);
|
|
2432
|
+
reader.releaseLock();
|
|
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
|
+
});
|
|
2449
|
+
log(
|
|
2450
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${durationMs2}ms`
|
|
2451
|
+
);
|
|
2452
|
+
return;
|
|
2453
|
+
}
|
|
2454
|
+
let resBuf;
|
|
2455
|
+
try {
|
|
2456
|
+
resBuf = Buffer.from(await upstreamRes.arrayBuffer());
|
|
2457
|
+
} finally {
|
|
2458
|
+
res.off("close", onClientClose);
|
|
2459
|
+
}
|
|
2460
|
+
if (hasMap && resContentType.includes("application/json")) {
|
|
2461
|
+
try {
|
|
2462
|
+
const parsed = JSON.parse(resBuf.toString("utf8"));
|
|
2463
|
+
const restored = restoreLlmResponseBody(parsed, sessionMap, { mutate: true });
|
|
2464
|
+
const restoredBuf = Buffer.from(JSON.stringify(restored), "utf8");
|
|
2465
|
+
res.writeHead(upstreamRes.status, outHeaders);
|
|
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
|
+
});
|
|
2481
|
+
log(
|
|
2482
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${durationMs2}ms`
|
|
2483
|
+
);
|
|
2484
|
+
return;
|
|
2485
|
+
} catch {
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
res.writeHead(upstreamRes.status, outHeaders);
|
|
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
|
+
});
|
|
2504
|
+
log(
|
|
2505
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${durationMs}ms`
|
|
2506
|
+
);
|
|
2507
|
+
}
|
|
2508
|
+
const server = createServer((req, res) => {
|
|
2509
|
+
void handleRequest(req, res).catch((err) => {
|
|
2510
|
+
if (res.destroyed || req.aborted) return;
|
|
2511
|
+
const statusCode = err instanceof PayloadTooLargeError ? err.statusCode : 502;
|
|
2512
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2513
|
+
log(`[maskera-proxy] error: ${message}`);
|
|
2514
|
+
if (!res.headersSent) {
|
|
2515
|
+
res.writeHead(statusCode, { "content-type": "application/json; charset=utf-8" });
|
|
2516
|
+
res.end(JSON.stringify({ error: { message: `maskera-proxy error: ${message}` } }));
|
|
2517
|
+
} else if (!res.writableEnded) {
|
|
2518
|
+
res.end();
|
|
2519
|
+
}
|
|
2520
|
+
});
|
|
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
|
+
});
|
|
2539
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
2540
|
+
server.once("error", rejectListen);
|
|
2541
|
+
server.listen(requestedPort, host, () => {
|
|
2542
|
+
server.off("error", rejectListen);
|
|
2543
|
+
resolveListen();
|
|
2544
|
+
});
|
|
2545
|
+
});
|
|
2546
|
+
const addr = server.address();
|
|
2547
|
+
const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
|
|
2548
|
+
boundPort = actualPort;
|
|
2549
|
+
boundUrl = `http://${host}:${actualPort}`;
|
|
2550
|
+
return {
|
|
2551
|
+
host,
|
|
2552
|
+
port: actualPort,
|
|
2553
|
+
url: boundUrl,
|
|
2554
|
+
inspectorUrl: `${boundUrl}/_maskera`,
|
|
2555
|
+
server,
|
|
2556
|
+
vault,
|
|
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
|
+
}
|
|
2565
|
+
};
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
// src/server.ts
|
|
2569
|
+
var SERVER_NAME = "maskera-mcp";
|
|
2570
|
+
var SERVER_VERSION = "0.2.0";
|
|
2571
|
+
var SUPPORTED_PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
|
|
2572
|
+
var TOOLS = [
|
|
2573
|
+
{
|
|
2574
|
+
name: "maskera_redact",
|
|
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
|
+
},
|
|
2583
|
+
inputSchema: {
|
|
2584
|
+
type: "object",
|
|
2585
|
+
properties: {
|
|
2586
|
+
text: { type: "string", description: "Text to redact locally." },
|
|
2587
|
+
session_id: {
|
|
2588
|
+
type: "string",
|
|
2589
|
+
description: "Optional session ID to reuse consistent placeholder numbering across calls."
|
|
2590
|
+
},
|
|
2591
|
+
mode: {
|
|
2592
|
+
type: "string",
|
|
2593
|
+
enum: ["auto", "rules"],
|
|
2594
|
+
description: '"auto" (default) runs hybrid Swedish NER + rules; "rules" runs fast deterministic rules only.'
|
|
2595
|
+
},
|
|
2596
|
+
profile: {
|
|
2597
|
+
type: "string",
|
|
2598
|
+
enum: ["general", "clinical"],
|
|
2599
|
+
description: 'Optional built-in precision profile (default "general").'
|
|
2600
|
+
},
|
|
2601
|
+
custom_terms: {
|
|
2602
|
+
type: "array",
|
|
2603
|
+
items: { type: "string" },
|
|
2604
|
+
description: "Optional extra protected words (client names, case IDs, codenames)."
|
|
2605
|
+
},
|
|
2606
|
+
include_map: {
|
|
2607
|
+
type: "boolean",
|
|
2608
|
+
description: "Set true only when the caller explicitly needs the raw placeholder->value map returned. Default false (recommended so raw PII stays local)."
|
|
2609
|
+
}
|
|
2610
|
+
},
|
|
2611
|
+
required: ["text"]
|
|
2612
|
+
}
|
|
2613
|
+
},
|
|
2614
|
+
{
|
|
2615
|
+
name: "maskera_restore",
|
|
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
|
+
},
|
|
2624
|
+
inputSchema: {
|
|
2625
|
+
type: "object",
|
|
2626
|
+
properties: {
|
|
2627
|
+
text: { type: "string", description: "Text containing Maskera placeholders." },
|
|
2628
|
+
session_id: {
|
|
2629
|
+
type: "string",
|
|
2630
|
+
description: "Session ID returned by maskera_redact or maskera_read_file."
|
|
2631
|
+
},
|
|
2632
|
+
map: {
|
|
2633
|
+
type: "object",
|
|
2634
|
+
additionalProperties: { type: "string" },
|
|
2635
|
+
description: "Optional explicit placeholder -> original value map."
|
|
2636
|
+
}
|
|
2637
|
+
},
|
|
2638
|
+
required: ["text"]
|
|
2639
|
+
}
|
|
2640
|
+
},
|
|
2641
|
+
{
|
|
2642
|
+
name: "maskera_read_file",
|
|
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
|
+
},
|
|
2651
|
+
inputSchema: {
|
|
2652
|
+
type: "object",
|
|
2653
|
+
properties: {
|
|
2654
|
+
path: {
|
|
2655
|
+
type: "string",
|
|
2656
|
+
description: "Path to a UTF-8 file inside the allowed workspace roots."
|
|
2657
|
+
},
|
|
2658
|
+
session_id: {
|
|
2659
|
+
type: "string",
|
|
2660
|
+
description: "Optional session ID to share placeholder numbering across multiple files."
|
|
2661
|
+
},
|
|
2662
|
+
mode: {
|
|
2663
|
+
type: "string",
|
|
2664
|
+
enum: ["auto", "rules"],
|
|
2665
|
+
description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
|
|
2666
|
+
},
|
|
2667
|
+
profile: {
|
|
2668
|
+
type: "string",
|
|
2669
|
+
enum: ["general", "clinical"],
|
|
2670
|
+
description: 'Optional built-in precision profile (default "general").'
|
|
2671
|
+
},
|
|
2672
|
+
custom_terms: {
|
|
2673
|
+
type: "array",
|
|
2674
|
+
items: { type: "string" },
|
|
2675
|
+
description: "Optional extra protected words (client names, project codenames)."
|
|
2676
|
+
}
|
|
2677
|
+
},
|
|
2678
|
+
required: ["path"]
|
|
2679
|
+
}
|
|
2680
|
+
},
|
|
2681
|
+
{
|
|
2682
|
+
name: "maskera_write_file",
|
|
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
|
+
},
|
|
2691
|
+
inputSchema: {
|
|
2692
|
+
type: "object",
|
|
2693
|
+
properties: {
|
|
2694
|
+
path: {
|
|
2695
|
+
type: "string",
|
|
2696
|
+
description: "Destination path inside the allowed workspace roots."
|
|
2697
|
+
},
|
|
2698
|
+
text: {
|
|
2699
|
+
type: "string",
|
|
2700
|
+
description: "Draft text containing Maskera placeholders to restore before writing."
|
|
2701
|
+
},
|
|
2702
|
+
session_id: {
|
|
2703
|
+
type: "string",
|
|
2704
|
+
description: "Session ID containing the local restore map."
|
|
2705
|
+
},
|
|
2706
|
+
overwrite: {
|
|
2707
|
+
type: "boolean",
|
|
2708
|
+
description: "Allow overwriting an existing file. Default false."
|
|
2709
|
+
}
|
|
2710
|
+
},
|
|
2711
|
+
required: ["path", "text", "session_id"]
|
|
2712
|
+
}
|
|
2713
|
+
},
|
|
2714
|
+
{
|
|
2715
|
+
name: "maskera_list_sessions",
|
|
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
|
+
},
|
|
2724
|
+
inputSchema: { type: "object", properties: {} }
|
|
2725
|
+
},
|
|
2726
|
+
{
|
|
2727
|
+
name: "maskera_clear_session",
|
|
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
|
+
},
|
|
2736
|
+
inputSchema: {
|
|
2737
|
+
type: "object",
|
|
2738
|
+
properties: {
|
|
2739
|
+
session_id: { type: "string", description: "Session ID to erase." }
|
|
2740
|
+
},
|
|
2741
|
+
required: ["session_id"]
|
|
2742
|
+
}
|
|
2743
|
+
},
|
|
2744
|
+
{
|
|
2745
|
+
name: "maskera_status",
|
|
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
|
+
},
|
|
2754
|
+
inputSchema: { type: "object", properties: {} }
|
|
2755
|
+
}
|
|
2756
|
+
];
|
|
2757
|
+
function asObject(value) {
|
|
2758
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
2759
|
+
}
|
|
2760
|
+
function asMode(value) {
|
|
2761
|
+
if (value === void 0) return void 0;
|
|
2762
|
+
if (value === "auto" || value === "rules") return value;
|
|
2763
|
+
throw new Error('Invalid mode: expected "auto" or "rules".');
|
|
2764
|
+
}
|
|
2765
|
+
function asProfile(value) {
|
|
2766
|
+
if (value === void 0) return void 0;
|
|
2767
|
+
if (value === "general" || value === "clinical") return value;
|
|
2768
|
+
throw new Error('Invalid profile: expected "general" or "clinical".');
|
|
2769
|
+
}
|
|
2770
|
+
function asStringArray(value) {
|
|
2771
|
+
if (value === void 0) return void 0;
|
|
2772
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
|
|
2773
|
+
throw new Error("custom_terms must be an array of strings.");
|
|
2774
|
+
}
|
|
2775
|
+
return value;
|
|
2776
|
+
}
|
|
2777
|
+
function toolOk(payload) {
|
|
2778
|
+
return {
|
|
2779
|
+
content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
|
|
2780
|
+
structuredContent: payload
|
|
2781
|
+
};
|
|
2782
|
+
}
|
|
2783
|
+
function toolError(message) {
|
|
2784
|
+
return {
|
|
2785
|
+
isError: true,
|
|
2786
|
+
content: [{ type: "text", text: message }]
|
|
2787
|
+
};
|
|
2788
|
+
}
|
|
2789
|
+
function createMaskeraMcpServer(options = {}) {
|
|
2790
|
+
const engine = options.engine ?? createMaskeraEngine();
|
|
2791
|
+
const vault = options.vault ?? new SessionVault();
|
|
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
|
+
}
|
|
2800
|
+
async function callTool(name, rawArgs) {
|
|
2801
|
+
const args = asObject(rawArgs);
|
|
2802
|
+
try {
|
|
2803
|
+
if (name === "maskera_redact") {
|
|
2804
|
+
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
2805
|
+
const { result, modeUsed } = await engine.redact(args.text, {
|
|
2806
|
+
mode: asMode(args.mode),
|
|
2807
|
+
profile: asProfile(args.profile) ?? defaultProfile,
|
|
2808
|
+
customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
|
|
2809
|
+
});
|
|
2810
|
+
const applied = vault.apply(
|
|
2811
|
+
args.text,
|
|
2812
|
+
result,
|
|
2813
|
+
typeof args.session_id === "string" ? args.session_id : void 0
|
|
2814
|
+
);
|
|
2815
|
+
const payload = {
|
|
2816
|
+
redacted: applied.redacted,
|
|
2817
|
+
session_id: applied.sessionId,
|
|
2818
|
+
counts: applied.counts,
|
|
2819
|
+
total_redactions: applied.totalRedactions,
|
|
2820
|
+
mode: modeUsed
|
|
2821
|
+
};
|
|
2822
|
+
if (args.include_map === true) payload.map = applied.map;
|
|
2823
|
+
return toolOk(payload);
|
|
2824
|
+
}
|
|
2825
|
+
if (name === "maskera_restore") {
|
|
2826
|
+
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
2827
|
+
const explicitMap = args.map && typeof args.map === "object" && !Array.isArray(args.map) ? Object.fromEntries(
|
|
2828
|
+
Object.entries(args.map).filter(
|
|
2829
|
+
(entry) => typeof entry[1] === "string"
|
|
2830
|
+
)
|
|
2831
|
+
) : void 0;
|
|
2832
|
+
const out = vault.restore(args.text, {
|
|
2833
|
+
sessionId: typeof args.session_id === "string" ? args.session_id : void 0,
|
|
2834
|
+
map: explicitMap
|
|
2835
|
+
});
|
|
2836
|
+
return toolOk({
|
|
2837
|
+
restored: out.restored,
|
|
2838
|
+
session_id: out.sessionId,
|
|
2839
|
+
known_placeholders: out.knownPlaceholders
|
|
2840
|
+
});
|
|
2841
|
+
}
|
|
2842
|
+
if (name === "maskera_read_file") {
|
|
2843
|
+
if (typeof args.path !== "string") return toolError("Missing required string: path");
|
|
2844
|
+
const file = await files.readText(args.path);
|
|
2845
|
+
const { result, modeUsed } = await engine.redact(file.content, {
|
|
2846
|
+
mode: asMode(args.mode),
|
|
2847
|
+
profile: asProfile(args.profile) ?? defaultProfile,
|
|
2848
|
+
customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
|
|
2849
|
+
});
|
|
2850
|
+
const applied = vault.apply(
|
|
2851
|
+
file.content,
|
|
2852
|
+
result,
|
|
2853
|
+
typeof args.session_id === "string" ? args.session_id : void 0
|
|
2854
|
+
);
|
|
2855
|
+
return toolOk({
|
|
2856
|
+
path: file.resolvedPath,
|
|
2857
|
+
bytes: file.bytes,
|
|
2858
|
+
redacted: applied.redacted,
|
|
2859
|
+
session_id: applied.sessionId,
|
|
2860
|
+
counts: applied.counts,
|
|
2861
|
+
total_redactions: applied.totalRedactions,
|
|
2862
|
+
mode: modeUsed
|
|
2863
|
+
});
|
|
2864
|
+
}
|
|
2865
|
+
if (name === "maskera_write_file") {
|
|
2866
|
+
if (typeof args.path !== "string") return toolError("Missing required string: path");
|
|
2867
|
+
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
2868
|
+
if (typeof args.session_id !== "string" || !args.session_id.trim()) {
|
|
2869
|
+
return toolError("Missing required non-empty string: session_id");
|
|
2870
|
+
}
|
|
2871
|
+
const normalizedSessionId = args.session_id.trim();
|
|
2872
|
+
const { restored, knownPlaceholders } = vault.restore(args.text, {
|
|
2873
|
+
sessionId: normalizedSessionId
|
|
2874
|
+
});
|
|
2875
|
+
const written = await files.writeText(args.path, restored, {
|
|
2876
|
+
overwrite: args.overwrite === true
|
|
2877
|
+
});
|
|
2878
|
+
return toolOk({
|
|
2879
|
+
path: written.resolvedPath,
|
|
2880
|
+
bytes: written.bytes,
|
|
2881
|
+
session_id: normalizedSessionId,
|
|
2882
|
+
known_placeholders: knownPlaceholders
|
|
2883
|
+
});
|
|
2884
|
+
}
|
|
2885
|
+
if (name === "maskera_list_sessions") {
|
|
2886
|
+
return toolOk({ sessions: vault.list() });
|
|
2887
|
+
}
|
|
2888
|
+
if (name === "maskera_clear_session") {
|
|
2889
|
+
if (typeof args.session_id !== "string" || !args.session_id.trim()) {
|
|
2890
|
+
return toolError("Missing required non-empty string: session_id");
|
|
2891
|
+
}
|
|
2892
|
+
const normalizedSessionId = args.session_id.trim();
|
|
2893
|
+
return toolOk({
|
|
2894
|
+
session_id: normalizedSessionId,
|
|
2895
|
+
cleared: vault.clear(normalizedSessionId)
|
|
2896
|
+
});
|
|
2897
|
+
}
|
|
2898
|
+
if (name === "maskera_status") {
|
|
2899
|
+
return toolOk({
|
|
2900
|
+
server: SERVER_NAME,
|
|
2901
|
+
version: SERVER_VERSION,
|
|
2902
|
+
engine: engine.status(),
|
|
2903
|
+
active_sessions: vault.size,
|
|
2904
|
+
allowed_roots: files.allowedRoots
|
|
2905
|
+
});
|
|
2906
|
+
}
|
|
2907
|
+
return toolError(`Unknown tool "${name}".`);
|
|
2908
|
+
} catch (err) {
|
|
2909
|
+
return toolError(err instanceof Error ? err.message : String(err));
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
return {
|
|
2913
|
+
vault,
|
|
2914
|
+
async handleMessage(raw) {
|
|
2915
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
2916
|
+
return {
|
|
2917
|
+
jsonrpc: "2.0",
|
|
2918
|
+
id: null,
|
|
2919
|
+
error: { code: -32600, message: "Invalid Request" }
|
|
2920
|
+
};
|
|
2921
|
+
}
|
|
2922
|
+
const req = raw;
|
|
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) {
|
|
2926
|
+
return {
|
|
2927
|
+
jsonrpc: "2.0",
|
|
2928
|
+
id: validId ?? null,
|
|
2929
|
+
error: { code: -32600, message: "Invalid Request" }
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
const id = validId;
|
|
2933
|
+
if (id === void 0) {
|
|
2934
|
+
return null;
|
|
2935
|
+
}
|
|
2936
|
+
if (req.method === "initialize") {
|
|
2937
|
+
const params = asObject(req.params);
|
|
2938
|
+
const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
|
|
2939
|
+
const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
|
|
2940
|
+
return {
|
|
2941
|
+
jsonrpc: "2.0",
|
|
2942
|
+
id,
|
|
2943
|
+
result: {
|
|
2944
|
+
protocolVersion,
|
|
2945
|
+
capabilities: { tools: { listChanged: false } },
|
|
2946
|
+
serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
|
|
2947
|
+
instructions: "Use maskera_read_file to read sensitive local files already redacted, maskera_redact for raw snippets, and maskera_write_file to restore placeholders directly to disk without exposing real PII to the model."
|
|
2948
|
+
}
|
|
2949
|
+
};
|
|
2950
|
+
}
|
|
2951
|
+
if (req.method === "ping") {
|
|
2952
|
+
return { jsonrpc: "2.0", id, result: {} };
|
|
2953
|
+
}
|
|
2954
|
+
if (req.method === "tools/list") {
|
|
2955
|
+
return { jsonrpc: "2.0", id, result: { tools: TOOLS } };
|
|
2956
|
+
}
|
|
2957
|
+
if (req.method === "tools/call") {
|
|
2958
|
+
const params = asObject(req.params);
|
|
2959
|
+
if (typeof params.name !== "string") {
|
|
2960
|
+
return {
|
|
2961
|
+
jsonrpc: "2.0",
|
|
2962
|
+
id,
|
|
2963
|
+
error: { code: -32602, message: "Invalid params: missing tool name" }
|
|
2964
|
+
};
|
|
2965
|
+
}
|
|
2966
|
+
const result = await callTool(params.name, params.arguments);
|
|
2967
|
+
return { jsonrpc: "2.0", id, result };
|
|
2968
|
+
}
|
|
2969
|
+
return {
|
|
2970
|
+
jsonrpc: "2.0",
|
|
2971
|
+
id,
|
|
2972
|
+
error: { code: -32601, message: `Method not found: ${req.method}` }
|
|
2973
|
+
};
|
|
2974
|
+
}
|
|
2975
|
+
};
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
export { ProxyInspector, SERVER_NAME, SERVER_VERSION, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createSseRestorer, extractGuardText, redactLlmRequestBody, renderInspectorHtml, restoreLlmResponseBody, runGuard, startMaskeraProxy };
|
|
2979
|
+
//# sourceMappingURL=index.js.map
|
|
2980
|
+
//# sourceMappingURL=index.js.map
|