@winstonsayno/mcp-gateway 1.1.0 → 1.3.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 (71) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/README.md +43 -7
  3. package/dashboard/README.md +4 -0
  4. package/dashboard/index.html +42 -3
  5. package/dist/auth/middleware.d.ts +38 -1
  6. package/dist/auth/middleware.d.ts.map +1 -1
  7. package/dist/auth/middleware.js +148 -19
  8. package/dist/auth/middleware.js.map +1 -1
  9. package/dist/auth/oauth.d.ts +86 -0
  10. package/dist/auth/oauth.d.ts.map +1 -0
  11. package/dist/auth/oauth.js +342 -0
  12. package/dist/auth/oauth.js.map +1 -0
  13. package/dist/cli.js +54 -1
  14. package/dist/cli.js.map +1 -1
  15. package/dist/config/loader.d.ts.map +1 -1
  16. package/dist/config/loader.js +141 -3
  17. package/dist/config/loader.js.map +1 -1
  18. package/dist/gateway/api.d.ts +5 -0
  19. package/dist/gateway/api.d.ts.map +1 -1
  20. package/dist/gateway/api.js +97 -6
  21. package/dist/gateway/api.js.map +1 -1
  22. package/dist/gateway/index.d.ts +9 -1
  23. package/dist/gateway/index.d.ts.map +1 -1
  24. package/dist/gateway/index.js +90 -5
  25. package/dist/gateway/index.js.map +1 -1
  26. package/dist/index.d.ts +11 -3
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +7 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/mcp/catalog.d.ts +1 -1
  31. package/dist/mcp/endpoint.d.ts +52 -1
  32. package/dist/mcp/endpoint.d.ts.map +1 -1
  33. package/dist/mcp/endpoint.js +339 -12
  34. package/dist/mcp/endpoint.js.map +1 -1
  35. package/dist/middleware/error-handler.d.ts +10 -1
  36. package/dist/middleware/error-handler.d.ts.map +1 -1
  37. package/dist/middleware/error-handler.js +17 -3
  38. package/dist/middleware/error-handler.js.map +1 -1
  39. package/dist/monitor/index.d.ts.map +1 -1
  40. package/dist/monitor/index.js +5 -0
  41. package/dist/monitor/index.js.map +1 -1
  42. package/dist/proxy/index.d.ts +15 -0
  43. package/dist/proxy/index.d.ts.map +1 -1
  44. package/dist/proxy/index.js +44 -4
  45. package/dist/proxy/index.js.map +1 -1
  46. package/dist/security/headers.d.ts +23 -0
  47. package/dist/security/headers.d.ts.map +1 -0
  48. package/dist/security/headers.js +71 -0
  49. package/dist/security/headers.js.map +1 -0
  50. package/dist/security/lockout.d.ts +41 -0
  51. package/dist/security/lockout.d.ts.map +1 -0
  52. package/dist/security/lockout.js +117 -0
  53. package/dist/security/lockout.js.map +1 -0
  54. package/dist/security/network.d.ts +31 -0
  55. package/dist/security/network.d.ts.map +1 -0
  56. package/dist/security/network.js +147 -0
  57. package/dist/security/network.js.map +1 -0
  58. package/dist/security/posture.d.ts +18 -0
  59. package/dist/security/posture.d.ts.map +1 -0
  60. package/dist/security/posture.js +76 -0
  61. package/dist/security/posture.js.map +1 -0
  62. package/dist/security/redact.d.ts +34 -0
  63. package/dist/security/redact.d.ts.map +1 -0
  64. package/dist/security/redact.js +115 -0
  65. package/dist/security/redact.js.map +1 -0
  66. package/dist/utils/logger.d.ts.map +1 -1
  67. package/dist/utils/logger.js +4 -2
  68. package/dist/utils/logger.js.map +1 -1
  69. package/dist/utils/types.d.ts +119 -6
  70. package/dist/utils/types.d.ts.map +1 -1
  71. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -9,6 +9,117 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [1.3.0] - 2026-10-07
13
+
14
+ MCP authorization (OAuth 2.1) and resumable streams.
15
+
16
+ ### Added
17
+ - **`auth.strategy: oauth2`** — the gateway is an OAuth 2.1 protected resource per the MCP authorization spec
18
+ (2025-06-18):
19
+ - RFC 9728 *Protected Resource Metadata* at `/.well-known/oauth-protected-resource` and
20
+ `/.well-known/oauth-protected-resource/<mcp path>` (`resource`, `authorization_servers`, `scopes_supported`,
21
+ `bearer_methods_supported`, `resource_signing_alg_values_supported`).
22
+ - Bearer token validation: JWTs against `auth.oauth.jwksUrl` or the `jwks_uri` discovered from the issuer's RFC 8414 /
23
+ OpenID metadata (asymmetric algorithms only, `exp` required, `iss` and `aud` = resource URI per RFC 8707), or RFC
24
+ 7662 token introspection for opaque tokens (client-secret basic auth, cached up to `cacheSeconds` / token expiry).
25
+ - RFC 6750 challenges: `401` + `WWW-Authenticate: Bearer resource_metadata="…"` (with `error="invalid_token"` when a
26
+ token was presented), `403` + `error="insufficient_scope", scope="…"` for missing `requiredScopes`.
27
+ - `mcp_servers` / `mcp_tools` claims scope OAuth clients like JWT clients; client ids are `oauth:<sub>`.
28
+ - `GET /api/v1/security` reports OAuth settings; new `oauth-no-resource` hint.
29
+ - **Streamable HTTP resumability**: events on the `GET` SSE stream carry session-wide ids and are buffered per session
30
+ (`mcp.eventBufferSize`, default 256, `0` = off). Reconnecting with `Last-Event-ID` replays missed events, including
31
+ ones emitted while no stream was open (previously dropped).
32
+ - `docs/configuration.md`: *OAuth 2.1* section and resumability notes.
33
+
34
+ ### Changed
35
+ - `auth.strategy: oauth2` now requires `auth.oauth`; the old unused `auth.oauth2 { issuer, audience }` type was removed
36
+ (it was never accepted by the config loader).
37
+
38
+ ## [1.2.0] - 2026-10-07
39
+
40
+ Security hardening and more of the MCP spec on `/mcp`. Every new protection that could reject traffic that 1.1
41
+ accepted is **opt-in**; see *Upgrade notes*.
42
+
43
+ ### Security
44
+ - **Hashed API keys**: `auth.apiKeys` entries (plain strings or `key`) may be `sha256:<64 hex>` digests, so the config
45
+ file never holds a usable key. Digest and plain form of a key share the same client id. New CLI commands
46
+ `mcp-gateway gen-key` (random `mgw_…` key + digest, `--bytes`, `--prefix`, `--json`) and
47
+ `mcp-gateway hash-key [key]` (reads stdin when no argument is given). Malformed `sha256:` values are a config error.
48
+ - **Key expiry / disabling**: `expiresAt` (ISO 8601) and `disabled` on object keys → `401`; open `/mcp` sessions of
49
+ such keys end on the next reload. Keys expiring within 7 days produce a warning.
50
+ - **JWT hardening** (`auth.jwt`): `issuer`, `audience` (string or list), `algorithms` allowlist, `clockToleranceSeconds`,
51
+ `requireExp`, `maxTokenAgeSeconds`; verification keys from `jwtSecret` (HS*), a PEM `publicKey` (RS/PS/ES/EdDSA) or
52
+ a `jwksUrl` (HTTPS, cached `jwksCacheSeconds`, refetch on unknown `kid`). HMAC and asymmetric algorithms are never
53
+ mixed (algorithm-confusion protection); exactly one key source must be configured.
54
+ - **Security headers** (`security.headers`, default on): `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
55
+ `Referrer-Policy: no-referrer`, `Cross-Origin-Opener-Policy`, `Cross-Origin-Resource-Policy`, a deny-all CSP on API
56
+ responses and a dashboard CSP that allows exactly its inline script by SHA-256 hash. Optional `security.hsts`.
57
+ - **Network guards**: `security.ipAllowlist` (IPv4 / IPv6 / CIDR, via `net.BlockList`), `security.allowedHosts` (Host
58
+ header allowlist with `*.domain` wildcards), `security.trustProxy` (Express "trust proxy": decides `req.ip` for rate
59
+ limits, lockout, allowlist and logs). Liveness / readiness probes stay reachable.
60
+ - **DNS-rebinding protection** (`security.dnsRebindingProtection`): Host must be a loopback name / the bind address
61
+ (or `allowedHosts`), and `/mcp` accepts browser `Origin`s only when same-origin, loopback or explicitly listed.
62
+ - **Size limits**: `security.maxBodyBytes` (default 10 MiB as before, now configurable for REST and `/mcp`) and
63
+ `security.maxToolArgumentsBytes` for `tools/call`, `prompts/get` and `completion/complete` arguments (`413` on REST,
64
+ `-32602` on `/mcp`).
65
+ - **Brute-force lockout** (`security.authLockout`): after `maxFailures` (10) failed authentications from one IP within
66
+ `windowSeconds` (300), the IP gets `429` + `Retry-After` for `lockoutSeconds` (900) on every authenticated route,
67
+ including `/mcp` and `/api/v1/events`.
68
+ - **Secret redaction**: log lines and metadata, recorded `errorMessage`s (request log, audit log, `/requests`,
69
+ `/stats`, `/events`, dashboard) mask Bearer / Basic tokens, JWTs, common provider keys (OpenAI, Anthropic, GitHub,
70
+ GitLab, Slack, AWS, Google), `password=` / `token=` / `api_key=` pairs, URL credentials and values under
71
+ secret-looking keys. `GET /servers` now also masks secret-looking stdio `args` (`--token x`, `--api-key=x`). Extra
72
+ patterns via `security.redactPatterns`.
73
+ - **Secure-defaults check**: startup warnings / hints (auth off on a public bind, DNS rebinding, `/mcp` open to any
74
+ origin, plain-text / short / expiring keys, JWT without iss / aud / exp, no lockout, `corsOrigins: ["*"]` with auth,
75
+ headers disabled, error details exposed). `mcp-gateway validate` prints them; `--strict` exits with code 2.
76
+ - `GET /api/v1/security`: auth strategy, warnings, key hygiene counts and upcoming expiries, JWT settings, effective
77
+ security settings and lockout state — never key material; scoped clients get `403`. The dashboard's *Connect*
78
+ page shows it as a *Security posture* card (demo mock updated).
79
+ - `SECURITY.md`: hardening table and scope; `docs/deployment.md` security checklist extended.
80
+
81
+ ### Fixed (security)
82
+ - Unexpected errors (500) no longer return their message and stack trace whenever `NODE_ENV` was not `production`
83
+ (the default for `npm i -g` installs). They are shown only with `NODE_ENV=development` or the new
84
+ `security.exposeErrorDetails: true`. Deliberate `GatewayError` details are unchanged.
85
+
86
+ ### Added (MCP)
87
+ - **Progress notifications**: a single `tools/call` with `params._meta.progressToken` from a client that accepts
88
+ `text/event-stream` is forwarded with a gateway-generated token; upstream `notifications/progress` are mapped back
89
+ and the reply becomes an SSE stream (progress events, then the result). Plain JSON otherwise.
90
+ - **Logging**: `logging` capability, `logging/setLevel` per session; upstream `notifications/message` are forwarded to
91
+ sessions in scope at or above their level (`logger: "<serverId>/<logger>"`), and upstream servers announcing
92
+ `logging` are set to the most verbose level any session requested (re-applied after reconnects).
93
+ - **Completion**: `completions` capability and `completion/complete` routed by prompt (exposed name translated back)
94
+ or resource template / URI; servers without the capability answer an empty completion.
95
+ - **Resource subscriptions**: `resources.subscribe` capability, `resources/subscribe` / `resources/unsubscribe`
96
+ (routed like `resources/read`; `-32601` when the owning server does not support subscriptions) and
97
+ `notifications/resources/updated` forwarding. One upstream subscription per (server, URI) is shared and
98
+ reference-counted across sessions, released when the last session unsubscribes or ends, and restored after an
99
+ upstream reconnect.
100
+ - Proxy: `RequestOptions.onProgress`, `connected` and `notification` events.
101
+ - Library exports: `hashApiKey`, `isHashedKey`, `buildJwtVerifier`, `HMAC_ALGORITHMS`, `ASYMMETRIC_ALGORITHMS`,
102
+ `redactString`, `redactValue`, `redactArgs`, `configureRedaction`, `securityWarnings`, `AuthLockout`,
103
+ `createIpMatcher`, `hostAllowed`, `dashboardCsp`, `inlineScriptHashes`, `LOG_LEVELS`; types `SecurityConfig`,
104
+ `JwtConfig`, `AuthLockoutConfig`, `SecurityWarning`, `McpLogLevel`, `RequestOptions`, `ProgressUpdate`.
105
+
106
+ ### Changed
107
+ - `auth.jwtSecret` is no longer required for `strategy: jwt` when `auth.jwt.publicKey` or `auth.jwt.jwksUrl` is set.
108
+ - `initialize` on `/mcp` now also announces `logging`, `completions` and `resources.subscribe` (clients ignore
109
+ capabilities they do not use).
110
+ - JWT verification failures are logged with the client IP.
111
+
112
+ ### Upgrade notes
113
+ - No configuration changes are required. New behaviour that is on by default: security headers (disable with
114
+ `security.headers: false`), secret redaction in logs / recorded error messages, hidden 500 error details, and the
115
+ extra capabilities on `/mcp`.
116
+ - If you embedded the dashboard in an `<iframe>` on another origin, set `security.headers: false` (the new
117
+ `frame-ancestors 'none'` / `X-Frame-Options: DENY` block that).
118
+ - Tests or tooling that relied on 500 responses carrying `error.message` / `details` outside production need
119
+ `NODE_ENV=development` or `security.exposeErrorDetails: true`.
120
+ - Everything else (`ipAllowlist`, `allowedHosts`, `dnsRebindingProtection`, `authLockout`, `maxToolArgumentsBytes`,
121
+ `hsts`, `trustProxy`, JWT checks, key expiry) is opt-in.
122
+
12
123
  ## [1.1.0] - 2026-10-07
13
124
 
14
125
  ### Added
package/README.md CHANGED
@@ -21,6 +21,8 @@ Route · Authenticate · Rate-limit · Monitor — all your [Model Context Proto
21
21
 
22
22
  ---
23
23
 
24
+ > **Live demo:** try the dashboard with simulated traffic — <https://harrisoncn.github.io/mcp-gateway/> (runs entirely in your browser).
25
+
24
26
  ## The Problem
25
27
 
26
28
  As [MCP](https://modelcontextprotocol.io) becomes the standard protocol for AI agents to interact with tools, teams are running **dozens of MCP servers** — filesystem, GitHub, databases, Slack, search, and more. Managing them is chaos:
@@ -63,10 +65,11 @@ As [MCP](https://modelcontextprotocol.io) becomes the standard protocol for AI a
63
65
  ## Features
64
66
 
65
67
  - **Unified API endpoint** — one URL for all your MCP tools, auto-routed by tool name
66
- - **MCP endpoint for clients** — `/mcp` speaks MCP Streamable HTTP (2025-06-18 / 2025-03-26), so Claude Code, Cursor or any MCP client sees every upstream tool through one server, with the same auth, limits and metrics
68
+ - **MCP endpoint for clients** — `/mcp` speaks MCP Streamable HTTP (2025-06-18 / 2025-03-26), so Claude Code, Cursor or any MCP client sees every upstream tool through one server, with the same auth, limits and metrics — including progress notifications, cancellation, logging, completions and resource subscriptions
67
69
  - **Every MCP transport** — `stdio`, `streamable-http` (current spec), legacy `sse` (HTTP+SSE) and `websocket` upstream servers, with per-server headers for upstream auth
68
70
  - **Automatic reconnect** — crashed or disconnected servers are reconnected with exponential backoff + jitter; state is visible in `/servers`, `/health`, the dashboard and Prometheus
69
- - **Authentication** — API key (constant-time compare), JWT (HS256/384/512), or no-auth; misconfiguration fails closed
71
+ - **Authentication** — API keys (constant-time compare, storable as `sha256:` digests, with expiry), JWT (HMAC secret, PEM public key or JWKS URL; issuer / audience / exp checks), or no-auth; misconfiguration fails closed
72
+ - **Hardening** — security headers + hash-based CSP, IP allowlist, Host / Origin checks against DNS rebinding, body and argument size limits, brute-force lockout, secret redaction in logs and history, startup security warnings (`mcp-gateway validate --strict`)
70
73
  - **Rate limiting** — per-key sliding-window counter, with standard `X-RateLimit-*` headers
71
74
  - **Per-key scopes** — restrict an API key (or a JWT via claims) to some servers / tools and give it its own rate limit; enforced on REST and `/mcp`
72
75
  - **Concurrency limits** — per-server `maxConcurrency`, queued requests count against `timeout`
@@ -199,9 +202,9 @@ What the endpoint does:
199
202
 
200
203
  | | |
201
204
  |---|---|
202
- | `POST /mcp` | JSON-RPC: `initialize`, `ping`, `tools/list` (paginated), `tools/call`, `resources/list`, `resources/templates/list`, `resources/read`, `prompts/list`, `prompts/get`, notifications (incl. `notifications/cancelled`). Batches are accepted. Responses are `application/json`. |
203
- | `GET /mcp` | SSE stream for server→client notifications: `notifications/tools/list_changed`, `notifications/resources/list_changed` and `notifications/prompts/list_changed` are sent when the aggregated list a session sees changes (a server announces changes, connects, is removed by hot reload, …). |
204
- | Resources & prompts | Resource URIs are passed through unchanged; when two servers list the same URI the lowest server id wins. `resources/read` is routed by exact URI, then by resource template, then to the only server with resources. Prompt names follow `toolNaming` like tools. `resources/subscribe` is not offered. |
205
+ | `POST /mcp` | JSON-RPC: `initialize`, `ping`, `tools/list` (paginated), `tools/call`, `resources/list`, `resources/templates/list`, `resources/read`, `resources/subscribe` / `unsubscribe`, `prompts/list`, `prompts/get`, `logging/setLevel`, `completion/complete`, notifications (incl. `notifications/cancelled`). Batches are accepted. Responses are `application/json`; a single `tools/call` with `_meta.progressToken` switches to an SSE reply when the upstream reports progress (`notifications/progress`, then the result). |
206
+ | `GET /mcp` | SSE stream for server→client notifications: `notifications/tools/list_changed`, `notifications/resources/list_changed` and `notifications/prompts/list_changed` are sent when the aggregated list a session sees changes (a server announces changes, connects, is removed by hot reload, …); `notifications/resources/updated` for subscribed URIs; upstream `notifications/message` at or above the session's `logging/setLevel` level (`logger` = `<serverId>/<logger>`). |
207
+ | Resources & prompts | Resource URIs are passed through unchanged; when two servers list the same URI the lowest server id wins. `resources/read` is routed by exact URI, then by resource template, then to the only server with resources. Prompt names follow `toolNaming` like tools. `resources/subscribe` is routed the same way; sessions share one upstream subscription per URI, restored after reconnects. `completion/complete` is routed by prompt name or resource template. |
205
208
  | `DELETE /mcp` | Ends the session. |
206
209
  | Sessions | `initialize` returns `Mcp-Session-Id`; later requests must send it (`400` if missing, `404` if unknown or expired). A session is bound to the API key / JWT subject that created it. Idle sessions expire after `mcp.sessionIdleTimeoutSeconds`. |
207
210
  | Tool names | `toolNaming: auto` (default) keeps a tool's name unless two servers expose the same name; then every copy becomes `<serverId>__<tool>`. `prefix` always uses `<serverId>__<tool>`. Ordering is deterministic (server id, then tool name). In `auto` mode the prefixed form is also accepted by `tools/call`. |
@@ -289,14 +292,16 @@ host: 0.0.0.0 # Bind address (env: MCP_GATEWAY_HOST)
289
292
  logLevel: info # debug | info | warn | error
290
293
 
291
294
  auth:
292
- strategy: api-key # none | api-key | jwt (oauth2 is not implemented and is rejected)
295
+ strategy: api-key # none | api-key | jwt | oauth2 (OAuth 2.1 resource server, see docs/configuration.md)
293
296
  apiKeys:
294
297
  - "your-secret-key" # full access
298
+ - "sha256:…" # a key stored as its digest (mcp-gateway gen-key / hash-key)
295
299
  - key: "${APP_KEY}" # scoped key (see "Per-key scopes")
296
300
  name: app
297
301
  servers: ["github"]
298
302
  tools: ["read_*"]
299
303
  rateLimit: { limit: 30, windowSeconds: 60 }
304
+ expiresAt: "2027-01-01" # optional expiry; disabled: true switches a key off
300
305
  protect:
301
306
  health: false # true → /api/v1/health requires auth
302
307
  metrics: false # true → /api/v1/metrics requires auth (configure your scraper)
@@ -323,6 +328,12 @@ monitor:
323
328
  prometheus: true # Enable Prometheus /metrics
324
329
  retentionHours: 24 # Metrics retention
325
330
 
331
+ security: # hardening (see docs/configuration.md#security)
332
+ authLockout: true # 429 for IPs with repeated auth failures
333
+ dnsRebindingProtection: false # true for a local gateway without auth
334
+ ipAllowlist: ["10.0.0.0/8"]
335
+ maxToolArgumentsBytes: 262144
336
+
326
337
  corsOrigins:
327
338
  - "https://your-app.com"
328
339
 
@@ -568,6 +579,27 @@ await gateway.start();
568
579
  process.on('SIGTERM', () => gateway.stop());
569
580
  ```
570
581
 
582
+ ## What's New in v1.3
583
+
584
+ | Feature | Description |
585
+ |---------|-------------|
586
+ | **OAuth 2.1 (MCP authorization)** | `auth.strategy: oauth2`: RFC 9728 protected-resource metadata, JWT validation via (discovered) JWKS or RFC 7662 introspection, audience binding (RFC 8707), `WWW-Authenticate` challenges, `requiredScopes` |
587
+ | **Resumable streams** | `Last-Event-ID` replay on `GET /mcp` from a per-session event buffer (`mcp.eventBufferSize`) |
588
+
589
+ Details: [CHANGELOG](CHANGELOG.md).
590
+
591
+ ## What's New in v1.2
592
+
593
+ | Feature | Description |
594
+ |---------|-------------|
595
+ | **Hashed & expiring keys** | `auth.apiKeys` entries can be `sha256:<hex>` digests (`mcp-gateway gen-key`, `hash-key`) and carry `expiresAt` / `disabled` |
596
+ | **JWT hardening** | `auth.jwt`: `issuer`, `audience`, `algorithms` (HMAC / asymmetric never mixed), `clockToleranceSeconds`, `requireExp`, `maxTokenAgeSeconds`, PEM `publicKey` or cached `jwksUrl` (works with OAuth 2.0 / OIDC providers) |
597
+ | **`security` block** | headers + dashboard CSP, `hsts`, `trustProxy`, `ipAllowlist`, `allowedHosts`, `dnsRebindingProtection`, `maxBodyBytes`, `maxToolArgumentsBytes`, `authLockout`, `redactPatterns` — all hot reloadable |
598
+ | **Secure-defaults check** | startup warnings, `validate --strict`, `GET /api/v1/security` and a *Security posture* card in the dashboard |
599
+ | **More of MCP on `/mcp`** | `notifications/progress` (SSE replies), `logging/setLevel` + forwarded `notifications/message`, `completion/complete`, `resources/subscribe` / `unsubscribe` + `notifications/resources/updated` |
600
+
601
+ Details and upgrade notes: [CHANGELOG](CHANGELOG.md#120---2026-10-07).
602
+
571
603
  ## What's New in v1.0
572
604
 
573
605
  | Feature | Description |
@@ -617,8 +649,12 @@ unknown fields). Deep imports, log format, the dashboard and the audit database
617
649
  | JS / Kotlin clients, OpenAI / Anthropic tool schemas | ✅ Done (v1.0) |
618
650
  | Resources & prompts passthrough, persistent audit log | ✅ Done (v1.0) |
619
651
  | Stable API, docs, container image | ✅ Done (v1.0) |
652
+ | Security hardening (hashed keys, JWKS, lockout, DNS-rebinding guard, CSP) | ✅ Done (v1.2) |
653
+ | Progress, logging, completions, resource subscriptions on `/mcp` | ✅ Done (v1.2) |
620
654
  | Redis-backed rate limiting | 📋 Planned |
621
- | OAuth2 / OIDC auth | 📋 Planned |
655
+ | OAuth 2.1 / OIDC auth (MCP authorization spec) | ✅ Done (v1.3) |
656
+ | Streamable HTTP resumability (`Last-Event-ID`) | ✅ Done (v1.3) |
657
+ | Forwarding sampling / elicitation / roots requests to downstream clients | 📋 Planned |
622
658
  | Tool-level access control | ✅ Done via per-key scopes (v0.6) |
623
659
  | Request replay & debugging | 📋 Planned (history is available via the audit log) |
624
660
  | Multi-tenant mode | 📋 Planned |
@@ -70,3 +70,7 @@ servers and tools.
70
70
  |---|---|
71
71
  | ![Onboarding](../docs/images/dashboard-onboarding-try-tool.png) | ![Playground (中文)](../docs/images/dashboard-playground-zh.png) |
72
72
  | ![Light theme](../docs/images/dashboard-overview-light.png) | ![Mobile](../docs/images/dashboard-mobile-zh.png) |
73
+
74
+ ## Demo build
75
+
76
+ `demo/mock.js` replaces `fetch` for the gateway API with an in-browser simulation (servers, tools, request stream, SSE events). The GitHub Pages workflow (`.github/workflows/pages.yml`) injects it before the dashboard script and publishes the result to <https://harrisoncn.github.io/mcp-gateway/>. It is not shipped in the npm package or Docker image.
@@ -196,6 +196,12 @@ main { max-width: 1320px; margin: 0 auto; padding: 20px 16px 96px; }
196
196
  .kv b { font-size: 13.5px; font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; }
197
197
  .srv .err { color: var(--bad); font-size: 12px; overflow-wrap: anywhere; }
198
198
  .chips { display: flex; flex-wrap: wrap; gap: 6px; }
199
+ .sec-card { margin-top: 14px; }
200
+ .sec-card .kv { margin-bottom: 12px; }
201
+ .sec-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
202
+ .sec-list li { display: flex; gap: 10px; align-items: flex-start; font-size: 13px; line-height: 1.45; color: var(--text); }
203
+ .sec-list li .badge { flex: none; margin-top: 1px; }
204
+ @media (max-width: 560px) { .sec-card .kv { grid-template-columns: repeat(2, 1fr); } }
199
205
  .chip { font-family: var(--mono); font-size: 11.5px; padding: 3px 8px; border-radius: 7px; background: var(--surface-2); border: 1px solid var(--border); cursor: pointer; transition: border-color .2s, transform .15s var(--ease); }
200
206
  .chip:hover { border-color: var(--accent); }
201
207
  .chip:active { transform: scale(.95); }
@@ -478,6 +484,7 @@ tbody tr:hover { background: var(--surface-2); }
478
484
  <section class="view" id="view-connect" role="tabpanel" aria-labelledby="tab-connect">
479
485
  <div class="page-head"><div><h1 data-i18n="cnTitle">Connect a client</h1><p data-i18n="cnSub">Point any MCP client at this gateway</p></div></div>
480
486
  <div class="card" id="connectCard"></div>
487
+ <div class="card sec-card" id="securityCard" hidden></div>
481
488
  </section>
482
489
  </main>
483
490
 
@@ -567,6 +574,7 @@ const I18N = {
567
574
  via: 'Via', kind: 'Kind', any: 'Any', ok: 'OK', failed: 'Failed', apply: 'Apply', reset: 'Reset', time: 'Time', duration: 'Duration',
568
575
  prev: '← Newer', next: 'Older →', page: 'Page {n}', srcAudit: 'Persistent audit log', srcMemory: 'In-memory log',
569
576
  cnTitle: 'Connect a client', cnSub: 'Point any MCP client at this gateway',
577
+ secTitle: 'Security posture', secOk: 'No issues', secIssues: '{n} to review', secAuth: 'Auth', secKeys: 'Hashed keys', secLockout: 'Lockout', secRebind: 'DNS-rebinding guard', secHeaders: 'Security headers', secLocked: 'Locked IPs', secOn: 'on', secOff: 'off', secWarn: 'warning', secHint: 'hint', secNone: 'Nothing to report.',
570
578
  ob1Eye: 'Step 1 · Connect', ob1Title: 'Welcome to your MCP gateway',
571
579
  ob1Lead: "One endpoint for every MCP server — with auth, rate limits and live metrics. Let's get you connected in under a minute.",
572
580
  hero1: 'Many servers', hero1s: 'stdio, SSE, WebSocket, HTTP', hero2: 'One secure door', hero2s: 'keys, scopes, limits', hero3: 'Live insight', hero3s: 'latency, errors, usage',
@@ -611,6 +619,7 @@ const I18N = {
611
619
  via: '通道', kind: '类型', any: '全部', ok: '成功', failed: '失败', apply: '应用', reset: '重置', time: '时间', duration: '耗时',
612
620
  prev: '← 较新', next: '较早 →', page: '第 {n} 页', srcAudit: '持久化审计日志', srcMemory: '内存日志',
613
621
  cnTitle: '接入客户端', cnSub: '让任意 MCP 客户端连接到本网关',
622
+ secTitle: '安全状态', secOk: '无问题', secIssues: '{n} 项待处理', secAuth: '认证', secKeys: '已哈希的密钥', secLockout: '失败锁定', secRebind: 'DNS 重绑定防护', secHeaders: '安全响应头', secLocked: '已锁定 IP', secOn: '开', secOff: '关', secWarn: '警告', secHint: '建议', secNone: '暂无可报告的问题。',
614
623
  ob1Eye: '第 1 步 · 连接', ob1Title: '欢迎使用 MCP 网关',
615
624
  ob1Lead: '一个入口接入所有 MCP 服务器——自带鉴权、限流与实时监控。一分钟内即可完成连接。',
616
625
  hero1: '多个服务器', hero1s: 'stdio、SSE、WebSocket、HTTP', hero2: '统一安全入口', hero2s: '密钥、权限范围、限流', hero3: '实时洞察', hero3s: '延迟、错误、用量',
@@ -672,7 +681,7 @@ const fmtNum = (v, d = 0) => (v == null || !isFinite(v) ? '—' : v >= 1e6 ? (v
672
681
  const fmtTime = (ts) => new Date(ts).toLocaleTimeString(lang === 'zh' ? 'zh-CN' : undefined, { hour12: false });
673
682
  const fmtDateTime = (ts) => new Date(ts).toLocaleString(lang === 'zh' ? 'zh-CN' : undefined, { hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' });
674
683
  const statusCls = (s) => ({ online: 'ok', degraded: 'warn', reconnecting: 'info', offline: 'bad' })[s] || '';
675
- const ORIGIN = location.origin;
684
+ const ORIGIN = window.__MCP_GATEWAY_DEMO__ ? 'http://localhost:4000' : location.origin;
676
685
  const ICON = {
677
686
  overview: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 13h4l3-8 4 14 3-6h4"/></svg>',
678
687
  servers: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="6" rx="2"/><rect x="3" y="14" width="18" height="6" rx="2"/><path d="M7 7h.01M7 17h.01"/></svg>',
@@ -828,7 +837,7 @@ function go(view, push = true) {
828
837
  if (view === 'servers') loadServers();
829
838
  if (view === 'playground') renderPlayground($('#pgMain'), 'main');
830
839
  if (view === 'history') loadHistory();
831
- if (view === 'connect') renderSnippets($('#connectCard'), 'main');
840
+ if (view === 'connect') { renderSnippets($('#connectCard'), 'main'); loadSecurity(); }
832
841
  if (view === 'overview') requestAnimationFrame(renderCharts);
833
842
  }
834
843
  window.addEventListener('hashchange', () => go(location.hash.slice(1), false));
@@ -1537,6 +1546,36 @@ document.addEventListener('keydown', (e) => {
1537
1546
  }
1538
1547
  });
1539
1548
 
1549
+ // ─── Security posture (Connect page) ─────────────────────────────────────────
1550
+ async function loadSecurity() {
1551
+ try { state.security = await api('/security'); }
1552
+ catch { state.security = null; } // older gateway, scoped key or no access: hide the card
1553
+ renderSecurity();
1554
+ }
1555
+ function renderSecurity() {
1556
+ const card = $('#securityCard');
1557
+ const s = state.security;
1558
+ if (!s || !Array.isArray(s.warnings)) { card.hidden = true; return; }
1559
+ card.hidden = false;
1560
+ const warns = s.warnings.filter((w) => w.level === 'warn').length;
1561
+ const onOff = (v) => esc(v ? t('secOn') : t('secOff'));
1562
+ const k = s.apiKeys || { total: 0, hashed: 0 };
1563
+ const facts = [
1564
+ [t('secAuth'), esc(s.authStrategy)],
1565
+ [t('secKeys'), k.total ? `${k.hashed}/${k.total}` : '—'],
1566
+ [t('secLockout'), onOff(s.settings?.authLockout)],
1567
+ [t('secRebind'), onOff(s.settings?.dnsRebindingProtection)],
1568
+ [t('secHeaders'), onOff(s.settings?.headers)],
1569
+ [t('secLocked'), s.lockout ? String(s.lockout.lockedClients) : '—'],
1570
+ ];
1571
+ card.innerHTML =
1572
+ `<h2><span>${esc(t('secTitle'))}</span><span class="badge ${warns ? 'warn' : 'ok'}" style="margin-left:auto">${esc(warns ? t('secIssues').replace('{n}', warns) : t('secOk'))}</span></h2>` +
1573
+ `<div class="kv">${facts.map(([a, b]) => `<div><span>${esc(a)}</span><b>${b}</b></div>`).join('')}</div>` +
1574
+ (s.warnings.length
1575
+ ? `<ul class="sec-list">${s.warnings.map((w) => `<li><span class="badge ${w.level === 'warn' ? 'warn' : 'info'}">${esc(w.level === 'warn' ? t('secWarn') : t('secHint'))}</span><span>${esc(w.message)}</span></li>`).join('')}</ul>`
1576
+ : `<div class="empty">${esc(t('secNone'))}</div>`);
1577
+ }
1578
+
1540
1579
  // ─── Language ────────────────────────────────────────────────────────────────
1541
1580
  $('#langBtn').addEventListener('click', () => transition(() => {
1542
1581
  lang = lang === 'zh' ? 'en' : 'zh';
@@ -1545,7 +1584,7 @@ $('#langBtn').addEventListener('click', () => transition(() => {
1545
1584
  if (state.servers.length) renderServers();
1546
1585
  delete $('#pgMain').dataset.built; delete $('#obPg').dataset.built;
1547
1586
  if (state.view === 'playground') renderPlayground($('#pgMain'), 'main');
1548
- if (state.view === 'connect') renderSnippets($('#connectCard'), 'main');
1587
+ if (state.view === 'connect') { renderSnippets($('#connectCard'), 'main'); renderSecurity(); }
1549
1588
  if (state.view === 'history') loadHistory();
1550
1589
  if (!$('#ob').hidden) showStep(obState.step);
1551
1590
  }));
@@ -10,16 +10,33 @@
10
10
  * - The client id attached to a request is a hash fingerprint of the key,
11
11
  * never a prefix of the key itself (prefixes were leaking into logs and the
12
12
  * /requests endpoint, and keys sharing a prefix shared a rate-limit bucket).
13
+ * - Keys may be stored as SHA-256 digests (`sha256:<hex>`), so the config
14
+ * file never holds a usable key. A digest key and its plain form produce
15
+ * the same client id.
16
+ * - Keys can expire (`expiresAt`) or be switched off (`disabled`).
17
+ * - JWTs: HMAC secret, PEM public key or JWKS URL; algorithm allowlist that
18
+ * never mixes HMAC and asymmetric algorithms; optional issuer / audience /
19
+ * exp / max-age checks and clock tolerance.
13
20
  */
21
+ import { type KeyObject } from 'crypto';
14
22
  import type { Request, RequestHandler } from 'express';
23
+ import { type JWTVerifyGetKey, type JWTVerifyOptions } from 'jose';
15
24
  import type { ApiKeyConfig, AuthConfig } from '../utils/types.js';
16
25
  import { type AccessScope } from './scopes.js';
26
+ import { type TokenInfo } from './oauth.js';
17
27
  export type AuthedRequest = Request & {
18
28
  clientId?: string;
19
29
  jwtPayload?: unknown;
20
30
  /** Servers / tools / rate limit this client is restricted to (absent = unrestricted). */
21
31
  scope?: AccessScope;
32
+ /** Validated OAuth access token (strategy `oauth2`). */
33
+ oauth?: TokenInfo;
22
34
  };
35
+ export interface AuthMiddlewareOptions {
36
+ /** Path of the MCP endpoint (OAuth resource URI / metadata). Default `/mcp`. */
37
+ mcpPath?: () => string;
38
+ fetch?: typeof fetch;
39
+ }
23
40
  /** An auth middleware that can also look up the current scope of a known client id (api keys). */
24
41
  export type AuthMiddleware = RequestHandler & {
25
42
  /**
@@ -34,10 +51,30 @@ export type AuthMiddleware = RequestHandler & {
34
51
  };
35
52
  /** Normalise `auth.apiKeys` entries (plain strings or objects). */
36
53
  export declare function normalizeApiKeys(keys: AuthConfig['apiKeys']): ApiKeyConfig[];
37
- export declare function createAuthMiddleware(config?: AuthConfig): AuthMiddleware;
54
+ export declare const HMAC_ALGORITHMS: string[];
55
+ export declare const ASYMMETRIC_ALGORITHMS: string[];
56
+ /** Whether a configured key is a `sha256:<hex>` digest rather than the key itself. */
57
+ export declare function isHashedKey(key: string): boolean;
58
+ /** `sha256:<hex>` digest of a key, the form to store in the config file. */
59
+ export declare function hashApiKey(key: string): string;
60
+ /** Expiry of a key entry as epoch ms (undefined = never; NaN for an unparsable date). */
61
+ export declare function keyExpiry(entry: ApiKeyConfig): number | undefined;
62
+ /** Why a key is currently unusable, or undefined when it is active. */
63
+ export declare function keyInactiveReason(entry: ApiKeyConfig, now?: number): 'disabled' | 'expired' | undefined;
64
+ export declare function createAuthMiddleware(config?: AuthConfig, options?: AuthMiddlewareOptions): AuthMiddleware;
38
65
  export declare function fingerprint(key: string): string;
39
66
  /** Constant-time membership check against a pre-hashed key list. */
40
67
  export declare function matchesAnyKey(candidate: string, keyDigests: Buffer[]): boolean;
41
68
  /** Constant-time lookup: index of the matching key digest, or -1. */
42
69
  export declare function matchKeyIndex(candidate: string, keyDigests: Buffer[]): number;
70
+ export interface JwtVerifier {
71
+ key: Uint8Array | KeyObject | JWTVerifyGetKey;
72
+ options: JWTVerifyOptions;
73
+ }
74
+ /**
75
+ * Key source + verification options for the `jwt` strategy. Throws on
76
+ * misconfiguration (missing / conflicting key sources, algorithms that do not
77
+ * fit the key type, non-HTTPS JWKS URL).
78
+ */
79
+ export declare function buildJwtVerifier(config: AuthConfig): JwtVerifier;
43
80
  //# sourceMappingURL=middleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/auth/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,OAAO,EAA0B,cAAc,EAAE,MAAM,SAAS,CAAC;AAE/E,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAElE,OAAO,EAAgB,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAE7D,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,yFAAyF;IACzF,KAAK,CAAC,EAAE,WAAW,CAAC;CACrB,CAAC;AAEF,kGAAkG;AAClG,MAAM,MAAM,cAAc,GAAG,cAAc,GAAG;IAC5C;;;;OAIG;IACH,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,KAAK;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,WAAW,CAAA;KAAE,CAAC;CAC3F,CAAC;AAEF,mEAAmE;AACnE,wBAAgB,gBAAgB,CAAC,IAAI,EAA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