@berthojoris/mcp-mysql-server 1.44.0 → 1.46.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.
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.inspectGrants = void 0;
4
+ /**
5
+ * Classifies the output of SHOW GRANTS FOR CURRENT_USER(). Anything that is
6
+ * not on the read-only list (including role grants, which cannot be resolved
7
+ * here) counts as a write privilege.
8
+ */
9
+ const READ_ONLY_PRIVILEGES = new Set(["SELECT", "SHOW VIEW", "SHOW DATABASES", "PROCESS", "USAGE"]);
10
+ const inspectGrants = (grantLines) => {
11
+ const writePrivileges = new Set();
12
+ for (const line of grantLines) {
13
+ const match = /^\s*GRANT\s+(.+?)\s+ON\s+/i.exec(line);
14
+ if (!match) {
15
+ // "GRANT `role`@`%` TO ..." assigns a role whose privileges are unknown
16
+ if (/^\s*GRANT\s+/i.test(line))
17
+ writePrivileges.add("ROLE");
18
+ continue;
19
+ }
20
+ if (/\bWITH\s+GRANT\s+OPTION\b/i.test(line))
21
+ writePrivileges.add("GRANT OPTION");
22
+ // Column privileges look like "SELECT (`a`, `b`)"; drop the column lists
23
+ const privileges = match[1].replace(/\([^)]*\)/g, "").split(",");
24
+ for (const raw of privileges) {
25
+ const privilege = raw.trim().toUpperCase().replace(/\s+/g, " ");
26
+ if (privilege && !READ_ONLY_PRIVILEGES.has(privilege))
27
+ writePrivileges.add(privilege);
28
+ }
29
+ }
30
+ return { readOnly: writePrivileges.size === 0, writePrivileges: [...writePrivileges] };
31
+ };
32
+ exports.inspectGrants = inspectGrants;
@@ -444,8 +444,9 @@ class SecurityLayer {
444
444
  */
445
445
  detectDangerousKeywords(cleanQuery, allowAdvancedQueries) {
446
446
  // Remove string literals to avoid false positives, and unwrap quoted
447
- // identifiers so `mysql`.`user` is still detected
448
- const queryWithoutStrings = this.maskQuotedContent(cleanQuery, true) ?? cleanQuery.replace(/`/g, "");
447
+ // identifiers so `mysql`.`user` is still detected. MySQL allows whitespace
448
+ // around the qualifier dot, so `mysql . user` is joined to mysql.user.
449
+ const queryWithoutStrings = (this.maskQuotedContent(cleanQuery, true) ?? cleanQuery.replace(/`/g, "")).replace(/\s*\.\s*/g, ".");
449
450
  for (const keyword of this.dangerousKeywords) {
450
451
  // Enhanced regex with word boundaries and case insensitivity
451
452
  const keywordRegex = new RegExp(`\\b${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
@@ -0,0 +1,24 @@
1
+ export interface AuditEntry {
2
+ event: "tool_call" | "auth_failed" | "session_opened" | "session_closed";
3
+ [key: string]: unknown;
4
+ }
5
+ /**
6
+ * Writes one JSON line per event to stderr or a file. Never writes to stdout,
7
+ * which carries the stdio MCP protocol.
8
+ */
9
+ export declare class AuditLogger {
10
+ private stream?;
11
+ private readonly toStderr;
12
+ readonly enabled: boolean;
13
+ constructor(target: string);
14
+ log(entry: AuditEntry): void;
15
+ close(): void;
16
+ }
17
+ /**
18
+ * Argument summary for audit records: the names of all arguments, plus the SQL
19
+ * text (truncated). Other values are omitted because they may hold row data.
20
+ */
21
+ export declare const summarizeArguments: (args: Record<string, unknown> | undefined) => {
22
+ names: string[];
23
+ sql?: string;
24
+ };
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.summarizeArguments = exports.AuditLogger = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const MAX_SQL_LENGTH = 1000;
10
+ const SQL_ARGUMENT_NAMES = ["query", "sql"];
11
+ /**
12
+ * Writes one JSON line per event to stderr or a file. Never writes to stdout,
13
+ * which carries the stdio MCP protocol.
14
+ */
15
+ class AuditLogger {
16
+ constructor(target) {
17
+ this.enabled = target !== "off";
18
+ this.toStderr = target === "stderr";
19
+ if (this.enabled && !this.toStderr) {
20
+ const filePath = path_1.default.resolve(target);
21
+ fs_1.default.mkdirSync(path_1.default.dirname(filePath), { recursive: true });
22
+ this.stream = fs_1.default.createWriteStream(filePath, { flags: "a" });
23
+ this.stream.on("error", (error) => {
24
+ console.error(`Audit log write failed: ${error.message}`);
25
+ });
26
+ }
27
+ }
28
+ log(entry) {
29
+ if (!this.enabled)
30
+ return;
31
+ const line = JSON.stringify({ time: new Date().toISOString(), ...entry });
32
+ if (this.toStderr) {
33
+ console.error(`[audit] ${line}`);
34
+ }
35
+ else {
36
+ this.stream?.write(`${line}\n`);
37
+ }
38
+ }
39
+ close() {
40
+ this.stream?.end();
41
+ }
42
+ }
43
+ exports.AuditLogger = AuditLogger;
44
+ /**
45
+ * Argument summary for audit records: the names of all arguments, plus the SQL
46
+ * text (truncated). Other values are omitted because they may hold row data.
47
+ */
48
+ const summarizeArguments = (args) => {
49
+ const input = args || {};
50
+ const summary = { names: Object.keys(input) };
51
+ for (const name of SQL_ARGUMENT_NAMES) {
52
+ const value = input[name];
53
+ if (typeof value === "string") {
54
+ summary.sql = value.length > MAX_SQL_LENGTH ? `${value.slice(0, MAX_SQL_LENGTH)}...` : value;
55
+ break;
56
+ }
57
+ }
58
+ return summary;
59
+ };
60
+ exports.summarizeArguments = summarizeArguments;
@@ -0,0 +1,56 @@
1
+ import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
2
+ import { HttpConfig, OAuthConfig } from "../config/runtimeConfig";
3
+ /** Authentication failure mapped to an HTTP status and OAuth error code. */
4
+ export declare class AuthError extends Error {
5
+ readonly status: 401 | 403;
6
+ readonly oauthError: "invalid_request" | "invalid_token" | "insufficient_scope";
7
+ constructor(message: string, status: 401 | 403, oauthError: "invalid_request" | "invalid_token" | "insufficient_scope");
8
+ }
9
+ export interface Authenticator {
10
+ /** Validates the Authorization header value (may be undefined). */
11
+ authenticate(authorization: string | undefined): Promise<AuthInfo>;
12
+ }
13
+ export declare class NoAuthenticator implements Authenticator {
14
+ authenticate(): Promise<AuthInfo>;
15
+ }
16
+ /** Static bearer tokens, compared by SHA-256 digest in constant time. */
17
+ export declare class TokenAuthenticator implements Authenticator {
18
+ private readonly digests;
19
+ constructor(tokens: string[]);
20
+ authenticate(authorization: string | undefined): Promise<AuthInfo>;
21
+ }
22
+ type Fetcher = (url: string) => Promise<any>;
23
+ /**
24
+ * OAuth 2.1 resource server: validates JWT access tokens issued by an external
25
+ * authorization server against its JWKS. Tokens are never issued here.
26
+ */
27
+ export declare class OAuthAuthenticator implements Authenticator {
28
+ private readonly config;
29
+ private readonly fetcher;
30
+ private readonly now;
31
+ private keys;
32
+ private keysFetchedAt;
33
+ private lastAttemptAt;
34
+ private jwksUri?;
35
+ private refreshing?;
36
+ constructor(config: OAuthConfig, fetcher?: Fetcher, now?: () => number);
37
+ authenticate(authorization: string | undefined): Promise<AuthInfo>;
38
+ private verifySignature;
39
+ private validateClaims;
40
+ private extractScopes;
41
+ private findKey;
42
+ private selectKey;
43
+ private refreshKeys;
44
+ private resolveJwksUri;
45
+ }
46
+ export declare const createAuthenticator: (http: HttpConfig) => Authenticator;
47
+ /** RFC 9728 Protected Resource Metadata for this server. */
48
+ export declare const protectedResourceMetadata: (http: HttpConfig) => {
49
+ resource_name: string;
50
+ scopes_supported?: string[] | undefined;
51
+ resource: string | undefined;
52
+ authorization_servers: string[];
53
+ bearer_methods_supported: string[];
54
+ };
55
+ export declare const protectedResourceMetadataUrl: (http: HttpConfig) => string | undefined;
56
+ export {};
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.protectedResourceMetadataUrl = exports.protectedResourceMetadata = exports.createAuthenticator = exports.OAuthAuthenticator = exports.TokenAuthenticator = exports.NoAuthenticator = exports.AuthError = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ /** Authentication failure mapped to an HTTP status and OAuth error code. */
9
+ class AuthError extends Error {
10
+ constructor(message, status, oauthError) {
11
+ super(message);
12
+ this.status = status;
13
+ this.oauthError = oauthError;
14
+ }
15
+ }
16
+ exports.AuthError = AuthError;
17
+ const extractBearer = (authorization) => {
18
+ if (!authorization) {
19
+ throw new AuthError("Missing Authorization header", 401, "invalid_request");
20
+ }
21
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization);
22
+ if (!match) {
23
+ throw new AuthError("Authorization header must use the Bearer scheme", 401, "invalid_request");
24
+ }
25
+ return match[1];
26
+ };
27
+ const sha256 = (value) => crypto_1.default.createHash("sha256").update(value).digest();
28
+ class NoAuthenticator {
29
+ async authenticate() {
30
+ return { token: "", clientId: "anonymous", scopes: [] };
31
+ }
32
+ }
33
+ exports.NoAuthenticator = NoAuthenticator;
34
+ /** Static bearer tokens, compared by SHA-256 digest in constant time. */
35
+ class TokenAuthenticator {
36
+ constructor(tokens) {
37
+ this.digests = tokens.map(sha256);
38
+ }
39
+ async authenticate(authorization) {
40
+ const token = extractBearer(authorization);
41
+ const digest = sha256(token);
42
+ // Compare against every token so timing does not reveal which one matched
43
+ let matched = false;
44
+ for (const candidate of this.digests) {
45
+ if (crypto_1.default.timingSafeEqual(candidate, digest))
46
+ matched = true;
47
+ }
48
+ if (!matched) {
49
+ throw new AuthError("Invalid bearer token", 401, "invalid_token");
50
+ }
51
+ return {
52
+ token,
53
+ clientId: `token-${digest.toString("hex").slice(0, 12)}`,
54
+ scopes: [],
55
+ };
56
+ }
57
+ }
58
+ exports.TokenAuthenticator = TokenAuthenticator;
59
+ const defaultFetcher = async (url) => {
60
+ const response = await fetch(url, { headers: { Accept: "application/json" } });
61
+ if (!response.ok) {
62
+ throw new Error(`GET ${url} returned ${response.status}`);
63
+ }
64
+ return response.json();
65
+ };
66
+ const ALGORITHMS = {
67
+ RS256: { kty: "RSA", hash: "sha256" },
68
+ RS384: { kty: "RSA", hash: "sha384" },
69
+ RS512: { kty: "RSA", hash: "sha512" },
70
+ PS256: { kty: "RSA", hash: "sha256", pss: true },
71
+ PS384: { kty: "RSA", hash: "sha384", pss: true },
72
+ PS512: { kty: "RSA", hash: "sha512", pss: true },
73
+ ES256: { kty: "EC", hash: "sha256", curve: "P-256", ecdsa: true },
74
+ ES384: { kty: "EC", hash: "sha384", curve: "P-384", ecdsa: true },
75
+ ES512: { kty: "EC", hash: "sha512", curve: "P-521", ecdsa: true },
76
+ EdDSA: { kty: "OKP", hash: null },
77
+ };
78
+ const CLOCK_SKEW_SECONDS = 60;
79
+ const JWKS_TTL_MS = 10 * 60 * 1000;
80
+ const JWKS_MIN_REFRESH_MS = 30 * 1000;
81
+ const decodeSegment = (segment) => {
82
+ try {
83
+ return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
84
+ }
85
+ catch {
86
+ throw new AuthError("Malformed access token", 401, "invalid_token");
87
+ }
88
+ };
89
+ const normalizeIssuer = (issuer) => issuer.replace(/\/+$/, "");
90
+ /**
91
+ * OAuth 2.1 resource server: validates JWT access tokens issued by an external
92
+ * authorization server against its JWKS. Tokens are never issued here.
93
+ */
94
+ class OAuthAuthenticator {
95
+ constructor(config, fetcher = defaultFetcher, now = Date.now) {
96
+ this.config = config;
97
+ this.fetcher = fetcher;
98
+ this.now = now;
99
+ this.keys = [];
100
+ this.keysFetchedAt = Number.NEGATIVE_INFINITY;
101
+ this.lastAttemptAt = Number.NEGATIVE_INFINITY;
102
+ this.jwksUri = config.jwksUri;
103
+ }
104
+ async authenticate(authorization) {
105
+ const token = extractBearer(authorization);
106
+ const parts = token.split(".");
107
+ if (parts.length !== 3) {
108
+ throw new AuthError("Access token is not a JWT", 401, "invalid_token");
109
+ }
110
+ const [headerSegment, payloadSegment, signatureSegment] = parts;
111
+ const header = decodeSegment(headerSegment);
112
+ const payload = decodeSegment(payloadSegment);
113
+ const algorithm = ALGORITHMS[header?.alg];
114
+ if (!algorithm) {
115
+ throw new AuthError(`Unsupported token algorithm: ${header?.alg}`, 401, "invalid_token");
116
+ }
117
+ const jwk = await this.findKey(header.kid, header.alg, algorithm.kty);
118
+ const signature = Buffer.from(signatureSegment, "base64url");
119
+ const signedData = Buffer.from(`${headerSegment}.${payloadSegment}`);
120
+ if (!this.verifySignature(jwk, algorithm, signedData, signature)) {
121
+ throw new AuthError("Invalid token signature", 401, "invalid_token");
122
+ }
123
+ this.validateClaims(payload);
124
+ const scopes = this.extractScopes(payload);
125
+ const missing = this.config.requiredScopes.filter((scope) => !scopes.includes(scope));
126
+ if (missing.length > 0) {
127
+ throw new AuthError(`Token is missing required scope(s): ${missing.join(", ")}`, 403, "insufficient_scope");
128
+ }
129
+ const clientId = String(payload.client_id || payload.azp || payload.sub || "unknown");
130
+ return {
131
+ token,
132
+ clientId,
133
+ scopes,
134
+ expiresAt: typeof payload.exp === "number" ? payload.exp : undefined,
135
+ extra: { subject: payload.sub },
136
+ };
137
+ }
138
+ verifySignature(jwk, algorithm, data, signature) {
139
+ try {
140
+ const key = crypto_1.default.createPublicKey({ key: jwk, format: "jwk" });
141
+ if (algorithm.pss) {
142
+ return crypto_1.default.verify(algorithm.hash, data, { key, padding: crypto_1.default.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto_1.default.constants.RSA_PSS_SALTLEN_DIGEST }, signature);
143
+ }
144
+ if (algorithm.ecdsa) {
145
+ return crypto_1.default.verify(algorithm.hash, data, { key, dsaEncoding: "ieee-p1363" }, signature);
146
+ }
147
+ return crypto_1.default.verify(algorithm.hash, data, key, signature);
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ }
153
+ validateClaims(payload) {
154
+ if (!payload || typeof payload !== "object") {
155
+ throw new AuthError("Malformed token payload", 401, "invalid_token");
156
+ }
157
+ const nowSeconds = Math.floor(this.now() / 1000);
158
+ if (typeof payload.iss !== "string" || normalizeIssuer(payload.iss) !== normalizeIssuer(this.config.issuer)) {
159
+ throw new AuthError("Token issuer does not match", 401, "invalid_token");
160
+ }
161
+ const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
162
+ if (!this.config.audience || !audiences.includes(this.config.audience)) {
163
+ throw new AuthError("Token audience does not match this server", 401, "invalid_token");
164
+ }
165
+ if (typeof payload.exp !== "number" || payload.exp + CLOCK_SKEW_SECONDS < nowSeconds) {
166
+ throw new AuthError("Token is expired", 401, "invalid_token");
167
+ }
168
+ if (typeof payload.nbf === "number" && payload.nbf - CLOCK_SKEW_SECONDS > nowSeconds) {
169
+ throw new AuthError("Token is not valid yet", 401, "invalid_token");
170
+ }
171
+ }
172
+ extractScopes(payload) {
173
+ if (typeof payload.scope === "string")
174
+ return payload.scope.split(" ").filter(Boolean);
175
+ if (Array.isArray(payload.scp))
176
+ return payload.scp.map(String);
177
+ if (typeof payload.scp === "string")
178
+ return payload.scp.split(" ").filter(Boolean);
179
+ return [];
180
+ }
181
+ async findKey(kid, alg, kty) {
182
+ const canRetry = () => this.now() - this.lastAttemptAt > JWKS_MIN_REFRESH_MS;
183
+ if (this.now() - this.keysFetchedAt > JWKS_TTL_MS && canRetry()) {
184
+ await this.refreshKeys();
185
+ }
186
+ let key = this.selectKey(kid, alg, kty);
187
+ // Unknown kid usually means the authorization server rotated its keys
188
+ if (!key && canRetry()) {
189
+ await this.refreshKeys();
190
+ key = this.selectKey(kid, alg, kty);
191
+ }
192
+ if (!key) {
193
+ throw new AuthError("No matching signing key for token", 401, "invalid_token");
194
+ }
195
+ return key;
196
+ }
197
+ selectKey(kid, alg, kty) {
198
+ const candidates = this.keys.filter((key) => key.kty === kty &&
199
+ (!key.use || key.use === "sig") &&
200
+ (!key.alg || key.alg === alg) &&
201
+ (!ALGORITHMS[alg].curve || key.crv === ALGORITHMS[alg].curve));
202
+ if (kid)
203
+ return candidates.find((key) => key.kid === kid);
204
+ return candidates.length === 1 ? candidates[0] : undefined;
205
+ }
206
+ refreshKeys() {
207
+ if (!this.refreshing) {
208
+ this.refreshing = (async () => {
209
+ this.lastAttemptAt = this.now();
210
+ try {
211
+ const uri = await this.resolveJwksUri();
212
+ const jwks = await this.fetcher(uri);
213
+ if (!jwks || !Array.isArray(jwks.keys)) {
214
+ throw new Error(`JWKS at ${uri} has no "keys" array`);
215
+ }
216
+ this.keys = jwks.keys;
217
+ this.keysFetchedAt = this.now();
218
+ }
219
+ catch (error) {
220
+ // Keep any previously fetched keys; lastAttemptAt throttles the next retry
221
+ console.error(`OAuth: failed to load signing keys: ${error.message}`);
222
+ }
223
+ finally {
224
+ this.refreshing = undefined;
225
+ }
226
+ })();
227
+ }
228
+ return this.refreshing;
229
+ }
230
+ async resolveJwksUri() {
231
+ if (this.jwksUri)
232
+ return this.jwksUri;
233
+ const issuer = normalizeIssuer(this.config.issuer);
234
+ const issuerUrl = new URL(issuer);
235
+ // OpenID Connect discovery, then RFC 8414 (path inserted after the well-known prefix)
236
+ const candidates = [
237
+ `${issuer}/.well-known/openid-configuration`,
238
+ `${issuerUrl.origin}/.well-known/oauth-authorization-server${issuerUrl.pathname === "/" ? "" : issuerUrl.pathname}`,
239
+ ];
240
+ for (const url of candidates) {
241
+ try {
242
+ const metadata = await this.fetcher(url);
243
+ if (metadata && typeof metadata.jwks_uri === "string") {
244
+ this.jwksUri = metadata.jwks_uri;
245
+ return metadata.jwks_uri;
246
+ }
247
+ }
248
+ catch {
249
+ // try the next discovery document
250
+ }
251
+ }
252
+ throw new Error(`Could not discover jwks_uri for issuer ${this.config.issuer}; set MCP_OAUTH_JWKS_URI`);
253
+ }
254
+ }
255
+ exports.OAuthAuthenticator = OAuthAuthenticator;
256
+ const createAuthenticator = (http) => {
257
+ if (http.auth === "token")
258
+ return new TokenAuthenticator(http.tokens);
259
+ if (http.auth === "oauth" && http.oauth)
260
+ return new OAuthAuthenticator(http.oauth);
261
+ return new NoAuthenticator();
262
+ };
263
+ exports.createAuthenticator = createAuthenticator;
264
+ /** RFC 9728 Protected Resource Metadata for this server. */
265
+ const protectedResourceMetadata = (http) => ({
266
+ resource: http.resourceUrl,
267
+ authorization_servers: http.oauth ? [http.oauth.issuer] : [],
268
+ bearer_methods_supported: ["header"],
269
+ ...(http.oauth && http.oauth.requiredScopes.length > 0 ? { scopes_supported: http.oauth.requiredScopes } : {}),
270
+ resource_name: "MySQL MCP Server",
271
+ });
272
+ exports.protectedResourceMetadata = protectedResourceMetadata;
273
+ const protectedResourceMetadataUrl = (http) => http.publicUrl ? `${http.publicUrl}/.well-known/oauth-protected-resource${http.path}` : undefined;
274
+ exports.protectedResourceMetadataUrl = protectedResourceMetadataUrl;
@@ -0,0 +1,22 @@
1
+ import http from "http";
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { HttpConfig } from "../config/runtimeConfig";
4
+ import { Authenticator } from "./auth";
5
+ import { AuditLogger } from "./auditLogger";
6
+ export interface HttpServerOptions {
7
+ config: HttpConfig;
8
+ /** Builds a fresh MCP server (with handlers) for each session */
9
+ createServer: () => Server;
10
+ auditLogger: AuditLogger;
11
+ /** Called once when a session ends (closed, deleted, or expired) */
12
+ onSessionClosed?: (sessionId: string) => void;
13
+ authenticator?: Authenticator;
14
+ }
15
+ export interface RunningHttpServer {
16
+ server: http.Server;
17
+ /** Address actually bound (port is resolved when 0 was requested) */
18
+ url: string;
19
+ sessionCount: () => number;
20
+ close: () => Promise<void>;
21
+ }
22
+ export declare const startHttpServer: (options: HttpServerOptions) => Promise<RunningHttpServer>;