@casys/mcp-server 0.26.0 → 0.27.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.
- package/CHANGELOG.md +1779 -0
- package/LICENSE +21 -0
- package/README.md +19 -5
- package/esm/_dnt.polyfills.d.ts +12 -0
- package/esm/_dnt.polyfills.d.ts.map +1 -0
- package/esm/_dnt.polyfills.js +15 -0
- package/esm/_dnt.shims.d.ts +2 -0
- package/esm/_dnt.shims.d.ts.map +1 -0
- package/esm/_dnt.shims.js +57 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +33 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +48 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +106 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +636 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +67 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +1393 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +44 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +117 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +103 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +32 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +96 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +159 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +14 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +10 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +22 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +29 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +19 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +30 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +10 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +14 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +9 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +81 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +20 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +32 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +6 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +4 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +13 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +51 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +53 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +79 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +91 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +100 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +33 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +111 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +104 -0
- package/esm/mod.d.ts +102 -0
- package/esm/mod.d.ts.map +1 -0
- package/esm/mod.js +103 -0
- package/esm/package.json +3 -0
- package/esm/src/auth/as-metadata-proxy.d.ts +112 -0
- package/esm/src/auth/as-metadata-proxy.d.ts.map +1 -0
- package/esm/src/auth/as-metadata-proxy.js +171 -0
- package/esm/src/auth/config.d.ts +117 -0
- package/esm/src/auth/config.d.ts.map +1 -0
- package/esm/src/auth/config.js +219 -0
- package/esm/src/auth/jwt-provider.d.ts +157 -0
- package/esm/src/auth/jwt-provider.d.ts.map +1 -0
- package/esm/src/auth/jwt-provider.js +187 -0
- package/esm/src/auth/middleware.d.ts +61 -0
- package/esm/src/auth/middleware.d.ts.map +1 -0
- package/esm/src/auth/middleware.js +209 -0
- package/esm/src/auth/mod.d.ts +23 -0
- package/esm/src/auth/mod.d.ts.map +1 -0
- package/esm/src/auth/mod.js +27 -0
- package/esm/src/auth/multi-tenant-middleware.d.ts +131 -0
- package/esm/src/auth/multi-tenant-middleware.d.ts.map +1 -0
- package/esm/src/auth/multi-tenant-middleware.js +128 -0
- package/esm/src/auth/presets.d.ts +231 -0
- package/esm/src/auth/presets.d.ts.map +1 -0
- package/esm/src/auth/presets.js +223 -0
- package/{src/auth/provider.ts → esm/src/auth/provider.d.ts} +13 -15
- package/esm/src/auth/provider.d.ts.map +1 -0
- package/esm/src/auth/provider.js +34 -0
- package/esm/src/auth/scope-middleware.d.ts +30 -0
- package/esm/src/auth/scope-middleware.d.ts.map +1 -0
- package/esm/src/auth/scope-middleware.js +48 -0
- package/esm/src/auth/static-token-provider.d.ts +155 -0
- package/esm/src/auth/static-token-provider.d.ts.map +1 -0
- package/esm/src/auth/static-token-provider.js +256 -0
- package/esm/src/auth/types.d.ts +151 -0
- package/esm/src/auth/types.d.ts.map +1 -0
- package/esm/src/auth/types.js +64 -0
- package/esm/src/client-auth/callback-server.d.ts +34 -0
- package/esm/src/client-auth/callback-server.d.ts.map +1 -0
- package/esm/src/client-auth/callback-server.js +141 -0
- package/esm/src/client-auth/client-id-metadata.d.ts +29 -0
- package/esm/src/client-auth/client-id-metadata.d.ts.map +1 -0
- package/esm/src/client-auth/client-id-metadata.js +149 -0
- package/esm/src/client-auth/connect.d.ts +32 -0
- package/esm/src/client-auth/connect.d.ts.map +1 -0
- package/esm/src/client-auth/connect.js +47 -0
- package/esm/src/client-auth/mod.d.ts +19 -0
- package/esm/src/client-auth/mod.d.ts.map +1 -0
- package/{src/client-auth/mod.ts → esm/src/client-auth/mod.js} +1 -26
- package/esm/src/client-auth/provider.d.ts +78 -0
- package/esm/src/client-auth/provider.d.ts.map +1 -0
- package/esm/src/client-auth/provider.js +246 -0
- package/esm/src/client-auth/token-store/file-store.d.ts +20 -0
- package/esm/src/client-auth/token-store/file-store.d.ts.map +1 -0
- package/esm/src/client-auth/token-store/file-store.js +62 -0
- package/esm/src/client-auth/token-store/memory-store.d.ts +14 -0
- package/esm/src/client-auth/token-store/memory-store.d.ts.map +1 -0
- package/esm/src/client-auth/token-store/memory-store.js +25 -0
- package/esm/src/client-auth/types.d.ts +89 -0
- package/esm/src/client-auth/types.d.ts.map +1 -0
- package/esm/src/client-auth/types.js +10 -0
- package/esm/src/concurrency/rate-limiter.d.ts +87 -0
- package/esm/src/concurrency/rate-limiter.d.ts.map +1 -0
- package/esm/src/concurrency/rate-limiter.js +165 -0
- package/esm/src/concurrency/request-queue.d.ts +71 -0
- package/esm/src/concurrency/request-queue.d.ts.map +1 -0
- package/esm/src/concurrency/request-queue.js +128 -0
- package/esm/src/http/body.d.ts +20 -0
- package/esm/src/http/body.d.ts.map +1 -0
- package/esm/src/http/body.js +63 -0
- package/esm/src/http/request-guards.d.ts +54 -0
- package/esm/src/http/request-guards.d.ts.map +1 -0
- package/esm/src/http/request-guards.js +114 -0
- package/esm/src/http/wire.d.ts +26 -0
- package/esm/src/http/wire.d.ts.map +1 -0
- package/{src/http/wire.ts → esm/src/http/wire.js} +13 -19
- package/esm/src/inspector/launcher.d.ts +48 -0
- package/esm/src/inspector/launcher.d.ts.map +1 -0
- package/esm/src/inspector/launcher.js +100 -0
- package/esm/src/mcp-app.d.ts +728 -0
- package/esm/src/mcp-app.d.ts.map +1 -0
- package/esm/src/mcp-app.js +3530 -0
- package/{src/middleware/backpressure.ts → esm/src/middleware/backpressure.d.ts} +2 -14
- package/esm/src/middleware/backpressure.d.ts.map +1 -0
- package/esm/src/middleware/backpressure.js +31 -0
- package/esm/src/middleware/mod.d.ts +11 -0
- package/esm/src/middleware/mod.d.ts.map +1 -0
- package/{src/middleware/mod.ts → esm/src/middleware/mod.js} +0 -10
- package/{src/middleware/rate-limit.ts → esm/src/middleware/rate-limit.d.ts} +2 -25
- package/esm/src/middleware/rate-limit.d.ts.map +1 -0
- package/esm/src/middleware/rate-limit.js +33 -0
- package/esm/src/middleware/runner.d.ts +32 -0
- package/esm/src/middleware/runner.d.ts.map +1 -0
- package/esm/src/middleware/runner.js +49 -0
- package/esm/src/middleware/types.d.ts +76 -0
- package/esm/src/middleware/types.d.ts.map +1 -0
- package/esm/src/middleware/types.js +9 -0
- package/esm/src/middleware/validation.d.ts +24 -0
- package/esm/src/middleware/validation.d.ts.map +1 -0
- package/esm/src/middleware/validation.js +30 -0
- package/esm/src/mrtr/capability-check.d.ts +75 -0
- package/esm/src/mrtr/capability-check.d.ts.map +1 -0
- package/esm/src/mrtr/capability-check.js +233 -0
- package/esm/src/mrtr/mod.d.ts +18 -0
- package/esm/src/mrtr/mod.d.ts.map +1 -0
- package/esm/src/mrtr/mod.js +12 -0
- package/esm/src/mrtr/replay-store.d.ts +50 -0
- package/esm/src/mrtr/replay-store.d.ts.map +1 -0
- package/esm/src/mrtr/replay-store.js +61 -0
- package/esm/src/mrtr/request-state.d.ts +181 -0
- package/esm/src/mrtr/request-state.d.ts.map +1 -0
- package/esm/src/mrtr/request-state.js +313 -0
- package/esm/src/mrtr/retry-guard.d.ts +61 -0
- package/esm/src/mrtr/retry-guard.d.ts.map +1 -0
- package/esm/src/mrtr/retry-guard.js +53 -0
- package/esm/src/mrtr/types.d.ts +99 -0
- package/esm/src/mrtr/types.d.ts.map +1 -0
- package/esm/src/mrtr/types.js +14 -0
- package/esm/src/observability/metrics.d.ts +104 -0
- package/esm/src/observability/metrics.d.ts.map +1 -0
- package/esm/src/observability/metrics.js +207 -0
- package/{src/observability/mod.ts → esm/src/observability/mod.d.ts} +2 -11
- package/esm/src/observability/mod.d.ts.map +1 -0
- package/esm/src/observability/mod.js +11 -0
- package/esm/src/observability/otel.d.ts +73 -0
- package/esm/src/observability/otel.d.ts.map +1 -0
- package/esm/src/observability/otel.js +260 -0
- package/esm/src/runtime/runtime.d.ts +10 -0
- package/esm/src/runtime/runtime.d.ts.map +1 -0
- package/esm/src/runtime/runtime.deno.d.ts +50 -0
- package/esm/src/runtime/runtime.deno.d.ts.map +1 -0
- package/esm/src/runtime/runtime.deno.js +120 -0
- package/{src/runtime/runtime.ts → esm/src/runtime/runtime.js} +5 -14
- package/esm/src/runtime/runtime.node.d.ts +51 -0
- package/esm/src/runtime/runtime.node.d.ts.map +1 -0
- package/esm/src/runtime/runtime.node.js +268 -0
- package/{src/runtime/types.ts → esm/src/runtime/types.d.ts} +28 -51
- package/esm/src/runtime/types.d.ts.map +1 -0
- package/esm/src/runtime/types.js +12 -0
- package/esm/src/security/channel-hmac.d.ts +43 -0
- package/esm/src/security/channel-hmac.d.ts.map +1 -0
- package/{src/security/channel-hmac.ts → esm/src/security/channel-hmac.js} +12 -17
- package/esm/src/security/csp.d.ts +50 -0
- package/esm/src/security/csp.d.ts.map +1 -0
- package/esm/src/security/csp.js +63 -0
- package/esm/src/security/message-signer.d.ts +88 -0
- package/esm/src/security/message-signer.d.ts.map +1 -0
- package/esm/src/security/message-signer.js +166 -0
- package/esm/src/subscriptions/subscription-registry.d.ts +256 -0
- package/esm/src/subscriptions/subscription-registry.d.ts.map +1 -0
- package/esm/src/subscriptions/subscription-registry.js +406 -0
- package/{src/tasks/mod.ts → esm/src/tasks/mod.d.ts} +3 -23
- package/esm/src/tasks/mod.d.ts.map +1 -0
- package/esm/src/tasks/mod.js +11 -0
- package/esm/src/tasks/task-store.d.ts +342 -0
- package/esm/src/tasks/task-store.d.ts.map +1 -0
- package/esm/src/tasks/task-store.js +649 -0
- package/esm/src/transport/request-headers.d.ts +145 -0
- package/esm/src/transport/request-headers.d.ts.map +1 -0
- package/esm/src/transport/request-headers.js +525 -0
- package/esm/src/types.d.ts +776 -0
- package/esm/src/types.d.ts.map +1 -0
- package/esm/src/types.js +92 -0
- package/esm/src/ui/viewer-utils.d.ts +45 -0
- package/esm/src/ui/viewer-utils.d.ts.map +1 -0
- package/esm/src/ui/viewer-utils.js +97 -0
- package/esm/src/validation/schema-validator.d.ts +115 -0
- package/esm/src/validation/schema-validator.d.ts.map +1 -0
- package/esm/src/validation/schema-validator.js +249 -0
- package/package.json +35 -23
- package/mod.ts +0 -302
- package/src/auth/as-metadata-proxy.ts +0 -288
- package/src/auth/config.ts +0 -368
- package/src/auth/jwt-provider.ts +0 -327
- package/src/auth/middleware.ts +0 -257
- package/src/auth/mod.ts +0 -89
- package/src/auth/multi-tenant-middleware.ts +0 -236
- package/src/auth/presets.ts +0 -351
- package/src/auth/scope-middleware.ts +0 -59
- package/src/auth/static-token-provider.ts +0 -197
- package/src/auth/types.ts +0 -207
- package/src/client-auth/callback-server.ts +0 -166
- package/src/client-auth/client-id-metadata.ts +0 -260
- package/src/client-auth/connect.ts +0 -72
- package/src/client-auth/provider.ts +0 -300
- package/src/client-auth/token-store/file-store.ts +0 -73
- package/src/client-auth/token-store/memory-store.ts +0 -32
- package/src/client-auth/types.ts +0 -95
- package/src/concurrency/rate-limiter.ts +0 -190
- package/src/concurrency/request-queue.ts +0 -140
- package/src/http/body.ts +0 -72
- package/src/http/request-guards.ts +0 -137
- package/src/inspector/launcher.ts +0 -131
- package/src/mcp-app.ts +0 -4426
- package/src/middleware/runner.ts +0 -63
- package/src/middleware/types.ts +0 -104
- package/src/middleware/validation.ts +0 -28
- package/src/mrtr/capability-check.ts +0 -303
- package/src/mrtr/mod.ts +0 -46
- package/src/mrtr/replay-store.ts +0 -103
- package/src/mrtr/request-state.ts +0 -435
- package/src/mrtr/types.ts +0 -107
- package/src/observability/metrics.ts +0 -336
- package/src/observability/otel.ts +0 -330
- package/src/runtime/runtime.deno.ts +0 -149
- package/src/runtime/runtime.node.ts +0 -324
- package/src/security/csp.ts +0 -89
- package/src/security/message-signer.ts +0 -223
- package/src/subscriptions/subscription-registry.ts +0 -558
- package/src/tasks/task-store.ts +0 -1014
- package/src/testdata/stdio-e2e-server.ts +0 -110
- package/src/transport/request-headers.ts +0 -661
- package/src/types.ts +0 -907
- package/src/ui/viewer-utils.ts +0 -117
- package/src/validation/schema-validator.ts +0 -307
package/src/auth/middleware.ts
DELETED
|
@@ -1,257 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Authentication middleware and utilities.
|
|
3
|
-
*
|
|
4
|
-
* Provides Bearer token extraction, 401/403 response factories,
|
|
5
|
-
* and the auth middleware for the pipeline.
|
|
6
|
-
*
|
|
7
|
-
* @module lib/server/auth/middleware
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import type { AuthProvider } from "./provider.js";
|
|
11
|
-
import type { AuthInfo } from "./types.js";
|
|
12
|
-
import type { Middleware } from "../middleware/types.js";
|
|
13
|
-
import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
|
|
14
|
-
|
|
15
|
-
// ── Auth error codes ────────────────────────────────────────────────────────
|
|
16
|
-
//
|
|
17
|
-
// Both codes moved OUT of the JSON-RPC reserved range (`-32768`..`-32000`) for
|
|
18
|
-
// spec 2026-07-28, which is stricter than earlier readings of it suggested:
|
|
19
|
-
//
|
|
20
|
-
// * `-32002` — "Implementations of this protocol version **MUST NOT** emit
|
|
21
|
-
// these codes", because 2025-11-25 and earlier used it for resource-not-found
|
|
22
|
-
// (now `-32602`). Keeping it for 403 was a conformance violation, not a
|
|
23
|
-
// grandfathered liberty. Two prior reviews, including one of this file, read
|
|
24
|
-
// the allocation policy as permitting it. It does not.
|
|
25
|
-
// * `-32001` — inside `-32000`..`-32019`, where "new implementations
|
|
26
|
-
// **SHOULD NOT** use codes from this sub-range at all" and receivers "**MUST
|
|
27
|
-
// NOT** assume any specific meaning".
|
|
28
|
-
//
|
|
29
|
-
// The spec's own guidance for codes it does not define: "**SHOULD** be allocated
|
|
30
|
-
// outside the JSON-RPC reserved range". Hence `-31401` / `-31403`, mnemonic for
|
|
31
|
-
// the HTTP statuses they accompany.
|
|
32
|
-
//
|
|
33
|
-
// BREAKING for anything matching on the old numbers — see the changelog.
|
|
34
|
-
|
|
35
|
-
/** 401 Unauthorized: no token, or an invalid one. */
|
|
36
|
-
export const JSONRPC_UNAUTHORIZED = -31401;
|
|
37
|
-
|
|
38
|
-
/** 403 Forbidden: authenticated, but missing a required scope. */
|
|
39
|
-
export const JSONRPC_FORBIDDEN = -31403;
|
|
40
|
-
|
|
41
|
-
function escapeAuthenticateParam(s: string): string {
|
|
42
|
-
return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Authentication error with structured information
|
|
47
|
-
* for generating proper HTTP error responses.
|
|
48
|
-
*/
|
|
49
|
-
export class AuthError extends Error {
|
|
50
|
-
constructor(
|
|
51
|
-
public readonly code:
|
|
52
|
-
| "missing_token"
|
|
53
|
-
| "invalid_token"
|
|
54
|
-
| "insufficient_scope",
|
|
55
|
-
public readonly resourceMetadataUrl: string,
|
|
56
|
-
public readonly requiredScopes?: string[],
|
|
57
|
-
) {
|
|
58
|
-
super(
|
|
59
|
-
code === "missing_token"
|
|
60
|
-
? "Authorization header with Bearer token required"
|
|
61
|
-
: code === "invalid_token"
|
|
62
|
-
? "Invalid or expired token"
|
|
63
|
-
: `Insufficient scope: requires ${requiredScopes?.join(", ")}`,
|
|
64
|
-
);
|
|
65
|
-
this.name = "AuthError";
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Extract Bearer token from Authorization header.
|
|
71
|
-
*
|
|
72
|
-
* @param request - HTTP Request
|
|
73
|
-
* @returns Token string or null if not present/invalid format
|
|
74
|
-
*/
|
|
75
|
-
export function extractBearerToken(request: Request): string | null {
|
|
76
|
-
const auth = request.headers.get("Authorization");
|
|
77
|
-
if (!auth?.startsWith("Bearer ")) return null;
|
|
78
|
-
const token = auth.slice(7).trim();
|
|
79
|
-
return token.length > 0 ? token : null;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Create a 401 Unauthorized response with WWW-Authenticate header.
|
|
84
|
-
*
|
|
85
|
-
* @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
|
|
86
|
-
* @param error - OAuth error code
|
|
87
|
-
* @param errorDescription - Human-readable error description
|
|
88
|
-
*/
|
|
89
|
-
export function createUnauthorizedResponse(
|
|
90
|
-
resourceMetadataUrl: string,
|
|
91
|
-
error?: string,
|
|
92
|
-
errorDescription?: string,
|
|
93
|
-
): Response {
|
|
94
|
-
const parts = [
|
|
95
|
-
`Bearer resource_metadata="${
|
|
96
|
-
escapeAuthenticateParam(resourceMetadataUrl)
|
|
97
|
-
}"`,
|
|
98
|
-
];
|
|
99
|
-
if (error) parts.push(`error="${escapeAuthenticateParam(error)}"`);
|
|
100
|
-
if (errorDescription) {
|
|
101
|
-
parts.push(
|
|
102
|
-
`error_description="${escapeAuthenticateParam(errorDescription)}"`,
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
return new Response(
|
|
107
|
-
JSON.stringify({
|
|
108
|
-
jsonrpc: "2.0",
|
|
109
|
-
id: null,
|
|
110
|
-
error: {
|
|
111
|
-
code: JSONRPC_UNAUTHORIZED,
|
|
112
|
-
message: errorDescription ?? "Unauthorized",
|
|
113
|
-
},
|
|
114
|
-
}),
|
|
115
|
-
{
|
|
116
|
-
status: 401,
|
|
117
|
-
headers: {
|
|
118
|
-
"Content-Type": "application/json",
|
|
119
|
-
"WWW-Authenticate": parts.join(", "),
|
|
120
|
-
},
|
|
121
|
-
},
|
|
122
|
-
);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Create a 403 Forbidden response for insufficient scopes.
|
|
127
|
-
*
|
|
128
|
-
* @param requiredScopes - Scopes that were required but missing
|
|
129
|
-
* @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
|
|
130
|
-
*/
|
|
131
|
-
export function createForbiddenResponse(
|
|
132
|
-
requiredScopes: string[],
|
|
133
|
-
resourceMetadataUrl: string,
|
|
134
|
-
): Response {
|
|
135
|
-
const requiredScopesDescription = requiredScopes.join(", ");
|
|
136
|
-
const parts = [
|
|
137
|
-
`Bearer resource_metadata="${
|
|
138
|
-
escapeAuthenticateParam(resourceMetadataUrl)
|
|
139
|
-
}"`,
|
|
140
|
-
`error="insufficient_scope"`,
|
|
141
|
-
`error_description="${escapeAuthenticateParam(requiredScopesDescription)}"`,
|
|
142
|
-
];
|
|
143
|
-
|
|
144
|
-
return new Response(
|
|
145
|
-
JSON.stringify({
|
|
146
|
-
jsonrpc: "2.0",
|
|
147
|
-
id: null,
|
|
148
|
-
error: {
|
|
149
|
-
code: JSONRPC_FORBIDDEN,
|
|
150
|
-
message: `Forbidden: requires scopes ${requiredScopes.join(", ")}`,
|
|
151
|
-
},
|
|
152
|
-
}),
|
|
153
|
-
{
|
|
154
|
-
status: 403,
|
|
155
|
-
headers: {
|
|
156
|
-
"Content-Type": "application/json",
|
|
157
|
-
"WWW-Authenticate": parts.join(", "),
|
|
158
|
-
},
|
|
159
|
-
},
|
|
160
|
-
);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
export function freezeAuthInfo(authInfo: AuthInfo): AuthInfo {
|
|
164
|
-
const scopes = Object.freeze([...authInfo.scopes]) as unknown as string[];
|
|
165
|
-
const frozen: AuthInfo = {
|
|
166
|
-
...authInfo,
|
|
167
|
-
scopes,
|
|
168
|
-
...(authInfo.claims
|
|
169
|
-
? {
|
|
170
|
-
claims: deepFreezeJson(structuredClone(authInfo.claims)) as Record<
|
|
171
|
-
string,
|
|
172
|
-
unknown
|
|
173
|
-
>,
|
|
174
|
-
}
|
|
175
|
-
: {}),
|
|
176
|
-
};
|
|
177
|
-
|
|
178
|
-
return Object.freeze(frozen);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function deepFreezeJson<T>(value: T): T {
|
|
182
|
-
if (typeof value !== "object" || value === null) return value;
|
|
183
|
-
for (const nested of Object.values(value)) {
|
|
184
|
-
deepFreezeJson(nested);
|
|
185
|
-
}
|
|
186
|
-
return Object.freeze(value);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* Create an authentication middleware for the MCP pipeline.
|
|
191
|
-
*
|
|
192
|
-
* Extracts the Bearer token from the HTTP request, validates it
|
|
193
|
-
* via the AuthProvider, and injects `authInfo` into the context.
|
|
194
|
-
*
|
|
195
|
-
* For STDIO transport (no `ctx.request`), the middleware is skipped
|
|
196
|
-
* since STDIO is a local transport with no auth needed.
|
|
197
|
-
*
|
|
198
|
-
* @param provider - AuthProvider implementation
|
|
199
|
-
*/
|
|
200
|
-
export function createAuthMiddleware(provider: AuthProvider): Middleware {
|
|
201
|
-
return async (ctx, next) => {
|
|
202
|
-
// STDIO transport: no request, skip auth
|
|
203
|
-
if (!ctx.request) {
|
|
204
|
-
return next();
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// 0.15.0+: provider's getResourceMetadata() always returns a valid
|
|
208
|
-
// absolute URL in resource_metadata_url (type system guarantees it).
|
|
209
|
-
// No derivation needed at the middleware level anymore.
|
|
210
|
-
const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
|
|
211
|
-
|
|
212
|
-
// Already authenticated by the HTTP-level gate (verifyHttpAuth).
|
|
213
|
-
// Skip the redundant verifyToken call to avoid JWKS race conditions
|
|
214
|
-
// when concurrent requests arrive on a cold cache.
|
|
215
|
-
if (ctx.authInfo) {
|
|
216
|
-
ctx.resourceMetadataUrl = metadataUrl;
|
|
217
|
-
return next();
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const token = extractBearerToken(ctx.request);
|
|
221
|
-
if (!token) {
|
|
222
|
-
if (isOtelEnabled()) {
|
|
223
|
-
recordAuthEvent("reject", {
|
|
224
|
-
reason: "missing_token",
|
|
225
|
-
tool: ctx.toolName ?? "",
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
throw new AuthError("missing_token", metadataUrl);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const authInfo = await provider.verifyToken(token);
|
|
232
|
-
if (!authInfo) {
|
|
233
|
-
if (isOtelEnabled()) {
|
|
234
|
-
recordAuthEvent("reject", {
|
|
235
|
-
reason: "invalid_token",
|
|
236
|
-
tool: ctx.toolName ?? "",
|
|
237
|
-
});
|
|
238
|
-
}
|
|
239
|
-
throw new AuthError("invalid_token", metadataUrl);
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
if (isOtelEnabled()) {
|
|
243
|
-
recordAuthEvent("verify", {
|
|
244
|
-
subject: authInfo.subject ?? "",
|
|
245
|
-
tool: ctx.toolName ?? "",
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
// Deep-freeze authInfo to prevent mutation by downstream middlewares
|
|
250
|
-
ctx.authInfo = freezeAuthInfo(authInfo);
|
|
251
|
-
|
|
252
|
-
// Propagate resourceMetadataUrl for downstream middlewares (scope-middleware)
|
|
253
|
-
ctx.resourceMetadataUrl = metadataUrl;
|
|
254
|
-
|
|
255
|
-
return next();
|
|
256
|
-
};
|
|
257
|
-
}
|
package/src/auth/mod.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Auth module for McpApp.
|
|
3
|
-
*
|
|
4
|
-
* @module lib/server/auth
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
// Types
|
|
8
|
-
export type {
|
|
9
|
-
AuthInfo,
|
|
10
|
-
AuthOptions,
|
|
11
|
-
HttpsUrl,
|
|
12
|
-
ProtectedResourceMetadata,
|
|
13
|
-
} from "./types.js";
|
|
14
|
-
// HttpsUrl brand factories (0.16.0) — construct branded URL values for
|
|
15
|
-
// `JwtAuthProviderOptions`, `ProtectedResourceMetadata`, and anywhere else
|
|
16
|
-
// that requires a validated absolute HTTP(S) URL.
|
|
17
|
-
export { httpsUrl, tryHttpsUrl } from "./types.js";
|
|
18
|
-
|
|
19
|
-
// Provider base class
|
|
20
|
-
export { AuthProvider } from "./provider.js";
|
|
21
|
-
|
|
22
|
-
// Middleware and utilities
|
|
23
|
-
export {
|
|
24
|
-
AuthError,
|
|
25
|
-
createAuthMiddleware,
|
|
26
|
-
createForbiddenResponse,
|
|
27
|
-
createUnauthorizedResponse,
|
|
28
|
-
extractBearerToken,
|
|
29
|
-
} from "./middleware.js";
|
|
30
|
-
|
|
31
|
-
// Scope enforcement
|
|
32
|
-
export { createScopeMiddleware } from "./scope-middleware.js";
|
|
33
|
-
|
|
34
|
-
// Multi-tenant resolution (tenant enforcement on top of auth)
|
|
35
|
-
export { createMultiTenantMiddleware } from "./multi-tenant-middleware.js";
|
|
36
|
-
export type {
|
|
37
|
-
MultiTenantMiddlewareOptions,
|
|
38
|
-
TenantResolution,
|
|
39
|
-
TenantResolver,
|
|
40
|
-
} from "./multi-tenant-middleware.js";
|
|
41
|
-
|
|
42
|
-
// JWT Provider
|
|
43
|
-
export { JwtAuthProvider } from "./jwt-provider.js";
|
|
44
|
-
// JwtAuthProviderOptions is a discriminated union in 0.16.0 — both branch
|
|
45
|
-
// types are exported so advanced callers can type-annotate variables
|
|
46
|
-
// explicitly.
|
|
47
|
-
export type {
|
|
48
|
-
JwtAuthProviderOptions,
|
|
49
|
-
JwtAuthProviderOptionsOpaqueResource,
|
|
50
|
-
JwtAuthProviderOptionsUrlResource,
|
|
51
|
-
} from "./jwt-provider.js";
|
|
52
|
-
|
|
53
|
-
// OIDC Presets
|
|
54
|
-
export {
|
|
55
|
-
buildJwtAuthProvider,
|
|
56
|
-
createAuth0AuthProvider,
|
|
57
|
-
createGitHubAuthProvider,
|
|
58
|
-
createGoogleAuthProvider,
|
|
59
|
-
createOIDCAuthProvider,
|
|
60
|
-
} from "./presets.js";
|
|
61
|
-
export type {
|
|
62
|
-
BuildJwtAuthProviderOptions,
|
|
63
|
-
OIDCPresetOptions,
|
|
64
|
-
PresetOptions,
|
|
65
|
-
} from "./presets.js";
|
|
66
|
-
|
|
67
|
-
// AS Metadata Proxy (DCR discovery for IdPs without native RFC 7591)
|
|
68
|
-
export { createAsMetadataHandler } from "./as-metadata-proxy.js";
|
|
69
|
-
export type { AsMetadataProxyOptions } from "./as-metadata-proxy.js";
|
|
70
|
-
|
|
71
|
-
// Config loader (YAML + env)
|
|
72
|
-
export { createAuthProviderFromConfig, loadAuthConfig } from "./config.js";
|
|
73
|
-
// `AuthConfig` is a discriminated union in 0.17.0 — each variant is also
|
|
74
|
-
// exported for callers that want to annotate variables explicitly.
|
|
75
|
-
export type {
|
|
76
|
-
Auth0AuthConfig,
|
|
77
|
-
AuthConfig,
|
|
78
|
-
AuthProviderName,
|
|
79
|
-
GitHubAuthConfig,
|
|
80
|
-
GoogleAuthConfig,
|
|
81
|
-
OIDCAuthConfig,
|
|
82
|
-
} from "./config.js";
|
|
83
|
-
|
|
84
|
-
// Static Token Provider (opaque pre-shared bearer tokens; no OIDC/JWT infra)
|
|
85
|
-
export {
|
|
86
|
-
createStaticTokenAuthProvider,
|
|
87
|
-
StaticTokenAuthProvider,
|
|
88
|
-
} from "./static-token-provider.js";
|
|
89
|
-
export type { StaticTokenAuthProviderOptions } from "./static-token-provider.js";
|
|
@@ -1,236 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Multi-tenant resolution middleware for MCP servers.
|
|
3
|
-
*
|
|
4
|
-
* Extends the auth pipeline with tenant identification and validation.
|
|
5
|
-
* Consumers provide a {@link TenantResolver} that knows how to map an
|
|
6
|
-
* authenticated request to a tenant identifier — typically by combining
|
|
7
|
-
* the HTTP Host header (subdomain-based tenancy) with a custom JWT claim.
|
|
8
|
-
*
|
|
9
|
-
* The resolved `tenantId` is injected into `ctx.authInfo.tenantId` so
|
|
10
|
-
* downstream middlewares and tool handlers can scope data access.
|
|
11
|
-
*
|
|
12
|
-
* This middleware is **optional**. Single-tenant servers do not need it.
|
|
13
|
-
* When used, it MUST be placed AFTER the auth middleware (which populates
|
|
14
|
-
* `ctx.authInfo`) and BEFORE the scope middleware and tool handlers.
|
|
15
|
-
*
|
|
16
|
-
* @example Pipeline wiring
|
|
17
|
-
* ```typescript
|
|
18
|
-
* server.use(createAuthMiddleware(authProvider));
|
|
19
|
-
* server.use(createMultiTenantMiddleware(new MyTenantResolver(), {
|
|
20
|
-
* onRejection: (ctx, reason) => auditLog.warn("tenant_reject", { reason }),
|
|
21
|
-
* }));
|
|
22
|
-
* server.use(createScopeMiddleware(toolScopes));
|
|
23
|
-
* ```
|
|
24
|
-
*
|
|
25
|
-
* @module lib/server/auth/multi-tenant-middleware
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
import type { Middleware, MiddlewareContext } from "../middleware/types.js";
|
|
29
|
-
import type { AuthInfo } from "./types.js";
|
|
30
|
-
import { AuthError } from "./middleware.js";
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Result of a tenant resolution attempt.
|
|
34
|
-
*
|
|
35
|
-
* Use `{ ok: true, tenantId }` when the request is valid and the tenant
|
|
36
|
-
* has been identified. Use `{ ok: false, reason }` to reject the request
|
|
37
|
-
* (the reason is passed to `onRejection` for logging but NEVER returned
|
|
38
|
-
* to the client, to avoid leaking tenant topology).
|
|
39
|
-
*/
|
|
40
|
-
export type TenantResolution =
|
|
41
|
-
| { ok: true; tenantId: string }
|
|
42
|
-
| { ok: false; reason: string };
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Resolves and validates the tenant for an incoming MCP request.
|
|
46
|
-
*
|
|
47
|
-
* Implementations typically:
|
|
48
|
-
* 1. Read a tenant hint from the request (subdomain, path, header, …)
|
|
49
|
-
* 2. Read the authoritative tenant from `ctx.authInfo.claims`
|
|
50
|
-
* 3. Validate they match
|
|
51
|
-
* 4. Return the tenant identifier, or a rejection reason
|
|
52
|
-
*
|
|
53
|
-
* @example Subdomain + JWT claim matching
|
|
54
|
-
* ```typescript
|
|
55
|
-
* class SubdomainTenantResolver implements TenantResolver {
|
|
56
|
-
* async resolve(ctx: MiddlewareContext): Promise<TenantResolution> {
|
|
57
|
-
* const host = ctx.request!.headers.get("host") ?? "";
|
|
58
|
-
* const subdomain = host.split(".")[0];
|
|
59
|
-
*
|
|
60
|
-
* const authInfo = ctx.authInfo as AuthInfo;
|
|
61
|
-
* const claim = authInfo.claims?.["urn:my-app:tenant_id"];
|
|
62
|
-
*
|
|
63
|
-
* if (typeof claim !== "string") {
|
|
64
|
-
* return { ok: false, reason: "tenant_id claim missing or not a string" };
|
|
65
|
-
* }
|
|
66
|
-
* if (claim !== subdomain) {
|
|
67
|
-
* return { ok: false, reason: `subdomain=${subdomain} claim=${claim}` };
|
|
68
|
-
* }
|
|
69
|
-
* return { ok: true, tenantId: subdomain };
|
|
70
|
-
* }
|
|
71
|
-
* }
|
|
72
|
-
* ```
|
|
73
|
-
*/
|
|
74
|
-
export interface TenantResolver {
|
|
75
|
-
/**
|
|
76
|
-
* Resolve the tenant for this request.
|
|
77
|
-
*
|
|
78
|
-
* @param ctx - Middleware context with `ctx.request` and `ctx.authInfo` populated
|
|
79
|
-
* @returns A successful resolution with the tenant id, or a rejection with a reason
|
|
80
|
-
* @throws May throw — throwing is treated identically to returning `{ ok: false }`
|
|
81
|
-
*/
|
|
82
|
-
resolve(ctx: MiddlewareContext): Promise<TenantResolution>;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Options for {@link createMultiTenantMiddleware}.
|
|
87
|
-
*/
|
|
88
|
-
export interface MultiTenantMiddlewareOptions {
|
|
89
|
-
/**
|
|
90
|
-
* Called whenever a request is rejected — either because the resolver
|
|
91
|
-
* returned `{ ok: false }`, threw an exception, or returned an empty
|
|
92
|
-
* `tenantId`.
|
|
93
|
-
*
|
|
94
|
-
* Typical use: write an audit log entry for compliance / forensics.
|
|
95
|
-
* The `reason` string may contain sensitive details (tenant ids, claim
|
|
96
|
-
* values) — log it server-side but never expose it to clients.
|
|
97
|
-
*
|
|
98
|
-
* Awaited before the client receives the 401 response, so audit writes
|
|
99
|
-
* are guaranteed to land before the error is observable. Keep it fast —
|
|
100
|
-
* slow callbacks delay the rejection.
|
|
101
|
-
*
|
|
102
|
-
* If this hook itself throws, the exception is **caught and logged to
|
|
103
|
-
* stderr** but NOT rethrown — the client still receives the standard
|
|
104
|
-
* generic `invalid_token` AuthError. A crashing audit hook must never
|
|
105
|
-
* change client-visible behaviour, otherwise a buggy audit path becomes
|
|
106
|
-
* an observable oracle for attackers probing tenant topology.
|
|
107
|
-
*/
|
|
108
|
-
onRejection?: (
|
|
109
|
-
ctx: MiddlewareContext,
|
|
110
|
-
reason: string,
|
|
111
|
-
) => void | Promise<void>;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Create a tenant resolution middleware.
|
|
116
|
-
*
|
|
117
|
-
* Pipeline behaviour:
|
|
118
|
-
*
|
|
119
|
-
* - **STDIO transport** (no `ctx.request`) → pass through unchanged. STDIO
|
|
120
|
-
* is a local trusted transport with no meaningful notion of tenant.
|
|
121
|
-
*
|
|
122
|
-
* - **HTTP without `ctx.authInfo`** → throws a configuration error. This
|
|
123
|
-
* indicates the auth middleware is missing from the pipeline. Fail fast
|
|
124
|
-
* rather than silently skipping tenant enforcement.
|
|
125
|
-
*
|
|
126
|
-
* - **HTTP with `ctx.authInfo`** → calls `resolver.resolve(ctx)`:
|
|
127
|
-
* - On success with a non-empty `tenantId`: copies `authInfo`, injects
|
|
128
|
-
* `tenantId`, re-freezes, continues.
|
|
129
|
-
* - On rejection (`ok: false`, thrown, or empty `tenantId`): calls
|
|
130
|
-
* `onRejection`, then throws {@link AuthError}`("invalid_token")` —
|
|
131
|
-
* the client sees a generic 401 with no tenant details leaked.
|
|
132
|
-
*
|
|
133
|
-
* @param resolver - Implementation that maps requests to tenant ids
|
|
134
|
-
* @param options - Optional hooks (notably `onRejection` for audit logging)
|
|
135
|
-
*/
|
|
136
|
-
export function createMultiTenantMiddleware(
|
|
137
|
-
resolver: TenantResolver,
|
|
138
|
-
options: MultiTenantMiddlewareOptions = {},
|
|
139
|
-
): Middleware {
|
|
140
|
-
return async (ctx, next) => {
|
|
141
|
-
// STDIO transport: no request, tenant routing does not apply
|
|
142
|
-
if (!ctx.request) {
|
|
143
|
-
return next();
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// Auth middleware MUST have populated authInfo before we run.
|
|
147
|
-
// MiddlewareContext is indexed as `[key: string]: unknown` for extensibility,
|
|
148
|
-
// so every auth-aware middleware in this lib casts to the concrete type —
|
|
149
|
-
// matches the convention in middleware.ts and scope-middleware.ts.
|
|
150
|
-
const authInfo = ctx.authInfo as AuthInfo | undefined;
|
|
151
|
-
if (!authInfo) {
|
|
152
|
-
throw new Error(
|
|
153
|
-
"[MultiTenantMiddleware] ctx.authInfo is not set. Ensure auth " +
|
|
154
|
-
"middleware is placed BEFORE multi-tenant middleware in the pipeline.",
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// Resolve the tenant — any failure path collapses to a generic 401
|
|
159
|
-
let resolution: TenantResolution;
|
|
160
|
-
try {
|
|
161
|
-
resolution = await resolver.resolve(ctx);
|
|
162
|
-
} catch (err) {
|
|
163
|
-
const reason = err instanceof Error ? err.message : String(err);
|
|
164
|
-
throw await rejectWithAudit(ctx, reason, options.onRejection);
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
if (!resolution.ok) {
|
|
168
|
-
throw await rejectWithAudit(ctx, resolution.reason, options.onRejection);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// Defense-in-depth: reject empty string tenantId even when the resolver
|
|
172
|
-
// reports success. Some consumers use truthy guards (`if (tenantId)`),
|
|
173
|
-
// and an empty string would slip past them without being noticed.
|
|
174
|
-
if (!resolution.tenantId) {
|
|
175
|
-
throw await rejectWithAudit(
|
|
176
|
-
ctx,
|
|
177
|
-
"resolver returned empty tenantId",
|
|
178
|
-
options.onRejection,
|
|
179
|
-
);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// Re-freeze authInfo with tenantId injected. Two reasons for the re-freeze:
|
|
183
|
-
// 1. Preserves the immutability guarantee downstream middleware and
|
|
184
|
-
// tool handlers rely on — they must never observe a mutable tenantId.
|
|
185
|
-
// 2. The original authInfo is already frozen by the auth middleware,
|
|
186
|
-
// so in-place mutation is impossible anyway. We must spread-copy.
|
|
187
|
-
ctx.authInfo = Object.freeze({
|
|
188
|
-
...authInfo,
|
|
189
|
-
tenantId: resolution.tenantId,
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
return next();
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/**
|
|
197
|
-
* Run the audit hook (if any) and return a generic `invalid_token` AuthError.
|
|
198
|
-
*
|
|
199
|
-
* The hook is intentionally shielded with try/catch: a crashing audit hook
|
|
200
|
-
* must NEVER change the client-visible response. If the hook throws, the
|
|
201
|
-
* audit is lost (logged to stderr as a last resort) but the client still
|
|
202
|
-
* receives the standard 401 AuthError — preserving the non-leak guarantee.
|
|
203
|
-
*
|
|
204
|
-
* @internal
|
|
205
|
-
*/
|
|
206
|
-
async function rejectWithAudit(
|
|
207
|
-
ctx: MiddlewareContext,
|
|
208
|
-
reason: string,
|
|
209
|
-
onRejection: MultiTenantMiddlewareOptions["onRejection"],
|
|
210
|
-
): Promise<AuthError> {
|
|
211
|
-
if (onRejection) {
|
|
212
|
-
try {
|
|
213
|
-
await onRejection(ctx, reason);
|
|
214
|
-
} catch (hookErr) {
|
|
215
|
-
// Last-resort logging: stderr is the only safe channel here — we must
|
|
216
|
-
// not rethrow (would defeat the non-leak guarantee) and we must not
|
|
217
|
-
// silently drop (would leave no trace of an audit failure).
|
|
218
|
-
console.error(
|
|
219
|
-
"[MultiTenantMiddleware] onRejection hook threw; audit entry lost:",
|
|
220
|
-
hookErr,
|
|
221
|
-
);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
return buildAuthError(ctx);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Build a generic `invalid_token` AuthError using the resource metadata URL
|
|
229
|
-
* already set by the upstream auth middleware. If the URL is missing (should
|
|
230
|
-
* not happen in a well-formed pipeline), fall back to an empty string — the
|
|
231
|
-
* AuthError still produces a valid 401 response.
|
|
232
|
-
*/
|
|
233
|
-
function buildAuthError(ctx: MiddlewareContext): AuthError {
|
|
234
|
-
const metadataUrl = (ctx.resourceMetadataUrl as string | undefined) ?? "";
|
|
235
|
-
return new AuthError("invalid_token", metadataUrl);
|
|
236
|
-
}
|