@berthojoris/mcp-mysql-server 1.43.5 → 1.45.2
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/CHANGELOG.md +61 -0
- package/DOCUMENTATIONS.md +674 -508
- package/README.md +468 -376
- package/bin/mcp-mysql.js +214 -168
- package/dist/cache/queryCache.js +1 -1
- package/dist/config/config.js +2 -1
- package/dist/config/featureConfig.d.ts +5 -0
- package/dist/config/featureConfig.js +11 -13
- package/dist/config/runtimeConfig.d.ts +50 -0
- package/dist/config/runtimeConfig.js +173 -0
- package/dist/db/connection.d.ts +40 -1
- package/dist/db/connection.js +188 -22
- package/dist/mcp-server.js +248 -375
- package/dist/security/grantInspector.d.ts +5 -0
- package/dist/security/grantInspector.js +32 -0
- package/dist/security/securityLayer.d.ts +21 -2
- package/dist/security/securityLayer.js +151 -21
- package/dist/server/auditLogger.d.ts +24 -0
- package/dist/server/auditLogger.js +60 -0
- package/dist/server/auth.d.ts +56 -0
- package/dist/server/auth.js +274 -0
- package/dist/server/httpServer.d.ts +22 -0
- package/dist/server/httpServer.js +320 -0
- package/dist/server/rateLimiter.d.ts +15 -0
- package/dist/server/rateLimiter.js +41 -0
- package/dist/server/requestContext.d.ts +12 -0
- package/dist/server/requestContext.js +9 -0
- package/dist/tools/toolAnnotations.d.ts +4 -0
- package/dist/tools/toolAnnotations.js +73 -0
- package/dist/tools/toolArgumentValidation.js +22 -22
- package/dist/tools/toolRegistry.d.ts +1 -1
- package/dist/tools/toolRegistry.js +7 -1
- package/manifest.json +1 -1
- package/package.json +86 -78
- package/dist/auth/authService.d.ts +0 -29
- package/dist/auth/authService.js +0 -114
- package/dist/tools/backupRestoreTools.d.ts +0 -18
- package/dist/tools/backupRestoreTools.js +0 -70
- package/dist/tools/documentationGeneratorTools.d.ts +0 -145
- package/dist/tools/documentationGeneratorTools.js +0 -820
- package/dist/tools/forecastingTools.d.ts +0 -36
- package/dist/tools/forecastingTools.js +0 -256
- package/dist/tools/functionTools.d.ts +0 -87
- package/dist/tools/functionTools.js +0 -358
- package/dist/tools/indexRecommendationTools.d.ts +0 -50
- package/dist/tools/indexRecommendationTools.js +0 -451
- package/dist/tools/intelligentQueryTools.d.ts +0 -94
- package/dist/tools/intelligentQueryTools.js +0 -713
- package/dist/tools/performanceTools.d.ts +0 -76
- package/dist/tools/performanceTools.js +0 -505
- package/dist/tools/processTools.d.ts +0 -61
- package/dist/tools/processTools.js +0 -181
- package/dist/tools/queryVisualizationTools.d.ts +0 -22
- package/dist/tools/queryVisualizationTools.js +0 -155
- package/dist/tools/schemaDesignTools.d.ts +0 -67
- package/dist/tools/schemaDesignTools.js +0 -359
- package/dist/tools/schemaPatternTools.d.ts +0 -19
- package/dist/tools/schemaPatternTools.js +0 -253
- package/dist/tools/schemaVersioningTools.d.ts +0 -138
- package/dist/tools/schemaVersioningTools.js +0 -1008
- package/dist/tools/securityAuditTools.d.ts +0 -39
- package/dist/tools/securityAuditTools.js +0 -319
- package/dist/tools/smartDiscoveryTools.d.ts +0 -163
- package/dist/tools/smartDiscoveryTools.js +0 -750
- package/dist/tools/testDataTools.d.ts +0 -26
- package/dist/tools/testDataTools.js +0 -325
|
@@ -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;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { FeatureConfig } from "../config/featureConfig
|
|
2
|
-
import { MaskingLayer } from "./maskingLayer
|
|
1
|
+
import { FeatureConfig } from "../config/featureConfig";
|
|
2
|
+
import { MaskingLayer } from "./maskingLayer";
|
|
3
3
|
export declare class SecurityLayer {
|
|
4
4
|
private ajv;
|
|
5
5
|
private readonly dangerousKeywords;
|
|
@@ -49,6 +49,25 @@ export declare class SecurityLayer {
|
|
|
49
49
|
error?: string;
|
|
50
50
|
queryType?: string;
|
|
51
51
|
};
|
|
52
|
+
/**
|
|
53
|
+
* Blank out the contents of string literals and quoted identifiers so that
|
|
54
|
+
* comment, statement-separator, and keyword checks only see SQL syntax.
|
|
55
|
+
* Strings become '' and identifiers become `` (or their bare content when
|
|
56
|
+
* keepIdentifiers is set). Returns null when the query cannot be lexed
|
|
57
|
+
* unambiguously: an unterminated quote, or a backslash inside a literal,
|
|
58
|
+
* whose meaning depends on the NO_BACKSLASH_ESCAPES sql_mode.
|
|
59
|
+
*/
|
|
60
|
+
private maskQuotedContent;
|
|
61
|
+
/**
|
|
62
|
+
* Return the main statement that follows the CTE definitions of a WITH
|
|
63
|
+
* clause, the statement itself when it has no WITH clause, or null when the
|
|
64
|
+
* WITH clause cannot be parsed.
|
|
65
|
+
*/
|
|
66
|
+
private resolveCteMainStatement;
|
|
67
|
+
/**
|
|
68
|
+
* Index of the parenthesis closing the one at position 0, or -1 if unbalanced.
|
|
69
|
+
*/
|
|
70
|
+
private findClosingParen;
|
|
52
71
|
/**
|
|
53
72
|
* Enhanced comment detection to prevent bypass techniques
|
|
54
73
|
*/
|
|
@@ -5,14 +5,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.SecurityLayer = void 0;
|
|
7
7
|
const ajv_1 = __importDefault(require("ajv"));
|
|
8
|
-
const
|
|
9
|
-
const
|
|
8
|
+
const featureConfig_1 = require("../config/featureConfig");
|
|
9
|
+
const maskingLayer_1 = require("./maskingLayer");
|
|
10
10
|
class SecurityLayer {
|
|
11
11
|
constructor(featureConfig) {
|
|
12
12
|
this.ajv = new ajv_1.default();
|
|
13
|
-
this.featureConfig = featureConfig || new
|
|
13
|
+
this.featureConfig = featureConfig || new featureConfig_1.FeatureConfig();
|
|
14
14
|
// Masking is intentionally not configurable via environment variables.
|
|
15
|
-
this.masking = new
|
|
15
|
+
this.masking = new maskingLayer_1.MaskingLayer("none");
|
|
16
16
|
// Define dangerous SQL keywords that should ALWAYS be blocked (critical security threats)
|
|
17
17
|
// These are blocked even with 'execute' permission
|
|
18
18
|
// Note: Avoid blocking common table/column names like "user" or "password"
|
|
@@ -61,11 +61,11 @@ class SecurityLayer {
|
|
|
61
61
|
: { valid: false, error: this.featureConfig.getPermissionError("executeDdl") };
|
|
62
62
|
}
|
|
63
63
|
const requiredPermissions = {
|
|
64
|
-
SELECT: [
|
|
65
|
-
INSERT: [
|
|
66
|
-
UPDATE: [
|
|
67
|
-
DELETE: [
|
|
68
|
-
INFORMATION: [
|
|
64
|
+
SELECT: [featureConfig_1.ToolCategory.READ],
|
|
65
|
+
INSERT: [featureConfig_1.ToolCategory.CREATE, featureConfig_1.ToolCategory.EXECUTE],
|
|
66
|
+
UPDATE: [featureConfig_1.ToolCategory.UPDATE, featureConfig_1.ToolCategory.EXECUTE],
|
|
67
|
+
DELETE: [featureConfig_1.ToolCategory.DELETE],
|
|
68
|
+
INFORMATION: [featureConfig_1.ToolCategory.LIST, featureConfig_1.ToolCategory.READ],
|
|
69
69
|
};
|
|
70
70
|
const permissions = requiredPermissions[queryType];
|
|
71
71
|
if (!permissions) {
|
|
@@ -200,10 +200,23 @@ class SecurityLayer {
|
|
|
200
200
|
}
|
|
201
201
|
// Enhanced query type detection with better parsing.
|
|
202
202
|
// EXPLAIN ANALYZE is classified by the inner statement it executes.
|
|
203
|
-
const
|
|
203
|
+
const statement = explainAnalyzeMatch ? explainAnalyzeMatch[1].trim() : cleanQuery;
|
|
204
|
+
// A WITH clause is authorized as the main statement that follows its CTEs.
|
|
205
|
+
const mainStatement = this.resolveCteMainStatement(statement);
|
|
206
|
+
if (mainStatement === null) {
|
|
207
|
+
return { valid: false, error: "Unable to parse WITH clause. Query type not allowed" };
|
|
208
|
+
}
|
|
209
|
+
const queryTypeResult = this.detectQueryType(mainStatement);
|
|
204
210
|
if (!queryTypeResult.valid) {
|
|
205
211
|
return queryTypeResult;
|
|
206
212
|
}
|
|
213
|
+
// CTEs are as expressive as derived tables, which also require execute permission.
|
|
214
|
+
if (!allowAdvancedQueries && /^WITH\b/.test(statement)) {
|
|
215
|
+
return {
|
|
216
|
+
valid: false,
|
|
217
|
+
error: "Common table expressions (WITH) not allowed without 'execute' permission",
|
|
218
|
+
};
|
|
219
|
+
}
|
|
207
220
|
if (!allowAdvancedQueries) {
|
|
208
221
|
// Additional checks for specific query types
|
|
209
222
|
if (queryTypeResult.queryType === "SELECT") {
|
|
@@ -215,10 +228,128 @@ class SecurityLayer {
|
|
|
215
228
|
}
|
|
216
229
|
return { valid: true, queryType: queryTypeResult.queryType };
|
|
217
230
|
}
|
|
231
|
+
/**
|
|
232
|
+
* Blank out the contents of string literals and quoted identifiers so that
|
|
233
|
+
* comment, statement-separator, and keyword checks only see SQL syntax.
|
|
234
|
+
* Strings become '' and identifiers become `` (or their bare content when
|
|
235
|
+
* keepIdentifiers is set). Returns null when the query cannot be lexed
|
|
236
|
+
* unambiguously: an unterminated quote, or a backslash inside a literal,
|
|
237
|
+
* whose meaning depends on the NO_BACKSLASH_ESCAPES sql_mode.
|
|
238
|
+
*/
|
|
239
|
+
maskQuotedContent(query, keepIdentifiers = false) {
|
|
240
|
+
let result = "";
|
|
241
|
+
let i = 0;
|
|
242
|
+
while (i < query.length) {
|
|
243
|
+
const quote = query[i];
|
|
244
|
+
if (quote !== "'" && quote !== '"' && quote !== "`") {
|
|
245
|
+
result += quote;
|
|
246
|
+
i++;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
let content = "";
|
|
250
|
+
let j = i + 1;
|
|
251
|
+
let closed = false;
|
|
252
|
+
while (j < query.length) {
|
|
253
|
+
if (query[j] === quote) {
|
|
254
|
+
// A doubled quote is an escaped quote in both sql_modes
|
|
255
|
+
if (query[j + 1] === quote) {
|
|
256
|
+
content += quote + quote;
|
|
257
|
+
j += 2;
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
closed = true;
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
if (query[j] === "\\" && quote !== "`") {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
content += query[j];
|
|
267
|
+
j++;
|
|
268
|
+
}
|
|
269
|
+
if (!closed) {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
if (quote === "`") {
|
|
273
|
+
result += keepIdentifiers ? content : "``";
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
result += quote + quote;
|
|
277
|
+
}
|
|
278
|
+
i = j + 1;
|
|
279
|
+
}
|
|
280
|
+
return result;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Return the main statement that follows the CTE definitions of a WITH
|
|
284
|
+
* clause, the statement itself when it has no WITH clause, or null when the
|
|
285
|
+
* WITH clause cannot be parsed.
|
|
286
|
+
*/
|
|
287
|
+
resolveCteMainStatement(statement) {
|
|
288
|
+
if (!/^WITH\b/i.test(statement)) {
|
|
289
|
+
return statement;
|
|
290
|
+
}
|
|
291
|
+
const masked = this.maskQuotedContent(statement);
|
|
292
|
+
if (masked === null) {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
let rest = masked.replace(/^WITH\s+(?:RECURSIVE\s+)?/i, "");
|
|
296
|
+
while (true) {
|
|
297
|
+
const nameMatch = rest.match(/^(?:``|[A-Z0-9_$]+)\s*/i);
|
|
298
|
+
if (!nameMatch) {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
rest = rest.slice(nameMatch[0].length);
|
|
302
|
+
// Optional column list
|
|
303
|
+
if (rest.startsWith("(")) {
|
|
304
|
+
const end = this.findClosingParen(rest);
|
|
305
|
+
if (end < 0) {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
rest = rest.slice(end + 1).trimStart();
|
|
309
|
+
}
|
|
310
|
+
const asMatch = rest.match(/^AS\s*/i);
|
|
311
|
+
if (!asMatch) {
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
rest = rest.slice(asMatch[0].length);
|
|
315
|
+
if (!rest.startsWith("(")) {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
const end = this.findClosingParen(rest);
|
|
319
|
+
if (end < 0) {
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
rest = rest.slice(end + 1).trimStart();
|
|
323
|
+
if (!rest.startsWith(",")) {
|
|
324
|
+
return rest;
|
|
325
|
+
}
|
|
326
|
+
rest = rest.slice(1).trimStart();
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Index of the parenthesis closing the one at position 0, or -1 if unbalanced.
|
|
331
|
+
*/
|
|
332
|
+
findClosingParen(text) {
|
|
333
|
+
let depth = 0;
|
|
334
|
+
for (let i = 0; i < text.length; i++) {
|
|
335
|
+
if (text[i] === "(") {
|
|
336
|
+
depth++;
|
|
337
|
+
}
|
|
338
|
+
else if (text[i] === ")") {
|
|
339
|
+
depth--;
|
|
340
|
+
if (depth === 0) {
|
|
341
|
+
return i;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return -1;
|
|
346
|
+
}
|
|
218
347
|
/**
|
|
219
348
|
* Enhanced comment detection to prevent bypass techniques
|
|
220
349
|
*/
|
|
221
|
-
detectComments(
|
|
350
|
+
detectComments(rawQuery) {
|
|
351
|
+
// Quoted content is data, not syntax; fall back to the raw text if ambiguous
|
|
352
|
+
const query = this.maskQuotedContent(rawQuery) ?? rawQuery;
|
|
222
353
|
// Check for various comment types and bypass attempts
|
|
223
354
|
const commentPatterns = [
|
|
224
355
|
/\/\*[\s\S]*?\*\//g, // Multi-line comments
|
|
@@ -261,15 +392,15 @@ class SecurityLayer {
|
|
|
261
392
|
* Enhanced multiple statement detection
|
|
262
393
|
*/
|
|
263
394
|
detectMultipleStatements(query) {
|
|
264
|
-
// Remove
|
|
265
|
-
const queryWithoutStrings =
|
|
395
|
+
// Remove quoted content to avoid false positives; fall back to the raw text if ambiguous
|
|
396
|
+
const queryWithoutStrings = this.maskQuotedContent(query) ?? query;
|
|
266
397
|
// Check for multiple semicolons not at the end
|
|
267
398
|
const semicolonMatches = queryWithoutStrings.match(/;/g);
|
|
268
399
|
if (semicolonMatches && semicolonMatches.length > 1) {
|
|
269
400
|
return { valid: false, error: "Multiple statements not allowed" };
|
|
270
401
|
}
|
|
271
402
|
// Check for semicolon not at the very end (after trimming)
|
|
272
|
-
const trimmedQuery =
|
|
403
|
+
const trimmedQuery = queryWithoutStrings.trim();
|
|
273
404
|
if (trimmedQuery.includes(';') && !trimmedQuery.endsWith(';')) {
|
|
274
405
|
return { valid: false, error: "Multiple statements not allowed" };
|
|
275
406
|
}
|
|
@@ -312,10 +443,9 @@ class SecurityLayer {
|
|
|
312
443
|
* Enhanced dangerous keyword detection
|
|
313
444
|
*/
|
|
314
445
|
detectDangerousKeywords(cleanQuery, allowAdvancedQueries) {
|
|
315
|
-
// Remove string literals to avoid false positives
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
.replace(/`([^`]*)`/g, "$1");
|
|
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, "");
|
|
319
449
|
for (const keyword of this.dangerousKeywords) {
|
|
320
450
|
// Enhanced regex with word boundaries and case insensitivity
|
|
321
451
|
const keywordRegex = new RegExp(`\\b${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
|
|
@@ -358,8 +488,8 @@ class SecurityLayer {
|
|
|
358
488
|
* Enhanced SELECT query validation
|
|
359
489
|
*/
|
|
360
490
|
validateSelectQuery(cleanQuery) {
|
|
361
|
-
// Remove
|
|
362
|
-
const queryWithoutStrings =
|
|
491
|
+
// Remove quoted content to avoid false positives
|
|
492
|
+
const queryWithoutStrings = this.maskQuotedContent(cleanQuery) ?? cleanQuery;
|
|
363
493
|
// Check for UNION attacks
|
|
364
494
|
if (/\bUNION\b/i.test(queryWithoutStrings)) {
|
|
365
495
|
return {
|
|
@@ -456,7 +586,7 @@ class SecurityLayer {
|
|
|
456
586
|
* Check if execute permission is enabled
|
|
457
587
|
*/
|
|
458
588
|
hasExecutePermission() {
|
|
459
|
-
return this.featureConfig.isCategoryEnabled(
|
|
589
|
+
return this.featureConfig.isCategoryEnabled(featureConfig_1.ToolCategory.EXECUTE);
|
|
460
590
|
}
|
|
461
591
|
/**
|
|
462
592
|
* Escape identifier for safe use in SQL queries
|
|
@@ -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 {};
|