express.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import express from 'express';
  2. import { hostHeaderValidation, localhostHostValidation } from './middleware/hostHeaderValidation.js';
  3. /**
  4. * Creates an Express application pre-configured for MCP servers.
  5. *
  6. * When the host is '127.0.0.1', 'localhost', or '::1' (the default is '127.0.0.1'),
  7. * DNS rebinding protection middleware is automatically applied to protect against
  8. * DNS rebinding attacks on localhost servers.
  9. *
  10. * @param options - Configuration options
  11. * @returns A configured Express application
  12. *
  13. * @example
  14. * ```typescript
  15. * // Basic usage - defaults to 127.0.0.1 with DNS rebinding protection
  16. * const app = createMcpExpressApp();
  17. *
  18. * // Custom host - DNS rebinding protection only applied for localhost hosts
  19. * const app = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection
  20. * const app = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled
  21. *
  22. * // Custom allowed hosts for non-localhost binding
  23. * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] });
  24. * ```
  25. */
  26. export function createMcpExpressApp(options = {}) {
  27. const { host = '127.0.0.1', allowedHosts } = options;
  28. const app = express();
  29. app.use(express.json());
  30. // If allowedHosts is explicitly provided, use that for validation
  31. if (allowedHosts) {
  32. app.use(hostHeaderValidation(allowedHosts));
  33. }
  34. else {
  35. // Apply DNS rebinding protection automatically for localhost hosts
  36. const localhostHosts = ['127.0.0.1', 'localhost', '::1'];
  37. if (localhostHosts.includes(host)) {
  38. app.use(localhostHostValidation());
  39. }
  40. else if (host === '0.0.0.0' || host === '::') {
  41. // Warn when binding to all interfaces without DNS rebinding protection
  42. // eslint-disable-next-line no-console
  43. console.warn(`Warning: Server is binding to ${host} without DNS rebinding protection. ` +
  44. 'Consider using the allowedHosts option to restrict allowed hosts, ' +
  45. 'or use authentication to protect your server.');
  46. }
  47. }
  48. return app;
  49. }
  50. //# sourceMappingURL=express.js.map