@maskera/mcp 0.2.0 → 0.4.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/dist/index.js CHANGED
@@ -1,11 +1,115 @@
1
1
  import { randomUUID, createHash } from 'crypto';
2
+ import { constants } from 'fs';
3
+ import { readFile, mkdir, realpath, writeFile, stat, access, appendFile, unlink, readdir, lstat, readlink } from 'fs/promises';
4
+ import { dirname, resolve, join, isAbsolute, relative, sep, delimiter } from 'path';
2
5
  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';
6
+ import { spawn, spawnSync } from 'child_process';
7
+ import { homedir } from 'os';
5
8
  import { createServer } from 'http';
6
9
  import * as zlib from 'zlib';
7
10
 
8
- // src/engine.ts
11
+ // src/approvals.ts
12
+ var DEFAULT_TTL_MS = 5 * 60 * 1e3;
13
+ var MAX_RECORDS = 50;
14
+ var ApprovalBroker = class {
15
+ constructor(ttlMs = DEFAULT_TTL_MS) {
16
+ this.records = /* @__PURE__ */ new Map();
17
+ this.listeners = /* @__PURE__ */ new Set();
18
+ this.ttlMs = Math.max(1e3, ttlMs);
19
+ }
20
+ expireStale(now = Date.now()) {
21
+ let changed = false;
22
+ for (const record of this.records.values()) {
23
+ if (record.summary.status === "pending" && now >= record.expiresAtMs) {
24
+ record.summary.status = "expired";
25
+ record.execute = null;
26
+ changed = true;
27
+ }
28
+ }
29
+ if (changed) this.notify();
30
+ }
31
+ notify() {
32
+ const snapshot = this.list();
33
+ for (const listener of this.listeners) {
34
+ try {
35
+ listener(snapshot);
36
+ } catch {
37
+ }
38
+ }
39
+ }
40
+ onChange(listener) {
41
+ this.listeners.add(listener);
42
+ return () => {
43
+ this.listeners.delete(listener);
44
+ };
45
+ }
46
+ create(input) {
47
+ this.expireStale();
48
+ if (this.records.size >= MAX_RECORDS) {
49
+ const oldestKey = this.records.keys().next().value;
50
+ if (oldestKey !== void 0) this.records.delete(oldestKey);
51
+ }
52
+ const now = Date.now();
53
+ const id = `apr_${randomUUID().slice(0, 12)}`;
54
+ const summary = {
55
+ id,
56
+ tool: input.tool,
57
+ reason: input.reason,
58
+ sessionId: input.sessionId ?? null,
59
+ placeholderCount: input.placeholderCount,
60
+ status: "pending",
61
+ createdAt: new Date(now).toISOString(),
62
+ expiresAt: new Date(now + this.ttlMs).toISOString(),
63
+ decidedAt: null
64
+ };
65
+ this.records.set(id, {
66
+ summary,
67
+ expiresAtMs: now + this.ttlMs,
68
+ execute: input.execute
69
+ });
70
+ this.notify();
71
+ return { ...summary };
72
+ }
73
+ list() {
74
+ this.expireStale();
75
+ return [...this.records.values()].map((r) => ({ ...r.summary })).reverse();
76
+ }
77
+ decide(id, decision) {
78
+ this.expireStale();
79
+ const record = this.records.get(id.trim());
80
+ if (!record) return null;
81
+ if (record.summary.status !== "pending") return { ...record.summary };
82
+ record.summary.status = decision === "approve" ? "approved" : "declined";
83
+ record.summary.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
84
+ if (decision === "decline") {
85
+ record.execute = null;
86
+ }
87
+ this.notify();
88
+ return { ...record.summary };
89
+ }
90
+ async resume(id) {
91
+ this.expireStale();
92
+ const record = this.records.get(id.trim());
93
+ if (!record) return { status: "not_found" };
94
+ const { status } = record.summary;
95
+ if (status === "pending" || status === "declined" || status === "expired") {
96
+ return { status, summary: { ...record.summary } };
97
+ }
98
+ if (status === "completed" || !record.execute) {
99
+ return { status: "expired", summary: { ...record.summary } };
100
+ }
101
+ const run = record.execute;
102
+ record.execute = null;
103
+ const result = await run();
104
+ record.summary.status = "completed";
105
+ this.notify();
106
+ return { status: "completed", result, summary: { ...record.summary } };
107
+ }
108
+ clearAll() {
109
+ this.records.clear();
110
+ this.notify();
111
+ }
112
+ };
9
113
  var WORD_CHAR = /[\p{L}\p{N}_]/u;
10
114
  var DEFAULT_MAX_CACHE_ENTRIES = 512;
11
115
  var MAX_CUSTOM_DETECTOR_CACHE = 64;
@@ -70,12 +174,35 @@ function createMaskeraEngine(options = {}) {
70
174
  function getRecognizer() {
71
175
  if (!recognizer) {
72
176
  const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
177
+ const loadStartedAt = Date.now();
178
+ options.onModelStatus?.({ phase: "loading", model });
73
179
  recognizer = createNerRecognizer({
74
180
  ...options.nerOptions,
75
181
  model,
76
182
  revision,
77
183
  dtype
78
184
  });
185
+ void recognizer.ready.then(
186
+ () => {
187
+ nerLoaded = true;
188
+ nerError = null;
189
+ options.onModelStatus?.({
190
+ phase: "ready",
191
+ model,
192
+ elapsedMs: Date.now() - loadStartedAt
193
+ });
194
+ },
195
+ (err) => {
196
+ const message = err instanceof Error ? err.message : String(err);
197
+ nerError = message;
198
+ options.onModelStatus?.({
199
+ phase: "error",
200
+ model,
201
+ elapsedMs: Date.now() - loadStartedAt,
202
+ error: message
203
+ });
204
+ }
205
+ );
79
206
  }
80
207
  return recognizer;
81
208
  }
@@ -218,9 +345,47 @@ function createMaskeraEngine(options = {}) {
218
345
  }
219
346
  };
220
347
  }
348
+ function createModelProgressLogger(write = (line) => process.stderr.write(`${line}
349
+ `), delayMs = 350) {
350
+ let timer = null;
351
+ let announcedLoading = false;
352
+ return (event) => {
353
+ if (event.phase === "loading") {
354
+ if (timer) clearTimeout(timer);
355
+ announcedLoading = false;
356
+ timer = setTimeout(() => {
357
+ announcedLoading = true;
358
+ write(
359
+ `[maskera] Loading Swedish ONNX model (${event.model}, ~43 MB on first run, cached locally)...`
360
+ );
361
+ }, delayMs);
362
+ timer.unref?.();
363
+ return;
364
+ }
365
+ if (timer) {
366
+ clearTimeout(timer);
367
+ timer = null;
368
+ }
369
+ if (event.phase === "ready" && announcedLoading) {
370
+ write(`[maskera] Swedish ONNX model ready (${event.elapsedMs ?? 0}ms).`);
371
+ announcedLoading = false;
372
+ } else if (event.phase === "error" && announcedLoading) {
373
+ write(`[maskera] Swedish ONNX model load failed: ${event.error ?? "unknown error"}`);
374
+ announcedLoading = false;
375
+ }
376
+ };
377
+ }
221
378
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
222
379
  var MAX_SYMLINK_HOPS = 40;
380
+ var DEFAULT_LIST_MAX_ENTRIES = 200;
381
+ var HARD_LIST_MAX_ENTRIES = 1e3;
382
+ var DEFAULT_LIST_MAX_DEPTH = 6;
383
+ var HARD_LIST_MAX_DEPTH = 12;
384
+ var DEFAULT_SEARCH_MAX_MATCHES = 50;
385
+ var HARD_SEARCH_MAX_MATCHES = 200;
386
+ var DEFAULT_SEARCH_MAX_FILES = 500;
223
387
  var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
388
+ var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "dist-ssr", ".next", ".turbo"]);
224
389
  function isWithinRoot(root, target) {
225
390
  const rel = relative(root, target);
226
391
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
@@ -263,6 +428,10 @@ async function resolveCanonicalTarget(target) {
263
428
  }
264
429
  throw new Error(`Too many symlink hops while resolving "${target}".`);
265
430
  }
431
+ function clampInt(value, fallback, min, max) {
432
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
433
+ return Math.min(max, Math.max(min, Math.trunc(value)));
434
+ }
266
435
  function createFileGuard(roots = [process.cwd()]) {
267
436
  const rawRoots = roots.length > 0 ? roots : [process.cwd()];
268
437
  let canonicalRootsPromise = null;
@@ -291,6 +460,74 @@ function createFileGuard(roots = [process.cwd()]) {
291
460
  if (!trimmed) throw new Error("Path must not be empty.");
292
461
  return isAbsolute(trimmed) ? resolve(trimmed) : resolve(rawRoots[0] ?? process.cwd(), trimmed);
293
462
  }
463
+ async function resolveAllowedDirectory(dirPath) {
464
+ const rootsList = await getCanonicalRoots();
465
+ const targetRaw = dirPath?.trim() ? resolveAgainstBase(dirPath) : resolve(rawRoots[0] ?? process.cwd());
466
+ const { ancestor, tail } = await resolveExistingAncestor(targetRaw);
467
+ const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
468
+ if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
469
+ throw new Error(
470
+ `Access denied: "${dirPath ?? targetRaw}" is outside allowed workspace roots (${rootsList.join(", ")}).`
471
+ );
472
+ }
473
+ const real = await realpath(targetRaw).catch(() => {
474
+ throw new Error(`Directory not found: "${dirPath ?? targetRaw}".`);
475
+ });
476
+ if (!rootsList.some((root) => isWithinRoot(root, real))) {
477
+ throw new Error(
478
+ `Access denied: "${dirPath ?? targetRaw}" is outside allowed workspace roots (${rootsList.join(", ")}).`
479
+ );
480
+ }
481
+ const info = await stat(real);
482
+ if (!info.isDirectory()) {
483
+ throw new Error(`"${dirPath ?? targetRaw}" is not a directory.`);
484
+ }
485
+ return { rootsList, baseDir: real };
486
+ }
487
+ async function walkFiles(baseDir, rootsList, maxEntries, maxDepth) {
488
+ const files = [];
489
+ const visitedDirs = /* @__PURE__ */ new Set([baseDir]);
490
+ let truncated = false;
491
+ async function visit(dir, depth) {
492
+ if (truncated) return;
493
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
494
+ entries.sort((a, b) => a.name.localeCompare(b.name));
495
+ for (const entry of entries) {
496
+ if (truncated) return;
497
+ if (entry.isDirectory() && SKIP_DIRS.has(entry.name)) continue;
498
+ const full = join(dir, entry.name);
499
+ let real;
500
+ try {
501
+ real = await realpath(full);
502
+ } catch {
503
+ continue;
504
+ }
505
+ if (!rootsList.some((root) => isWithinRoot(root, real))) continue;
506
+ let info;
507
+ try {
508
+ info = await stat(real);
509
+ } catch {
510
+ continue;
511
+ }
512
+ if (info.isDirectory()) {
513
+ if (depth < maxDepth && !visitedDirs.has(real)) {
514
+ visitedDirs.add(real);
515
+ await visit(real, depth + 1);
516
+ }
517
+ continue;
518
+ }
519
+ if (!info.isFile()) continue;
520
+ if (files.length >= maxEntries) {
521
+ truncated = true;
522
+ return;
523
+ }
524
+ const relPath = relative(baseDir, full).split(sep).join("/");
525
+ files.push({ relPath, realPath: real, bytes: info.size });
526
+ }
527
+ }
528
+ await visit(baseDir, 0);
529
+ return { files, truncated };
530
+ }
294
531
  return {
295
532
  allowedRoots: rawRoots.map((r) => resolve(r)),
296
533
  async readText(filePath) {
@@ -368,191 +605,1958 @@ function createFileGuard(roots = [process.cwd()]) {
368
605
  throw err;
369
606
  });
370
607
  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 };
608
+ },
609
+ async listFiles(dirPath, options = {}) {
610
+ const { rootsList, baseDir } = await resolveAllowedDirectory(dirPath);
611
+ const maxEntries = clampInt(
612
+ options.maxEntries,
613
+ DEFAULT_LIST_MAX_ENTRIES,
614
+ 1,
615
+ HARD_LIST_MAX_ENTRIES
616
+ );
617
+ const maxDepth = clampInt(options.maxDepth, DEFAULT_LIST_MAX_DEPTH, 0, HARD_LIST_MAX_DEPTH);
618
+ const { files, truncated } = await walkFiles(baseDir, rootsList, maxEntries, maxDepth);
619
+ return {
620
+ root: baseDir,
621
+ files: files.map((f) => ({ path: f.relPath, bytes: f.bytes })),
622
+ truncated
623
+ };
624
+ },
625
+ async searchFiles(query, options = {}) {
626
+ const trimmedQuery = query.trim();
627
+ if (!trimmedQuery) throw new Error("Search query must not be empty.");
628
+ const { rootsList, baseDir } = await resolveAllowedDirectory(options.path);
629
+ const maxMatches = clampInt(
630
+ options.maxMatches,
631
+ DEFAULT_SEARCH_MAX_MATCHES,
632
+ 1,
633
+ HARD_SEARCH_MAX_MATCHES
634
+ );
635
+ const maxFiles = clampInt(
636
+ options.maxFiles,
637
+ DEFAULT_SEARCH_MAX_FILES,
638
+ 1,
639
+ HARD_LIST_MAX_ENTRIES
640
+ );
641
+ const caseSensitive = options.caseSensitive === true;
642
+ const needle = caseSensitive ? trimmedQuery : trimmedQuery.toLowerCase();
643
+ const { files, truncated: walkTruncated } = await walkFiles(
644
+ baseDir,
645
+ rootsList,
646
+ maxFiles,
647
+ DEFAULT_LIST_MAX_DEPTH
648
+ );
649
+ const matches = [];
650
+ let scannedFiles = 0;
651
+ let truncated = walkTruncated;
652
+ for (const file of files) {
653
+ if (file.bytes > MAX_FILE_BYTES) continue;
654
+ let buffer;
655
+ try {
656
+ buffer = await readFile(file.realPath);
657
+ } catch {
658
+ continue;
416
659
  }
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
660
+ if (buffer.includes(0)) continue;
661
+ let text;
662
+ try {
663
+ text = UTF8_DECODER.decode(buffer);
664
+ } catch {
665
+ continue;
666
+ }
667
+ scannedFiles += 1;
668
+ const lines = text.split(/\r?\n/);
669
+ for (let i = 0; i < lines.length; i++) {
670
+ const lineText = lines[i] ?? "";
671
+ const haystack = caseSensitive ? lineText : lineText.toLowerCase();
672
+ if (haystack.includes(needle)) {
673
+ matches.push({
674
+ path: file.relPath,
675
+ line: i + 1,
676
+ lineText: lineText.length > 500 ? `${lineText.slice(0, 500)}...` : lineText
440
677
  });
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);
678
+ if (matches.length >= maxMatches) {
679
+ truncated = true;
680
+ return { root: baseDir, scannedFiles, matches, truncated };
457
681
  }
458
- return obj;
459
682
  }
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
- };
683
+ }
470
684
  }
471
- } catch {
685
+ return { root: baseDir, scannedFiles, matches, truncated };
472
686
  }
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
687
  };
500
688
  }
501
689
 
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)}
690
+ // src/skill-content.ts
691
+ var MASKERA_SKILL_URI = "maskera://skills/maskera/SKILL.md";
692
+ var MASKERA_STATUS_URI = "maskera://status";
693
+ var MASKERA_SKILL_MARKDOWN = `---
694
+ name: maskera
695
+ description: Redact Swedish personal data (names, personnummer, addresses, phones, emails, IBAN, org numbers) locally before text or files reach an AI model, and restore answers locally. Use when working with Swedish client files, HR/CVs, legal or municipal cases, healthcare notes, support transcripts, or when setting up @maskera/mcp (local LLM proxy, Streamable HTTP or stdio MCP server, guard) or the maskera npm SDK.
696
+ ---
517
697
 
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: {}
698
+ # Maskera: local Swedish PII redaction
699
+
700
+ Maskera runs 100% locally on-device using deterministic Swedish rules plus the 43 MB Swedish ONNX NER model (\`joelhagvall/maskera-sv-ner\`). Raw PII and restore maps stay local so cloud LLMs only see placeholders such as \`[NAMN_1]\` and \`[PERSONNUMMER_1]\`.
701
+
702
+ ## Choose the right mode
703
+
704
+ Pick by where the text comes from: **proxy for text typed straight into the chat**, **MCP for files the agent reads with the Maskera tools**. Before the user sends real personal data, verify the setup with made-up data (a fictional address) and confirm a placeholder in the local inspector at \`http://127.0.0.1:8787/_maskera\`, or run \`npx -y @maskera/mcp doctor\`.
705
+
706
+ 1. **Local LLM proxy + warm Streamable HTTP MCP (\`maskera-mcp wrap\` / \`proxy\` / \`service\`):**
707
+ Use when no prompt, history or tool output may leave the machine unredacted, or when multiple clients should share one warm ONNX model and session vault.
708
+ \`\`\`bash
709
+ # Single-command launch (starts local proxy, verifies 0 leaks, injects env vars, prints session receipt on exit):
710
+ npx -y @maskera/mcp wrap -- claude
711
+ # Or run a persistent local proxy (+ Streamable HTTP /mcp + live inspector with self-test button):
712
+ npx -y @maskera/mcp proxy --root /path/to/workspace --open
713
+ # Or install as a background service (launchd on macOS, systemd --user on Linux):
714
+ npx -y @maskera/mcp service install --root /path/to/workspace --no-raw-restore
715
+ # Point any harness or SDK at the loopback proxy:
716
+ ANTHROPIC_BASE_URL=http://127.0.0.1:8787 claude
717
+ OPENAI_BASE_URL=http://127.0.0.1:8787/v1 codex # API key mode; ChatGPT-login Codex requires HTTPS so use MCP below
718
+ # Same warm process also serves Streamable HTTP MCP:
719
+ # http://127.0.0.1:8787/mcp (supports ?no_raw_restore=1&read_only=1&approval_mode=browser)
720
+ \`\`\`
721
+ - Claude Desktop: Help -> Troubleshooting -> Enable Developer Mode, then Developer -> Configure Third-Party Inference. Set Inference provider to **Gateway**, Credential kind **Static API key**, Gateway base URL \`http://127.0.0.1:8787\` (no \`/v1\`), Gateway API key = the user's Anthropic API key, Gateway auth scheme **x-api-key**. Apply Changes, then Save & Restart. Full guide: \`https://maskera.dev/docs/guides\`.
722
+ - Routes Anthropic (\`/v1/messages\`) and OpenAI (\`/v1/chat/completions\`, \`/v1/responses\`) automatically, or set \`--upstream <url>\`.
723
+ - Restores placeholders transparently in JSON, tool arguments and chunk-split SSE streams.
724
+ - Fails closed (\`502\`) if local redaction fails. Inspect counts only at \`http://127.0.0.1:8787/_maskera/status\`.
725
+
726
+ 2. **Working with sensitive local Swedish files (MCP stdio or Streamable HTTP):**
727
+ Auto-detect or install automatically with \`npx -y @maskera/mcp install [client|all]\` (\`claude-code\`, \`claude-desktop\`, \`codex\`, \`cursor\`, \`opencode\`, \`t3-code\`; pass \`--apply\` to run \`claude\`/\`codex mcp add\`, \`--with-hook\` to install a \`guard\` hook). It verifies local Swedish PII masking (and any running \`/mcp\` server) automatically and prints a zero-PII setup receipt (\`--receipt <file.json>\` to save it, \`--no-verify\` to skip). Or configure manually:
728
+ - Claude Code / Cursor (\`mcpServers\`):
729
+ \`\`\`json
730
+ {
731
+ "mcpServers": {
732
+ "maskera": {
733
+ "command": "npx",
734
+ "args": ["-y", "@maskera/mcp", "--root", "/path/to/workspace", "--no-raw-restore"]
735
+ }
736
+ }
737
+ }
738
+ \`\`\`
739
+ - Codex CLI:
740
+ \`\`\`bash
741
+ codex mcp add maskera -- npx -y @maskera/mcp --root /path/to/workspace --no-raw-restore
742
+ \`\`\`
743
+ - OpenCode v2:
744
+ \`\`\`bash
745
+ opencode mcp add maskera -- npx -y @maskera/mcp --root /path/to/workspace --no-raw-restore
746
+ \`\`\`
747
+ Workflow rules when the Maskera MCP tools are available:
748
+ - List and search sensitive Swedish directories with \`maskera_list_files\` and \`maskera_search_files\` instead of raw \`grep\`/\`rg\` so matched lines are redacted before entering context.
749
+ - Read sensitive Swedish files with \`maskera_read_file\` instead of raw file-reading tools. Reuse one \`session_id\` across related files so \`[NAMN_1]\` stays consistent.
750
+ - Pass \`custom_terms\` for client codenames, project names or case references not covered by built-in rules.
751
+ - Pass \`profile: "clinical"\` for Swedish medical or care notes so diagnoses, doses and measurements stay intact while personal data is masked.
752
+ - Write finished drafts directly to disk with \`maskera_write_file\` so placeholders are restored locally without echoing raw PII back into the conversation.
753
+ - Use \`--no-raw-restore\` (or \`--approval-mode browser\`) when the agent should never pull raw PII back into chat via \`maskera_restore\` or \`include_map: true\`.
754
+ - Clear the in-memory restore map with \`maskera_clear_session\` once the task is done.
755
+
756
+ 3. **Hooks and Unix pipes (guard):**
757
+ \`\`\`bash
758
+ # Block prompts or JSON hook payloads containing PII (exits 2, prints counts only):
759
+ npx -y @maskera/mcp guard
760
+ # Redact text locally in a pipeline:
761
+ cat input.txt | npx -y @maskera/mcp guard --redact
762
+ \`\`\`
763
+
764
+ 4. **Embedding in application code (browser or Node 18+):**
765
+ \`\`\`bash
766
+ npm install maskera @huggingface/transformers
767
+ \`\`\`
768
+ Reuse one \`createNerRecognizer()\` instance across calls and run \`await redactWithNer(text, { recognizer })\` (or \`redact(text)\` from \`@maskera/core\` for zero-dependency structured rules only).
769
+
770
+ ## Boundaries
535
771
 
772
+ - A skill guides agent behaviour; for hard enforcement that cannot be bypassed by raw shell or file tools, use \`maskera-mcp proxy\` or restrict file access to \`maskera-mcp\` with \`--no-raw-restore\`.
773
+ - Automated masking reduces exposure risk but is not a zero-leak guarantee. Never log restore maps or write them next to redacted outputs.
774
+ - Reference docs and machine-readable details: \`https://maskera.dev/docs\` and \`https://maskera.dev/llms.txt\`.
536
775
  `;
537
- for (const res of [...this.subscribers]) {
538
- if (res.writableEnded || res.destroyed) {
539
- this.subscribers.delete(res);
540
- continue;
776
+ var MASKERA_PROMPTS = [
777
+ {
778
+ name: "maskera-workflow",
779
+ description: "Operating guide for working safely with Swedish personal data using Maskera MCP tools without leaking raw PII into the conversation.",
780
+ arguments: [
781
+ {
782
+ name: "profile",
783
+ description: 'Optional precision profile: "general" (default) or "clinical".',
784
+ required: false
785
+ },
786
+ {
787
+ name: "custom_terms",
788
+ description: "Optional comma-separated extra protected terms (client names, case IDs).",
789
+ required: false
541
790
  }
542
- res.write(payload);
543
- }
791
+ ]
792
+ },
793
+ {
794
+ name: "maskera-redact-file",
795
+ description: "Step-by-step instructions to read a sensitive Swedish local file through Maskera, draft an edited result with placeholders, and restore it directly to disk.",
796
+ arguments: [
797
+ {
798
+ name: "path",
799
+ description: "Relative or workspace path to the sensitive UTF-8 file.",
800
+ required: true
801
+ },
802
+ {
803
+ name: "output_path",
804
+ description: "Optional destination path for maskera_write_file.",
805
+ required: false
806
+ }
807
+ ]
544
808
  }
545
- subscribe(res, extraHeaders = {}) {
546
- res.writeHead(200, {
547
- ...extraHeaders,
548
- "content-type": "text/event-stream; charset=utf-8",
809
+ ];
810
+ function renderMaskeraPrompt(name, args) {
811
+ if (name === "maskera-workflow") {
812
+ const profile = args.profile === "clinical" ? "clinical" : "general";
813
+ const customTerms = typeof args.custom_terms === "string" && args.custom_terms.trim() ? args.custom_terms.trim() : null;
814
+ const extraLines = [
815
+ `Active profile: "${profile}".`,
816
+ ...customTerms ? [
817
+ `Pass custom_terms: [${customTerms.split(",").map((s) => JSON.stringify(s.trim())).filter((s) => s !== '""').join(", ")}].`
818
+ ] : []
819
+ ];
820
+ return {
821
+ description: "Safe Swedish PII workflow with Maskera MCP",
822
+ messages: [
823
+ {
824
+ role: "user",
825
+ content: {
826
+ type: "text",
827
+ text: `${extraLines.join("\n")}
828
+
829
+ ${MASKERA_SKILL_MARKDOWN}`
830
+ }
831
+ }
832
+ ]
833
+ };
834
+ }
835
+ if (name === "maskera-redact-file") {
836
+ const filePath = typeof args.path === "string" && args.path.trim() ? args.path.trim() : "<path>";
837
+ const outputPath = typeof args.output_path === "string" && args.output_path.trim() ? args.output_path.trim() : "<output_path>";
838
+ return {
839
+ description: "Redacted file read, edit, and local restore workflow",
840
+ messages: [
841
+ {
842
+ role: "user",
843
+ content: {
844
+ type: "text",
845
+ text: [
846
+ `1. Read "${filePath}" using maskera_read_file (never raw shell or raw file tools) and note the returned session_id.`,
847
+ "2. Keep all placeholders such as [NAMN_1] and [PERSONNUMMER_1] intact while drafting your edit or summary.",
848
+ `3. Write the finished result to "${outputPath}" using maskera_write_file with the same session_id so placeholders are restored directly on disk without exposing raw PII in chat.`,
849
+ "4. Call maskera_clear_session with that session_id once finished."
850
+ ].join("\n")
851
+ }
852
+ }
853
+ ]
854
+ };
855
+ }
856
+ return null;
857
+ }
858
+ var DEFAULT_MAX_SESSIONS = 100;
859
+ var DEFAULT_MAX_ENTITIES_PER_SESSION = 5e3;
860
+ var EXISTING_TOKEN_RE = /\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]/g;
861
+ function valueKey(label, value) {
862
+ return `${label.length}:${label}:${value}`;
863
+ }
864
+ function labelFromKey(key) {
865
+ const firstColon = key.indexOf(":");
866
+ if (firstColon < 1) return null;
867
+ const len = Number(key.slice(0, firstColon));
868
+ if (!Number.isInteger(len) || len <= 0) return null;
869
+ return key.slice(firstColon + 1, firstColon + 1 + len);
870
+ }
871
+ var SessionVault = class {
872
+ constructor(maxSessions = DEFAULT_MAX_SESSIONS, maxEntitiesPerSession = DEFAULT_MAX_ENTITIES_PER_SESSION) {
873
+ this.sessions = /* @__PURE__ */ new Map();
874
+ this.maxSessions = Math.max(1, maxSessions);
875
+ this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
876
+ }
877
+ getOrCreate(sessionId) {
878
+ const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
879
+ const existing = this.sessions.get(id);
880
+ if (existing) {
881
+ this.sessions.delete(id);
882
+ this.sessions.set(id, existing);
883
+ existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
884
+ return existing;
885
+ }
886
+ if (this.sessions.size >= this.maxSessions) {
887
+ const oldestKey = this.sessions.keys().next().value;
888
+ if (oldestKey !== void 0) this.sessions.delete(oldestKey);
889
+ }
890
+ const now = (/* @__PURE__ */ new Date()).toISOString();
891
+ const created = {
892
+ id,
893
+ createdAt: now,
894
+ updatedAt: now,
895
+ tokenByKey: /* @__PURE__ */ new Map(),
896
+ map: {},
897
+ counters: /* @__PURE__ */ new Map(),
898
+ countsByLabel: {}
899
+ };
900
+ this.sessions.set(id, created);
901
+ return created;
902
+ }
903
+ /**
904
+ * Re-number a RedactResult's replacements into a persistent session so that
905
+ * the same entity receives the exact same placeholder across multiple calls
906
+ * and files in the same session, while avoiding collisions with literal text.
907
+ */
908
+ apply(originalInput, result, sessionId) {
909
+ const session = this.getOrCreate(sessionId);
910
+ if (result.redactions.length === 0) {
911
+ return {
912
+ sessionId: session.id,
913
+ redacted: originalInput,
914
+ counts: {},
915
+ totalRedactions: 0,
916
+ map: {}
917
+ };
918
+ }
919
+ const counts = {};
920
+ const localMap = {};
921
+ const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
922
+ let redacted = "";
923
+ let cursor = 0;
924
+ for (const r of result.redactions) {
925
+ const key = valueKey(r.label, r.value);
926
+ let token = session.tokenByKey.get(key);
927
+ if (token) {
928
+ session.tokenByKey.delete(key);
929
+ session.tokenByKey.set(key, token);
930
+ } else {
931
+ let next = session.counters.get(r.label) ?? 0;
932
+ for (; ; ) {
933
+ next += 1;
934
+ const candidate = `[${r.label}_${next}]`;
935
+ if (!(candidate in session.map) && !existingTokens?.has(candidate)) {
936
+ token = candidate;
937
+ break;
938
+ }
939
+ }
940
+ if (session.tokenByKey.size >= this.maxEntitiesPerSession) {
941
+ const oldestEntry = session.tokenByKey.entries().next().value;
942
+ if (oldestEntry) {
943
+ const [oldestKey, oldestToken] = oldestEntry;
944
+ session.tokenByKey.delete(oldestKey);
945
+ delete session.map[oldestToken];
946
+ const oldLabel = labelFromKey(oldestKey);
947
+ if (oldLabel && session.countsByLabel[oldLabel]) {
948
+ session.countsByLabel[oldLabel] -= 1;
949
+ if (session.countsByLabel[oldLabel] <= 0) delete session.countsByLabel[oldLabel];
950
+ }
951
+ }
952
+ }
953
+ session.counters.set(r.label, next);
954
+ session.tokenByKey.set(key, token);
955
+ session.map[token] = r.value;
956
+ session.countsByLabel[r.label] = (session.countsByLabel[r.label] ?? 0) + 1;
957
+ }
958
+ localMap[token] = r.value;
959
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
960
+ redacted += originalInput.slice(cursor, r.start) + token;
961
+ cursor = r.end;
962
+ }
963
+ redacted += originalInput.slice(cursor);
964
+ return {
965
+ sessionId: session.id,
966
+ redacted,
967
+ counts,
968
+ totalRedactions: result.redactions.length,
969
+ map: localMap
970
+ };
971
+ }
972
+ restore(text, options) {
973
+ const normalizedId = options.sessionId?.trim() || void 0;
974
+ if (options.map && Object.keys(options.map).length > 0) {
975
+ return {
976
+ restored: restore(text, options.map),
977
+ sessionId: normalizedId ?? null,
978
+ knownPlaceholders: Object.keys(options.map).length
979
+ };
980
+ }
981
+ if (!normalizedId) {
982
+ throw new Error("Provide either session_id or map to restore placeholders.");
983
+ }
984
+ const session = this.sessions.get(normalizedId);
985
+ if (!session) {
986
+ throw new Error(`Unknown session_id "${normalizedId}".`);
987
+ }
988
+ return {
989
+ restored: restore(text, session.map),
990
+ sessionId: session.id,
991
+ knownPlaceholders: Object.keys(session.map).length
992
+ };
993
+ }
994
+ getMap(sessionId) {
995
+ const session = this.sessions.get(sessionId.trim());
996
+ return session ? { ...session.map } : {};
997
+ }
998
+ entries() {
999
+ const out = [];
1000
+ for (const s of this.sessions.values()) {
1001
+ for (const [token, value] of Object.entries(s.map)) {
1002
+ out.push({ sessionId: s.id, token, value });
1003
+ }
1004
+ }
1005
+ return out;
1006
+ }
1007
+ clearAll() {
1008
+ this.sessions.clear();
1009
+ }
1010
+ list() {
1011
+ return [...this.sessions.values()].map((s) => ({
1012
+ sessionId: s.id,
1013
+ entityCount: Object.keys(s.map).length,
1014
+ countsByLabel: { ...s.countsByLabel },
1015
+ createdAt: s.createdAt,
1016
+ updatedAt: s.updatedAt
1017
+ }));
1018
+ }
1019
+ clear(sessionId) {
1020
+ return this.sessions.delete(sessionId.trim());
1021
+ }
1022
+ get size() {
1023
+ return this.sessions.size;
1024
+ }
1025
+ };
1026
+
1027
+ // src/server.ts
1028
+ var SERVER_NAME = "maskera-mcp";
1029
+ var SERVER_VERSION = "0.4.0";
1030
+ var SUPPORTED_PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
1031
+ var PLACEHOLDER_QUERY_RE = /^\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]$/;
1032
+ var COUNTS_SCHEMA = {
1033
+ type: "object",
1034
+ additionalProperties: { type: "integer" }
1035
+ };
1036
+ var TOOLS = [
1037
+ {
1038
+ name: "maskera_redact",
1039
+ 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.",
1040
+ annotations: {
1041
+ title: "Redact Swedish PII locally",
1042
+ readOnlyHint: true,
1043
+ destructiveHint: false,
1044
+ idempotentHint: false,
1045
+ openWorldHint: false
1046
+ },
1047
+ inputSchema: {
1048
+ type: "object",
1049
+ properties: {
1050
+ text: { type: "string", description: "Text to redact locally." },
1051
+ session_id: {
1052
+ type: "string",
1053
+ description: "Optional session ID to reuse consistent placeholder numbering across calls."
1054
+ },
1055
+ mode: {
1056
+ type: "string",
1057
+ enum: ["auto", "rules"],
1058
+ description: '"auto" (default) runs hybrid Swedish NER + rules; "rules" runs fast deterministic rules only.'
1059
+ },
1060
+ profile: {
1061
+ type: "string",
1062
+ enum: ["general", "clinical"],
1063
+ description: 'Optional built-in precision profile (default "general").'
1064
+ },
1065
+ custom_terms: {
1066
+ type: "array",
1067
+ items: { type: "string" },
1068
+ description: "Optional extra protected words (client names, case IDs, codenames)."
1069
+ },
1070
+ include_map: {
1071
+ type: "boolean",
1072
+ description: "Set true only when the caller explicitly needs the raw placeholder->value map returned. Default false (recommended so raw PII stays local)."
1073
+ }
1074
+ },
1075
+ required: ["text"]
1076
+ },
1077
+ outputSchema: {
1078
+ type: "object",
1079
+ properties: {
1080
+ redacted: { type: "string" },
1081
+ session_id: { type: "string" },
1082
+ counts: COUNTS_SCHEMA,
1083
+ total_redactions: { type: "integer" },
1084
+ mode: { type: "string", enum: ["hybrid", "rules"] },
1085
+ map: { type: "object", additionalProperties: { type: "string" } },
1086
+ status: { type: "string" },
1087
+ request_id: { type: "string" },
1088
+ approval_url: { type: "string" }
1089
+ }
1090
+ }
1091
+ },
1092
+ {
1093
+ name: "maskera_restore",
1094
+ description: "Restore Maskera placeholders (e.g. [NAMN_1], [PERSONNUMMER_1]) in text using a locally stored session_id or an explicit map.",
1095
+ annotations: {
1096
+ title: "Restore Maskera placeholders",
1097
+ readOnlyHint: true,
1098
+ destructiveHint: false,
1099
+ idempotentHint: true,
1100
+ openWorldHint: false
1101
+ },
1102
+ inputSchema: {
1103
+ type: "object",
1104
+ properties: {
1105
+ text: { type: "string", description: "Text containing Maskera placeholders." },
1106
+ session_id: {
1107
+ type: "string",
1108
+ description: "Session ID returned by maskera_redact or maskera_read_file."
1109
+ },
1110
+ map: {
1111
+ type: "object",
1112
+ additionalProperties: { type: "string" },
1113
+ description: "Optional explicit placeholder -> original value map."
1114
+ }
1115
+ },
1116
+ required: ["text"]
1117
+ },
1118
+ outputSchema: {
1119
+ type: "object",
1120
+ properties: {
1121
+ restored: { type: "string" },
1122
+ session_id: { type: ["string", "null"] },
1123
+ known_placeholders: { type: "integer" },
1124
+ status: { type: "string" },
1125
+ request_id: { type: "string" },
1126
+ approval_url: { type: "string" }
1127
+ }
1128
+ }
1129
+ },
1130
+ {
1131
+ name: "maskera_read_file",
1132
+ 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.",
1133
+ annotations: {
1134
+ title: "Read local file with PII redaction",
1135
+ readOnlyHint: true,
1136
+ destructiveHint: false,
1137
+ idempotentHint: false,
1138
+ openWorldHint: false
1139
+ },
1140
+ inputSchema: {
1141
+ type: "object",
1142
+ properties: {
1143
+ path: {
1144
+ type: "string",
1145
+ description: "Path to a UTF-8 file inside the allowed workspace roots."
1146
+ },
1147
+ session_id: {
1148
+ type: "string",
1149
+ description: "Optional session ID to share placeholder numbering across multiple files."
1150
+ },
1151
+ mode: {
1152
+ type: "string",
1153
+ enum: ["auto", "rules"],
1154
+ description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
1155
+ },
1156
+ profile: {
1157
+ type: "string",
1158
+ enum: ["general", "clinical"],
1159
+ description: 'Optional built-in precision profile (default "general").'
1160
+ },
1161
+ custom_terms: {
1162
+ type: "array",
1163
+ items: { type: "string" },
1164
+ description: "Optional extra protected words (client names, project codenames)."
1165
+ }
1166
+ },
1167
+ required: ["path"]
1168
+ },
1169
+ outputSchema: {
1170
+ type: "object",
1171
+ properties: {
1172
+ path: { type: "string" },
1173
+ bytes: { type: "integer" },
1174
+ redacted: { type: "string" },
1175
+ session_id: { type: "string" },
1176
+ counts: COUNTS_SCHEMA,
1177
+ total_redactions: { type: "integer" },
1178
+ mode: { type: "string", enum: ["hybrid", "rules"] }
1179
+ },
1180
+ required: ["path", "bytes", "redacted", "session_id", "counts", "total_redactions", "mode"]
1181
+ }
1182
+ },
1183
+ {
1184
+ name: "maskera_write_file",
1185
+ 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.",
1186
+ annotations: {
1187
+ title: "Restore placeholders and write local file",
1188
+ readOnlyHint: false,
1189
+ destructiveHint: false,
1190
+ idempotentHint: false,
1191
+ openWorldHint: false
1192
+ },
1193
+ inputSchema: {
1194
+ type: "object",
1195
+ properties: {
1196
+ path: {
1197
+ type: "string",
1198
+ description: "Destination path inside the allowed workspace roots."
1199
+ },
1200
+ text: {
1201
+ type: "string",
1202
+ description: "Draft text containing Maskera placeholders to restore before writing."
1203
+ },
1204
+ session_id: {
1205
+ type: "string",
1206
+ description: "Session ID containing the local restore map."
1207
+ },
1208
+ overwrite: {
1209
+ type: "boolean",
1210
+ description: "Allow overwriting an existing file. Default false."
1211
+ }
1212
+ },
1213
+ required: ["path", "text", "session_id"]
1214
+ },
1215
+ outputSchema: {
1216
+ type: "object",
1217
+ properties: {
1218
+ path: { type: "string" },
1219
+ bytes: { type: "integer" },
1220
+ session_id: { type: "string" },
1221
+ known_placeholders: { type: "integer" }
1222
+ },
1223
+ required: ["path", "bytes", "session_id", "known_placeholders"]
1224
+ }
1225
+ },
1226
+ {
1227
+ name: "maskera_list_files",
1228
+ description: "List regular files inside the allowed workspace roots without reading file contents. Use this before maskera_read_file or maskera_search_files.",
1229
+ annotations: {
1230
+ title: "List files inside allowed roots",
1231
+ readOnlyHint: true,
1232
+ destructiveHint: false,
1233
+ idempotentHint: true,
1234
+ openWorldHint: false
1235
+ },
1236
+ inputSchema: {
1237
+ type: "object",
1238
+ properties: {
1239
+ path: {
1240
+ type: "string",
1241
+ description: "Optional subdirectory inside the allowed workspace roots."
1242
+ },
1243
+ max_entries: {
1244
+ type: "integer",
1245
+ description: "Maximum files to return (default 200, max 1000)."
1246
+ },
1247
+ max_depth: {
1248
+ type: "integer",
1249
+ description: "Maximum directory depth (default 6, max 12)."
1250
+ }
1251
+ }
1252
+ },
1253
+ outputSchema: {
1254
+ type: "object",
1255
+ properties: {
1256
+ root: { type: "string" },
1257
+ files: {
1258
+ type: "array",
1259
+ items: {
1260
+ type: "object",
1261
+ properties: {
1262
+ path: { type: "string" },
1263
+ bytes: { type: "integer" }
1264
+ },
1265
+ required: ["path", "bytes"]
1266
+ }
1267
+ },
1268
+ truncated: { type: "boolean" }
1269
+ },
1270
+ required: ["root", "files", "truncated"]
1271
+ }
1272
+ },
1273
+ {
1274
+ name: "maskera_search_files",
1275
+ description: "Search UTF-8 text files inside the allowed workspace roots and redact Swedish PII in every matched line BEFORE returning results. Accepts either a normal search term or a known placeholder from session_id (e.g. [NAMN_1]).",
1276
+ annotations: {
1277
+ title: "Search local files with PII redaction",
1278
+ readOnlyHint: true,
1279
+ destructiveHint: false,
1280
+ idempotentHint: false,
1281
+ openWorldHint: false
1282
+ },
1283
+ inputSchema: {
1284
+ type: "object",
1285
+ properties: {
1286
+ query: {
1287
+ type: "string",
1288
+ description: "Text or session placeholder (e.g. [NAMN_1]) to search for."
1289
+ },
1290
+ path: {
1291
+ type: "string",
1292
+ description: "Optional subdirectory inside the allowed workspace roots."
1293
+ },
1294
+ session_id: {
1295
+ type: "string",
1296
+ description: "Optional session ID for consistent placeholders across matches."
1297
+ },
1298
+ case_sensitive: {
1299
+ type: "boolean",
1300
+ description: "Case-sensitive search. Default false."
1301
+ },
1302
+ max_matches: {
1303
+ type: "integer",
1304
+ description: "Maximum matched lines to return (default 50, max 200)."
1305
+ },
1306
+ mode: {
1307
+ type: "string",
1308
+ enum: ["auto", "rules"],
1309
+ description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
1310
+ },
1311
+ profile: {
1312
+ type: "string",
1313
+ enum: ["general", "clinical"],
1314
+ description: 'Optional built-in precision profile (default "general").'
1315
+ },
1316
+ custom_terms: {
1317
+ type: "array",
1318
+ items: { type: "string" },
1319
+ description: "Optional extra protected words (client names, project codenames)."
1320
+ }
1321
+ },
1322
+ required: ["query"]
1323
+ },
1324
+ outputSchema: {
1325
+ type: "object",
1326
+ properties: {
1327
+ root: { type: "string" },
1328
+ scanned_files: { type: "integer" },
1329
+ session_id: { type: "string" },
1330
+ counts: COUNTS_SCHEMA,
1331
+ total_redactions: { type: "integer" },
1332
+ truncated: { type: "boolean" },
1333
+ matches: {
1334
+ type: "array",
1335
+ items: {
1336
+ type: "object",
1337
+ properties: {
1338
+ path: { type: "string" },
1339
+ line: { type: "integer" },
1340
+ redacted_line: { type: "string" }
1341
+ },
1342
+ required: ["path", "line", "redacted_line"]
1343
+ }
1344
+ }
1345
+ },
1346
+ required: [
1347
+ "root",
1348
+ "scanned_files",
1349
+ "session_id",
1350
+ "counts",
1351
+ "total_redactions",
1352
+ "truncated",
1353
+ "matches"
1354
+ ]
1355
+ }
1356
+ },
1357
+ {
1358
+ name: "maskera_list_sessions",
1359
+ description: "List active local redaction sessions and entity counts (never returns raw PII values).",
1360
+ annotations: {
1361
+ title: "List active Maskera sessions",
1362
+ readOnlyHint: true,
1363
+ destructiveHint: false,
1364
+ idempotentHint: true,
1365
+ openWorldHint: false
1366
+ },
1367
+ inputSchema: { type: "object", properties: {} },
1368
+ outputSchema: {
1369
+ type: "object",
1370
+ properties: {
1371
+ sessions: {
1372
+ type: "array",
1373
+ items: {
1374
+ type: "object",
1375
+ properties: {
1376
+ sessionId: { type: "string" },
1377
+ entityCount: { type: "integer" },
1378
+ countsByLabel: COUNTS_SCHEMA,
1379
+ createdAt: { type: "string" },
1380
+ updatedAt: { type: "string" }
1381
+ },
1382
+ required: ["sessionId", "entityCount", "countsByLabel", "createdAt", "updatedAt"]
1383
+ }
1384
+ }
1385
+ },
1386
+ required: ["sessions"]
1387
+ }
1388
+ },
1389
+ {
1390
+ name: "maskera_clear_session",
1391
+ description: "Erase a session's local in-memory restore map immediately.",
1392
+ annotations: {
1393
+ title: "Clear Maskera session vault",
1394
+ readOnlyHint: false,
1395
+ destructiveHint: true,
1396
+ idempotentHint: true,
1397
+ openWorldHint: false
1398
+ },
1399
+ inputSchema: {
1400
+ type: "object",
1401
+ properties: {
1402
+ session_id: { type: "string", description: "Session ID to erase." }
1403
+ },
1404
+ required: ["session_id"]
1405
+ },
1406
+ outputSchema: {
1407
+ type: "object",
1408
+ properties: {
1409
+ session_id: { type: "string" },
1410
+ cleared: { type: "boolean" }
1411
+ },
1412
+ required: ["session_id", "cleared"]
1413
+ }
1414
+ },
1415
+ {
1416
+ name: "maskera_status",
1417
+ description: "Report local Maskera MCP server status: model pin, readiness, active sessions, policy, and allowed file roots.",
1418
+ annotations: {
1419
+ title: "Maskera MCP server status",
1420
+ readOnlyHint: true,
1421
+ destructiveHint: false,
1422
+ idempotentHint: true,
1423
+ openWorldHint: false
1424
+ },
1425
+ inputSchema: { type: "object", properties: {} },
1426
+ outputSchema: {
1427
+ type: "object",
1428
+ properties: {
1429
+ server: { type: "string" },
1430
+ version: { type: "string" },
1431
+ engine: { type: "object" },
1432
+ active_sessions: { type: "integer" },
1433
+ allowed_roots: { type: "array", items: { type: "string" } },
1434
+ policy: {
1435
+ type: "object",
1436
+ properties: {
1437
+ read_only: { type: "boolean" },
1438
+ allow_raw_restore: { type: "boolean" },
1439
+ approval_mode: { type: "string", enum: ["automatic", "browser", "native"] }
1440
+ },
1441
+ required: ["read_only", "allow_raw_restore", "approval_mode"]
1442
+ }
1443
+ },
1444
+ required: ["server", "version", "engine", "active_sessions", "allowed_roots", "policy"]
1445
+ }
1446
+ },
1447
+ {
1448
+ name: "maskera_resume",
1449
+ description: "Resume a paused Maskera approval request after the user approves or declines it in the local browser inspector.",
1450
+ annotations: {
1451
+ title: "Resume pending Maskera approval",
1452
+ readOnlyHint: true,
1453
+ destructiveHint: false,
1454
+ idempotentHint: false,
1455
+ openWorldHint: false
1456
+ },
1457
+ inputSchema: {
1458
+ type: "object",
1459
+ properties: {
1460
+ request_id: {
1461
+ type: "string",
1462
+ description: "Approval request_id returned by a paused tool call."
1463
+ }
1464
+ },
1465
+ required: ["request_id"]
1466
+ },
1467
+ outputSchema: {
1468
+ type: "object",
1469
+ properties: {
1470
+ status: { type: "string" },
1471
+ request_id: { type: "string" }
1472
+ },
1473
+ required: ["status", "request_id"]
1474
+ }
1475
+ }
1476
+ ];
1477
+ var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_clear_session"]);
1478
+ function asObject(value) {
1479
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1480
+ }
1481
+ function asMode(value) {
1482
+ if (value === void 0) return void 0;
1483
+ if (value === "auto" || value === "rules") return value;
1484
+ throw new Error('Invalid mode: expected "auto" or "rules".');
1485
+ }
1486
+ function asProfile(value) {
1487
+ if (value === void 0) return void 0;
1488
+ if (value === "general" || value === "clinical") return value;
1489
+ throw new Error('Invalid profile: expected "general" or "clinical".');
1490
+ }
1491
+ function asStringArray(value) {
1492
+ if (value === void 0) return void 0;
1493
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
1494
+ throw new Error("custom_terms must be an array of strings.");
1495
+ }
1496
+ return value;
1497
+ }
1498
+ function asOptionalInt(value) {
1499
+ if (value === void 0) return void 0;
1500
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1501
+ throw new Error("Expected a finite integer.");
1502
+ }
1503
+ return Math.trunc(value);
1504
+ }
1505
+ function toolOk(payload) {
1506
+ return {
1507
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
1508
+ structuredContent: payload
1509
+ };
1510
+ }
1511
+ function toolError(message) {
1512
+ return {
1513
+ isError: true,
1514
+ content: [{ type: "text", text: message }]
1515
+ };
1516
+ }
1517
+ function createMaskeraMcpServer(options = {}) {
1518
+ const engine = options.engine ?? createMaskeraEngine();
1519
+ const vault = options.vault ?? new SessionVault();
1520
+ const files = options.files ?? createFileGuard(options.allowedRoots);
1521
+ const defaultProfile = options.defaultProfile;
1522
+ const defaultCustomTerms = options.defaultCustomTerms;
1523
+ const approvals = options.approvals;
1524
+ const approvalBaseUrl = options.approvalBaseUrl;
1525
+ const requestElicitation = options.requestElicitation;
1526
+ const onToolCall = options.onToolCall;
1527
+ let clientSupportsElicitation = false;
1528
+ function resolvePolicy(override) {
1529
+ return {
1530
+ allowRawRestore: override?.allowRawRestore ?? options.allowRawRestore ?? true,
1531
+ readOnly: override?.readOnly ?? options.readOnly ?? false,
1532
+ approvalMode: override?.approvalMode ?? options.approvalMode ?? "automatic"
1533
+ };
1534
+ }
1535
+ function visibleTools(policy) {
1536
+ return TOOLS.filter((tool) => {
1537
+ if (tool.name === "maskera_resume") {
1538
+ return policy.approvalMode === "browser" && Boolean(approvals);
1539
+ }
1540
+ if (!policy.allowRawRestore && tool.name === "maskera_restore") return false;
1541
+ if (policy.readOnly && WRITE_TOOLS.has(tool.name)) return false;
1542
+ return true;
1543
+ });
1544
+ }
1545
+ function mergeCustomTerms(callTerms) {
1546
+ if (!defaultCustomTerms?.length) return callTerms;
1547
+ if (!callTerms?.length) return defaultCustomTerms;
1548
+ return [...defaultCustomTerms, ...callTerms];
1549
+ }
1550
+ function statusPayload(policy) {
1551
+ return {
1552
+ server: SERVER_NAME,
1553
+ version: SERVER_VERSION,
1554
+ engine: engine.status(),
1555
+ active_sessions: vault.size,
1556
+ allowed_roots: files.allowedRoots,
1557
+ policy: {
1558
+ read_only: policy.readOnly,
1559
+ allow_raw_restore: policy.allowRawRestore,
1560
+ approval_mode: policy.approvalMode
1561
+ }
1562
+ };
1563
+ }
1564
+ async function gateRawPiiExport(input) {
1565
+ const { policy } = input;
1566
+ if (!policy.allowRawRestore) {
1567
+ return toolError(
1568
+ `Raw PII export is disabled by server policy (--no-raw-restore). Use maskera_write_file to restore directly to disk without exposing raw PII to the model.`
1569
+ );
1570
+ }
1571
+ if (policy.approvalMode === "automatic") {
1572
+ return toolOk(await input.execute());
1573
+ }
1574
+ if (policy.approvalMode === "native") {
1575
+ if (!requestElicitation || !clientSupportsElicitation) {
1576
+ return toolError(
1577
+ `Approval mode "native" requires an MCP client with elicitation support. Reconnect with approval_mode=browser or write restored output directly via maskera_write_file.`
1578
+ );
1579
+ }
1580
+ const response = await requestElicitation({
1581
+ message: `${input.tool} wants to release ${input.placeholderCount} original Swedish PII value(s) into the model context (${input.reason}). Approve only if you intend to send raw PII to the LLM.`,
1582
+ requestedSchema: {
1583
+ type: "object",
1584
+ properties: {
1585
+ confirm: {
1586
+ type: "boolean",
1587
+ title: "Release raw PII into model context",
1588
+ default: false
1589
+ }
1590
+ },
1591
+ required: ["confirm"]
1592
+ }
1593
+ });
1594
+ if (response.action !== "accept" || response.content?.confirm !== true) {
1595
+ return toolError(
1596
+ `Raw PII export via ${input.tool} was declined. Use maskera_write_file to restore directly to disk instead.`
1597
+ );
1598
+ }
1599
+ return toolOk(await input.execute());
1600
+ }
1601
+ if (!approvals) {
1602
+ return toolError(
1603
+ `Approval mode "browser" requires the local HTTP inspector/approval server (start "maskera-mcp proxy" and connect to /mcp?approval_mode=browser).`
1604
+ );
1605
+ }
1606
+ const summary = approvals.create({
1607
+ tool: input.tool,
1608
+ reason: input.reason,
1609
+ sessionId: input.sessionId,
1610
+ placeholderCount: input.placeholderCount,
1611
+ execute: input.execute
1612
+ });
1613
+ const approvalUrl = approvalBaseUrl ? `${approvalBaseUrl.replace(/\/$/, "")}/_maskera#approval-${summary.id}` : "/_maskera";
1614
+ return toolOk({
1615
+ status: "approval_required",
1616
+ request_id: summary.id,
1617
+ approval_url: approvalUrl,
1618
+ tool: summary.tool,
1619
+ placeholder_count: summary.placeholderCount,
1620
+ message: `Open ${approvalUrl} to approve or decline releasing raw PII, then call maskera_resume with request_id="${summary.id}".`
1621
+ });
1622
+ }
1623
+ async function callTool(name, rawArgs, policy) {
1624
+ const startedAt = Date.now();
1625
+ const args = asObject(rawArgs);
1626
+ let telemetrySessionId;
1627
+ let telemetryRedactions = 0;
1628
+ let telemetryCounts = {};
1629
+ const finish = (result) => {
1630
+ onToolCall?.({
1631
+ tool: name,
1632
+ sessionId: telemetrySessionId,
1633
+ redactions: telemetryRedactions,
1634
+ counts: telemetryCounts,
1635
+ durationMs: Date.now() - startedAt,
1636
+ isError: "isError" in result && result.isError === true
1637
+ });
1638
+ return result;
1639
+ };
1640
+ try {
1641
+ if (policy.readOnly && WRITE_TOOLS.has(name)) {
1642
+ return finish(toolError(`Tool "${name}" is disabled in read-only mode (--read-only).`));
1643
+ }
1644
+ if (name === "maskera_redact") {
1645
+ if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1646
+ const wantsMap = args.include_map === true;
1647
+ if (wantsMap && !policy.allowRawRestore) {
1648
+ return finish(
1649
+ toolError(
1650
+ "include_map=true is disabled by server policy (--no-raw-restore). Omit include_map and use session_id with maskera_write_file instead."
1651
+ )
1652
+ );
1653
+ }
1654
+ const { result, modeUsed } = await engine.redact(args.text, {
1655
+ mode: asMode(args.mode),
1656
+ profile: asProfile(args.profile) ?? defaultProfile,
1657
+ customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
1658
+ });
1659
+ const applied = vault.apply(
1660
+ args.text,
1661
+ result,
1662
+ typeof args.session_id === "string" ? args.session_id : void 0
1663
+ );
1664
+ telemetrySessionId = applied.sessionId;
1665
+ telemetryRedactions = applied.totalRedactions;
1666
+ telemetryCounts = applied.counts;
1667
+ const payload = {
1668
+ redacted: applied.redacted,
1669
+ session_id: applied.sessionId,
1670
+ counts: applied.counts,
1671
+ total_redactions: applied.totalRedactions,
1672
+ mode: modeUsed
1673
+ };
1674
+ if (wantsMap && Object.keys(applied.map).length > 0) {
1675
+ return finish(
1676
+ await gateRawPiiExport({
1677
+ policy,
1678
+ tool: "maskera_redact",
1679
+ reason: "include_map=true requested raw placeholder map",
1680
+ sessionId: applied.sessionId,
1681
+ placeholderCount: Object.keys(applied.map).length,
1682
+ execute: async () => ({ ...payload, map: applied.map })
1683
+ })
1684
+ );
1685
+ }
1686
+ if (wantsMap) payload.map = applied.map;
1687
+ return finish(toolOk(payload));
1688
+ }
1689
+ if (name === "maskera_restore") {
1690
+ if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1691
+ const explicitMap = args.map && typeof args.map === "object" && !Array.isArray(args.map) ? Object.fromEntries(
1692
+ Object.entries(args.map).filter(
1693
+ (entry) => typeof entry[1] === "string"
1694
+ )
1695
+ ) : void 0;
1696
+ const sessionIdArg = typeof args.session_id === "string" ? args.session_id.trim() : void 0;
1697
+ telemetrySessionId = sessionIdArg;
1698
+ const preview = vault.restore(args.text, {
1699
+ sessionId: sessionIdArg,
1700
+ map: explicitMap
1701
+ });
1702
+ return finish(
1703
+ await gateRawPiiExport({
1704
+ policy,
1705
+ tool: "maskera_restore",
1706
+ reason: "restore placeholders into model context",
1707
+ sessionId: preview.sessionId,
1708
+ placeholderCount: preview.knownPlaceholders,
1709
+ execute: async () => ({
1710
+ restored: preview.restored,
1711
+ session_id: preview.sessionId,
1712
+ known_placeholders: preview.knownPlaceholders
1713
+ })
1714
+ })
1715
+ );
1716
+ }
1717
+ if (name === "maskera_resume") {
1718
+ if (policy.approvalMode !== "browser" || !approvals) {
1719
+ return finish(toolError("maskera_resume is only available in browser approval mode."));
1720
+ }
1721
+ if (typeof args.request_id !== "string" || !args.request_id.trim()) {
1722
+ return finish(toolError("Missing required non-empty string: request_id"));
1723
+ }
1724
+ const requestId = args.request_id.trim();
1725
+ const resumed = await approvals.resume(requestId);
1726
+ if (resumed.status === "not_found") {
1727
+ return finish(toolError(`Unknown approval request_id "${requestId}".`));
1728
+ }
1729
+ if (resumed.status === "completed") {
1730
+ return finish(
1731
+ toolOk({
1732
+ status: "completed",
1733
+ request_id: requestId,
1734
+ ...resumed.result
1735
+ })
1736
+ );
1737
+ }
1738
+ return finish(
1739
+ toolOk({
1740
+ status: resumed.status,
1741
+ request_id: requestId
1742
+ })
1743
+ );
1744
+ }
1745
+ if (name === "maskera_read_file") {
1746
+ if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1747
+ const file = await files.readText(args.path);
1748
+ const { result, modeUsed } = await engine.redact(file.content, {
1749
+ mode: asMode(args.mode),
1750
+ profile: asProfile(args.profile) ?? defaultProfile,
1751
+ customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
1752
+ });
1753
+ const applied = vault.apply(
1754
+ file.content,
1755
+ result,
1756
+ typeof args.session_id === "string" ? args.session_id : void 0
1757
+ );
1758
+ telemetrySessionId = applied.sessionId;
1759
+ telemetryRedactions = applied.totalRedactions;
1760
+ telemetryCounts = applied.counts;
1761
+ return finish(
1762
+ toolOk({
1763
+ path: file.resolvedPath,
1764
+ bytes: file.bytes,
1765
+ redacted: applied.redacted,
1766
+ session_id: applied.sessionId,
1767
+ counts: applied.counts,
1768
+ total_redactions: applied.totalRedactions,
1769
+ mode: modeUsed
1770
+ })
1771
+ );
1772
+ }
1773
+ if (name === "maskera_write_file") {
1774
+ if (typeof args.path !== "string") return finish(toolError("Missing required string: path"));
1775
+ if (typeof args.text !== "string") return finish(toolError("Missing required string: text"));
1776
+ if (typeof args.session_id !== "string" || !args.session_id.trim()) {
1777
+ return finish(toolError("Missing required non-empty string: session_id"));
1778
+ }
1779
+ const normalizedSessionId = args.session_id.trim();
1780
+ telemetrySessionId = normalizedSessionId;
1781
+ const { restored, knownPlaceholders } = vault.restore(args.text, {
1782
+ sessionId: normalizedSessionId
1783
+ });
1784
+ const written = await files.writeText(args.path, restored, {
1785
+ overwrite: args.overwrite === true
1786
+ });
1787
+ return finish(
1788
+ toolOk({
1789
+ path: written.resolvedPath,
1790
+ bytes: written.bytes,
1791
+ session_id: normalizedSessionId,
1792
+ known_placeholders: knownPlaceholders
1793
+ })
1794
+ );
1795
+ }
1796
+ if (name === "maskera_list_files") {
1797
+ const listed = await files.listFiles(
1798
+ typeof args.path === "string" ? args.path : void 0,
1799
+ {
1800
+ maxEntries: asOptionalInt(args.max_entries),
1801
+ maxDepth: asOptionalInt(args.max_depth)
1802
+ }
1803
+ );
1804
+ return finish(
1805
+ toolOk({
1806
+ root: listed.root,
1807
+ files: listed.files,
1808
+ truncated: listed.truncated
1809
+ })
1810
+ );
1811
+ }
1812
+ if (name === "maskera_search_files") {
1813
+ if (typeof args.query !== "string" || !args.query.trim()) {
1814
+ return finish(toolError("Missing required non-empty string: query"));
1815
+ }
1816
+ const requestedSession = typeof args.session_id === "string" && args.session_id.trim() ? args.session_id.trim() : void 0;
1817
+ let resolvedQuery = args.query.trim();
1818
+ if (requestedSession && PLACEHOLDER_QUERY_RE.test(resolvedQuery)) {
1819
+ const map = vault.getMap(requestedSession);
1820
+ const mapped = map[resolvedQuery];
1821
+ if (mapped) {
1822
+ resolvedQuery = mapped;
1823
+ }
1824
+ }
1825
+ const search = await files.searchFiles(resolvedQuery, {
1826
+ path: typeof args.path === "string" ? args.path : void 0,
1827
+ caseSensitive: args.case_sensitive === true,
1828
+ maxMatches: asOptionalInt(args.max_matches)
1829
+ });
1830
+ const mode = asMode(args.mode);
1831
+ const profile = asProfile(args.profile) ?? defaultProfile;
1832
+ const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
1833
+ let activeSessionId = requestedSession;
1834
+ const totalCounts = {};
1835
+ let totalRedactions = 0;
1836
+ const redactedMatches = [];
1837
+ for (const match of search.matches) {
1838
+ const { result } = await engine.redact(match.lineText, {
1839
+ mode,
1840
+ profile,
1841
+ customTerms
1842
+ });
1843
+ const applied = vault.apply(match.lineText, result, activeSessionId);
1844
+ activeSessionId = applied.sessionId;
1845
+ totalRedactions += applied.totalRedactions;
1846
+ for (const [label, count] of Object.entries(applied.counts)) {
1847
+ totalCounts[label] = (totalCounts[label] ?? 0) + count;
1848
+ }
1849
+ redactedMatches.push({
1850
+ path: match.path,
1851
+ line: match.line,
1852
+ redacted_line: applied.redacted
1853
+ });
1854
+ }
1855
+ const ensuredSessionId = activeSessionId ?? vault.apply(
1856
+ "",
1857
+ { text: "", map: {}, redactions: [], restore: (s) => s },
1858
+ requestedSession
1859
+ ).sessionId;
1860
+ telemetrySessionId = ensuredSessionId;
1861
+ telemetryRedactions = totalRedactions;
1862
+ telemetryCounts = totalCounts;
1863
+ return finish(
1864
+ toolOk({
1865
+ root: search.root,
1866
+ scanned_files: search.scannedFiles,
1867
+ session_id: ensuredSessionId,
1868
+ counts: totalCounts,
1869
+ total_redactions: totalRedactions,
1870
+ truncated: search.truncated,
1871
+ matches: redactedMatches
1872
+ })
1873
+ );
1874
+ }
1875
+ if (name === "maskera_list_sessions") {
1876
+ return finish(toolOk({ sessions: vault.list() }));
1877
+ }
1878
+ if (name === "maskera_clear_session") {
1879
+ if (typeof args.session_id !== "string" || !args.session_id.trim()) {
1880
+ return finish(toolError("Missing required non-empty string: session_id"));
1881
+ }
1882
+ const normalizedSessionId = args.session_id.trim();
1883
+ telemetrySessionId = normalizedSessionId;
1884
+ return finish(
1885
+ toolOk({
1886
+ session_id: normalizedSessionId,
1887
+ cleared: vault.clear(normalizedSessionId)
1888
+ })
1889
+ );
1890
+ }
1891
+ if (name === "maskera_status") {
1892
+ return finish(toolOk(statusPayload(policy)));
1893
+ }
1894
+ return finish(toolError(`Unknown tool "${name}".`));
1895
+ } catch (err) {
1896
+ return finish(toolError(err instanceof Error ? err.message : String(err)));
1897
+ }
1898
+ }
1899
+ return {
1900
+ vault,
1901
+ async handleMessage(raw, policyOverride) {
1902
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1903
+ return {
1904
+ jsonrpc: "2.0",
1905
+ id: null,
1906
+ error: { code: -32600, message: "Invalid Request" }
1907
+ };
1908
+ }
1909
+ const req = raw;
1910
+ const hasIdProp = Object.prototype.hasOwnProperty.call(req, "id");
1911
+ const validId = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
1912
+ if (req.jsonrpc !== "2.0" || typeof req.method !== "string" || hasIdProp && validId === void 0) {
1913
+ return {
1914
+ jsonrpc: "2.0",
1915
+ id: validId ?? null,
1916
+ error: { code: -32600, message: "Invalid Request" }
1917
+ };
1918
+ }
1919
+ const id = validId;
1920
+ if (id === void 0) {
1921
+ return null;
1922
+ }
1923
+ const policy = resolvePolicy(policyOverride);
1924
+ if (req.method === "initialize") {
1925
+ const params = asObject(req.params);
1926
+ const clientCaps = asObject(params.capabilities);
1927
+ if ("elicitation" in clientCaps && clientCaps.elicitation) {
1928
+ clientSupportsElicitation = true;
1929
+ }
1930
+ const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
1931
+ const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
1932
+ return {
1933
+ jsonrpc: "2.0",
1934
+ id,
1935
+ result: {
1936
+ protocolVersion,
1937
+ capabilities: {
1938
+ tools: { listChanged: false },
1939
+ prompts: { listChanged: false },
1940
+ resources: { subscribe: false, listChanged: false }
1941
+ },
1942
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
1943
+ instructions: [
1944
+ "Maskera redacts Swedish personal data locally on-device.",
1945
+ "Use maskera_list_files and maskera_search_files to explore sensitive folders without leaking raw PII via grep.",
1946
+ "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.",
1947
+ 'Pass profile="clinical" for Swedish healthcare text and custom_terms for client codenames.',
1948
+ `Read resource ${MASKERA_SKILL_URI} or prompt "maskera-workflow" for the full operating guide.`
1949
+ ].join(" ")
1950
+ }
1951
+ };
1952
+ }
1953
+ if (req.method === "ping") {
1954
+ return { jsonrpc: "2.0", id, result: {} };
1955
+ }
1956
+ if (req.method === "tools/list") {
1957
+ return { jsonrpc: "2.0", id, result: { tools: visibleTools(policy) } };
1958
+ }
1959
+ if (req.method === "tools/call") {
1960
+ const params = asObject(req.params);
1961
+ if (typeof params.name !== "string") {
1962
+ return {
1963
+ jsonrpc: "2.0",
1964
+ id,
1965
+ error: { code: -32602, message: "Invalid params: missing tool name" }
1966
+ };
1967
+ }
1968
+ const result = await callTool(params.name, params.arguments, policy);
1969
+ return { jsonrpc: "2.0", id, result };
1970
+ }
1971
+ if (req.method === "prompts/list") {
1972
+ return { jsonrpc: "2.0", id, result: { prompts: MASKERA_PROMPTS } };
1973
+ }
1974
+ if (req.method === "prompts/get") {
1975
+ const params = asObject(req.params);
1976
+ if (typeof params.name !== "string") {
1977
+ return {
1978
+ jsonrpc: "2.0",
1979
+ id,
1980
+ error: { code: -32602, message: "Invalid params: missing prompt name" }
1981
+ };
1982
+ }
1983
+ const rendered = renderMaskeraPrompt(params.name, asObject(params.arguments));
1984
+ if (!rendered) {
1985
+ return {
1986
+ jsonrpc: "2.0",
1987
+ id,
1988
+ error: { code: -32602, message: `Unknown prompt "${params.name}".` }
1989
+ };
1990
+ }
1991
+ return { jsonrpc: "2.0", id, result: rendered };
1992
+ }
1993
+ if (req.method === "resources/list") {
1994
+ return {
1995
+ jsonrpc: "2.0",
1996
+ id,
1997
+ result: {
1998
+ resources: [
1999
+ {
2000
+ uri: MASKERA_SKILL_URI,
2001
+ name: "maskera-skill",
2002
+ title: "Maskera agent workflow skill",
2003
+ description: "Complete local Swedish PII redaction operating guide for AI agents (proxy, MCP tools, guard, clinical profile).",
2004
+ mimeType: "text/markdown"
2005
+ },
2006
+ {
2007
+ uri: MASKERA_STATUS_URI,
2008
+ name: "maskera-status",
2009
+ title: "Maskera MCP server status",
2010
+ description: "Live local engine, session count, allowed roots, and policy state.",
2011
+ mimeType: "application/json"
2012
+ }
2013
+ ]
2014
+ }
2015
+ };
2016
+ }
2017
+ if (req.method === "resources/read") {
2018
+ const params = asObject(req.params);
2019
+ if (typeof params.uri !== "string") {
2020
+ return {
2021
+ jsonrpc: "2.0",
2022
+ id,
2023
+ error: { code: -32602, message: "Invalid params: missing resource uri" }
2024
+ };
2025
+ }
2026
+ if (params.uri === MASKERA_SKILL_URI) {
2027
+ return {
2028
+ jsonrpc: "2.0",
2029
+ id,
2030
+ result: {
2031
+ contents: [
2032
+ {
2033
+ uri: MASKERA_SKILL_URI,
2034
+ mimeType: "text/markdown",
2035
+ text: MASKERA_SKILL_MARKDOWN
2036
+ }
2037
+ ]
2038
+ }
2039
+ };
2040
+ }
2041
+ if (params.uri === MASKERA_STATUS_URI) {
2042
+ return {
2043
+ jsonrpc: "2.0",
2044
+ id,
2045
+ result: {
2046
+ contents: [
2047
+ {
2048
+ uri: MASKERA_STATUS_URI,
2049
+ mimeType: "application/json",
2050
+ text: JSON.stringify(statusPayload(policy), null, 2)
2051
+ }
2052
+ ]
2053
+ }
2054
+ };
2055
+ }
2056
+ return {
2057
+ jsonrpc: "2.0",
2058
+ id,
2059
+ error: { code: -32002, message: `Resource not found: ${params.uri}` }
2060
+ };
2061
+ }
2062
+ return {
2063
+ jsonrpc: "2.0",
2064
+ id,
2065
+ error: { code: -32601, message: `Method not found: ${req.method}` }
2066
+ };
2067
+ }
2068
+ };
2069
+ }
2070
+
2071
+ // src/doctor.ts
2072
+ var SYNTHETIC_SAMPLE = "Kontakta Anna Lindqvist (19900101-2385) p\xE5 provnamn.maskera@example.com eller 070-174 06 58.";
2073
+ var SYNTHETIC_SECRETS = [
2074
+ "19900101-2385",
2075
+ "provnamn.maskera@example.com",
2076
+ "070-174 06 58"
2077
+ ];
2078
+ async function probeLiveHttpMcp(mcpUrl) {
2079
+ const startedAt = Date.now();
2080
+ try {
2081
+ const initRes = await fetch(mcpUrl, {
2082
+ method: "POST",
2083
+ headers: { "content-type": "application/json" },
2084
+ body: JSON.stringify({
2085
+ jsonrpc: "2.0",
2086
+ id: 1,
2087
+ method: "initialize",
2088
+ params: { protocolVersion: "2025-11-25" }
2089
+ }),
2090
+ signal: AbortSignal.timeout(1500)
2091
+ });
2092
+ if (!initRes.ok) {
2093
+ return {
2094
+ name: "mcp-http",
2095
+ status: "fail",
2096
+ detail: `${mcpUrl} initialize returned HTTP ${initRes.status}`
2097
+ };
2098
+ }
2099
+ const sessionId = initRes.headers.get("mcp-session-id");
2100
+ const callHeaders = { "content-type": "application/json" };
2101
+ if (sessionId) callHeaders["mcp-session-id"] = sessionId;
2102
+ const redactRes = await fetch(mcpUrl, {
2103
+ method: "POST",
2104
+ headers: callHeaders,
2105
+ body: JSON.stringify({
2106
+ jsonrpc: "2.0",
2107
+ id: 2,
2108
+ method: "tools/call",
2109
+ params: {
2110
+ name: "maskera_redact",
2111
+ arguments: {
2112
+ text: "Test provnamn.maskera@example.com 19900101-2385",
2113
+ session_id: "doctor-http-probe"
2114
+ }
2115
+ }
2116
+ }),
2117
+ signal: AbortSignal.timeout(5e3)
2118
+ });
2119
+ const bodyText = await redactRes.text();
2120
+ if (sessionId) {
2121
+ await fetch(mcpUrl, {
2122
+ method: "DELETE",
2123
+ headers: { "mcp-session-id": sessionId },
2124
+ signal: AbortSignal.timeout(800)
2125
+ }).catch(() => {
2126
+ });
2127
+ }
2128
+ if (!redactRes.ok) {
2129
+ return {
2130
+ name: "mcp-http",
2131
+ status: "fail",
2132
+ detail: `${mcpUrl} tools/call returned HTTP ${redactRes.status}`
2133
+ };
2134
+ }
2135
+ const leaked = bodyText.includes("provnamn.maskera@example.com") || bodyText.includes("19900101-2385");
2136
+ const hasPlaceholders = bodyText.includes("[EPOST_1]") && bodyText.includes("[PERSONNUMMER_1]");
2137
+ if (leaked || !hasPlaceholders) {
2138
+ return {
2139
+ name: "mcp-http",
2140
+ status: "fail",
2141
+ detail: `Live /mcp probe failed (leaked=${leaked}, placeholders=${hasPlaceholders})`
2142
+ };
2143
+ }
2144
+ return {
2145
+ name: "mcp-http",
2146
+ status: "ok",
2147
+ detail: `Live ${mcpUrl} masked synthetic PII (0 leaks, ${Date.now() - startedAt}ms)`
2148
+ };
2149
+ } catch (err) {
2150
+ return {
2151
+ name: "mcp-http",
2152
+ status: "fail",
2153
+ detail: `Live /mcp probe error: ${err instanceof Error ? err.message : String(err)}`
2154
+ };
2155
+ }
2156
+ }
2157
+ async function runDoctor(options) {
2158
+ const checks = [];
2159
+ const mode = options.mode ?? options.engine.status().defaultMode;
2160
+ let sampleProof = null;
2161
+ const major = Number(process.versions.node.split(".")[0] ?? 0);
2162
+ checks.push({
2163
+ name: "node",
2164
+ status: major >= 18 ? "ok" : "fail",
2165
+ detail: `Node ${process.versions.node} (requires >=18)`
2166
+ });
2167
+ for (const rawRoot of options.roots) {
2168
+ const abs = resolve(rawRoot);
2169
+ try {
2170
+ const info = await stat(abs);
2171
+ if (!info.isDirectory()) {
2172
+ checks.push({ name: `root:${abs}`, status: "fail", detail: "Not a directory" });
2173
+ continue;
2174
+ }
2175
+ await access(abs, constants.R_OK);
2176
+ checks.push({ name: `root:${abs}`, status: "ok", detail: "Readable directory" });
2177
+ } catch (err) {
2178
+ checks.push({
2179
+ name: `root:${abs}`,
2180
+ status: "fail",
2181
+ detail: err instanceof Error ? err.message : String(err)
2182
+ });
2183
+ }
2184
+ }
2185
+ const startedAt = Date.now();
2186
+ try {
2187
+ const { result, modeUsed } = await options.engine.redact(SYNTHETIC_SAMPLE, {
2188
+ mode,
2189
+ profile: options.profile,
2190
+ customTerms: options.customTerms
2191
+ });
2192
+ const vault = new SessionVault();
2193
+ const applied = vault.apply(SYNTHETIC_SAMPLE, result, "doctor-check");
2194
+ const restored = vault.restore(applied.redacted, { sessionId: applied.sessionId });
2195
+ const leaks = SYNTHETIC_SECRETS.filter((s) => applied.redacted.includes(s));
2196
+ const roundtripOk = restored.restored === SYNTHETIC_SAMPLE;
2197
+ const elapsedMs = Date.now() - startedAt;
2198
+ sampleProof = {
2199
+ modeUsed,
2200
+ maskedCount: applied.totalRedactions,
2201
+ countsByLabel: applied.counts,
2202
+ redactedPreview: applied.redacted,
2203
+ rawPiiLeaked: leaks.length > 0,
2204
+ roundtripRestored: roundtripOk,
2205
+ elapsedMs
2206
+ };
2207
+ if (leaks.length > 0 || !roundtripOk) {
2208
+ checks.push({
2209
+ name: "redaction",
2210
+ status: "fail",
2211
+ detail: `Self-test failed (leaks=${leaks.length}, roundtrip=${roundtripOk})`
2212
+ });
2213
+ } else {
2214
+ checks.push({
2215
+ name: "redaction",
2216
+ status: "ok",
2217
+ detail: `mode=${modeUsed}, masked=${applied.totalRedactions} items, roundtrip=ok (${elapsedMs}ms)`
2218
+ });
2219
+ }
2220
+ } catch (err) {
2221
+ checks.push({
2222
+ name: "redaction",
2223
+ status: "fail",
2224
+ detail: err instanceof Error ? err.message : String(err)
2225
+ });
2226
+ }
2227
+ let proxyBase = (options.proxyUrl ?? "http://127.0.0.1:8787").replace(/\/$/, "");
2228
+ if (!options.proxyUrl && options.mcpUrl) {
2229
+ try {
2230
+ const parsed = new URL(options.mcpUrl);
2231
+ proxyBase = parsed.origin;
2232
+ } catch {
2233
+ }
2234
+ }
2235
+ let liveMcpUrl = null;
2236
+ try {
2237
+ const res = await fetch(`${proxyBase}/_maskera/status`, {
2238
+ signal: AbortSignal.timeout(800)
2239
+ });
2240
+ if (res.ok) {
2241
+ const data = await res.json();
2242
+ liveMcpUrl = options.mcpUrl ?? data.mcp_url ?? `${proxyBase}/mcp`;
2243
+ checks.push({
2244
+ name: "proxy",
2245
+ status: "ok",
2246
+ detail: `Running at ${proxyBase} (mcp=${liveMcpUrl}, requests=${data.requests_proxied ?? 0}, redacted=${data.total_redactions ?? 0})`
2247
+ });
2248
+ } else {
2249
+ checks.push({
2250
+ name: "proxy",
2251
+ status: "warn",
2252
+ detail: `${proxyBase}/_maskera/status returned HTTP ${res.status}`
2253
+ });
2254
+ }
2255
+ } catch {
2256
+ checks.push({
2257
+ name: "proxy",
2258
+ status: "warn",
2259
+ detail: `Not running on ${proxyBase} (start with "npx -y @maskera/mcp proxy" if needed)`
2260
+ });
2261
+ }
2262
+ if (liveMcpUrl) {
2263
+ checks.push(await probeLiveHttpMcp(liveMcpUrl));
2264
+ }
2265
+ return {
2266
+ schema: "maskera-setup-receipt/v1",
2267
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2268
+ version: SERVER_VERSION,
2269
+ ok: checks.every((c) => c.status !== "fail"),
2270
+ mode,
2271
+ ...options.client ? { client: options.client } : {},
2272
+ ...options.transport ? { transport: options.transport } : {},
2273
+ ...options.configPath !== void 0 ? { configPath: options.configPath } : {},
2274
+ sampleProof,
2275
+ checks
2276
+ };
2277
+ }
2278
+ async function writeDoctorReceipt(filePath, report) {
2279
+ const abs = resolve(filePath);
2280
+ await mkdir(dirname(abs), { recursive: true });
2281
+ await writeFile(abs, `${JSON.stringify(report, null, 2)}
2282
+ `, "utf8");
2283
+ return abs;
2284
+ }
2285
+ function formatDoctorReport(report, heading) {
2286
+ const title = heading ?? `maskera-mcp doctor (${report.ok ? "OK" : "FAILED"}, v${report.version}, mode=${report.mode})`;
2287
+ const lines = [title];
2288
+ for (const check of report.checks) {
2289
+ const tag = check.status === "ok" ? "[ok] " : check.status === "warn" ? "[warn]" : "[fail]";
2290
+ lines.push(` ${tag} ${check.name}: ${check.detail}`);
2291
+ }
2292
+ if (report.sampleProof && !report.sampleProof.rawPiiLeaked) {
2293
+ lines.push(` [ok] proof: "${report.sampleProof.redactedPreview}" (0 leaks, restored=ok)`);
2294
+ }
2295
+ return `${lines.join("\n")}
2296
+ `;
2297
+ }
2298
+
2299
+ // src/guard.ts
2300
+ var HOOK_PAYLOAD_KEYS = [
2301
+ "prompt",
2302
+ "user_prompt",
2303
+ "tool_input",
2304
+ "tool_response",
2305
+ "tool_output",
2306
+ "command",
2307
+ "content",
2308
+ "edits",
2309
+ "attachments"
2310
+ ];
2311
+ var HOOK_META_SKIP_KEYS = /* @__PURE__ */ new Set([
2312
+ "hook_event_name",
2313
+ "tool_name",
2314
+ "permission_mode",
2315
+ "session_id"
2316
+ ]);
2317
+ function collectScalars(value, parts, skipKey) {
2318
+ if (skipKey && HOOK_META_SKIP_KEYS.has(skipKey)) return;
2319
+ if (typeof value === "string") {
2320
+ if (value.trim()) parts.push(value);
2321
+ } else if (typeof value === "number" && Number.isFinite(value)) {
2322
+ parts.push(String(value));
2323
+ } else if (Array.isArray(value)) {
2324
+ for (const item of value) collectScalars(item, parts);
2325
+ } else if (value && typeof value === "object") {
2326
+ for (const [k, v] of Object.entries(value)) collectScalars(v, parts, k);
2327
+ }
2328
+ }
2329
+ function extractGuardText(rawInput) {
2330
+ const trimmed = rawInput.trim();
2331
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
2332
+ try {
2333
+ const parsed = JSON.parse(trimmed);
2334
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
2335
+ const isHookEnvelope = HOOK_PAYLOAD_KEYS.some((key) => key in parsed);
2336
+ if (isHookEnvelope) {
2337
+ const parts = [];
2338
+ collectScalars(parsed, parts);
2339
+ return { text: parts.join("\n"), isHookEnvelope: true };
2340
+ }
2341
+ }
2342
+ } catch {
2343
+ }
2344
+ }
2345
+ return { text: rawInput, isHookEnvelope: false };
2346
+ }
2347
+ async function runGuard(rawInput, engine, options = {}) {
2348
+ const trimmed = rawInput.trim();
2349
+ if (options.preserveJsonStructure && trimmed.startsWith("{") && trimmed.endsWith("}")) {
2350
+ try {
2351
+ const parsed = JSON.parse(trimmed);
2352
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
2353
+ const counts2 = {};
2354
+ let totalRedactions = 0;
2355
+ let modeUsed2 = options.mode === "rules" ? "rules" : "hybrid";
2356
+ const redactJson = async (value, key) => {
2357
+ if (key && HOOK_META_SKIP_KEYS.has(key)) return value;
2358
+ if (typeof value === "string") {
2359
+ if (!value.trim()) return value;
2360
+ const out = await engine.redact(value, {
2361
+ mode: options.mode,
2362
+ profile: options.profile,
2363
+ customTerms: options.customTerms
2364
+ });
2365
+ modeUsed2 = out.modeUsed;
2366
+ totalRedactions += out.result.redactions.length;
2367
+ for (const r of out.result.redactions) {
2368
+ counts2[r.label] = (counts2[r.label] ?? 0) + 1;
2369
+ }
2370
+ return out.result.text;
2371
+ }
2372
+ if (Array.isArray(value)) {
2373
+ const arr = [];
2374
+ for (const item of value) arr.push(await redactJson(item));
2375
+ return arr;
2376
+ }
2377
+ if (value && typeof value === "object") {
2378
+ const obj = {};
2379
+ for (const [k, v] of Object.entries(value)) {
2380
+ obj[k] = await redactJson(v, k);
2381
+ }
2382
+ return obj;
2383
+ }
2384
+ return value;
2385
+ };
2386
+ const redactedObj = await redactJson(parsed);
2387
+ return {
2388
+ blocked: totalRedactions > 0,
2389
+ totalRedactions,
2390
+ counts: counts2,
2391
+ redacted: JSON.stringify(redactedObj),
2392
+ modeUsed: modeUsed2
2393
+ };
2394
+ }
2395
+ } catch {
2396
+ }
2397
+ }
2398
+ const { text } = extractGuardText(rawInput);
2399
+ if (!text.trim()) {
2400
+ return {
2401
+ blocked: false,
2402
+ totalRedactions: 0,
2403
+ counts: {},
2404
+ redacted: text,
2405
+ modeUsed: options.mode === "rules" ? "rules" : "hybrid"
2406
+ };
2407
+ }
2408
+ const { result, modeUsed } = await engine.redact(text, {
2409
+ mode: options.mode,
2410
+ profile: options.profile,
2411
+ customTerms: options.customTerms
2412
+ });
2413
+ const counts = {};
2414
+ for (const r of result.redactions) {
2415
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
2416
+ }
2417
+ return {
2418
+ blocked: result.redactions.length > 0,
2419
+ totalRedactions: result.redactions.length,
2420
+ counts,
2421
+ redacted: result.text,
2422
+ modeUsed
2423
+ };
2424
+ }
2425
+ function isLoopbackUrl(rawUrl) {
2426
+ try {
2427
+ const parsed = new URL(rawUrl);
2428
+ if (parsed.protocol !== "http:") return null;
2429
+ const host = parsed.hostname.toLowerCase();
2430
+ if (host !== "127.0.0.1" && host !== "localhost" && host !== "::1" && host !== "[::1]") {
2431
+ return null;
2432
+ }
2433
+ return parsed.origin;
2434
+ } catch {
2435
+ return null;
2436
+ }
2437
+ }
2438
+ async function runGuardViaWarmProxy(rawInput, options = {}) {
2439
+ const origin = isLoopbackUrl(options.proxyUrl ?? "http://127.0.0.1:8787");
2440
+ if (!origin) return null;
2441
+ let res;
2442
+ try {
2443
+ res = await fetch(`${origin}/_maskera/guard`, {
2444
+ method: "POST",
2445
+ headers: {
2446
+ "content-type": "application/json",
2447
+ "x-maskera-action": "guard"
2448
+ },
2449
+ body: JSON.stringify({
2450
+ raw: rawInput,
2451
+ mode: options.mode,
2452
+ profile: options.profile,
2453
+ customTerms: options.customTerms,
2454
+ preserveJsonStructure: options.preserveJsonStructure,
2455
+ includeRedacted: options.includeRedacted
2456
+ }),
2457
+ signal: AbortSignal.timeout(options.timeoutMs ?? 4e3)
2458
+ });
2459
+ } catch {
2460
+ return null;
2461
+ }
2462
+ if (res.status === 404 || res.status === 405) {
2463
+ return null;
2464
+ }
2465
+ if (!res.ok) {
2466
+ let message = `Warm proxy guard returned HTTP ${res.status}`;
2467
+ try {
2468
+ const errBody = await res.json();
2469
+ if (typeof errBody.error === "string") message = errBody.error;
2470
+ else if (errBody.error?.message) message = errBody.error.message;
2471
+ } catch {
2472
+ }
2473
+ throw new Error(message);
2474
+ }
2475
+ const data = await res.json();
2476
+ if (typeof data.blocked !== "boolean" || typeof data.totalRedactions !== "number" || !data.counts || typeof data.counts !== "object") {
2477
+ return null;
2478
+ }
2479
+ return {
2480
+ blocked: data.blocked,
2481
+ totalRedactions: data.totalRedactions,
2482
+ counts: data.counts,
2483
+ redacted: typeof data.redacted === "string" ? data.redacted : "",
2484
+ modeUsed: data.modeUsed === "rules" ? "rules" : "hybrid"
2485
+ };
2486
+ }
2487
+
2488
+ // src/inspector.ts
2489
+ var MAX_EVENTS = 100;
2490
+ var ProxyInspector = class {
2491
+ constructor() {
2492
+ this.items = [];
2493
+ this.subscribers = /* @__PURE__ */ new Set();
2494
+ this.approvalsSnapshot = [];
2495
+ this.seq = 0;
2496
+ }
2497
+ record(entry) {
2498
+ this.seq += 1;
2499
+ const item = { id: `req_${this.seq}`, ...entry };
2500
+ this.items.unshift(item);
2501
+ if (this.items.length > MAX_EVENTS) this.items.length = MAX_EVENTS;
2502
+ const payload = `event: request
2503
+ data: ${JSON.stringify(item)}
2504
+
2505
+ `;
2506
+ for (const res of [...this.subscribers]) {
2507
+ if (res.writableEnded || res.destroyed) {
2508
+ this.subscribers.delete(res);
2509
+ continue;
2510
+ }
2511
+ res.write(payload);
2512
+ }
2513
+ return item;
2514
+ }
2515
+ publishApprovals(approvals) {
2516
+ this.approvalsSnapshot = approvals;
2517
+ const payload = `event: approvals
2518
+ data: ${JSON.stringify({ approvals })}
2519
+
2520
+ `;
2521
+ for (const res of [...this.subscribers]) {
2522
+ if (res.writableEnded || res.destroyed) {
2523
+ this.subscribers.delete(res);
2524
+ continue;
2525
+ }
2526
+ res.write(payload);
2527
+ }
2528
+ }
2529
+ list() {
2530
+ return this.items;
2531
+ }
2532
+ clear() {
2533
+ this.items.length = 0;
2534
+ this.approvalsSnapshot = [];
2535
+ const payload = `event: cleared
2536
+ data: {}
2537
+
2538
+ `;
2539
+ for (const res of [...this.subscribers]) {
2540
+ if (res.writableEnded || res.destroyed) {
2541
+ this.subscribers.delete(res);
2542
+ continue;
2543
+ }
2544
+ res.write(payload);
2545
+ }
2546
+ }
2547
+ subscribe(res, extraHeaders = {}) {
2548
+ res.writeHead(200, {
2549
+ ...extraHeaders,
2550
+ "content-type": "text/event-stream; charset=utf-8",
549
2551
  "cache-control": "no-cache, no-transform",
550
2552
  connection: "keep-alive"
551
2553
  });
552
- res.write(`event: init
553
- data: ${JSON.stringify({ items: this.items })}
2554
+ res.write(
2555
+ `event: init
2556
+ data: ${JSON.stringify({ items: this.items, approvals: this.approvalsSnapshot })}
554
2557
 
555
- `);
2558
+ `
2559
+ );
556
2560
  this.subscribers.add(res);
557
2561
  res.on("close", () => {
558
2562
  this.subscribers.delete(res);
@@ -570,12 +2574,13 @@ data: ${JSON.stringify({ items: this.items })}
570
2574
  };
571
2575
  function renderInspectorHtml(info) {
572
2576
  const safeUrl = info.url.replace(/[<>&"']/g, "");
2577
+ const safeMcpUrl = (info.mcpUrl ?? `${info.url}/mcp`).replace(/[<>&"']/g, "");
573
2578
  return `<!doctype html>
574
2579
  <html lang="sv">
575
2580
  <head>
576
2581
  <meta charset="utf-8" />
577
2582
  <meta name="viewport" content="width=device-width, initial-scale=1" />
578
- <title>Maskera Proxy Inspector</title>
2583
+ <title>Maskera Proxy & MCP Inspector</title>
579
2584
  <style>
580
2585
  :root {
581
2586
  --bg: #ffffff;
@@ -583,8 +2588,6 @@ function renderInspectorHtml(info) {
583
2588
  --fg: #111113;
584
2589
  --muted: #666670;
585
2590
  --border: #e4e4e7;
586
- --ok: #15803d;
587
- --ok-bg: #f0fdf4;
588
2591
  --err: #b91c1c;
589
2592
  --err-bg: #fef2f2;
590
2593
  --tok-bg: #eff6ff;
@@ -600,8 +2603,6 @@ function renderInspectorHtml(info) {
600
2603
  --fg: #f4f4f5;
601
2604
  --muted: #a1a1aa;
602
2605
  --border: #27272a;
603
- --ok: #4ade80;
604
- --ok-bg: #052e16;
605
2606
  --err: #f87171;
606
2607
  --err-bg: #450a0a;
607
2608
  --tok-bg: #172554;
@@ -629,24 +2630,20 @@ function renderInspectorHtml(info) {
629
2630
  }
630
2631
  h1 { margin: 0; font-size: 18px; font-weight: 650; letter-spacing: -0.02em; }
631
2632
  .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
2633
  .actions { display: flex; gap: 8px; flex-wrap: wrap; }
637
2634
  button {
638
2635
  font-family: var(--sans);
639
2636
  font-weight: 500;
640
2637
  font-size: 12.5px;
641
2638
  padding: 7px 12px;
642
- border-radius: 7px;
2639
+ border-radius: 6px;
643
2640
  border: 1px solid var(--border);
644
2641
  background: var(--bg);
645
2642
  color: var(--fg);
646
2643
  cursor: pointer;
647
2644
  }
648
2645
  button:hover { background: var(--bg-subtle); }
649
- button.active { background: var(--fg); color: var(--bg); border-color: var(--fg); }
2646
+ button.active, button.primary { background: var(--fg); color: var(--bg); border-color: var(--fg); }
650
2647
  .stats {
651
2648
  display: grid;
652
2649
  grid-template-columns: repeat(4, minmax(0, 1fr));
@@ -656,29 +2653,93 @@ function renderInspectorHtml(info) {
656
2653
  @media (max-width: 640px) { .stats { grid-template-columns: repeat(2, 1fr); } }
657
2654
  .stat {
658
2655
  border: 1px solid var(--border);
659
- border-radius: 8px;
2656
+ border-radius: 6px;
660
2657
  padding: 12px 14px;
661
2658
  background: var(--bg-subtle);
662
2659
  }
663
2660
  .stat-k { font-size: 11.5px; color: var(--muted); }
664
2661
  .stat-v { font-size: 20px; font-weight: 650; margin-top: 2px; font-variant-numeric: tabular-nums; }
2662
+ .approvals {
2663
+ margin: 0 0 22px;
2664
+ border: 1px solid var(--border);
2665
+ border-radius: 6px;
2666
+ padding: 14px 16px;
2667
+ background: var(--bg-subtle);
2668
+ }
2669
+ .approvals h2 { margin: 0 0 8px; font-size: 14px; }
2670
+ .approval-row {
2671
+ display: flex;
2672
+ align-items: center;
2673
+ justify-content: space-between;
2674
+ gap: 12px;
2675
+ flex-wrap: wrap;
2676
+ padding: 10px 0;
2677
+ border-top: 1px solid var(--border);
2678
+ font-size: 13px;
2679
+ }
2680
+ .approval-row:first-of-type { border-top: 0; padding-top: 2px; }
2681
+ .approval-meta { color: var(--muted); font-size: 12px; }
665
2682
  .empty {
666
2683
  border: 1px dashed var(--border);
667
- border-radius: 8px;
2684
+ border-radius: 6px;
668
2685
  padding: 28px 20px;
669
2686
  text-align: center;
670
2687
  color: var(--muted);
671
2688
  font-size: 13.5px;
672
2689
  }
673
2690
  .empty code {
674
- display: block; margin: 10px auto 0; max-width: 560px; padding: 10px 12px;
2691
+ display: block; margin: 10px auto 0; max-width: 640px; padding: 10px 12px;
675
2692
  background: var(--bg-subtle); border: 1px solid var(--border); border-radius: 6px;
676
2693
  font: 12px/1.6 var(--mono); color: var(--fg); text-align: left; white-space: pre-wrap;
677
2694
  }
2695
+ .empty-title { margin: 0 0 6px; font-size: 14px; font-weight: 600; color: var(--fg); }
2696
+ .sample-row {
2697
+ margin: 12px auto 0;
2698
+ max-width: 640px;
2699
+ display: flex;
2700
+ align-items: center;
2701
+ justify-content: space-between;
2702
+ gap: 10px;
2703
+ flex-wrap: wrap;
2704
+ padding: 10px 12px;
2705
+ border: 1px solid var(--border);
2706
+ border-radius: 6px;
2707
+ background: var(--bg-subtle);
2708
+ text-align: left;
2709
+ }
2710
+ .sample-text { font-size: 12.5px; color: var(--fg); flex: 1 1 320px; }
2711
+ .receipt-box {
2712
+ margin: 0 0 22px;
2713
+ border: 1px solid var(--border);
2714
+ border-radius: 6px;
2715
+ padding: 14px 16px;
2716
+ background: var(--bg-subtle);
2717
+ }
2718
+ .receipt-head {
2719
+ display: flex;
2720
+ align-items: center;
2721
+ justify-content: space-between;
2722
+ gap: 10px;
2723
+ flex-wrap: wrap;
2724
+ margin-bottom: 10px;
2725
+ }
2726
+ .receipt-head h2 { margin: 0; font-size: 14px; }
2727
+ .receipt-checks {
2728
+ list-style: none;
2729
+ margin: 0 0 10px;
2730
+ padding: 0;
2731
+ display: flex;
2732
+ flex-direction: column;
2733
+ gap: 4px;
2734
+ font-size: 12.5px;
2735
+ }
2736
+ .receipt-checks li { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
2737
+ .receipt-tag { font-family: var(--mono); font-size: 11px; color: var(--muted); min-width: 48px; }
2738
+ .receipt-tag.fail { color: var(--err); font-weight: 600; }
678
2739
  .list { display: flex; flex-direction: column; gap: 8px; }
679
2740
  details.item {
680
2741
  border: 1px solid var(--border);
681
- border-radius: 8px;
2742
+ border-radius: 6px;
682
2743
  background: var(--bg);
683
2744
  overflow: hidden;
684
2745
  }
@@ -698,21 +2759,20 @@ function renderInspectorHtml(info) {
698
2759
  .left { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
699
2760
  .right { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
700
2761
  .badge {
701
- font-family: var(--mono);
702
2762
  font-weight: 600;
703
2763
  font-size: 11px;
704
2764
  padding: 2px 6px;
705
- border-radius: 5px;
2765
+ border-radius: 4px;
2766
+ border: 1px solid var(--border);
2767
+ background: var(--bg-subtle);
706
2768
  }
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);
2769
+ .badge.err { background: var(--err-bg); color: var(--err); border-color: var(--err); }
2770
+ .path { font-weight: 500; font-size: 12.5px; }
2771
+ .count-tag {
712
2772
  font-weight: 500;
713
2773
  font-size: 11px;
714
2774
  padding: 2px 6px;
715
- border-radius: 5px;
2775
+ border-radius: 3px;
716
2776
  background: var(--tok-bg);
717
2777
  color: var(--tok-fg);
718
2778
  border: 1px solid var(--tok-border);
@@ -736,7 +2796,7 @@ function renderInspectorHtml(info) {
736
2796
  .tok {
737
2797
  display: inline-block;
738
2798
  padding: 0 4px;
739
- border-radius: 4px;
2799
+ border-radius: 3px;
740
2800
  background: var(--tok-bg);
741
2801
  color: var(--tok-fg);
742
2802
  border: 1px solid var(--tok-border);
@@ -745,25 +2805,26 @@ function renderInspectorHtml(info) {
745
2805
  .vault-box {
746
2806
  margin-top: 24px;
747
2807
  border: 1px solid var(--border);
748
- border-radius: 8px;
2808
+ border-radius: 6px;
749
2809
  padding: 14px 16px;
750
2810
  background: var(--bg-subtle);
751
2811
  }
752
2812
  .vault-box h2 { margin: 0 0 6px; font-size: 14px; }
753
2813
  .vault-box p { margin: 0 0 10px; font-size: 12.5px; color: var(--muted); }
754
2814
  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); }
2815
+ th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--border); }
2816
+ th { font-size: 11.5px; color: var(--muted); }
757
2817
  </style>
758
2818
  </head>
759
2819
  <body>
760
2820
  <div class="wrap">
761
2821
  <header>
762
2822
  <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>
2823
+ <h1>Maskera lokal proxy-inspekt\xF6r</h1>
2824
+ <p class="sub">Proxy: ${safeUrl} \xB7 MCP: ${safeMcpUrl} \xB7 l\xE4ge: ${info.defaultMode} \xB7 \xE5terst\xE4llning: ${info.restoreResponses ? "p\xE5" : "av"} \xB7 enbart i lokalt RAM</p>
765
2825
  </div>
766
2826
  <div class="actions">
2827
+ <button id="selftest-btn" type="button" class="primary">K\xF6r sj\xE4lvtest</button>
767
2828
  <button id="reveal-btn" type="button">Visa originalv\xE4rden lokalt</button>
768
2829
  <button id="clear-btn" type="button">Rensa minne</button>
769
2830
  </div>
@@ -776,28 +2837,93 @@ function renderInspectorHtml(info) {
776
2837
  <div class="stat"><div class="stat-k">AI-modell</div><div class="stat-v" id="st-model">Redo</div></div>
777
2838
  </section>
778
2839
 
2840
+ <div id="receipt-root"></div>
2841
+ <div id="approvals-root"></div>
779
2842
  <div id="feed"></div>
780
2843
  <div id="vault-root"></div>
781
2844
  </div>
782
2845
  <script>
783
2846
  (() => {
784
2847
  const feedEl = document.getElementById("feed");
2848
+ const receiptRoot = document.getElementById("receipt-root");
2849
+ const approvalsRoot = document.getElementById("approvals-root");
785
2850
  const vaultRoot = document.getElementById("vault-root");
2851
+ const selftestBtn = document.getElementById("selftest-btn");
786
2852
  const revealBtn = document.getElementById("reveal-btn");
787
2853
  const clearBtn = document.getElementById("clear-btn");
788
2854
  const stReq = document.getElementById("st-req");
789
2855
  const stRed = document.getElementById("st-red");
790
2856
  const stUniq = document.getElementById("st-uniq");
791
2857
  const stModel = document.getElementById("st-model");
2858
+ const SAMPLE_PROMPT = "Skriv ett kort mejl till Anna Lindqvist (provnamn.maskera@example.com, 19900101-2385) och bekr\xE4fta m\xF6tet.";
792
2859
  let items = [];
2860
+ let approvals = [];
2861
+ let lastReceipt = null;
793
2862
  let reveal = false;
794
2863
  let userToggled = false;
795
2864
  const openIds = new Set();
796
2865
  const seenIds = new Set();
797
2866
 
798
- const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
2867
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
799
2868
  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
2869
 
2870
+ function renderReceipt() {
2871
+ if (!lastReceipt) {
2872
+ receiptRoot.innerHTML = "";
2873
+ return;
2874
+ }
2875
+ const r = lastReceipt;
2876
+ const checksHtml = (r.checks || []).map((c) => {
2877
+ const cls = c.status === "fail" ? " fail" : "";
2878
+ return '<li><span class="receipt-tag' + cls + '">[' + esc(c.status) + ']</span><span><strong>' + esc(c.name) + ':</strong> ' + esc(c.detail) + '</span></li>';
2879
+ }).join("");
2880
+ const proofHtml = r.sampleProof && !r.sampleProof.rawPiiLeaked
2881
+ ? '<p class="body-label">Verifierat maskerat utdata (0 l\xE4ckor, \xE5terst\xE4llning klar):</p><pre class="preview">' + highlightTokens(r.sampleProof.redactedPreview) + '</pre>'
2882
+ : "";
2883
+ receiptRoot.innerHTML =
2884
+ '<section class="receipt-box"><div class="receipt-head"><h2>Setup-kvitto (' + (r.ok ? "OK" : "FEL") + ' \xB7 v' + esc(r.version) + ' \xB7 ' + esc(r.sampleProof?.modeUsed || r.mode) + ')</h2>' +
2885
+ '<div class="actions"><button id="download-receipt-btn" type="button">Ladda ner kvitto (.json)</button><button id="close-receipt-btn" type="button">St\xE4ng</button></div></div>' +
2886
+ '<ul class="receipt-checks">' + checksHtml + '</ul>' + proofHtml + '</section>';
2887
+ const dlBtn = document.getElementById("download-receipt-btn");
2888
+ if (dlBtn) {
2889
+ dlBtn.addEventListener("click", () => {
2890
+ const blob = new Blob([JSON.stringify(r, null, 2) + "\\n"], { type: "application/json" });
2891
+ const a = document.createElement("a");
2892
+ a.href = URL.createObjectURL(blob);
2893
+ a.download = "maskera-setup-receipt.json";
2894
+ a.click();
2895
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
2896
+ });
2897
+ }
2898
+ const closeBtn = document.getElementById("close-receipt-btn");
2899
+ if (closeBtn) {
2900
+ closeBtn.addEventListener("click", () => {
2901
+ lastReceipt = null;
2902
+ renderReceipt();
2903
+ });
2904
+ }
2905
+ }
2906
+
2907
+ selftestBtn.addEventListener("click", async () => {
2908
+ selftestBtn.disabled = true;
2909
+ const prevText = selftestBtn.textContent;
2910
+ selftestBtn.textContent = "K\xF6r sj\xE4lvtest...";
2911
+ try {
2912
+ const r = await fetch("/_maskera/self-test", {
2913
+ method: "POST",
2914
+ headers: { "x-maskera-action": "self-test" },
2915
+ });
2916
+ lastReceipt = await r.json();
2917
+ renderReceipt();
2918
+ await refreshStatus();
2919
+ } catch (err) {
2920
+ receiptRoot.innerHTML = '<section class="receipt-box"><h2>Sj\xE4lvtest misslyckades</h2><p>' + esc(err) + '</p></section>';
2921
+ } finally {
2922
+ selftestBtn.disabled = false;
2923
+ selftestBtn.textContent = prevText;
2924
+ }
2925
+ });
2926
+
801
2927
  async function refreshStatus() {
802
2928
  try {
803
2929
  const r = await fetch("/_maskera/status");
@@ -812,6 +2938,37 @@ function renderInspectorHtml(info) {
812
2938
  } catch {}
813
2939
  }
814
2940
 
2941
+ async function decideApproval(id, action) {
2942
+ try {
2943
+ await fetch("/_maskera/approvals/" + encodeURIComponent(id) + "/" + action, {
2944
+ method: "POST",
2945
+ headers: { "x-maskera-action": "decide" },
2946
+ });
2947
+ } catch {}
2948
+ }
2949
+
2950
+ function renderApprovals() {
2951
+ const visible = (approvals || []).filter((a) => a.status === "pending" || a.status === "approved" || a.status === "declined");
2952
+ if (!visible.length) {
2953
+ approvalsRoot.innerHTML = "";
2954
+ return;
2955
+ }
2956
+ const rows = visible.map((a) => {
2957
+ const btns = a.status === "pending"
2958
+ ? '<div class="actions"><button type="button" class="primary" data-apr="' + esc(a.id) + '" data-act="approve">Godk\xE4nn</button><button type="button" data-apr="' + esc(a.id) + '" data-act="decline">Neka</button></div>'
2959
+ : '<span class="badge">' + esc(a.status) + "</span>";
2960
+ return '<div class="approval-row" id="approval-' + esc(a.id) + '"><div><strong>' + esc(a.tool) + '</strong> \xB7 ' + esc(a.reason) + '<div class="approval-meta">F\xF6rfr\xE5gan ' + esc(a.id) + (a.sessionId ? ' \xB7 session ' + esc(a.sessionId) : '') + ' \xB7 ' + esc(a.placeholderCount) + ' v\xE4rden</div></div>' + btns + '</div>';
2961
+ }).join("");
2962
+ approvalsRoot.innerHTML = '<section class="approvals"><h2>V\xE4ntande godk\xE4nnanden (r\xE5 PII)</h2>' + rows + "</section>";
2963
+ for (const btn of approvalsRoot.querySelectorAll("button[data-apr]")) {
2964
+ btn.addEventListener("click", () => {
2965
+ const id = btn.getAttribute("data-apr");
2966
+ const act = btn.getAttribute("data-act");
2967
+ if (id && act) void decideApproval(id, act);
2968
+ });
2969
+ }
2970
+ }
2971
+
815
2972
  async function refreshVault() {
816
2973
  if (!reveal) { vaultRoot.innerHTML = ""; return; }
817
2974
  try {
@@ -826,7 +2983,21 @@ function renderInspectorHtml(info) {
826
2983
 
827
2984
  function render() {
828
2985
  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>';
2986
+ feedEl.innerHTML =
2987
+ '<div class="empty"><p class="empty-title">V\xE4ntar p\xE5 f\xF6rsta riktiga anropet fr\xE5n din AI-klient.</p>' +
2988
+ 'Klicka p\xE5 <strong>K\xF6r sj\xE4lvtest</strong> ovan f\xF6r ett omedelbart kvitto, eller klistra in testmeningen i din klient och se platsh\xE5llarna dyka upp h\xE4r:' +
2989
+ '<div class="sample-row"><span class="sample-text">' + esc(SAMPLE_PROMPT) + '</span><button id="copy-sample-btn" type="button">Kopiera testmening</button></div>' +
2990
+ '<code>npx -y @maskera/mcp wrap -- claude\\nANTHROPIC_BASE_URL=${safeUrl} claude\\nOPENAI_BASE_URL=${safeUrl}/v1 codex\\nclaude mcp add --transport http maskera ${safeMcpUrl}</code></div>';
2991
+ const copyBtn = document.getElementById("copy-sample-btn");
2992
+ if (copyBtn) {
2993
+ copyBtn.addEventListener("click", async () => {
2994
+ try {
2995
+ await navigator.clipboard.writeText(SAMPLE_PROMPT);
2996
+ copyBtn.textContent = "Kopierad";
2997
+ setTimeout(() => { copyBtn.textContent = "Kopiera testmening"; }, 1800);
2998
+ } catch {}
2999
+ });
3000
+ }
830
3001
  return;
831
3002
  }
832
3003
  if (seenIds.size === 0 && items[0]?.id) {
@@ -835,14 +3006,14 @@ function renderInspectorHtml(info) {
835
3006
  for (const it of items) seenIds.add(it.id);
836
3007
  feedEl.innerHTML = '<div class="list">' + items.map((it) => {
837
3008
  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("");
3009
+ const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
839
3010
  const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
840
- const statusCls = it.status >= 200 && it.status < 400 ? "ok" : "err";
3011
+ const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
841
3012
  const isOpen = openIds.has(it.id);
842
3013
  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>' +
3014
+ '<summary><span class="left"><span class="badge' + statusCls + '">' + it.status + '</span><span class="path">' + esc(it.method + " " + it.path) + '</span>' + tags + (it.redactions === 0 ? '<span style="color:var(--muted);font-size:12px">0 PII</span>' : "") + '</span>' +
844
3015
  '<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>';
3016
+ '<div class="body"><p class="body-label">Vad som skickades vidare (0 r\xE5 PII):</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
846
3017
  }).join("") + "</div>";
847
3018
  for (const det of feedEl.querySelectorAll("details.item")) {
848
3019
  det.addEventListener("toggle", () => {
@@ -865,9 +3036,11 @@ function renderInspectorHtml(info) {
865
3036
  clearBtn.addEventListener("click", async () => {
866
3037
  await fetch("/_maskera/clear", { method: "POST", headers: { "x-maskera-action": "clear" } });
867
3038
  items = [];
3039
+ approvals = [];
868
3040
  userToggled = false;
869
3041
  openIds.clear();
870
3042
  seenIds.clear();
3043
+ renderApprovals();
871
3044
  render();
872
3045
  await refreshStatus();
873
3046
  await refreshVault();
@@ -875,10 +3048,19 @@ function renderInspectorHtml(info) {
875
3048
 
876
3049
  const es = new EventSource("/_maskera/events");
877
3050
  es.addEventListener("init", (ev) => {
878
- items = JSON.parse(ev.data).items || [];
3051
+ const data = JSON.parse(ev.data);
3052
+ items = data.items || [];
3053
+ approvals = data.approvals || [];
3054
+ renderApprovals();
879
3055
  render();
880
3056
  void refreshStatus();
881
3057
  });
3058
+ es.addEventListener("approvals", (ev) => {
3059
+ const data = JSON.parse(ev.data);
3060
+ approvals = data.approvals || [];
3061
+ renderApprovals();
3062
+ void refreshStatus();
3063
+ });
882
3064
  es.addEventListener("request", (ev) => {
883
3065
  const next = JSON.parse(ev.data);
884
3066
  items.unshift(next);
@@ -890,9 +3072,11 @@ function renderInspectorHtml(info) {
890
3072
  });
891
3073
  es.addEventListener("cleared", () => {
892
3074
  items = [];
3075
+ approvals = [];
893
3076
  userToggled = false;
894
3077
  openIds.clear();
895
3078
  seenIds.clear();
3079
+ renderApprovals();
896
3080
  render();
897
3081
  void refreshStatus();
898
3082
  void refreshVault();
@@ -903,176 +3087,388 @@ function renderInspectorHtml(info) {
903
3087
  </body>
904
3088
  </html>`;
905
3089
  }
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}`;
3090
+ var SUPPORTED_CLIENTS = [
3091
+ "claude-code",
3092
+ "claude-desktop",
3093
+ "codex",
3094
+ "cursor",
3095
+ "opencode",
3096
+ "t3-code"
3097
+ ];
3098
+ function isInstallClient(value) {
3099
+ return SUPPORTED_CLIENTS.includes(value);
911
3100
  }
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);
3101
+ async function pathExists(target) {
3102
+ try {
3103
+ await access(target);
3104
+ return true;
3105
+ } catch {
3106
+ return false;
3107
+ }
3108
+ }
3109
+ async function binaryOnPath(name, pathEnv, platform) {
3110
+ const dirs = pathEnv.split(delimiter).filter(Boolean);
3111
+ const candidates = platform === "win32" ? [`${name}.cmd`, `${name}.exe`, name] : [name];
3112
+ for (const dir of dirs) {
3113
+ for (const candidate of candidates) {
3114
+ if (await pathExists(join(dir, candidate))) return true;
3115
+ }
3116
+ }
3117
+ return false;
3118
+ }
3119
+ function claudeDesktopDir(home, platform) {
3120
+ if (platform === "darwin") {
3121
+ return join(home, "Library", "Application Support", "Claude");
3122
+ }
3123
+ if (platform === "win32") {
3124
+ const appData = process.env.APPDATA || join(home, "AppData", "Roaming");
3125
+ return join(appData, "Claude");
3126
+ }
3127
+ return join(home, ".config", "Claude");
3128
+ }
3129
+ async function detectInstalledClients(options = {}) {
3130
+ const cwd = options.cwd ?? process.cwd();
3131
+ const home = options.homeDir ?? homedir();
3132
+ const platform = options.platform ?? process.platform;
3133
+ const pathEnv = options.pathEnv ?? process.env.PATH ?? "";
3134
+ const detected = [];
3135
+ const [
3136
+ hasCursorDir,
3137
+ hasCursorBin,
3138
+ hasOpencodeCfg,
3139
+ hasOpencodeBin,
3140
+ hasClaudeDir,
3141
+ hasClaudeBin,
3142
+ hasCodexBin,
3143
+ hasClaudeDesktopDir
3144
+ ] = await Promise.all([
3145
+ pathExists(join(cwd, ".cursor")),
3146
+ binaryOnPath("cursor", pathEnv, platform),
3147
+ pathExists(join(cwd, "opencode.json")),
3148
+ binaryOnPath("opencode", pathEnv, platform),
3149
+ pathExists(join(cwd, ".claude")),
3150
+ binaryOnPath("claude", pathEnv, platform),
3151
+ binaryOnPath("codex", pathEnv, platform),
3152
+ pathExists(claudeDesktopDir(home, platform))
3153
+ ]);
3154
+ if (hasClaudeDir || hasClaudeBin) detected.push("claude-code");
3155
+ if (hasCodexBin) detected.push("codex");
3156
+ if (hasCursorDir || hasCursorBin) detected.push("cursor");
3157
+ if (hasOpencodeCfg || hasOpencodeBin) detected.push("opencode");
3158
+ if (hasClaudeDesktopDir) detected.push("claude-desktop");
3159
+ return detected;
3160
+ }
3161
+ function buildStdioArgs(options) {
3162
+ const args = ["-y", "@maskera/mcp"];
3163
+ const roots = options.roots?.length ? options.roots : [options.cwd ?? process.cwd()];
3164
+ for (const root of roots) {
3165
+ args.push("--root", resolve(root));
3166
+ }
3167
+ if (options.rulesOnly) args.push("--rules-only");
3168
+ if (options.noRawRestore) args.push("--no-raw-restore");
3169
+ if (options.readOnly) args.push("--read-only");
3170
+ if (options.approvalMode && options.approvalMode !== "automatic") {
3171
+ args.push("--approval-mode", options.approvalMode);
3172
+ }
3173
+ if (options.profile) args.push("--profile", options.profile);
3174
+ for (const term of options.customTerms ?? []) {
3175
+ args.push("--custom-term", term);
3176
+ }
3177
+ return args;
3178
+ }
3179
+ function buildGuardCommand(options) {
3180
+ const parts = ["npx", "-y", "@maskera/mcp", "guard"];
3181
+ if (options.rulesOnly) parts.push("--rules-only");
3182
+ if (options.profile) parts.push("--profile", options.profile);
3183
+ for (const term of options.customTerms ?? []) {
3184
+ parts.push("--custom-term", shellQuote(term));
3185
+ }
3186
+ return parts.join(" ");
3187
+ }
3188
+ function buildHttpUrl(options) {
3189
+ const base = (options.mcpUrl ?? "http://127.0.0.1:8787/mcp").trim();
3190
+ const url = new URL(base);
3191
+ if (options.noRawRestore) url.searchParams.set("no_raw_restore", "1");
3192
+ if (options.readOnly) url.searchParams.set("read_only", "1");
3193
+ if (options.approvalMode && options.approvalMode !== "automatic") {
3194
+ url.searchParams.set("approval_mode", options.approvalMode);
3195
+ }
3196
+ return url.toString();
3197
+ }
3198
+ function shellQuote(arg) {
3199
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(arg)) return arg;
3200
+ return `'${arg.replace(/'/g, "'\\''")}'`;
3201
+ }
3202
+ function defaultConfigPath(client, cwd, home, platform) {
3203
+ if (client === "cursor") return join(cwd, ".cursor", "mcp.json");
3204
+ if (client === "opencode") return join(cwd, "opencode.json");
3205
+ if (client === "claude-desktop") {
3206
+ return join(claudeDesktopDir(home, platform), "claude_desktop_config.json");
3207
+ }
3208
+ return null;
3209
+ }
3210
+ function buildServerEntry(transport, stdioArgs, httpUrl) {
3211
+ if (transport === "http") {
3212
+ return {
3213
+ type: "http",
3214
+ url: httpUrl
3215
+ };
3216
+ }
3217
+ return {
3218
+ command: "npx",
3219
+ args: stdioArgs
3220
+ };
3221
+ }
3222
+ async function readJsonObjectOrEmpty(filePath) {
3223
+ try {
3224
+ const existingRaw = await readFile(filePath, "utf8");
3225
+ const parsed = JSON.parse(existingRaw);
3226
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
3227
+ throw new Error(`Existing config "${filePath}" is not a JSON object.`);
3228
+ }
3229
+ return parsed;
3230
+ } catch (err) {
3231
+ if (err.code === "ENOENT") {
3232
+ return {};
3233
+ }
3234
+ throw err;
3235
+ }
3236
+ }
3237
+ async function mergeJsonConfig(filePath, keyPath, entry, dryRun) {
3238
+ const rootObj = await readJsonObjectOrEmpty(filePath);
3239
+ if (keyPath[0] === "mcpServers") {
3240
+ const current = rootObj.mcpServers && typeof rootObj.mcpServers === "object" && !Array.isArray(rootObj.mcpServers) ? rootObj.mcpServers : {};
3241
+ rootObj.mcpServers = { ...current, maskera: entry };
3242
+ } else {
3243
+ const mcpObj = rootObj.mcp && typeof rootObj.mcp === "object" && !Array.isArray(rootObj.mcp) ? rootObj.mcp : {};
3244
+ const serversObj = mcpObj.servers && typeof mcpObj.servers === "object" && !Array.isArray(mcpObj.servers) ? mcpObj.servers : {};
3245
+ rootObj.mcp = { ...mcpObj, servers: { ...serversObj, maskera: entry } };
3246
+ }
3247
+ const snippet = `${JSON.stringify(rootObj, null, 2)}
3248
+ `;
3249
+ if (!dryRun) {
3250
+ await mkdir(dirname(filePath), { recursive: true });
3251
+ await writeFile(filePath, snippet, "utf8");
3252
+ }
3253
+ return { snippet, written: !dryRun };
918
3254
  }
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);
3255
+ async function installGuardHook(client, cwd, guardCommand, dryRun) {
3256
+ if (client === "claude-code") {
3257
+ const hookPath = join(cwd, ".claude", "settings.json");
3258
+ const rootObj = await readJsonObjectOrEmpty(hookPath);
3259
+ const hooksObj = rootObj.hooks && typeof rootObj.hooks === "object" && !Array.isArray(rootObj.hooks) ? { ...rootObj.hooks } : {};
3260
+ const existingList = Array.isArray(hooksObj.UserPromptSubmit) ? [...hooksObj.UserPromptSubmit] : [];
3261
+ const alreadyConfigured = existingList.some(
3262
+ (entry) => typeof entry === "object" && entry !== null && JSON.stringify(entry).includes("@maskera/mcp guard")
3263
+ );
3264
+ if (!alreadyConfigured) {
3265
+ existingList.push({
3266
+ hooks: [
3267
+ {
3268
+ type: "command",
3269
+ command: guardCommand
3270
+ }
3271
+ ]
3272
+ });
3273
+ }
3274
+ hooksObj.UserPromptSubmit = existingList;
3275
+ rootObj.hooks = hooksObj;
3276
+ if (!dryRun) {
3277
+ await mkdir(dirname(hookPath), { recursive: true });
3278
+ await writeFile(hookPath, `${JSON.stringify(rootObj, null, 2)}
3279
+ `, "utf8");
3280
+ }
3281
+ return { hookPath, hookWritten: !dryRun };
924
3282
  }
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;
3283
+ if (client === "cursor") {
3284
+ const hookPath = join(cwd, ".cursor", "hooks.json");
3285
+ const rootObj = await readJsonObjectOrEmpty(hookPath);
3286
+ const hooksObj = rootObj.hooks && typeof rootObj.hooks === "object" && !Array.isArray(rootObj.hooks) ? { ...rootObj.hooks } : {};
3287
+ const existingList = Array.isArray(hooksObj.beforeSubmitPrompt) ? [...hooksObj.beforeSubmitPrompt] : [];
3288
+ const alreadyConfigured = existingList.some(
3289
+ (entry) => typeof entry === "object" && entry !== null && JSON.stringify(entry).includes("@maskera/mcp guard")
3290
+ );
3291
+ if (!alreadyConfigured) {
3292
+ existingList.push({ command: guardCommand });
933
3293
  }
934
- if (this.sessions.size >= this.maxSessions) {
935
- const oldestKey = this.sessions.keys().next().value;
936
- if (oldestKey !== void 0) this.sessions.delete(oldestKey);
3294
+ hooksObj.beforeSubmitPrompt = existingList;
3295
+ rootObj.version = typeof rootObj.version === "number" ? rootObj.version : 1;
3296
+ rootObj.hooks = hooksObj;
3297
+ if (!dryRun) {
3298
+ await mkdir(dirname(hookPath), { recursive: true });
3299
+ await writeFile(hookPath, `${JSON.stringify(rootObj, null, 2)}
3300
+ `, "utf8");
937
3301
  }
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;
3302
+ return { hookPath, hookWritten: !dryRun };
950
3303
  }
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) {
3304
+ return { hookPath: null, hookWritten: false };
3305
+ }
3306
+ var defaultCommandRunner = (command, args, cwd) => {
3307
+ const res = spawnSync(command, args, { cwd, encoding: "utf8" });
3308
+ return {
3309
+ status: res.status,
3310
+ stdout: res.stdout ?? "",
3311
+ stderr: res.stderr ?? "",
3312
+ error: res.error
3313
+ };
3314
+ };
3315
+ async function runInstall(options) {
3316
+ const cwd = options.cwd ?? process.cwd();
3317
+ const home = options.homeDir ?? homedir();
3318
+ const platform = options.platform ?? process.platform;
3319
+ const transport = options.transport ?? "stdio";
3320
+ const dryRun = options.dryRun === true;
3321
+ const stdioArgs = buildStdioArgs(options);
3322
+ const httpUrl = buildHttpUrl(options);
3323
+ const entry = buildServerEntry(transport, stdioArgs, httpUrl);
3324
+ const execCommand = options.execCommand ?? defaultCommandRunner;
3325
+ const guardCommand = buildGuardCommand(options);
3326
+ const hookResult = options.withHook ? await installGuardHook(options.client, cwd, guardCommand, dryRun) : void 0;
3327
+ const verifyStep = transport === "http" ? `Start "npx -y @maskera/mcp proxy" first, open http://127.0.0.1:8787/_maskera, and ask your agent to call maskera_status.` : `Restart ${options.client} (or open a new session) and ask the agent to call maskera_status.`;
3328
+ const hookFields = hookResult ? { hookPath: hookResult.hookPath, hookWritten: hookResult.hookWritten } : {};
3329
+ if (options.client === "claude-code") {
3330
+ const cliArgs = transport === "http" ? ["mcp", "add", "--transport", "http", "maskera", httpUrl] : ["mcp", "add", "maskera", "--", "npx", ...stdioArgs];
3331
+ const command = `claude ${cliArgs.map(shellQuote).join(" ")}`;
3332
+ if (options.configPath || options.project) {
3333
+ const targetPath2 = options.configPath ? resolve(options.configPath) : join(cwd, ".mcp.json");
3334
+ const merged2 = await mergeJsonConfig(targetPath2, ["mcpServers"], entry, dryRun);
959
3335
  return {
960
- sessionId: session.id,
961
- redacted: originalInput,
962
- counts: {},
963
- totalRedactions: 0,
964
- map: {}
3336
+ client: options.client,
3337
+ transport,
3338
+ configPath: targetPath2,
3339
+ command,
3340
+ snippet: merged2.snippet,
3341
+ written: merged2.written,
3342
+ ...hookFields,
3343
+ verifyStep
965
3344
  };
966
3345
  }
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;
3346
+ if (options.apply && !dryRun) {
3347
+ const run = execCommand("claude", cliArgs, cwd);
3348
+ if (run.error) {
3349
+ throw new Error(`Failed to execute "claude": ${run.error.message}`);
1005
3350
  }
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;
3351
+ if (run.status !== 0) {
3352
+ throw new Error(
3353
+ `Command "${command}" exited with status ${String(run.status)}: ${(run.stderr || run.stdout).trim()}`
3354
+ );
3355
+ }
3356
+ return {
3357
+ client: options.client,
3358
+ transport,
3359
+ configPath: null,
3360
+ command,
3361
+ snippet: `${command}
3362
+ `,
3363
+ written: false,
3364
+ applied: true,
3365
+ applyOutput: (run.stdout || run.stderr).trim(),
3366
+ ...hookFields,
3367
+ verifyStep
3368
+ };
1010
3369
  }
1011
- redacted += originalInput.slice(cursor);
1012
3370
  return {
1013
- sessionId: session.id,
1014
- redacted,
1015
- counts,
1016
- totalRedactions: result.redactions.length,
1017
- map: localMap
3371
+ client: options.client,
3372
+ transport,
3373
+ configPath: null,
3374
+ command,
3375
+ snippet: `${command}
3376
+ `,
3377
+ written: false,
3378
+ ...hookFields,
3379
+ verifyStep
1018
3380
  };
1019
3381
  }
1020
- restore(text, options) {
1021
- const normalizedId = options.sessionId?.trim() || void 0;
1022
- if (options.map && Object.keys(options.map).length > 0) {
3382
+ if (options.client === "codex") {
3383
+ const cliArgs = transport === "http" ? ["mcp", "add", "maskera", "--url", httpUrl] : ["mcp", "add", "maskera", "--", "npx", ...stdioArgs];
3384
+ const command = `codex ${cliArgs.map(shellQuote).join(" ")}`;
3385
+ if (options.apply && !dryRun) {
3386
+ const run = execCommand("codex", cliArgs, cwd);
3387
+ if (run.error) {
3388
+ throw new Error(`Failed to execute "codex": ${run.error.message}`);
3389
+ }
3390
+ if (run.status !== 0) {
3391
+ throw new Error(
3392
+ `Command "${command}" exited with status ${String(run.status)}: ${(run.stderr || run.stdout).trim()}`
3393
+ );
3394
+ }
1023
3395
  return {
1024
- restored: restore(text, options.map),
1025
- sessionId: normalizedId ?? null,
1026
- knownPlaceholders: Object.keys(options.map).length
3396
+ client: options.client,
3397
+ transport,
3398
+ configPath: null,
3399
+ command,
3400
+ snippet: `${command}
3401
+ `,
3402
+ written: false,
3403
+ applied: true,
3404
+ applyOutput: (run.stdout || run.stderr).trim(),
3405
+ ...hookFields,
3406
+ verifyStep
1027
3407
  };
1028
3408
  }
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
3409
  return {
1037
- restored: restore(text, session.map),
1038
- sessionId: session.id,
1039
- knownPlaceholders: Object.keys(session.map).length
3410
+ client: options.client,
3411
+ transport,
3412
+ configPath: null,
3413
+ command,
3414
+ snippet: `${command}
3415
+ `,
3416
+ written: false,
3417
+ ...hookFields,
3418
+ verifyStep
1040
3419
  };
1041
3420
  }
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
- }
3421
+ if (options.client === "t3-code") {
3422
+ const config = { mcpServers: { maskera: entry } };
3423
+ if (options.configPath) {
3424
+ const merged2 = await mergeJsonConfig(
3425
+ resolve(options.configPath),
3426
+ ["mcpServers"],
3427
+ entry,
3428
+ dryRun
3429
+ );
3430
+ return {
3431
+ client: options.client,
3432
+ transport,
3433
+ configPath: resolve(options.configPath),
3434
+ command: null,
3435
+ snippet: merged2.snippet,
3436
+ written: merged2.written,
3437
+ ...hookFields,
3438
+ verifyStep
3439
+ };
1052
3440
  }
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());
3441
+ return {
3442
+ client: options.client,
3443
+ transport,
3444
+ configPath: null,
3445
+ command: null,
3446
+ snippet: `${JSON.stringify(config, null, 2)}
3447
+ `,
3448
+ written: false,
3449
+ ...hookFields,
3450
+ verifyStep
3451
+ };
1069
3452
  }
1070
- get size() {
1071
- return this.sessions.size;
3453
+ const targetPath = options.configPath ? resolve(options.configPath) : defaultConfigPath(options.client, cwd, home, platform);
3454
+ if (!targetPath) {
3455
+ throw new Error(
3456
+ `Unable to determine config path for "${options.client}". Pass --config <path>.`
3457
+ );
1072
3458
  }
1073
- };
1074
-
1075
- // src/proxy.ts
3459
+ const keyPath = options.client === "opencode" ? ["mcp", "servers"] : ["mcpServers"];
3460
+ const merged = await mergeJsonConfig(targetPath, keyPath, entry, dryRun);
3461
+ return {
3462
+ client: options.client,
3463
+ transport,
3464
+ configPath: targetPath,
3465
+ command: null,
3466
+ snippet: merged.snippet,
3467
+ written: merged.written,
3468
+ ...hookFields,
3469
+ verifyStep
3470
+ };
3471
+ }
1076
3472
  var DEFAULT_ANTHROPIC_UPSTREAM = "https://api.anthropic.com";
1077
3473
  var DEFAULT_OPENAI_UPSTREAM = "https://api.openai.com";
1078
3474
  var MAX_BODY_BYTES = 16 * 1024 * 1024;
@@ -2099,30 +4495,108 @@ function shouldRedactPath(pathname) {
2099
4495
  const clean = (pathname.split("?")[0] ?? pathname).replace(/\/+$/, "").toLowerCase();
2100
4496
  return clean.endsWith("/messages") || clean.endsWith("/messages/count_tokens") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
2101
4497
  }
4498
+ var APPROVAL_STRICTNESS = {
4499
+ automatic: 0,
4500
+ native: 1,
4501
+ browser: 2
4502
+ };
4503
+ function parseScopedMcpPolicy(urlPath, base) {
4504
+ const qIndex = urlPath.indexOf("?");
4505
+ if (qIndex < 0) return base;
4506
+ const params = new URLSearchParams(urlPath.slice(qIndex + 1));
4507
+ const flagTrue = (name) => {
4508
+ const v = params.get(name)?.trim().toLowerCase();
4509
+ return v === "1" || v === "true" || v === "yes";
4510
+ };
4511
+ const flagFalse = (name) => {
4512
+ const v = params.get(name)?.trim().toLowerCase();
4513
+ return v === "0" || v === "false" || v === "no";
4514
+ };
4515
+ const allowRawRestore = base.allowRawRestore && !flagTrue("no_raw_restore") && !flagFalse("allow_raw_restore");
4516
+ const readOnly = base.readOnly || flagTrue("read_only");
4517
+ let approvalMode = base.approvalMode;
4518
+ const requestedMode = (params.get("approval_mode") ?? params.get("elicitation_mode") ?? "").trim().toLowerCase();
4519
+ if (requestedMode === "automatic" || requestedMode === "native" || requestedMode === "browser") {
4520
+ if (APPROVAL_STRICTNESS[requestedMode] >= APPROVAL_STRICTNESS[base.approvalMode]) {
4521
+ approvalMode = requestedMode;
4522
+ }
4523
+ }
4524
+ return { allowRawRestore, readOnly, approvalMode };
4525
+ }
2102
4526
  async function startMaskeraProxy(options = {}) {
2103
4527
  const host = options.host ?? "127.0.0.1";
2104
4528
  const requestedPort = options.port ?? 8787;
2105
4529
  const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
2106
4530
  const vault = options.vault ?? new SessionVault();
4531
+ const approvals = options.approvals ?? new ApprovalBroker();
2107
4532
  const inspector = new ProxyInspector();
4533
+ const unsubscribeApprovals = approvals.onChange((snapshot) => {
4534
+ inspector.publishApprovals(snapshot);
4535
+ });
2108
4536
  const restoreResponses = options.restoreResponses !== false;
2109
4537
  const anthropicUpstream = options.anthropicUpstream ?? DEFAULT_ANTHROPIC_UPSTREAM;
2110
4538
  const openaiUpstream = options.openaiUpstream ?? DEFAULT_OPENAI_UPSTREAM;
2111
4539
  const auditLogPath = options.auditLogPath;
2112
4540
  const log = options.onLog ?? (() => {
2113
4541
  });
4542
+ const baseMcpPolicy = {
4543
+ allowRawRestore: options.allowRawRestore ?? true,
4544
+ readOnly: options.readOnly ?? false,
4545
+ approvalMode: options.approvalMode ?? "automatic"
4546
+ };
4547
+ const mcpSessions = /* @__PURE__ */ new Map();
4548
+ const closedMcpSessions = /* @__PURE__ */ new Set();
2114
4549
  if (auditLogPath) {
2115
4550
  await mkdir(dirname(auditLogPath), { recursive: true });
2116
4551
  await appendFile(auditLogPath, "", "utf8");
2117
4552
  }
2118
4553
  let totalRequests = 0;
2119
4554
  let totalRedactions = 0;
4555
+ let totalCounts = {};
2120
4556
  let boundPort = requestedPort;
2121
4557
  let boundUrl = `http://${host}:${requestedPort}`;
2122
4558
  let auditChain = Promise.resolve();
4559
+ let mcpServerInstance = null;
4560
+ function getMcpServer() {
4561
+ if (!mcpServerInstance) {
4562
+ mcpServerInstance = createMaskeraMcpServer({
4563
+ engine,
4564
+ vault,
4565
+ allowedRoots: options.mcpRoots,
4566
+ defaultProfile: options.profile,
4567
+ defaultCustomTerms: options.customTerms,
4568
+ allowRawRestore: baseMcpPolicy.allowRawRestore,
4569
+ readOnly: baseMcpPolicy.readOnly,
4570
+ approvalMode: baseMcpPolicy.approvalMode,
4571
+ approvals,
4572
+ approvalBaseUrl: boundUrl,
4573
+ onToolCall: (event) => {
4574
+ if (event.sessionId === "doctor-http-probe") {
4575
+ vault.clear("doctor-http-probe");
4576
+ return;
4577
+ }
4578
+ recordAuditAndInspector({
4579
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4580
+ method: "MCP",
4581
+ path: `/mcp/${event.tool}`,
4582
+ upstream: "local-mcp",
4583
+ sessionId: event.sessionId ?? "mcp",
4584
+ status: event.isError ? 400 : 200,
4585
+ streamed: false,
4586
+ durationMs: event.durationMs,
4587
+ redactions: event.redactions,
4588
+ counts: event.counts,
4589
+ redactedPreview: []
4590
+ });
4591
+ }
4592
+ });
4593
+ }
4594
+ return mcpServerInstance;
4595
+ }
2123
4596
  function recordAuditAndInspector(entry) {
2124
4597
  totalRequests += 1;
2125
4598
  totalRedactions += entry.redactions;
4599
+ mergeCounts(totalCounts, entry.counts);
2126
4600
  inspector.record(entry);
2127
4601
  if (auditLogPath) {
2128
4602
  const auditLine = JSON.stringify({
@@ -2171,6 +4645,7 @@ async function startMaskeraProxy(options = {}) {
2171
4645
  res.end(
2172
4646
  renderInspectorHtml({
2173
4647
  url: boundUrl,
4648
+ mcpUrl: `${boundUrl}/mcp`,
2174
4649
  defaultMode: engine.status().defaultMode,
2175
4650
  restoreResponses
2176
4651
  })
@@ -2181,6 +4656,44 @@ async function startMaskeraProxy(options = {}) {
2181
4656
  inspector.subscribe(res, INSPECTOR_SECURITY_HEADERS);
2182
4657
  return;
2183
4658
  }
4659
+ if (method === "GET" && pathname === "/_maskera/approvals") {
4660
+ res.writeHead(200, {
4661
+ ...INSPECTOR_SECURITY_HEADERS,
4662
+ "content-type": "application/json; charset=utf-8"
4663
+ });
4664
+ res.end(JSON.stringify({ approvals: approvals.list() }));
4665
+ return;
4666
+ }
4667
+ const approvalMatch = /^\/_maskera\/approvals\/([^/]+)\/(approve|decline)$/.exec(pathname);
4668
+ if (method === "POST" && approvalMatch) {
4669
+ if (req.headers["x-maskera-action"] !== "decide" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
4670
+ res.writeHead(403, {
4671
+ ...INSPECTOR_SECURITY_HEADERS,
4672
+ "content-type": "application/json; charset=utf-8"
4673
+ });
4674
+ res.end(
4675
+ JSON.stringify({ error: "Pass x-maskera-action: decide from same-origin loopback." })
4676
+ );
4677
+ return;
4678
+ }
4679
+ const approvalId = decodeURIComponent(approvalMatch[1] ?? "");
4680
+ const decision = approvalMatch[2] === "approve" ? "approve" : "decline";
4681
+ const updated = approvals.decide(approvalId, decision);
4682
+ if (!updated) {
4683
+ res.writeHead(404, {
4684
+ ...INSPECTOR_SECURITY_HEADERS,
4685
+ "content-type": "application/json; charset=utf-8"
4686
+ });
4687
+ res.end(JSON.stringify({ error: "Unknown approval id." }));
4688
+ return;
4689
+ }
4690
+ res.writeHead(200, {
4691
+ ...INSPECTOR_SECURITY_HEADERS,
4692
+ "content-type": "application/json; charset=utf-8"
4693
+ });
4694
+ res.end(JSON.stringify({ approval: updated }));
4695
+ return;
4696
+ }
2184
4697
  if (method === "GET" && pathname === "/_maskera/vault") {
2185
4698
  if (req.headers["x-maskera-reveal"] !== "1" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
2186
4699
  res.writeHead(403, {
@@ -2203,30 +4716,117 @@ async function startMaskeraProxy(options = {}) {
2203
4716
  ...INSPECTOR_SECURITY_HEADERS,
2204
4717
  "content-type": "application/json; charset=utf-8"
2205
4718
  });
2206
- res.end(
2207
- JSON.stringify({ error: "Pass x-maskera-action: clear from same-origin loopback." })
2208
- );
4719
+ res.end(
4720
+ JSON.stringify({ error: "Pass x-maskera-action: clear from same-origin loopback." })
4721
+ );
4722
+ return;
4723
+ }
4724
+ vault.clearAll();
4725
+ approvals.clearAll();
4726
+ engine.clearCache();
4727
+ inspector.clear();
4728
+ totalRequests = 0;
4729
+ totalRedactions = 0;
4730
+ totalCounts = {};
4731
+ res.writeHead(200, {
4732
+ ...INSPECTOR_SECURITY_HEADERS,
4733
+ "content-type": "application/json; charset=utf-8"
4734
+ });
4735
+ res.end(JSON.stringify({ cleared: true }));
4736
+ return;
4737
+ }
4738
+ if (method === "POST" && pathname === "/_maskera/self-test") {
4739
+ if (req.headers["x-maskera-action"] !== "self-test" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
4740
+ res.writeHead(403, {
4741
+ ...INSPECTOR_SECURITY_HEADERS,
4742
+ "content-type": "application/json; charset=utf-8"
4743
+ });
4744
+ res.end(
4745
+ JSON.stringify({ error: "Pass x-maskera-action: self-test from same-origin loopback." })
4746
+ );
4747
+ return;
4748
+ }
4749
+ const report = await runDoctor({
4750
+ engine,
4751
+ roots: options.mcpRoots ?? [process.cwd()],
4752
+ mode: engine.status().defaultMode,
4753
+ profile: options.profile,
4754
+ customTerms: options.customTerms,
4755
+ proxyUrl: boundUrl,
4756
+ mcpUrl: `${boundUrl}/mcp`
4757
+ });
4758
+ res.writeHead(report.ok ? 200 : 500, {
4759
+ ...INSPECTOR_SECURITY_HEADERS,
4760
+ "content-type": "application/json; charset=utf-8"
4761
+ });
4762
+ res.end(JSON.stringify(report, null, 2));
4763
+ return;
4764
+ }
4765
+ if (method === "POST" && pathname === "/_maskera/guard") {
4766
+ if (req.headers["x-maskera-action"] !== "guard" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
4767
+ res.writeHead(403, {
4768
+ ...INSPECTOR_SECURITY_HEADERS,
4769
+ "content-type": "application/json; charset=utf-8"
4770
+ });
4771
+ res.end(
4772
+ JSON.stringify({ error: "Pass x-maskera-action: guard from same-origin loopback." })
4773
+ );
4774
+ return;
4775
+ }
4776
+ const guardBodyBuf = await readRequestBody(req);
4777
+ let parsedGuard;
4778
+ try {
4779
+ parsedGuard = JSON.parse(guardBodyBuf.toString("utf8"));
4780
+ } catch {
4781
+ res.writeHead(400, {
4782
+ ...INSPECTOR_SECURITY_HEADERS,
4783
+ "content-type": "application/json; charset=utf-8"
4784
+ });
4785
+ res.end(JSON.stringify({ error: "Invalid JSON body for /_maskera/guard." }));
4786
+ return;
4787
+ }
4788
+ if (!isPlainObject(parsedGuard) || typeof parsedGuard.raw !== "string") {
4789
+ res.writeHead(400, {
4790
+ ...INSPECTOR_SECURITY_HEADERS,
4791
+ "content-type": "application/json; charset=utf-8"
4792
+ });
4793
+ res.end(JSON.stringify({ error: 'Expected JSON object with string field "raw".' }));
2209
4794
  return;
2210
4795
  }
2211
- vault.clearAll();
2212
- engine.clearCache();
2213
- inspector.clear();
2214
- totalRequests = 0;
2215
- totalRedactions = 0;
4796
+ const guardMode = parsedGuard.mode === "rules" || parsedGuard.mode === "auto" ? parsedGuard.mode : void 0;
4797
+ const guardProfile = parsedGuard.profile === "clinical" || parsedGuard.profile === "general" ? parsedGuard.profile : options.profile;
4798
+ const guardTerms = Array.isArray(parsedGuard.customTerms) ? parsedGuard.customTerms.filter((t) => typeof t === "string") : options.customTerms;
4799
+ const guardRes = await runGuard(parsedGuard.raw, engine, {
4800
+ mode: guardMode,
4801
+ profile: guardProfile,
4802
+ customTerms: guardTerms,
4803
+ preserveJsonStructure: parsedGuard.preserveJsonStructure === true
4804
+ });
4805
+ const includeRedacted = parsedGuard.includeRedacted === true || parsedGuard.preserveJsonStructure === true;
2216
4806
  res.writeHead(200, {
2217
4807
  ...INSPECTOR_SECURITY_HEADERS,
2218
4808
  "content-type": "application/json; charset=utf-8"
2219
4809
  });
2220
- res.end(JSON.stringify({ cleared: true }));
4810
+ res.end(
4811
+ JSON.stringify({
4812
+ blocked: guardRes.blocked,
4813
+ totalRedactions: guardRes.totalRedactions,
4814
+ counts: guardRes.counts,
4815
+ modeUsed: guardRes.modeUsed,
4816
+ ...includeRedacted ? { redacted: guardRes.redacted } : {}
4817
+ })
4818
+ );
2221
4819
  return;
2222
4820
  }
2223
4821
  if (method === "GET" && (pathname === "/healthz" || pathname === "/_maskera/status")) {
2224
4822
  const payload = {
2225
4823
  status: "ok",
2226
4824
  inspector_url: `${boundUrl}/_maskera`,
4825
+ mcp_url: `${boundUrl}/mcp`,
2227
4826
  engine: engine.status(),
2228
4827
  requests_proxied: totalRequests,
2229
4828
  total_redactions: totalRedactions,
4829
+ pending_approvals: approvals.list().filter((a) => a.status === "pending").length,
2230
4830
  sessions: vault.list()
2231
4831
  };
2232
4832
  res.writeHead(200, {
@@ -2244,6 +4844,120 @@ async function startMaskeraProxy(options = {}) {
2244
4844
  res.end(JSON.stringify({ error: "Unknown inspector route." }));
2245
4845
  return;
2246
4846
  }
4847
+ if (normalizedPath === "/mcp" || normalizedPath === "/mcp/") {
4848
+ if (!isLoopbackHost(req.headers.host, host, boundPort, true)) {
4849
+ res.writeHead(403, {
4850
+ ...INSPECTOR_SECURITY_HEADERS,
4851
+ "content-type": "application/json; charset=utf-8"
4852
+ });
4853
+ res.end(JSON.stringify({ error: "Forbidden host header for local MCP endpoint." }));
4854
+ return;
4855
+ }
4856
+ if (req.headers.origin && !isSameOriginLoopbackRequest(req, host, boundPort)) {
4857
+ res.writeHead(403, {
4858
+ ...INSPECTOR_SECURITY_HEADERS,
4859
+ "content-type": "application/json; charset=utf-8"
4860
+ });
4861
+ res.end(
4862
+ JSON.stringify({ error: "Cross-origin requests to local MCP endpoint are forbidden." })
4863
+ );
4864
+ return;
4865
+ }
4866
+ const incomingSessionId = typeof req.headers["mcp-session-id"] === "string" ? req.headers["mcp-session-id"].trim() : "";
4867
+ if (method === "DELETE") {
4868
+ if (incomingSessionId) {
4869
+ mcpSessions.delete(incomingSessionId);
4870
+ closedMcpSessions.add(incomingSessionId);
4871
+ if (closedMcpSessions.size > 500) {
4872
+ const first = closedMcpSessions.values().next().value;
4873
+ if (first !== void 0) closedMcpSessions.delete(first);
4874
+ }
4875
+ }
4876
+ res.writeHead(204, INSPECTOR_SECURITY_HEADERS);
4877
+ res.end();
4878
+ return;
4879
+ }
4880
+ if (method === "GET") {
4881
+ res.writeHead(405, {
4882
+ ...INSPECTOR_SECURITY_HEADERS,
4883
+ allow: "POST, DELETE",
4884
+ "content-type": "application/json; charset=utf-8"
4885
+ });
4886
+ res.end(
4887
+ JSON.stringify({
4888
+ error: "Streamable HTTP MCP expects JSON-RPC POST requests on /mcp."
4889
+ })
4890
+ );
4891
+ return;
4892
+ }
4893
+ if (method !== "POST") {
4894
+ res.writeHead(405, {
4895
+ ...INSPECTOR_SECURITY_HEADERS,
4896
+ allow: "POST, DELETE",
4897
+ "content-type": "application/json; charset=utf-8"
4898
+ });
4899
+ res.end(JSON.stringify({ error: `Unsupported HTTP method ${method} for /mcp.` }));
4900
+ return;
4901
+ }
4902
+ if (incomingSessionId && closedMcpSessions.has(incomingSessionId)) {
4903
+ res.writeHead(404, {
4904
+ ...INSPECTOR_SECURITY_HEADERS,
4905
+ "content-type": "application/json; charset=utf-8"
4906
+ });
4907
+ res.end(JSON.stringify({ error: "MCP session has been closed." }));
4908
+ return;
4909
+ }
4910
+ const mcpBody = await readRequestBody(req);
4911
+ let parsedMcp;
4912
+ try {
4913
+ parsedMcp = JSON.parse(mcpBody.toString("utf8"));
4914
+ } catch {
4915
+ res.writeHead(400, {
4916
+ ...INSPECTOR_SECURITY_HEADERS,
4917
+ "content-type": "application/json; charset=utf-8"
4918
+ });
4919
+ res.end(
4920
+ JSON.stringify({
4921
+ jsonrpc: "2.0",
4922
+ id: null,
4923
+ error: { code: -32700, message: "Parse error" }
4924
+ })
4925
+ );
4926
+ return;
4927
+ }
4928
+ const sessionBasePolicy = (incomingSessionId ? mcpSessions.get(incomingSessionId) : void 0) ?? baseMcpPolicy;
4929
+ const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
4930
+ const mcpServer = getMcpServer();
4931
+ const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
4932
+ const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
4933
+ let responseSessionId = incomingSessionId;
4934
+ if (isInit) {
4935
+ responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
4936
+ if (mcpSessions.size >= 200) {
4937
+ const oldest = mcpSessions.keys().next().value;
4938
+ if (oldest !== void 0) mcpSessions.delete(oldest);
4939
+ }
4940
+ mcpSessions.set(responseSessionId, effectivePolicy);
4941
+ }
4942
+ const responses = [];
4943
+ for (const msg of messages) {
4944
+ const reply = await mcpServer.handleMessage(msg, effectivePolicy);
4945
+ if (reply !== null) responses.push(reply);
4946
+ }
4947
+ const mcpHeaders = {
4948
+ ...INSPECTOR_SECURITY_HEADERS
4949
+ };
4950
+ if (responseSessionId) mcpHeaders["mcp-session-id"] = responseSessionId;
4951
+ if (responses.length === 0) {
4952
+ res.writeHead(202, mcpHeaders);
4953
+ res.end();
4954
+ return;
4955
+ }
4956
+ mcpHeaders["content-type"] = "application/json; charset=utf-8";
4957
+ res.writeHead(200, mcpHeaders);
4958
+ res.end(JSON.stringify(Array.isArray(parsedMcp) ? responses : responses[0]));
4959
+ return;
4960
+ }
2247
4961
  if (String(req.headers.upgrade ?? "").toLowerCase() === "websocket") {
2248
4962
  res.writeHead(426, {
2249
4963
  "content-type": "application/json; charset=utf-8",
@@ -2550,431 +5264,447 @@ ${body}`
2550
5264
  return {
2551
5265
  host,
2552
5266
  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"]
5267
+ url: boundUrl,
5268
+ mcpUrl: `${boundUrl}/mcp`,
5269
+ inspectorUrl: `${boundUrl}/_maskera`,
5270
+ server,
5271
+ vault,
5272
+ inspector,
5273
+ approvals,
5274
+ stats: () => ({
5275
+ requests: totalRequests,
5276
+ redactions: totalRedactions,
5277
+ counts: { ...totalCounts },
5278
+ sessions: vault.list().length
5279
+ }),
5280
+ close: async () => {
5281
+ unsubscribeApprovals();
5282
+ inspector.closeAll();
5283
+ await new Promise((resolveClose, rejectClose) => {
5284
+ server.close((err) => err ? rejectClose(err) : resolveClose());
5285
+ });
5286
+ await auditChain;
2742
5287
  }
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 : {};
5288
+ };
2759
5289
  }
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".');
5290
+ var LAUNCHD_LABEL = "dev.maskera.proxy";
5291
+ var SYSTEMD_UNIT = "maskera-proxy.service";
5292
+ function xmlEscape(value) {
5293
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2764
5294
  }
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".');
5295
+ function systemdQuote(arg) {
5296
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(arg)) return arg;
5297
+ return `"${arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
2769
5298
  }
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.");
5299
+ function buildProxyProgramArgs(options) {
5300
+ const nodePath = options.nodePath ?? process.execPath;
5301
+ const cliPath = options.cliPath ?? process.argv[1] ?? "";
5302
+ const isEphemeralNpx = !cliPath || cliPath.includes("_npx") || cliPath.startsWith("/tmp/") || cliPath.startsWith("/var/folders/");
5303
+ const base = isEphemeralNpx ? ["npx", "-y", "@maskera/mcp"] : [nodePath, resolve(cliPath)];
5304
+ const args = [
5305
+ ...base,
5306
+ "proxy",
5307
+ "--host",
5308
+ options.host ?? "127.0.0.1",
5309
+ "--port",
5310
+ String(options.port ?? 8787)
5311
+ ];
5312
+ for (const root of options.roots ?? []) {
5313
+ args.push("--root", resolve(root));
2774
5314
  }
2775
- return value;
5315
+ if (options.rulesOnly) args.push("--rules-only");
5316
+ if (options.noRawRestore) args.push("--no-raw-restore");
5317
+ if (options.readOnly) args.push("--read-only");
5318
+ if (options.approvalMode && options.approvalMode !== "automatic") {
5319
+ args.push("--approval-mode", options.approvalMode);
5320
+ }
5321
+ if (options.profile) args.push("--profile", options.profile);
5322
+ for (const term of options.customTerms ?? []) {
5323
+ args.push("--custom-term", term);
5324
+ }
5325
+ if (options.auditLogPath) args.push("--audit-log", resolve(options.auditLogPath));
5326
+ return args;
2776
5327
  }
2777
- function toolOk(payload) {
2778
- return {
2779
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
2780
- structuredContent: payload
2781
- };
5328
+ function renderLaunchdPlist(options) {
5329
+ const argLines = options.programArguments.map((arg) => ` <string>${xmlEscape(arg)}</string>`).join("\n");
5330
+ const envBlock = options.pathEnv ? ` <key>EnvironmentVariables</key>
5331
+ <dict>
5332
+ <key>PATH</key>
5333
+ <string>${xmlEscape(options.pathEnv)}</string>
5334
+ </dict>
5335
+ ` : "";
5336
+ return `<?xml version="1.0" encoding="UTF-8"?>
5337
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5338
+ <plist version="1.0">
5339
+ <dict>
5340
+ <key>Label</key>
5341
+ <string>${LAUNCHD_LABEL}</string>
5342
+ <key>ProgramArguments</key>
5343
+ <array>
5344
+ ${argLines}
5345
+ </array>
5346
+ ${envBlock} <key>RunAtLoad</key>
5347
+ <true/>
5348
+ <key>KeepAlive</key>
5349
+ <true/>
5350
+ <key>StandardOutPath</key>
5351
+ <string>${xmlEscape(options.stdoutLogPath)}</string>
5352
+ <key>StandardErrorPath</key>
5353
+ <string>${xmlEscape(options.stderrLogPath)}</string>
5354
+ </dict>
5355
+ </plist>
5356
+ `;
2782
5357
  }
2783
- function toolError(message) {
5358
+ function renderSystemdUnit(options) {
5359
+ const execStart = options.programArguments.map(systemdQuote).join(" ");
5360
+ const envLine = options.pathEnv ? `Environment="PATH=${options.pathEnv.replace(/"/g, '\\"')}"
5361
+ ` : "";
5362
+ return `[Unit]
5363
+ Description=Maskera local Swedish PII proxy and Streamable HTTP MCP server
5364
+ After=network.target
5365
+
5366
+ [Service]
5367
+ Type=simple
5368
+ ${envLine}ExecStart=${execStart}
5369
+ Restart=on-failure
5370
+ RestartSec=2
5371
+
5372
+ [Install]
5373
+ WantedBy=default.target
5374
+ `;
5375
+ }
5376
+ var defaultCommandRunner2 = (command, args, cwd) => {
5377
+ const res = spawnSync(command, args, { cwd, encoding: "utf8" });
2784
5378
  return {
2785
- isError: true,
2786
- content: [{ type: "text", text: message }]
5379
+ status: res.status,
5380
+ stdout: res.stdout ?? "",
5381
+ stderr: res.stderr ?? "",
5382
+ error: res.error
2787
5383
  };
5384
+ };
5385
+ async function fileExists(path) {
5386
+ try {
5387
+ await access(path);
5388
+ return true;
5389
+ } catch {
5390
+ return false;
5391
+ }
2788
5392
  }
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];
5393
+ async function probeProxyHealth(proxyUrl) {
5394
+ try {
5395
+ const res = await fetch(`${proxyUrl}/_maskera/status`, {
5396
+ signal: AbortSignal.timeout(800)
5397
+ });
5398
+ return res.ok;
5399
+ } catch {
5400
+ return false;
2799
5401
  }
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
- });
5402
+ }
5403
+ async function runService(options) {
5404
+ const platform = options.platform ?? process.platform;
5405
+ const home = options.homeDir ?? homedir();
5406
+ const host = options.host ?? "127.0.0.1";
5407
+ const port = options.port ?? 8787;
5408
+ const proxyUrl = `http://${host}:${port}`;
5409
+ const mcpUrl = `${proxyUrl}/mcp`;
5410
+ const inspectorUrl = `${proxyUrl}/_maskera`;
5411
+ const dryRun = options.dryRun === true;
5412
+ const execCommand = options.execCommand ?? defaultCommandRunner2;
5413
+ const pathEnv = options.pathEnv ?? process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
5414
+ if (platform !== "darwin" && platform !== "linux") {
5415
+ return {
5416
+ action: options.action,
5417
+ platform,
5418
+ manager: "unsupported",
5419
+ serviceName: LAUNCHD_LABEL,
5420
+ serviceFile: null,
5421
+ proxyUrl,
5422
+ mcpUrl,
5423
+ inspectorUrl,
5424
+ installed: false,
5425
+ running: await probeProxyHealth(proxyUrl),
5426
+ written: false,
5427
+ detail: `Background service installation is supported on macOS (launchd) and Linux (systemd --user). On ${platform}, run "npx -y @maskera/mcp proxy" or "npx -y @maskera/mcp wrap -- <cmd>".`
5428
+ };
5429
+ }
5430
+ const isMac = platform === "darwin";
5431
+ const manager = isMac ? "launchd" : "systemd";
5432
+ const serviceName = isMac ? LAUNCHD_LABEL : SYSTEMD_UNIT;
5433
+ const serviceFile = isMac ? join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`) : join(home, ".config", "systemd", "user", SYSTEMD_UNIT);
5434
+ if (options.action === "status") {
5435
+ const installed = await fileExists(serviceFile);
5436
+ const running2 = await probeProxyHealth(proxyUrl);
5437
+ return {
5438
+ action: "status",
5439
+ platform,
5440
+ manager,
5441
+ serviceName,
5442
+ serviceFile,
5443
+ proxyUrl,
5444
+ mcpUrl,
5445
+ inspectorUrl,
5446
+ installed,
5447
+ running: running2,
5448
+ written: false,
5449
+ detail: running2 ? `Running on ${proxyUrl} (${installed ? `service file ${serviceFile}` : "started manually"}).` : installed ? `Installed at ${serviceFile}, but not responding on ${proxyUrl}.` : `Not installed (${serviceFile} does not exist) and not running on ${proxyUrl}.`
5450
+ };
5451
+ }
5452
+ if (options.action === "uninstall") {
5453
+ const existed = await fileExists(serviceFile);
5454
+ if (!dryRun) {
5455
+ if (isMac) {
5456
+ const uid = options.uid ?? process.getuid?.() ?? 501;
5457
+ execCommand("launchctl", ["bootout", `gui/${uid}`, serviceFile], home);
5458
+ } else {
5459
+ execCommand("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT], home);
2864
5460
  }
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
5461
+ if (existed) {
5462
+ await unlink(serviceFile).catch(() => {
2883
5463
  });
2884
5464
  }
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
- });
5465
+ if (!isMac) {
5466
+ execCommand("systemctl", ["--user", "daemon-reload"], home);
2897
5467
  }
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
- });
5468
+ }
5469
+ return {
5470
+ action: "uninstall",
5471
+ platform,
5472
+ manager,
5473
+ serviceName,
5474
+ serviceFile,
5475
+ proxyUrl,
5476
+ mcpUrl,
5477
+ inspectorUrl,
5478
+ installed: false,
5479
+ running: false,
5480
+ written: !dryRun && existed,
5481
+ detail: dryRun ? `Dry run: would unload and remove ${serviceFile}.` : existed ? `Stopped and removed ${serviceFile}.` : `Service file ${serviceFile} was not present.`
5482
+ };
5483
+ }
5484
+ const programArguments = buildProxyProgramArgs(options);
5485
+ const snippet = isMac ? renderLaunchdPlist({
5486
+ programArguments,
5487
+ stdoutLogPath: join(home, "Library", "Logs", "maskera-proxy.log"),
5488
+ stderrLogPath: join(home, "Library", "Logs", "maskera-proxy.err.log"),
5489
+ pathEnv
5490
+ }) : renderSystemdUnit({ programArguments, pathEnv });
5491
+ if (dryRun) {
5492
+ return {
5493
+ action: "install",
5494
+ platform,
5495
+ manager,
5496
+ serviceName,
5497
+ serviceFile,
5498
+ proxyUrl,
5499
+ mcpUrl,
5500
+ inspectorUrl,
5501
+ installed: false,
5502
+ running: await probeProxyHealth(proxyUrl),
5503
+ written: false,
5504
+ snippet,
5505
+ detail: `Dry run: would write ${serviceFile} and start ${serviceName}.`
5506
+ };
5507
+ }
5508
+ await mkdir(dirname(serviceFile), { recursive: true });
5509
+ if (isMac) {
5510
+ await mkdir(join(home, "Library", "Logs"), { recursive: true });
5511
+ }
5512
+ await writeFile(serviceFile, snippet, "utf8");
5513
+ if (isMac) {
5514
+ const uid = options.uid ?? process.getuid?.() ?? 501;
5515
+ execCommand("launchctl", ["bootout", `gui/${uid}`, serviceFile], home);
5516
+ const boot = execCommand("launchctl", ["bootstrap", `gui/${uid}`, serviceFile], home);
5517
+ if (boot.error || boot.status !== 0) {
5518
+ const legacy = execCommand("launchctl", ["load", "-w", serviceFile], home);
5519
+ if (legacy.error || legacy.status !== 0) {
5520
+ throw new Error(
5521
+ `Failed to load LaunchAgent ${serviceFile}: ${(boot.stderr || legacy.stderr || boot.error?.message || "launchctl failed").trim()}`
5522
+ );
2906
5523
  }
2907
- return toolError(`Unknown tool "${name}".`);
2908
- } catch (err) {
2909
- return toolError(err instanceof Error ? err.message : String(err));
2910
5524
  }
5525
+ } else {
5526
+ const reload = execCommand("systemctl", ["--user", "daemon-reload"], home);
5527
+ if (reload.error) {
5528
+ throw new Error(`Failed to run systemctl --user: ${reload.error.message}`);
5529
+ }
5530
+ const enable = execCommand("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT], home);
5531
+ if (enable.error || enable.status !== 0) {
5532
+ throw new Error(
5533
+ `Failed to enable ${SYSTEMD_UNIT}: ${(enable.stderr || enable.stdout || enable.error?.message || "systemctl failed").trim()}`
5534
+ );
5535
+ }
5536
+ }
5537
+ let running = false;
5538
+ for (let attempt = 0; attempt < 10; attempt += 1) {
5539
+ if (await probeProxyHealth(proxyUrl)) {
5540
+ running = true;
5541
+ break;
5542
+ }
5543
+ await new Promise((r) => setTimeout(r, 150));
2911
5544
  }
2912
5545
  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 };
5546
+ action: "install",
5547
+ platform,
5548
+ manager,
5549
+ serviceName,
5550
+ serviceFile,
5551
+ proxyUrl,
5552
+ mcpUrl,
5553
+ inspectorUrl,
5554
+ installed: true,
5555
+ running,
5556
+ written: true,
5557
+ snippet,
5558
+ detail: running ? `Installed and started ${serviceName} (${serviceFile}). Listening on ${proxyUrl}.` : `Installed ${serviceName} (${serviceFile}). Check logs if ${proxyUrl} is still warming up.`
5559
+ };
5560
+ }
5561
+ function openUrlInBrowser(url, platform = process.platform) {
5562
+ try {
5563
+ let cmd;
5564
+ let args;
5565
+ if (platform === "darwin") {
5566
+ cmd = "open";
5567
+ args = [url];
5568
+ } else if (platform === "win32") {
5569
+ cmd = "cmd";
5570
+ args = ["/c", "start", "", url];
5571
+ } else {
5572
+ cmd = "xdg-open";
5573
+ args = [url];
5574
+ }
5575
+ const child = spawn(cmd, args, {
5576
+ stdio: "ignore",
5577
+ detached: true
5578
+ });
5579
+ child.on("error", () => {
5580
+ });
5581
+ child.unref();
5582
+ return true;
5583
+ } catch {
5584
+ return false;
5585
+ }
5586
+ }
5587
+ function formatCountSummary(counts) {
5588
+ const entries = Object.entries(counts).filter(([, n]) => n > 0);
5589
+ if (entries.length === 0) return "";
5590
+ return ` (${entries.map(([k, n]) => `${k}=${n}`).join(", ")})`;
5591
+ }
5592
+ async function runWrap(options) {
5593
+ if (!options.command.trim()) {
5594
+ throw new Error("Missing command to wrap. Usage: maskera-mcp wrap -- <command> [args...]");
5595
+ }
5596
+ const writeStderr = options.onStderr ?? ((line) => process.stderr.write(`${line}
5597
+ `));
5598
+ const mode = options.engine.status().defaultMode;
5599
+ const running = await startMaskeraProxy({
5600
+ host: options.host ?? "127.0.0.1",
5601
+ port: options.port ?? 0,
5602
+ upstream: options.upstream,
5603
+ anthropicUpstream: options.anthropicUpstream,
5604
+ openaiUpstream: options.openaiUpstream,
5605
+ engine: options.engine,
5606
+ mcpRoots: options.roots,
5607
+ allowRawRestore: options.allowRawRestore,
5608
+ readOnly: options.readOnly,
5609
+ approvalMode: options.approvalMode,
5610
+ profile: options.profile,
5611
+ customTerms: options.customTerms,
5612
+ restoreResponses: options.restoreResponses,
5613
+ auditLogPath: options.auditLogPath
5614
+ });
5615
+ let startupReceipt = null;
5616
+ try {
5617
+ if (options.verify !== false) {
5618
+ startupReceipt = await runDoctor({
5619
+ engine: options.engine,
5620
+ roots: options.roots,
5621
+ mode,
5622
+ profile: options.profile,
5623
+ customTerms: options.customTerms,
5624
+ proxyUrl: running.url,
5625
+ mcpUrl: running.mcpUrl
5626
+ });
5627
+ if (!startupReceipt.ok) {
5628
+ const failed = startupReceipt.checks.filter((c) => c.status === "fail").map((c) => `${c.name}: ${c.detail}`).join("; ");
5629
+ throw new Error(`Startup self-check failed (${failed})`);
2968
5630
  }
2969
- return {
2970
- jsonrpc: "2.0",
2971
- id,
2972
- error: { code: -32601, message: `Method not found: ${req.method}` }
5631
+ } else {
5632
+ options.engine.warmup();
5633
+ }
5634
+ const proofMode = startupReceipt?.sampleProof?.modeUsed ?? mode;
5635
+ const verifiedNote = startupReceipt ? ", 0 leaks verified" : "";
5636
+ writeStderr(
5637
+ `[maskera-wrap] active on ${running.url} (mode=${proofMode}${verifiedNote}) | inspector ${running.inspectorUrl}`
5638
+ );
5639
+ if (options.openInspector) {
5640
+ openUrlInBrowser(running.inspectorUrl);
5641
+ }
5642
+ const childEnv = {
5643
+ ...options.env ?? process.env,
5644
+ ANTHROPIC_BASE_URL: running.url,
5645
+ OPENAI_BASE_URL: `${running.url}/v1`,
5646
+ MASKERA_PROXY_URL: running.url,
5647
+ MASKERA_MCP_URL: running.mcpUrl
5648
+ };
5649
+ const child = spawn(options.command, [...options.args], {
5650
+ stdio: "inherit",
5651
+ env: childEnv
5652
+ });
5653
+ const forwardSigInt = () => {
5654
+ if (!child.killed) child.kill("SIGINT");
5655
+ };
5656
+ const forwardSigTerm = () => {
5657
+ if (!child.killed) child.kill("SIGTERM");
5658
+ };
5659
+ process.on("SIGINT", forwardSigInt);
5660
+ process.on("SIGTERM", forwardSigTerm);
5661
+ const { exitCode, signal } = await new Promise((resolveExit, rejectExit) => {
5662
+ child.on("error", rejectExit);
5663
+ child.on("exit", (code, sig) => {
5664
+ resolveExit({
5665
+ exitCode: code ?? (sig ? 1 : 0),
5666
+ signal: sig
5667
+ });
5668
+ });
5669
+ }).finally(() => {
5670
+ process.off("SIGINT", forwardSigInt);
5671
+ process.off("SIGTERM", forwardSigTerm);
5672
+ });
5673
+ const session = running.stats();
5674
+ let receiptSavedPath;
5675
+ if (options.receiptPath) {
5676
+ const payload = {
5677
+ schema: "maskera-wrap-receipt/v1",
5678
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5679
+ command: options.command,
5680
+ exitCode,
5681
+ proxyUrl: running.url,
5682
+ mcpUrl: running.mcpUrl,
5683
+ startupReceipt,
5684
+ session
2973
5685
  };
5686
+ receiptSavedPath = await writeDoctorReceipt(
5687
+ options.receiptPath,
5688
+ payload
5689
+ );
2974
5690
  }
2975
- };
5691
+ writeStderr(
5692
+ `[maskera-wrap] session done: ${session.requests} request(s), ${session.redactions} masked item(s)${formatCountSummary(session.counts)}, vault cleared.${receiptSavedPath ? ` receipt: ${receiptSavedPath}` : ""}`
5693
+ );
5694
+ return {
5695
+ exitCode,
5696
+ signal,
5697
+ proxyUrl: running.url,
5698
+ mcpUrl: running.mcpUrl,
5699
+ startupReceipt,
5700
+ session,
5701
+ ...receiptSavedPath ? { receiptPath: receiptSavedPath } : {}
5702
+ };
5703
+ } finally {
5704
+ await running.close();
5705
+ }
2976
5706
  }
2977
5707
 
2978
- export { ProxyInspector, SERVER_NAME, SERVER_VERSION, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createSseRestorer, extractGuardText, redactLlmRequestBody, renderInspectorHtml, restoreLlmResponseBody, runGuard, startMaskeraProxy };
5708
+ export { ApprovalBroker, LAUNCHD_LABEL, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, ProxyInspector, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, SYSTEMD_UNIT, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createModelProgressLogger, createSseRestorer, detectInstalledClients, extractGuardText, formatDoctorReport, isInstallClient, openUrlInBrowser, redactLlmRequestBody, renderInspectorHtml, renderLaunchdPlist, renderMaskeraPrompt, renderSystemdUnit, restoreLlmResponseBody, runDoctor, runGuard, runGuardViaWarmProxy, runInstall, runService, runWrap, startMaskeraProxy, writeDoctorReceipt };
2979
5709
  //# sourceMappingURL=index.js.map
2980
5710
  //# sourceMappingURL=index.js.map