-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathindex.ts
More file actions
199 lines (167 loc) · 6.57 KB
/
Copy pathindex.ts
File metadata and controls
199 lines (167 loc) · 6.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { BearerAuthMiddlewareOptions, requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
import { AuthRouterOptions, getOAuthProtectedResourceMetadataUrl, mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js";
import cors from "cors";
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import { EverythingAuthProvider } from "./auth/provider.js";
import { BASE_URI, PORT } from "./config.js";
import { authContext } from "./handlers/common.js";
import { handleFakeAuthorize, handleFakeAuthorizeRedirect } from "./handlers/fakeauth.js";
import { handleStreamableHTTP } from "./handlers/shttp.js";
import { handleMessage, handleSSEConnection } from "./handlers/sse.js";
import { redisClient } from "./redis.js";
import { logger } from "./utils/logger.js";
const app = express();
// Get the directory of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Base security middleware - applied to all routes
const baseSecurityHeaders = (req: express.Request, res: express.Response, next: express.NextFunction) => {
// Basic security headers
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
// Content Security Policy
const csp = [
"default-src 'self'",
"object-src 'none'", // Disable plugins
"frame-ancestors 'none'", // No embedding
"form-action 'self'", // Only allow forms to submit to our domain
"base-uri 'self'", // Restrict base tag
"upgrade-insecure-requests",
"block-all-mixed-content"
].join('; ');
res.setHeader('Content-Security-Policy', csp);
next();
};
// Structured logging middleware
const loggingMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
const startTime = Date.now();
// Sanitize headers to remove sensitive information
const sanitizedHeaders = { ...req.headers };
delete sanitizedHeaders.authorization;
delete sanitizedHeaders.cookie;
delete sanitizedHeaders['x-api-key'];
// Log request (without sensitive data)
logger.info('Request received', {
method: req.method,
url: req.url,
// Only log specific safe headers
headers: {
'content-type': sanitizedHeaders['content-type'],
'user-agent': sanitizedHeaders['user-agent'],
'mcp-protocol-version': sanitizedHeaders['mcp-protocol-version'],
'mcp-session-id': sanitizedHeaders['mcp-session-id'],
'accept': sanitizedHeaders['accept'],
'x-cloud-trace-context': sanitizedHeaders['x-cloud-trace-context']
},
// Don't log request body as it may contain sensitive data
bodySize: req.headers['content-length']
});
// Log response when finished
res.on('finish', () => {
const duration = Date.now() - startTime;
logger.info('Request completed', {
method: req.method,
url: req.url,
statusCode: res.statusCode,
duration: `${duration}ms`
});
});
next();
};
// Sensitive data middleware - for routes with sensitive data
const sensitiveDataHeaders = (req: express.Request, res: express.Response, next: express.NextFunction) => {
res.setHeader('Cache-Control', 'no-store, max-age=0');
next();
};
// SSE middleware - specific for SSE endpoint
const sseHeaders = (req: express.Request, res: express.Response, next: express.NextFunction) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-store, max-age=0');
res.setHeader('Connection', 'keep-alive');
next();
};
// Configure CORS to allow any origin since this is a public API service
const corsOptions = {
origin: true, // Allow any origin
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization', "Mcp-Protocol-Version", "Mcp-Protocol-Id"],
exposedHeaders: ["Mcp-Protocol-Version", "Mcp-Protocol-Id"],
credentials: true
};
app.use(express.json());
// Add structured logging context middleware first
app.use(logger.middleware());
// Then add the logging middleware
app.use(loggingMiddleware);
// Apply base security headers to all routes
app.use(baseSecurityHeaders);
// Enable CORS pre-flight requests
app.options('*', cors(corsOptions));
const authProvider = new EverythingAuthProvider();
// Auth configuration
const options: AuthRouterOptions = {
provider: new EverythingAuthProvider(),
issuerUrl: new URL(BASE_URI),
tokenOptions: {
rateLimit: {
windowMs: 5 * 1000,
limit: 100,
}
},
clientRegistrationOptions: {
rateLimit: {
windowMs: 60 * 1000, // 1 minute
limit: 10, // Limit to 10 registrations per minute
},
},
};
const dearerAuthMiddlewareOptions: BearerAuthMiddlewareOptions = {
// verifyAccessToken(token: string): Promise<AuthInfo>;
verifier: {
verifyAccessToken: authProvider.verifyAccessToken.bind(authProvider),
},
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(new URL(BASE_URI)),
}
app.use(mcpAuthRouter(options));
const bearerAuth = requireBearerAuth(dearerAuthMiddlewareOptions);
// MCP routes (legacy SSE transport)
app.get("/sse", cors(corsOptions), bearerAuth, authContext, sseHeaders, handleSSEConnection);
app.post("/message", cors(corsOptions), bearerAuth, authContext, sensitiveDataHeaders, handleMessage);
// MCP routes (new streamable HTTP transport)
app.get("/mcp", cors(corsOptions), bearerAuth, authContext, handleStreamableHTTP);
app.post("/mcp", cors(corsOptions), bearerAuth, authContext, handleStreamableHTTP);
app.delete("/mcp", cors(corsOptions), bearerAuth, authContext, handleStreamableHTTP);
// Static assets
app.get("/mcp-logo.png", (req, res) => {
const logoPath = path.join(__dirname, "static", "mcp.png");
res.sendFile(logoPath);
});
app.get("/styles.css", (req, res) => {
const cssPath = path.join(__dirname, "static", "styles.css");
res.setHeader('Content-Type', 'text/css');
res.sendFile(cssPath);
});
// Splash page
app.get("/", (req, res) => {
const splashPath = path.join(__dirname, "static", "index.html");
res.sendFile(splashPath);
});
// Upstream auth routes
app.get("/fakeupstreamauth/authorize", cors(corsOptions), handleFakeAuthorize);
app.get("/fakeupstreamauth/callback", cors(corsOptions), handleFakeAuthorizeRedirect);
try {
await redisClient.connect();
} catch (error) {
logger.error("Could not connect to Redis", error as Error);
process.exit(1);
}
app.listen(PORT, () => {
logger.info('Server started', {
port: PORT,
url: `http://localhost:${PORT}`,
environment: process.env.NODE_ENV || 'development'
});
});