mandat 0.0.0-stage → 0.1.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.
Files changed (70) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +293 -3
  3. package/dist/approvals/approvals.d.ts +136 -0
  4. package/dist/approvals/approvals.js +262 -0
  5. package/dist/bridge.d.ts +38 -0
  6. package/dist/bridge.js +117 -0
  7. package/dist/cli/args.d.ts +9 -0
  8. package/dist/cli/args.js +39 -0
  9. package/dist/cli/bin.d.ts +2 -0
  10. package/dist/cli/bin.js +3 -0
  11. package/dist/cli/main.d.ts +1 -0
  12. package/dist/cli/main.js +649 -0
  13. package/dist/cli/templates.d.ts +91 -0
  14. package/dist/cli/templates.js +57 -0
  15. package/dist/client.d.ts +54 -0
  16. package/dist/client.js +88 -0
  17. package/dist/controlplane/config.d.ts +48 -0
  18. package/dist/controlplane/config.js +33 -0
  19. package/dist/controlplane/console/.claude-flow/neural/patterns.json +402 -0
  20. package/dist/controlplane/console/.claude-flow/neural/stats.json +6 -0
  21. package/dist/controlplane/console/.claude-flow/policy/ledger-anchors.json +3 -0
  22. package/dist/controlplane/console/.claude-flow/policy/state.json +54 -0
  23. package/dist/controlplane/console/app.css +93 -0
  24. package/dist/controlplane/console/app.js +330 -0
  25. package/dist/controlplane/console/index.html +70 -0
  26. package/dist/controlplane/server.d.ts +17 -0
  27. package/dist/controlplane/server.js +427 -0
  28. package/dist/guard/guard.d.ts +154 -0
  29. package/dist/guard/guard.js +290 -0
  30. package/dist/guard/pinning.d.ts +46 -0
  31. package/dist/guard/pinning.js +49 -0
  32. package/dist/guard/remote.d.ts +78 -0
  33. package/dist/guard/remote.js +185 -0
  34. package/dist/index.d.ts +43 -0
  35. package/dist/index.js +67 -0
  36. package/dist/ledger/export.d.ts +27 -0
  37. package/dist/ledger/export.js +169 -0
  38. package/dist/ledger/ledger.d.ts +117 -0
  39. package/dist/ledger/ledger.js +139 -0
  40. package/dist/ledger/redact.d.ts +13 -0
  41. package/dist/ledger/redact.js +73 -0
  42. package/dist/ledger/report.d.ts +71 -0
  43. package/dist/ledger/report.js +128 -0
  44. package/dist/mcp/protect.d.ts +8 -0
  45. package/dist/mcp/protect.js +68 -0
  46. package/dist/mcp/server.d.ts +49 -0
  47. package/dist/mcp/server.js +211 -0
  48. package/dist/oidc.d.ts +52 -0
  49. package/dist/oidc.js +194 -0
  50. package/dist/policy/engine.d.ts +135 -0
  51. package/dist/policy/engine.js +243 -0
  52. package/dist/policy/expr.d.ts +56 -0
  53. package/dist/policy/expr.js +506 -0
  54. package/dist/scan/findings.d.ts +32 -0
  55. package/dist/scan/findings.js +105 -0
  56. package/dist/scan/remote.d.ts +7 -0
  57. package/dist/scan/remote.js +225 -0
  58. package/dist/scan/static.d.ts +15 -0
  59. package/dist/scan/static.js +245 -0
  60. package/dist/store.d.ts +14 -0
  61. package/dist/store.js +40 -0
  62. package/dist/sts/jwt.d.ts +64 -0
  63. package/dist/sts/jwt.js +168 -0
  64. package/dist/sts/revocation.d.ts +38 -0
  65. package/dist/sts/revocation.js +52 -0
  66. package/dist/sts/sts.d.ts +83 -0
  67. package/dist/sts/sts.js +239 -0
  68. package/dist/util.d.ts +28 -0
  69. package/dist/util.js +137 -0
  70. package/package.json +47 -4
@@ -0,0 +1,225 @@
1
+ // External scan of a remote MCP server's authorization surface (MCP Authorization rev. 2026-07-28):
2
+ // unauthenticated tools, token validation, PRM (RFC 9728), AS metadata (RFC 8414), PKCE S256,
3
+ // DCR vs CIMD, `iss` (RFC 9207), CORS, transport. Passive by default; `active` adds a DCR redirect probe.
4
+ const FIX_PROTECT = `// npm i mandat — then wrap your server:
5
+ import { createGuard, protect } from "mandat";
6
+ const guard = await createGuard({ resource: "https://mcp.example.com/mcp", controlPlane: process.env.MANDAT_URL, apiKey: process.env.MANDAT_API_KEY });
7
+ protect(mcpServer, guard); // policy + audit on every tools/call
8
+ app.use("/mcp", requireBearerAuth({ verifier: guard.sdkTokenVerifier({ InvalidTokenError }) }));`;
9
+ const POISON_PATTERNS = [
10
+ [/ignore (all |any )?(previous|prior|above) (instructions|prompts)/i, "instruction override"],
11
+ [/<\s*(important|system|instructions?)\s*>/i, "hidden instruction tag"],
12
+ [/do not (tell|inform|mention|reveal)[^.]{0,40}(user|human)/i, "concealment from user"],
13
+ [/(~\/\.ssh|id_rsa|\.aws\/credentials|\.env\b|mcp\.json|claude_desktop_config)/i, "credential file reference"],
14
+ [/\b(bcc|forward|send|exfiltrat\w*|upload)\b[^.]{0,60}\b(to|@)\s*[\w.-]+\.(com|net|io|ru|xyz)/i, "data forwarding to external address"],
15
+ [/before (using|calling) (this|any other) tool/i, "cross-tool instruction"],
16
+ ];
17
+ export async function scanRemote(target, opts = {}) {
18
+ const findings = [];
19
+ const passed = [];
20
+ const info = {};
21
+ const timeout = opts.timeoutMs ?? 8000;
22
+ const url = new URL(target);
23
+ const loc = { url: target };
24
+ const add = (f) => findings.push({ ...f, location: loc });
25
+ const req = async (u, init = {}) => {
26
+ try {
27
+ return await fetch(u, { redirect: "manual", ...init, headers: { ...opts.headers, ...init.headers }, signal: AbortSignal.timeout(timeout) });
28
+ }
29
+ catch (e) {
30
+ return null;
31
+ }
32
+ };
33
+ const rpc = (method, id, token) => req(target, {
34
+ method: "POST",
35
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": "2026-07-28", ...(token ? { authorization: `Bearer ${token}` } : {}) },
36
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params: method === "initialize" ? { protocolVersion: "2026-07-28", capabilities: {}, clientInfo: { name: "mandat-scan", version: "0.1.0" } } : {} }),
37
+ });
38
+ // 1. Transport
39
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
40
+ if (url.protocol !== "https:" && !loopback) {
41
+ add({ rule: "MDT-R001", severity: "high", title: "MCP endpoint not served over HTTPS", detail: `${url.origin} uses ${url.protocol} — bearer tokens travel in clear text.`, fix: "Terminate TLS in front of the MCP server; MCP authorization requires HTTPS for all non-loopback endpoints.", owasp: ["MCP07"] });
42
+ }
43
+ else
44
+ passed.push("transport");
45
+ // 2. Unauthenticated access
46
+ const init = await rpc("initialize", 1);
47
+ if (!init) {
48
+ add({ rule: "MDT-R000", severity: "info", title: "Server unreachable", detail: `No response from ${target} within ${timeout} ms.`, fix: "Check the URL and network access.", owasp: [] });
49
+ return { target, kind: "remote", scanned_at: new Date().toISOString(), findings, passed, info };
50
+ }
51
+ info.unauthenticated_status = init.status;
52
+ let wwwAuth = init.headers.get("www-authenticate");
53
+ if (init.status === 200) {
54
+ const sid = init.headers.get("mcp-session-id");
55
+ const list = await req(target, {
56
+ method: "POST",
57
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...(sid ? { "mcp-session-id": sid } : {}) },
58
+ body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }),
59
+ });
60
+ const tools = list ? await parseRpcTools(list) : null;
61
+ if (tools) {
62
+ info.exposed_tools = tools.map((t) => t.name);
63
+ add({
64
+ rule: "MDT-R002", severity: "critical", title: "Tools exposed without authentication",
65
+ detail: `tools/list answered without any credentials and exposed ${tools.length} tools (${tools.slice(0, 8).map((t) => t.name).join(", ")}${tools.length > 8 ? ", …" : ""}). 40.55% of public MCP servers are in this state.`,
66
+ fix: "Require an OAuth bearer token on every MCP request (including initialize and tools/list) and return 401 with a resource_metadata challenge.",
67
+ fixCode: FIX_PROTECT, owasp: ["MCP07", "ASI03"],
68
+ });
69
+ for (const t of tools) {
70
+ const text = `${t.description ?? ""} ${JSON.stringify(t.inputSchema ?? {})}`;
71
+ const hit = POISON_PATTERNS.find(([re]) => re.test(text));
72
+ if (hit)
73
+ add({
74
+ rule: "MDT-R013", severity: "high", title: `Possible tool poisoning in '${t.name}'`,
75
+ detail: `The tool description contains a ${hit[1]} pattern — hidden instructions to the model are a known MCP attack (rug pull / tool poisoning).`,
76
+ fix: "Review the tool description; pin tool definitions so changes are detected (`mandat pin <url>`).", owasp: ["MCP03", "ASI02"],
77
+ });
78
+ }
79
+ }
80
+ else {
81
+ add({ rule: "MDT-R002", severity: "high", title: "MCP initialize succeeds without authentication", detail: "The server accepted an unauthenticated initialize request.", fix: "Authenticate every MCP request, not only tools/call.", fixCode: FIX_PROTECT, owasp: ["MCP07", "ASI03"] });
82
+ }
83
+ }
84
+ else if (init.status === 401) {
85
+ passed.push("auth-required");
86
+ }
87
+ else {
88
+ info.note = `initialize without credentials returned ${init.status}`;
89
+ }
90
+ // 3. Garbage token must be rejected
91
+ const bogus = await rpc("initialize", 3, "mandat-scan-invalid-token");
92
+ if (bogus && bogus.status === 200 && init.status === 401) {
93
+ add({ rule: "MDT-R012", severity: "critical", title: "Server accepts an invalid bearer token", detail: "Any non-empty Authorization header is accepted: the token is not validated.", fix: "Validate signature, issuer, audience (this server's URL) and expiry of every access token.", fixCode: FIX_PROTECT, owasp: ["MCP07", "ASI03"] });
94
+ }
95
+ else if (bogus && bogus.status === 401)
96
+ passed.push("rejects-invalid-token");
97
+ // 3b. CORS
98
+ const pre = await req(target, { method: "OPTIONS", headers: { origin: "https://evil.mandat-scan.invalid", "access-control-request-method": "POST", "access-control-request-headers": "authorization,content-type" } });
99
+ const acao = pre?.headers.get("access-control-allow-origin");
100
+ const acac = pre?.headers.get("access-control-allow-credentials");
101
+ if (acao === "https://evil.mandat-scan.invalid" || (acao === "*" && acac === "true"))
102
+ add({ rule: "MDT-R010", severity: "high", title: "CORS reflects arbitrary origins", detail: `Access-Control-Allow-Origin: ${acao}${acac ? `, Allow-Credentials: ${acac}` : ""}. Any website can drive this MCP server from a victim's browser.`, fix: "Allow-list the exact origins of your web clients and validate the Origin header (DNS rebinding protection).", owasp: ["MCP07"] });
103
+ else if (acao === "*")
104
+ add({ rule: "MDT-R010", severity: "low", title: "CORS allows any origin", detail: "Access-Control-Allow-Origin: * on the MCP endpoint.", fix: "Restrict to known origins.", owasp: ["MCP07"] });
105
+ else
106
+ passed.push("cors");
107
+ // 4. WWW-Authenticate + Protected Resource Metadata (RFC 9728)
108
+ wwwAuth ??= bogus?.headers.get("www-authenticate") ?? null;
109
+ info.www_authenticate = wwwAuth;
110
+ let prmUrl = wwwAuth ? /resource_metadata="([^"]+)"/.exec(wwwAuth)?.[1] : undefined;
111
+ if (init.status === 401 && !prmUrl) {
112
+ add({ rule: "MDT-R003", severity: "high", title: "401 without resource_metadata challenge", detail: `WWW-Authenticate is ${wwwAuth ? `"${wwwAuth}"` : "missing"}; MCP clients cannot discover the authorization server.`, fix: 'Return `WWW-Authenticate: Bearer resource_metadata="https://<host>/.well-known/oauth-protected-resource"` on 401.', owasp: ["MCP07"] });
113
+ }
114
+ const candidates = [prmUrl, `${url.origin}/.well-known/oauth-protected-resource${url.pathname === "/" ? "" : url.pathname}`, `${url.origin}/.well-known/oauth-protected-resource`].filter(Boolean);
115
+ let prm = null;
116
+ for (const c of candidates) {
117
+ const r = await req(c);
118
+ if (r?.ok) {
119
+ try {
120
+ prm = (await r.json());
121
+ prmUrl = c;
122
+ break;
123
+ }
124
+ catch { /* not JSON */ }
125
+ }
126
+ }
127
+ info.prm_url = prm ? prmUrl : null;
128
+ if (!prm) {
129
+ if (init.status !== 200 || findings.some((f) => f.rule === "MDT-R002"))
130
+ add({ rule: "MDT-R004", severity: "high", title: "Protected Resource Metadata missing", detail: "No RFC 9728 document found; required by MCP Authorization (2025-06-18 and later).", fix: "Serve /.well-known/oauth-protected-resource with `resource` and `authorization_servers`.", fixCode: `app.get("/.well-known/oauth-protected-resource", (_req, res) => res.json(guard.protectedResourceMetadata()));`, owasp: ["MCP07"] });
131
+ return { target, kind: "remote", scanned_at: new Date().toISOString(), findings, passed, info };
132
+ }
133
+ passed.push("prm");
134
+ const resource = String(prm.resource ?? "");
135
+ if (resource && normalize(resource) !== normalize(target) && !normalize(target).startsWith(normalize(resource)))
136
+ add({ rule: "MDT-R005", severity: "medium", title: "PRM `resource` does not match the endpoint", detail: `PRM resource is ${resource} but the endpoint is ${target}; clients bind tokens (RFC 8707) to the wrong audience.`, fix: "Set `resource` to the canonical MCP endpoint URL and validate `aud` against it.", owasp: ["MCP07"] });
137
+ const asList = Array.isArray(prm.authorization_servers) ? prm.authorization_servers : [];
138
+ if (!asList.length) {
139
+ add({ rule: "MDT-R004", severity: "high", title: "PRM lists no authorization server", detail: "`authorization_servers` is empty or missing.", fix: "List your issuer in `authorization_servers`.", owasp: ["MCP07"] });
140
+ return { target, kind: "remote", scanned_at: new Date().toISOString(), findings, passed, info };
141
+ }
142
+ // 5. Authorization server metadata (RFC 8414 / OIDC discovery)
143
+ const issuer = asList[0];
144
+ const iu = new URL(issuer);
145
+ const asCandidates = [
146
+ `${iu.origin}/.well-known/oauth-authorization-server${iu.pathname === "/" ? "" : iu.pathname}`,
147
+ `${iu.origin}/.well-known/openid-configuration${iu.pathname === "/" ? "" : iu.pathname}`,
148
+ `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`,
149
+ ];
150
+ let asm = null;
151
+ for (const c of asCandidates) {
152
+ const r = await req(c);
153
+ if (r?.ok) {
154
+ try {
155
+ asm = (await r.json());
156
+ info.as_metadata_url = c;
157
+ break;
158
+ }
159
+ catch { /* ignore */ }
160
+ }
161
+ }
162
+ if (!asm) {
163
+ add({ rule: "MDT-R006", severity: "high", title: "Authorization server metadata not found", detail: `Could not fetch RFC 8414 / OIDC metadata for ${issuer}.`, fix: "Publish /.well-known/oauth-authorization-server on the issuer.", owasp: ["MCP07"] });
164
+ return { target, kind: "remote", scanned_at: new Date().toISOString(), findings, passed, info };
165
+ }
166
+ passed.push("as-metadata");
167
+ if (asm.issuer && asm.issuer !== issuer)
168
+ add({ rule: "MDT-R009", severity: "medium", title: "Issuer mismatch in AS metadata", detail: `metadata issuer is ${String(asm.issuer)}, PRM says ${issuer}.`, fix: "The `issuer` value must exactly equal the URL listed in PRM.", owasp: ["MCP07"] });
169
+ const pkce = asm.code_challenge_methods_supported ?? [];
170
+ if (!pkce.includes("S256"))
171
+ add({ rule: "MDT-R007", severity: "high", title: "PKCE S256 not advertised", detail: `code_challenge_methods_supported = ${JSON.stringify(pkce)}; MCP clients MUST refuse to proceed without S256.`, fix: 'Enforce PKCE and advertise `"code_challenge_methods_supported": ["S256"]`.', owasp: ["MCP07"] });
172
+ else
173
+ passed.push("pkce-s256");
174
+ if (pkce.includes("plain"))
175
+ add({ rule: "MDT-R007", severity: "medium", title: "PKCE downgrade to `plain` allowed", detail: "The AS accepts the plain method, which offers no protection against code interception.", fix: "Remove `plain`; accept S256 only.", owasp: ["MCP07"] });
176
+ const grants = asm.grant_types_supported ?? [];
177
+ for (const g of ["implicit", "password"])
178
+ if (grants.includes(g))
179
+ add({ rule: "MDT-R014", severity: "medium", title: `Legacy grant '${g}' enabled`, detail: `OAuth 2.1 removes the ${g} grant.`, fix: `Disable the ${g} grant.`, owasp: ["MCP07"] });
180
+ const cimd = asm.client_id_metadata_document_supported === true;
181
+ if (asm.registration_endpoint && !cimd)
182
+ add({ rule: "MDT-R008", severity: "low", title: "Dynamic Client Registration without CIMD", detail: "DCR is deprecated in MCP 2026-07-28 (removal no earlier than 2027-07-28); Client ID Metadata Documents are the recommended mechanism.", fix: "Support CIMD (fetch client metadata from the client_id URL with SSRF protection) and advertise `client_id_metadata_document_supported: true`.", owasp: ["MCP07"] });
183
+ else if (cimd)
184
+ passed.push("cimd");
185
+ if (asm.authorization_response_iss_parameter_supported !== true)
186
+ add({ rule: "MDT-R009", severity: "medium", title: "No `iss` in authorization responses (RFC 9207)", detail: "Without the iss parameter, clients using several authorization servers are exposed to mix-up attacks.", fix: "Return `iss` in authorization responses and advertise `authorization_response_iss_parameter_supported: true`.", owasp: ["MCP07"] });
187
+ else
188
+ passed.push("iss-rfc9207");
189
+ // 7. Active: does DCR accept an arbitrary redirect URI from an anonymous registrant?
190
+ if (opts.active && typeof asm.registration_endpoint === "string") {
191
+ const r = await req(asm.registration_endpoint, {
192
+ method: "POST",
193
+ headers: { "content-type": "application/json" },
194
+ body: JSON.stringify({ client_name: "mandat-scan-probe", redirect_uris: ["https://attacker.mandat-scan.invalid/callback"], grant_types: ["authorization_code"], token_endpoint_auth_method: "none" }),
195
+ });
196
+ if (r && (r.status === 200 || r.status === 201))
197
+ add({ rule: "MDT-R011", severity: "high", title: "Anonymous DCR accepts any redirect URI", detail: "The registration endpoint registered a client with an attacker-controlled redirect_uri (found on 114 of 119 OAuth MCP servers in the Fudan 2026 study). Combined with consent reuse this enables code theft.", fix: "Require initial access tokens or allow-list redirect URI hosts; prefer CIMD.", owasp: ["MCP07", "ASI03"] });
198
+ else
199
+ passed.push("dcr-redirect-allowlist");
200
+ }
201
+ return { target, kind: "remote", scanned_at: new Date().toISOString(), findings, passed, info };
202
+ }
203
+ function normalize(u) {
204
+ return u.replace(/\/+$/, "").toLowerCase();
205
+ }
206
+ async function parseRpcTools(res) {
207
+ if (!res.ok)
208
+ return null;
209
+ const text = await res.text();
210
+ const ct = res.headers.get("content-type") ?? "";
211
+ let msg = null;
212
+ try {
213
+ if (ct.includes("text/event-stream")) {
214
+ const data = text.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).find((l) => l.includes('"tools"'));
215
+ msg = data ? JSON.parse(data) : null;
216
+ }
217
+ else
218
+ msg = JSON.parse(text);
219
+ }
220
+ catch {
221
+ return null;
222
+ }
223
+ const tools = msg?.result?.tools;
224
+ return Array.isArray(tools) ? tools : null;
225
+ }
@@ -0,0 +1,15 @@
1
+ import type { ScanReport } from "./findings.ts";
2
+ interface ServerEntry {
3
+ command?: string;
4
+ args?: string[];
5
+ env?: Record<string, string>;
6
+ url?: string;
7
+ serverUrl?: string;
8
+ type?: string;
9
+ headers?: Record<string, string>;
10
+ }
11
+ export declare function scanConfigFile(path: string): ScanReport;
12
+ export declare function scanServers(servers: Record<string, ServerEntry>, file: string, rawText?: string): ScanReport;
13
+ export declare function scanSource(dir: string, maxFiles?: number): ScanReport;
14
+ export declare function levenshtein(a: string, b: string): number;
15
+ export {};
@@ -0,0 +1,245 @@
1
+ // Static analysis of MCP client configurations (Claude Desktop, Cursor, VS Code, Windsurf…) and of
2
+ // MCP server source code. Detects supply-chain, command-execution and exfiltration risks.
3
+ import { readdirSync, readFileSync, statSync } from "node:fs";
4
+ import { extname, join, relative } from "node:path";
5
+ /** Popular legitimate MCP packages, used for typosquat distance checks. */
6
+ const KNOWN_PACKAGES = [
7
+ "@modelcontextprotocol/server-filesystem", "@modelcontextprotocol/server-github", "@modelcontextprotocol/server-postgres",
8
+ "@modelcontextprotocol/server-slack", "@modelcontextprotocol/server-memory", "@modelcontextprotocol/server-puppeteer",
9
+ "@modelcontextprotocol/server-brave-search", "@modelcontextprotocol/server-google-maps", "@modelcontextprotocol/server-everything",
10
+ "@modelcontextprotocol/server-sequential-thinking", "@modelcontextprotocol/inspector", "@playwright/mcp", "@supabase/mcp-server-supabase",
11
+ "@notionhq/notion-mcp-server", "@stripe/mcp", "@sentry/mcp-server", "@azure-devops/mcp", "@cloudflare/mcp-server-cloudflare",
12
+ "mcp-server-fetch", "mcp-server-git", "mcp-server-time", "mcp-server-sqlite", "firecrawl-mcp", "figma-developer-mcp", "mcp-remote",
13
+ ];
14
+ /** Package versions publicly reported as malicious. */
15
+ const MALICIOUS = [
16
+ { pkg: "postmark-mcp", versions: (v) => !v || cmpVersion(v, "1.0.16") >= 0, why: "versions >= 1.0.16 silently BCC every e-mail to an attacker address (Sep 2025)" },
17
+ { pkg: "litellm", versions: (v) => !v || ["1.82.7", "1.82.8", "1.107.0"].includes(v), why: "1.82.7, 1.82.8 and 1.107.0 were published from stolen CI credentials with a credential stealer (2026)" },
18
+ ];
19
+ const RUNNERS = {
20
+ npx: { pinned: (s) => /^(@[^/]+\/)?[^@]+@\d+\.\d+\.\d+/.test(s), eco: "npm" },
21
+ bunx: { pinned: (s) => /^(@[^/]+\/)?[^@]+@\d+\.\d+\.\d+/.test(s), eco: "npm" },
22
+ pnpx: { pinned: (s) => /^(@[^/]+\/)?[^@]+@\d+\.\d+\.\d+/.test(s), eco: "npm" },
23
+ uvx: { pinned: (s) => /==\d/.test(s) || /@\d+\.\d+/.test(s), eco: "pypi" },
24
+ pipx: { pinned: (s) => /==\d/.test(s), eco: "pypi" },
25
+ };
26
+ const SHELLS = ["sh", "bash", "zsh", "cmd", "cmd.exe", "powershell", "powershell.exe", "pwsh", "pwsh.exe"];
27
+ const SECRET_ENV = /(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|PRIVATE_KEY|ACCESS_KEY|CLIENT_SECRET|CREDENTIALS?)/i;
28
+ export function scanConfigFile(path) {
29
+ const text = readFileSync(path, "utf8");
30
+ let json;
31
+ try {
32
+ json = JSON.parse(stripJsonComments(text));
33
+ }
34
+ catch (e) {
35
+ return { target: path, kind: "config", scanned_at: new Date().toISOString(), passed: [], findings: [{ rule: "MDT-C000", severity: "info", title: "Not valid JSON", detail: e.message, fix: "Fix the JSON syntax.", owasp: [], location: { file: path } }] };
36
+ }
37
+ const servers = json.mcpServers ?? json.servers ?? json.mcp?.servers ?? json.context_servers ?? {};
38
+ return scanServers(servers, path, text);
39
+ }
40
+ export function scanServers(servers, file, rawText = "") {
41
+ const findings = [];
42
+ const lineOf = (needle) => {
43
+ const i = rawText.indexOf(needle);
44
+ return i < 0 ? undefined : rawText.slice(0, i).split("\n").length;
45
+ };
46
+ for (const [name, s] of Object.entries(servers)) {
47
+ const location = { file, server: name, line: lineOf(`"${name}"`) };
48
+ const add = (f) => findings.push({ ...f, location });
49
+ const cmd = (s.command ?? "").split(/[\\/]/).pop().toLowerCase();
50
+ const args = (s.args ?? []).map(String);
51
+ const all = [s.command ?? "", ...args].join(" ");
52
+ // Package runners: pinning, malicious versions, typosquats
53
+ const runner = RUNNERS[cmd.replace(/\.(cmd|exe)$/, "")];
54
+ if (runner) {
55
+ const spec = args.find((a) => !a.startsWith("-"));
56
+ if (spec) {
57
+ const { pkg, version } = parseSpec(spec, runner.eco);
58
+ if (!runner.pinned(spec) || /@latest\b/.test(spec)) {
59
+ add({
60
+ rule: "MDT-C001", severity: "high", title: `Unpinned package '${pkg}' executed by ${cmd}`,
61
+ detail: `${cmd}${args.includes("-y") || args.includes("--yes") ? " -y" : ""} fetches and runs whatever version is current. A compromised maintainer account ships code straight to this machine (postmark-mcp, LiteLLM 2026).`,
62
+ fix: `Pin an exact, reviewed version and verify provenance.`,
63
+ fixCode: `"args": ["-y", "${pkg}@<exact-version>"]`,
64
+ owasp: ["ASI04", "MCP04"],
65
+ });
66
+ }
67
+ const bad = MALICIOUS.find((m) => m.pkg === pkg && m.versions(version));
68
+ if (bad)
69
+ add({ rule: "MDT-C002", severity: "critical", title: `Known-malicious package '${pkg}${version ? "@" + version : ""}'`, detail: bad.why, fix: "Remove it, rotate every credential it could access, and audit outbound traffic.", owasp: ["ASI04", "MCP04"] });
70
+ const squat = KNOWN_PACKAGES.find((k) => k !== pkg && levenshtein(k, pkg) <= 2 && pkg.length > 5);
71
+ if (squat)
72
+ add({ rule: "MDT-C003", severity: "high", title: `Possible typosquat: '${pkg}' looks like '${squat}'`, detail: "Package names one or two characters away from popular MCP servers are a common supply-chain lure.", fix: `Verify the publisher; did you mean '${squat}'?`, owasp: ["ASI04", "MCP04"] });
73
+ }
74
+ }
75
+ // Shell interpreters / remote code
76
+ if (SHELLS.includes(cmd) && args.some((a) => ["-c", "/c", "-command", "-encodedcommand", "/k"].includes(a.toLowerCase()))) {
77
+ add({ rule: "MDT-C004", severity: "high", title: "MCP server launched through a shell", detail: `'${all.slice(0, 120)}' runs an arbitrary shell string. stdio transports execute whatever command they are given (CVE-2026-30623 class).`, fix: "Invoke the server binary directly with an argument array; never build stdio commands from untrusted input.", owasp: ["ASI05", "MCP05"] });
78
+ }
79
+ if (/(curl|wget|iwr|invoke-webrequest)[^|]*\|\s*(sh|bash|iex|python)/i.test(all) || /\beval\b/.test(all)) {
80
+ add({ rule: "MDT-C005", severity: "critical", title: "Remote code piped into an interpreter", detail: `'${all.slice(0, 120)}' downloads and executes code at every start.`, fix: "Install a pinned, verified artifact instead.", owasp: ["ASI04", "ASI05", "MCP05"] });
81
+ }
82
+ // Containers
83
+ if (cmd === "docker" || cmd === "podman") {
84
+ if (args.includes("--privileged"))
85
+ add({ rule: "MDT-C010", severity: "high", title: "Container runs --privileged", detail: "A privileged container is effectively root on the host.", fix: "Drop --privileged; grant only needed capabilities.", owasp: ["ASI05"] });
86
+ const mount = args.find((a, i) => (args[i - 1] === "-v" || args[i - 1] === "--volume") && /^(\/|~|[A-Za-z]:\\?):/.test(a));
87
+ if (mount)
88
+ add({ rule: "MDT-C010", severity: "high", title: "Container mounts the host root / home", detail: `Volume '${mount}' exposes the whole filesystem to the tool.`, fix: "Mount only the directories the server needs, read-only where possible.", owasp: ["ASI02", "MCP10"] });
89
+ if (args.some((a, i) => a === "--network=host" || (a === "--network" && args[i + 1] === "host")))
90
+ add({ rule: "MDT-C010", severity: "medium", title: "Container shares the host network", detail: "--network host lets the tool reach every local service.", fix: "Use an isolated network.", owasp: ["ASI02"] });
91
+ const img = args.find((a) => /^[\w.\-/]+(:[\w.\-]+)?(@sha256:[a-f0-9]{64})?$/.test(a) && a.includes("/") && !a.startsWith("-"));
92
+ if (img && !img.includes("@sha256:"))
93
+ add({ rule: "MDT-C001", severity: "medium", title: `Container image '${img}' not pinned by digest`, detail: "Tags are mutable; the image can change under you.", fix: "Reference the image by digest (image@sha256:…).", owasp: ["ASI04", "MCP04"] });
94
+ }
95
+ // Filesystem breadth
96
+ if (/server-filesystem|filesystem/i.test(all)) {
97
+ const broad = args.find((a) => ["/", "~", "$HOME", "%USERPROFILE%", "C:\\", "C:/", "/Users", "/home"].includes(a.replace(/[\\/]+$/, "") || "/"));
98
+ if (broad)
99
+ add({ rule: "MDT-C009", severity: "medium", title: `Filesystem server exposes '${broad}'`, detail: "Agents can read SSH keys, cloud credentials and other configs, then exfiltrate them via another tool.", fix: "Allow-list only project directories.", owasp: ["ASI02", "MCP10"] });
100
+ }
101
+ // Network binding
102
+ if (/0\.0\.0\.0|--host[= ]::(\s|$)/.test(all) || Object.values(s.env ?? {}).some((v) => v === "0.0.0.0"))
103
+ add({ rule: "MDT-C008", severity: "medium", title: "Server binds to all interfaces", detail: "0.0.0.0 exposes a local MCP server to the LAN — often without authentication.", fix: "Bind to 127.0.0.1 for local servers.", owasp: ["MCP07", "MCP09"] });
104
+ // Secrets
105
+ for (const [k, v] of Object.entries(s.env ?? {})) {
106
+ if (SECRET_ENV.test(k) && typeof v === "string" && v.length >= 8 && !/^\$\{|^\$[A-Z_]|^%[A-Z_]+%$|^<.*>$|^op:\/\/|^env:/.test(v))
107
+ add({ rule: "MDT-C006", severity: "medium", title: `Plain-text secret in env '${k}'`, detail: "Long-lived credentials stored in a config file are readable by every tool that can read files.", fix: "Reference a secret manager or environment variable (e.g. \"${env:" + k + "}\"); prefer short-lived OAuth tokens.", owasp: ["MCP01", "ASI03"] });
108
+ }
109
+ for (const [k, v] of Object.entries(s.headers ?? {})) {
110
+ if (/^authorization$/i.test(k) && /^Bearer\s+[A-Za-z0-9._~+/-]{12,}/.test(v) && !/\$\{/.test(v))
111
+ add({ rule: "MDT-C011", severity: "medium", title: "Static bearer token in remote server config", detail: "Static tokens (29% of MCP servers) never expire and are not bound to a user or task.", fix: "Use the MCP OAuth flow so tokens are short-lived and audience-bound.", owasp: ["MCP01", "MCP07"] });
112
+ }
113
+ // Remote transport
114
+ const remote = s.url ?? s.serverUrl;
115
+ if (remote) {
116
+ try {
117
+ const u = new URL(remote);
118
+ if (u.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(u.hostname))
119
+ add({ rule: "MDT-C007", severity: "high", title: "Remote MCP server over plain HTTP", detail: `${remote} — tokens and tool data in clear text.`, fix: "Use https://.", owasp: ["MCP07"] });
120
+ }
121
+ catch { /* not a URL */ }
122
+ }
123
+ }
124
+ const passed = findings.length ? [] : ["no-issues"];
125
+ return { target: file, kind: "config", scanned_at: new Date().toISOString(), findings, passed, info: { servers: Object.keys(servers) } };
126
+ }
127
+ // ---------- source scan ----------
128
+ const SOURCE_RULES = [
129
+ { rule: "MDT-S001", severity: "high", ext: [".js", ".mjs", ".cjs", ".ts", ".mts"], re: /(?<![.\w])eval\s*\((?!\s*\w+\s*:)|new\s+Function\s*\(/, title: "Dynamic code evaluation", fix: "Never evaluate model- or user-provided strings.", owasp: ["ASI05", "MCP05"] },
130
+ { rule: "MDT-S002", severity: "high", ext: [".js", ".mjs", ".cjs", ".ts", ".mts"], re: /(?<![.\w])(exec|execSync)\s*\(\s*[`'"][^`'"]*\$\{|(?<![.\w])(exec|execSync)\s*\(\s*[a-zA-Z_]+\s*[+,)]|spawn\s*\([^)]*shell\s*:\s*true/, title: "Shell command built from variables", fix: "Use execFile/spawn with an argument array and an allow-list of commands.", owasp: ["ASI05", "MCP05"] },
131
+ { rule: "MDT-S002", severity: "high", ext: [".py"], re: /subprocess\.\w+\([^)]*shell\s*=\s*True|os\.system\s*\(|os\.popen\s*\(/, title: "Shell command execution", fix: "Use subprocess.run([...], shell=False) with validated arguments.", owasp: ["ASI05", "MCP05"] },
132
+ { rule: "MDT-S001", severity: "high", ext: [".py"], re: /(?<![.\w])(eval|exec)\s*\((?!\s*\))/, title: "Dynamic code evaluation", fix: "Never evaluate model- or user-provided strings.", owasp: ["ASI05", "MCP05"] },
133
+ { rule: "MDT-S003", severity: "medium", ext: [".js", ".mjs", ".cjs", ".ts", ".mts", ".py"], re: /(listen\s*\([^)]*|host\s*[:=]\s*)["']0\.0\.0\.0["']/i, title: "Listens on all interfaces", fix: "Bind to 127.0.0.1 unless behind an authenticating reverse proxy.", owasp: ["MCP07", "MCP09"] },
134
+ { rule: "MDT-S004", severity: "high", ext: [".js", ".mjs", ".cjs", ".ts", ".mts"], re: /authorization\s*:\s*(req|request|extra|ctx)\.(headers\.authorization|authInfo\.token|headers\[["']authorization["']\])/i, title: "Token passthrough to downstream API", fix: "Forbidden by the MCP spec: exchange for a downstream token (RFC 8693) instead of forwarding the client's token.", owasp: ["MCP01", "ASI03"] },
135
+ { rule: "MDT-S004", severity: "high", ext: [".py"], re: /["']Authorization["']\s*:\s*request\.headers\[["']Authorization["']\]/, title: "Token passthrough to downstream API", fix: "Exchange for a downstream token instead of forwarding the client's token.", owasp: ["MCP01", "ASI03"] },
136
+ { rule: "MDT-S005", severity: "info", ext: [".js", ".mjs", ".ts", ".mts"], re: /StreamableHTTPServerTransport|SSEServerTransport/, title: "HTTP MCP transport — check authentication", fix: "Ensure every request passes bearer authentication (requireBearerAuth + guard.sdkTokenVerifier()).", owasp: ["MCP07"] },
137
+ ];
138
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".venv", "venv", "__pycache__", ".mandat", "coverage"]);
139
+ export function scanSource(dir, maxFiles = 5000) {
140
+ const findings = [];
141
+ let files = 0;
142
+ const walk = (d) => {
143
+ for (const name of readdirSync(d)) {
144
+ if (files >= maxFiles)
145
+ return;
146
+ const p = join(d, name);
147
+ const st = statSync(p);
148
+ if (st.isDirectory()) {
149
+ if (!SKIP_DIRS.has(name))
150
+ walk(p);
151
+ continue;
152
+ }
153
+ const ext = extname(name);
154
+ const rules = SOURCE_RULES.filter((r) => r.ext.includes(ext));
155
+ if (!rules.length || st.size > 1_000_000)
156
+ continue;
157
+ files++;
158
+ const lines = readFileSync(p, "utf8").split("\n");
159
+ const hasAuth = lines.some((l) => /requireBearerAuth|sdkTokenVerifier|McpHttpServer|guard\.verify/.test(l));
160
+ lines.forEach((line, i) => {
161
+ if (/^\s*(\/\/|#|\/?\*)/.test(line))
162
+ return;
163
+ for (const r of rules) {
164
+ if (!r.re.test(line))
165
+ continue;
166
+ if (r.rule === "MDT-S005" && hasAuth)
167
+ continue;
168
+ findings.push({ rule: r.rule, severity: r.severity, title: r.title, detail: line.trim().slice(0, 160), fix: r.fix, owasp: r.owasp, location: { file: relative(process.cwd(), p) || p, line: i + 1 } });
169
+ }
170
+ });
171
+ }
172
+ };
173
+ walk(dir);
174
+ return { target: dir, kind: "source", scanned_at: new Date().toISOString(), findings, passed: findings.length ? [] : ["no-issues"], info: { files } };
175
+ }
176
+ // ---------- helpers ----------
177
+ function parseSpec(spec, eco) {
178
+ if (eco === "pypi") {
179
+ const m = /^([A-Za-z0-9_.\-[\]]+?)(?:==|@)([\w.]+)?$/.exec(spec);
180
+ return m ? { pkg: m[1].toLowerCase(), version: m[2] ?? null } : { pkg: spec.toLowerCase(), version: null };
181
+ }
182
+ const at = spec.lastIndexOf("@");
183
+ if (at > 0)
184
+ return { pkg: spec.slice(0, at), version: spec.slice(at + 1) || null };
185
+ return { pkg: spec, version: null };
186
+ }
187
+ function cmpVersion(a, b) {
188
+ const pa = a.split(".").map((x) => parseInt(x, 10) || 0), pb = b.split(".").map((x) => parseInt(x, 10) || 0);
189
+ for (let i = 0; i < 3; i++)
190
+ if ((pa[i] ?? 0) !== (pb[i] ?? 0))
191
+ return (pa[i] ?? 0) - (pb[i] ?? 0);
192
+ return 0;
193
+ }
194
+ export function levenshtein(a, b) {
195
+ if (Math.abs(a.length - b.length) > 3)
196
+ return 99;
197
+ const dp = Array.from({ length: b.length + 1 }, (_, i) => i);
198
+ for (let i = 1; i <= a.length; i++) {
199
+ let prev = dp[0];
200
+ dp[0] = i;
201
+ for (let j = 1; j <= b.length; j++) {
202
+ const tmp = dp[j];
203
+ dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
204
+ prev = tmp;
205
+ }
206
+ }
207
+ return dp[b.length];
208
+ }
209
+ function stripJsonComments(s) {
210
+ // JSONC (VS Code / Cursor): drop // and /* */ comments outside strings, and trailing commas.
211
+ let out = "", inStr = false;
212
+ for (let i = 0; i < s.length; i++) {
213
+ const c = s[i], n = s[i + 1];
214
+ if (inStr) {
215
+ out += c;
216
+ if (c === "\\") {
217
+ out += n ?? "";
218
+ i++;
219
+ }
220
+ else if (c === '"')
221
+ inStr = false;
222
+ continue;
223
+ }
224
+ if (c === '"') {
225
+ inStr = true;
226
+ out += c;
227
+ continue;
228
+ }
229
+ if (c === "/" && n === "/") {
230
+ while (i < s.length && s[i] !== "\n")
231
+ i++;
232
+ out += "\n";
233
+ continue;
234
+ }
235
+ if (c === "/" && n === "*") {
236
+ i += 2;
237
+ while (i < s.length && !(s[i] === "*" && s[i + 1] === "/"))
238
+ i++;
239
+ i++;
240
+ continue;
241
+ }
242
+ out += c;
243
+ }
244
+ return out.replace(/,(\s*[}\]])/g, "$1");
245
+ }
@@ -0,0 +1,14 @@
1
+ export declare class JsonCollection<T extends {
2
+ id: string;
3
+ }> {
4
+ private items;
5
+ readonly path: string | null;
6
+ constructor(path: string | null);
7
+ get(id: string): T | undefined;
8
+ all(): T[];
9
+ filter(fn: (t: T) => boolean): T[];
10
+ put(item: T): T;
11
+ update(id: string, fn: (t: T) => T): T | undefined;
12
+ delete(id: string): boolean;
13
+ private flush;
14
+ }
package/dist/store.js ADDED
@@ -0,0 +1,40 @@
1
+ // Tiny durable key/value collection persisted as one JSON file (atomic rewrite on change).
2
+ // Good enough for an MVP control plane; swap for Postgres behind the same interface later.
3
+ import { readJson, writeJsonAtomic } from "./util.js";
4
+ export class JsonCollection {
5
+ items = new Map();
6
+ path;
7
+ constructor(path) {
8
+ this.path = path;
9
+ if (path)
10
+ for (const item of readJson(path, []))
11
+ this.items.set(item.id, item);
12
+ }
13
+ get(id) { return this.items.get(id); }
14
+ all() { return [...this.items.values()]; }
15
+ filter(fn) { return this.all().filter(fn); }
16
+ put(item) {
17
+ this.items.set(item.id, item);
18
+ this.flush();
19
+ return item;
20
+ }
21
+ update(id, fn) {
22
+ const cur = this.items.get(id);
23
+ if (!cur)
24
+ return undefined;
25
+ const next = fn(cur);
26
+ this.items.set(id, next);
27
+ this.flush();
28
+ return next;
29
+ }
30
+ delete(id) {
31
+ const ok = this.items.delete(id);
32
+ if (ok)
33
+ this.flush();
34
+ return ok;
35
+ }
36
+ flush() {
37
+ if (this.path)
38
+ writeJsonAtomic(this.path, this.all());
39
+ }
40
+ }
@@ -0,0 +1,64 @@
1
+ import { type KeyObject, type JsonWebKey } from "node:crypto";
2
+ export type Alg = "ES256" | "RS256" | "PS256" | "EdDSA";
3
+ export interface JwtHeader {
4
+ alg: string;
5
+ kid?: string;
6
+ typ?: string;
7
+ }
8
+ export type JwtPayload = Record<string, unknown> & {
9
+ iss?: string;
10
+ sub?: string;
11
+ aud?: string | string[];
12
+ exp?: number;
13
+ iat?: number;
14
+ nbf?: number;
15
+ jti?: string;
16
+ };
17
+ export interface SigningKey {
18
+ kid: string;
19
+ alg: Alg;
20
+ privateKey: KeyObject;
21
+ publicJwk: JsonWebKey & {
22
+ kid: string;
23
+ alg: Alg;
24
+ use: "sig";
25
+ };
26
+ }
27
+ export declare class JwtError extends Error {
28
+ code: string;
29
+ constructor(code: string, message: string);
30
+ }
31
+ export declare function signJwt(payload: JwtPayload, key: SigningKey, typ?: string): string;
32
+ export declare function decodeJwt(token: string): {
33
+ header: JwtHeader;
34
+ payload: JwtPayload;
35
+ signingInput: string;
36
+ signature: Buffer;
37
+ };
38
+ export type KeyResolver = (header: JwtHeader, payload: JwtPayload) => Promise<KeyObject | null> | KeyObject | null;
39
+ export interface VerifyOptions {
40
+ issuer?: string | string[];
41
+ audience?: string | string[];
42
+ clockToleranceSec?: number;
43
+ requireExp?: boolean;
44
+ maxTokenAgeSec?: number;
45
+ typ?: string;
46
+ }
47
+ export declare function verifyJwt(token: string, resolveKey: KeyResolver, opts?: VerifyOptions): Promise<JwtPayload>;
48
+ export declare function jwkThumbprint(jwk: JsonWebKey): string;
49
+ export declare function signingKeyFromPem(pem: string): SigningKey;
50
+ /** Loads the ES256 signing key from `dir/signing-key.pem`, creating it (mode 0600) on first run. */
51
+ export declare function loadOrCreateSigningKey(dir: string): SigningKey;
52
+ export declare function publicKeyFromJwk(jwk: JsonWebKey): KeyObject;
53
+ /** Caches a remote JWKS; refetches on unknown kid at most once per `minRefreshMs`. */
54
+ export declare class JwksClient {
55
+ private keys;
56
+ private fetchedAt;
57
+ private inflight;
58
+ readonly url: string;
59
+ private ttlMs;
60
+ private minRefreshMs;
61
+ constructor(url: string, ttlMs?: number, minRefreshMs?: number);
62
+ getKey(kid: string | undefined): Promise<KeyObject | null>;
63
+ private refresh;
64
+ }