@casys/mcp-server 0.27.0 → 0.27.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.
Files changed (253) hide show
  1. package/CHANGELOG.md +18 -1764
  2. package/README.md +21 -631
  3. package/esm/mod.d.ts +1 -102
  4. package/esm/mod.js +1 -103
  5. package/package.json +17 -25
  6. package/esm/_dnt.polyfills.d.ts +0 -12
  7. package/esm/_dnt.polyfills.d.ts.map +0 -1
  8. package/esm/_dnt.polyfills.js +0 -15
  9. package/esm/_dnt.shims.d.ts +0 -2
  10. package/esm/_dnt.shims.d.ts.map +0 -1
  11. package/esm/_dnt.shims.js +0 -57
  12. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +0 -33
  13. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +0 -1
  14. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +0 -48
  15. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +0 -106
  16. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +0 -1
  17. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +0 -636
  18. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +0 -67
  19. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +0 -1
  20. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +0 -1393
  21. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +0 -44
  22. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +0 -1
  23. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +0 -117
  24. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +0 -3
  25. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +0 -1
  26. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +0 -103
  27. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +0 -3
  28. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +0 -1
  29. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +0 -32
  30. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +0 -3
  31. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +0 -1
  32. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +0 -96
  33. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +0 -3
  34. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +0 -1
  35. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +0 -159
  36. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +0 -3
  37. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +0 -1
  38. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +0 -14
  39. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +0 -3
  40. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +0 -1
  41. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +0 -10
  42. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +0 -3
  43. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +0 -1
  44. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +0 -22
  45. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +0 -3
  46. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +0 -1
  47. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +0 -29
  48. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +0 -3
  49. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +0 -1
  50. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +0 -19
  51. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +0 -3
  52. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +0 -1
  53. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +0 -30
  54. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +0 -3
  55. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +0 -1
  56. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +0 -10
  57. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +0 -3
  58. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +0 -1
  59. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +0 -14
  60. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +0 -3
  61. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +0 -1
  62. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +0 -9
  63. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +0 -3
  64. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +0 -1
  65. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +0 -81
  66. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +0 -3
  67. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +0 -1
  68. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +0 -20
  69. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +0 -32
  70. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +0 -1
  71. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +0 -6
  72. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +0 -4
  73. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +0 -1
  74. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +0 -13
  75. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +0 -51
  76. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +0 -1
  77. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +0 -53
  78. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +0 -79
  79. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +0 -1
  80. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +0 -91
  81. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +0 -100
  82. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +0 -1
  83. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +0 -33
  84. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +0 -111
  85. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +0 -1
  86. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +0 -104
  87. package/esm/mod.d.ts.map +0 -1
  88. package/esm/package.json +0 -3
  89. package/esm/src/auth/as-metadata-proxy.d.ts +0 -112
  90. package/esm/src/auth/as-metadata-proxy.d.ts.map +0 -1
  91. package/esm/src/auth/as-metadata-proxy.js +0 -171
  92. package/esm/src/auth/config.d.ts +0 -117
  93. package/esm/src/auth/config.d.ts.map +0 -1
  94. package/esm/src/auth/config.js +0 -219
  95. package/esm/src/auth/jwt-provider.d.ts +0 -157
  96. package/esm/src/auth/jwt-provider.d.ts.map +0 -1
  97. package/esm/src/auth/jwt-provider.js +0 -187
  98. package/esm/src/auth/middleware.d.ts +0 -61
  99. package/esm/src/auth/middleware.d.ts.map +0 -1
  100. package/esm/src/auth/middleware.js +0 -209
  101. package/esm/src/auth/mod.d.ts +0 -23
  102. package/esm/src/auth/mod.d.ts.map +0 -1
  103. package/esm/src/auth/mod.js +0 -27
  104. package/esm/src/auth/multi-tenant-middleware.d.ts +0 -131
  105. package/esm/src/auth/multi-tenant-middleware.d.ts.map +0 -1
  106. package/esm/src/auth/multi-tenant-middleware.js +0 -128
  107. package/esm/src/auth/presets.d.ts +0 -231
  108. package/esm/src/auth/presets.d.ts.map +0 -1
  109. package/esm/src/auth/presets.js +0 -223
  110. package/esm/src/auth/provider.d.ts +0 -47
  111. package/esm/src/auth/provider.d.ts.map +0 -1
  112. package/esm/src/auth/provider.js +0 -34
  113. package/esm/src/auth/scope-middleware.d.ts +0 -30
  114. package/esm/src/auth/scope-middleware.d.ts.map +0 -1
  115. package/esm/src/auth/scope-middleware.js +0 -48
  116. package/esm/src/auth/static-token-provider.d.ts +0 -155
  117. package/esm/src/auth/static-token-provider.d.ts.map +0 -1
  118. package/esm/src/auth/static-token-provider.js +0 -256
  119. package/esm/src/auth/types.d.ts +0 -151
  120. package/esm/src/auth/types.d.ts.map +0 -1
  121. package/esm/src/auth/types.js +0 -64
  122. package/esm/src/client-auth/callback-server.d.ts +0 -34
  123. package/esm/src/client-auth/callback-server.d.ts.map +0 -1
  124. package/esm/src/client-auth/callback-server.js +0 -141
  125. package/esm/src/client-auth/client-id-metadata.d.ts +0 -29
  126. package/esm/src/client-auth/client-id-metadata.d.ts.map +0 -1
  127. package/esm/src/client-auth/client-id-metadata.js +0 -149
  128. package/esm/src/client-auth/connect.d.ts +0 -32
  129. package/esm/src/client-auth/connect.d.ts.map +0 -1
  130. package/esm/src/client-auth/connect.js +0 -47
  131. package/esm/src/client-auth/mod.d.ts +0 -19
  132. package/esm/src/client-auth/mod.d.ts.map +0 -1
  133. package/esm/src/client-auth/mod.js +0 -19
  134. package/esm/src/client-auth/provider.d.ts +0 -78
  135. package/esm/src/client-auth/provider.d.ts.map +0 -1
  136. package/esm/src/client-auth/provider.js +0 -246
  137. package/esm/src/client-auth/token-store/file-store.d.ts +0 -20
  138. package/esm/src/client-auth/token-store/file-store.d.ts.map +0 -1
  139. package/esm/src/client-auth/token-store/file-store.js +0 -62
  140. package/esm/src/client-auth/token-store/memory-store.d.ts +0 -14
  141. package/esm/src/client-auth/token-store/memory-store.d.ts.map +0 -1
  142. package/esm/src/client-auth/token-store/memory-store.js +0 -25
  143. package/esm/src/client-auth/types.d.ts +0 -89
  144. package/esm/src/client-auth/types.d.ts.map +0 -1
  145. package/esm/src/client-auth/types.js +0 -10
  146. package/esm/src/concurrency/rate-limiter.d.ts +0 -87
  147. package/esm/src/concurrency/rate-limiter.d.ts.map +0 -1
  148. package/esm/src/concurrency/rate-limiter.js +0 -165
  149. package/esm/src/concurrency/request-queue.d.ts +0 -71
  150. package/esm/src/concurrency/request-queue.d.ts.map +0 -1
  151. package/esm/src/concurrency/request-queue.js +0 -128
  152. package/esm/src/http/body.d.ts +0 -20
  153. package/esm/src/http/body.d.ts.map +0 -1
  154. package/esm/src/http/body.js +0 -63
  155. package/esm/src/http/request-guards.d.ts +0 -54
  156. package/esm/src/http/request-guards.d.ts.map +0 -1
  157. package/esm/src/http/request-guards.js +0 -114
  158. package/esm/src/http/wire.d.ts +0 -26
  159. package/esm/src/http/wire.d.ts.map +0 -1
  160. package/esm/src/http/wire.js +0 -35
  161. package/esm/src/inspector/launcher.d.ts +0 -48
  162. package/esm/src/inspector/launcher.d.ts.map +0 -1
  163. package/esm/src/inspector/launcher.js +0 -100
  164. package/esm/src/mcp-app.d.ts +0 -728
  165. package/esm/src/mcp-app.d.ts.map +0 -1
  166. package/esm/src/mcp-app.js +0 -3530
  167. package/esm/src/middleware/backpressure.d.ts +0 -24
  168. package/esm/src/middleware/backpressure.d.ts.map +0 -1
  169. package/esm/src/middleware/backpressure.js +0 -31
  170. package/esm/src/middleware/mod.d.ts +0 -11
  171. package/esm/src/middleware/mod.d.ts.map +0 -1
  172. package/esm/src/middleware/mod.js +0 -11
  173. package/esm/src/middleware/rate-limit.d.ts +0 -22
  174. package/esm/src/middleware/rate-limit.d.ts.map +0 -1
  175. package/esm/src/middleware/rate-limit.js +0 -33
  176. package/esm/src/middleware/runner.d.ts +0 -32
  177. package/esm/src/middleware/runner.d.ts.map +0 -1
  178. package/esm/src/middleware/runner.js +0 -49
  179. package/esm/src/middleware/types.d.ts +0 -76
  180. package/esm/src/middleware/types.d.ts.map +0 -1
  181. package/esm/src/middleware/types.js +0 -9
  182. package/esm/src/middleware/validation.d.ts +0 -24
  183. package/esm/src/middleware/validation.d.ts.map +0 -1
  184. package/esm/src/middleware/validation.js +0 -30
  185. package/esm/src/mrtr/capability-check.d.ts +0 -75
  186. package/esm/src/mrtr/capability-check.d.ts.map +0 -1
  187. package/esm/src/mrtr/capability-check.js +0 -233
  188. package/esm/src/mrtr/mod.d.ts +0 -18
  189. package/esm/src/mrtr/mod.d.ts.map +0 -1
  190. package/esm/src/mrtr/mod.js +0 -12
  191. package/esm/src/mrtr/replay-store.d.ts +0 -50
  192. package/esm/src/mrtr/replay-store.d.ts.map +0 -1
  193. package/esm/src/mrtr/replay-store.js +0 -61
  194. package/esm/src/mrtr/request-state.d.ts +0 -181
  195. package/esm/src/mrtr/request-state.d.ts.map +0 -1
  196. package/esm/src/mrtr/request-state.js +0 -313
  197. package/esm/src/mrtr/retry-guard.d.ts +0 -61
  198. package/esm/src/mrtr/retry-guard.d.ts.map +0 -1
  199. package/esm/src/mrtr/retry-guard.js +0 -53
  200. package/esm/src/mrtr/types.d.ts +0 -99
  201. package/esm/src/mrtr/types.d.ts.map +0 -1
  202. package/esm/src/mrtr/types.js +0 -14
  203. package/esm/src/observability/metrics.d.ts +0 -104
  204. package/esm/src/observability/metrics.d.ts.map +0 -1
  205. package/esm/src/observability/metrics.js +0 -207
  206. package/esm/src/observability/mod.d.ts +0 -12
  207. package/esm/src/observability/mod.d.ts.map +0 -1
  208. package/esm/src/observability/mod.js +0 -11
  209. package/esm/src/observability/otel.d.ts +0 -73
  210. package/esm/src/observability/otel.d.ts.map +0 -1
  211. package/esm/src/observability/otel.js +0 -260
  212. package/esm/src/runtime/runtime.d.ts +0 -10
  213. package/esm/src/runtime/runtime.d.ts.map +0 -1
  214. package/esm/src/runtime/runtime.deno.d.ts +0 -50
  215. package/esm/src/runtime/runtime.deno.d.ts.map +0 -1
  216. package/esm/src/runtime/runtime.deno.js +0 -120
  217. package/esm/src/runtime/runtime.js +0 -41
  218. package/esm/src/runtime/runtime.node.d.ts +0 -51
  219. package/esm/src/runtime/runtime.node.d.ts.map +0 -1
  220. package/esm/src/runtime/runtime.node.js +0 -268
  221. package/esm/src/runtime/types.d.ts +0 -107
  222. package/esm/src/runtime/types.d.ts.map +0 -1
  223. package/esm/src/runtime/types.js +0 -12
  224. package/esm/src/security/channel-hmac.d.ts +0 -43
  225. package/esm/src/security/channel-hmac.d.ts.map +0 -1
  226. package/esm/src/security/channel-hmac.js +0 -135
  227. package/esm/src/security/csp.d.ts +0 -50
  228. package/esm/src/security/csp.d.ts.map +0 -1
  229. package/esm/src/security/csp.js +0 -63
  230. package/esm/src/security/message-signer.d.ts +0 -88
  231. package/esm/src/security/message-signer.d.ts.map +0 -1
  232. package/esm/src/security/message-signer.js +0 -166
  233. package/esm/src/subscriptions/subscription-registry.d.ts +0 -256
  234. package/esm/src/subscriptions/subscription-registry.d.ts.map +0 -1
  235. package/esm/src/subscriptions/subscription-registry.js +0 -406
  236. package/esm/src/tasks/mod.d.ts +0 -13
  237. package/esm/src/tasks/mod.d.ts.map +0 -1
  238. package/esm/src/tasks/mod.js +0 -11
  239. package/esm/src/tasks/task-store.d.ts +0 -342
  240. package/esm/src/tasks/task-store.d.ts.map +0 -1
  241. package/esm/src/tasks/task-store.js +0 -649
  242. package/esm/src/transport/request-headers.d.ts +0 -145
  243. package/esm/src/transport/request-headers.d.ts.map +0 -1
  244. package/esm/src/transport/request-headers.js +0 -525
  245. package/esm/src/types.d.ts +0 -776
  246. package/esm/src/types.d.ts.map +0 -1
  247. package/esm/src/types.js +0 -92
  248. package/esm/src/ui/viewer-utils.d.ts +0 -45
  249. package/esm/src/ui/viewer-utils.d.ts.map +0 -1
  250. package/esm/src/ui/viewer-utils.js +0 -97
  251. package/esm/src/validation/schema-validator.d.ts +0 -115
  252. package/esm/src/validation/schema-validator.d.ts.map +0 -1
  253. package/esm/src/validation/schema-validator.js +0 -249
@@ -1,187 +0,0 @@
1
- /**
2
- * JWT Auth Provider using JWKS for token validation.
3
- *
4
- * Validates JWT tokens against a remote JWKS endpoint,
5
- * checking issuer, audience, and expiration.
6
- *
7
- * @module lib/server/auth/jwt-provider
8
- */
9
- import { createRemoteJWKSet, jwtVerify } from "jose";
10
- import { AuthProvider } from "./provider.js";
11
- import { httpsUrl, } from "./types.js";
12
- import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
13
- /**
14
- * JWT Auth Provider with JWKS validation.
15
- *
16
- * @example URL resource (auto-derives metadata URL)
17
- * ```typescript
18
- * import { httpsUrl, JwtAuthProvider } from "@casys/mcp-server";
19
- *
20
- * const provider = new JwtAuthProvider({
21
- * kind: "url",
22
- * issuer: "https://accounts.google.com",
23
- * audience: "https://my-mcp.example.com",
24
- * resource: httpsUrl("https://my-mcp.example.com"),
25
- * authorizationServers: [httpsUrl("https://accounts.google.com")],
26
- * });
27
- * ```
28
- *
29
- * @example Opaque resource (explicit metadata URL required)
30
- * ```typescript
31
- * import { httpsUrl, JwtAuthProvider } from "@casys/mcp-server";
32
- *
33
- * // RFC 9728 § 2 Option B: OIDC project ID as JWT audience
34
- * const provider = new JwtAuthProvider({
35
- * kind: "opaque",
36
- * issuer: "https://my-tenant.zitadel.cloud",
37
- * audience: "367545125829670172",
38
- * resource: "367545125829670172",
39
- * resourceMetadataUrl: httpsUrl(
40
- * "https://my-mcp.example.com/.well-known/oauth-protected-resource",
41
- * ),
42
- * authorizationServers: [httpsUrl("https://my-tenant.zitadel.cloud")],
43
- * });
44
- * ```
45
- */
46
- export class JwtAuthProvider extends AuthProvider {
47
- jwks;
48
- options;
49
- resourceMetadataUrl;
50
- // Token verification cache: hash(token) → AuthInfo with TTL
51
- // Prevents redundant JWKS fetches (network round-trip per tool call)
52
- tokenCache = new Map();
53
- static MAX_CACHE_SIZE = 1000;
54
- static DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
55
- constructor(options) {
56
- super();
57
- if (!options.issuer) {
58
- throw new Error("[JwtAuthProvider] issuer is required");
59
- }
60
- if (!options.audience) {
61
- throw new Error("[JwtAuthProvider] audience is required");
62
- }
63
- if (!options.resource) {
64
- throw new Error("[JwtAuthProvider] resource is required");
65
- }
66
- if (!options.authorizationServers?.length) {
67
- throw new Error("[JwtAuthProvider] at least one authorizationServer is required");
68
- }
69
- // 0.17.0: narrow on the `kind` discriminant tag. TypeScript structurally
70
- // narrows the DU here — after `if (options.kind === "opaque")`, `options`
71
- // is `JwtAuthProviderOptionsOpaqueResource` and `resourceMetadataUrl` is
72
- // guaranteed non-undefined; after `else`, `options` is
73
- // `JwtAuthProviderOptionsUrlResource` and `options.resource` is
74
- // `HttpsUrl` (no widening, no runtime guess). This fixes finding C1 from
75
- // the 0.16.0 review — the previous narrowing on `resourceMetadataUrl !==
76
- // undefined` was unsound because `HttpsUrl extends string` collapsed the
77
- // union back to `string`. Tagging makes the branches strictly disjoint.
78
- //
79
- // URL branch derivation follows RFC 9728 § 3.1: when `resource` has a
80
- // path or query component, the well-known suffix is INSERTED between
81
- // the host and the path, not appended after it:
82
- //
83
- // resource = https://api.example.com/v1/mcp
84
- // metadata = https://api.example.com/.well-known/oauth-protected-resource/v1/mcp
85
- //
86
- // Fragments (`#...`) are intentionally dropped — they're client-side-only
87
- // per RFC 3986 § 3.5 and never part of a server-side metadata endpoint.
88
- if (options.kind === "opaque") {
89
- this.resourceMetadataUrl = options.resourceMetadataUrl;
90
- }
91
- else if (options.resourceMetadataUrl !== undefined) {
92
- this.resourceMetadataUrl = options.resourceMetadataUrl;
93
- }
94
- else {
95
- const parsed = new URL(options.resource);
96
- const pathPart = parsed.pathname === "/" ? "" : parsed.pathname;
97
- this.resourceMetadataUrl = httpsUrl(`${parsed.origin}/.well-known/oauth-protected-resource${pathPart}${parsed.search}`);
98
- }
99
- this.options = options;
100
- const jwksUri = options.jwksUri ??
101
- `${options.issuer}/.well-known/jwks.json`;
102
- this.jwks = createRemoteJWKSet(new URL(jwksUri));
103
- }
104
- async verifyToken(token) {
105
- // Check cache first (avoids JWKS network round-trip)
106
- const cacheKey = await this.hashToken(token);
107
- const cached = this.tokenCache.get(cacheKey);
108
- if (cached && Date.now() < cached.expiresAt) {
109
- if (isOtelEnabled()) {
110
- recordAuthEvent("cache_hit", {
111
- subject: cached.authInfo.subject ?? "",
112
- });
113
- }
114
- return cached.authInfo;
115
- }
116
- // Evict expired entry if present
117
- if (cached)
118
- this.tokenCache.delete(cacheKey);
119
- try {
120
- const { payload } = await jwtVerify(token, this.jwks, {
121
- issuer: this.options.issuer,
122
- audience: this.options.audience,
123
- });
124
- const authInfo = {
125
- subject: payload.sub ?? "unknown",
126
- clientId: payload.azp ??
127
- payload.client_id,
128
- scopes: this.extractScopes(payload),
129
- claims: payload,
130
- expiresAt: payload.exp,
131
- };
132
- // Cache with TTL = min(token remaining lifetime, 5 minutes)
133
- const tokenExpiresMs = payload.exp ? payload.exp * 1000 : Infinity;
134
- const cacheTtl = Math.min(tokenExpiresMs - Date.now(), JwtAuthProvider.DEFAULT_CACHE_TTL_MS);
135
- if (cacheTtl > 0) {
136
- // Evict oldest entries if cache is full
137
- if (this.tokenCache.size >= JwtAuthProvider.MAX_CACHE_SIZE) {
138
- const oldestKey = this.tokenCache.keys().next().value;
139
- if (oldestKey)
140
- this.tokenCache.delete(oldestKey);
141
- }
142
- this.tokenCache.set(cacheKey, {
143
- authInfo: Object.freeze(authInfo),
144
- expiresAt: Date.now() + cacheTtl,
145
- });
146
- }
147
- return authInfo;
148
- }
149
- catch (err) {
150
- // Log the actual rejection reason so JWKS fetch failures, audience
151
- // mismatches, and expiration errors are distinguishable in logs.
152
- const msg = err instanceof Error ? err.message : String(err);
153
- console.error(`[JwtAuthProvider] Token rejected: ${msg}`);
154
- return null;
155
- }
156
- }
157
- /**
158
- * Hash a token for cache key (avoids storing raw tokens in memory)
159
- */
160
- async hashToken(token) {
161
- const data = new TextEncoder().encode(token);
162
- const hash = await crypto.subtle.digest("SHA-256", data);
163
- return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
164
- }
165
- getResourceMetadata() {
166
- return {
167
- resource: this.options.resource,
168
- resource_metadata_url: this.resourceMetadataUrl,
169
- authorization_servers: this.options.authorizationServers,
170
- scopes_supported: this.options.scopesSupported,
171
- bearer_methods_supported: ["header"],
172
- };
173
- }
174
- /**
175
- * Extract scopes from JWT payload.
176
- * Supports: "scope" claim (space-separated string) and "scp" claim (array).
177
- */
178
- extractScopes(payload) {
179
- if (typeof payload.scope === "string") {
180
- return payload.scope.split(" ").filter(Boolean);
181
- }
182
- if (Array.isArray(payload.scp)) {
183
- return payload.scp.filter((s) => typeof s === "string");
184
- }
185
- return [];
186
- }
187
- }
@@ -1,61 +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
- import type { AuthProvider } from "./provider.js";
10
- import type { AuthInfo } from "./types.js";
11
- import type { Middleware } from "../middleware/types.js";
12
- /** 401 Unauthorized: no token, or an invalid one. */
13
- export declare const JSONRPC_UNAUTHORIZED = -31401;
14
- /** 403 Forbidden: authenticated, but missing a required scope. */
15
- export declare const JSONRPC_FORBIDDEN = -31403;
16
- /**
17
- * Authentication error with structured information
18
- * for generating proper HTTP error responses.
19
- */
20
- export declare class AuthError extends Error {
21
- readonly code: "missing_token" | "invalid_token" | "insufficient_scope";
22
- readonly resourceMetadataUrl: string;
23
- readonly requiredScopes?: string[] | undefined;
24
- constructor(code: "missing_token" | "invalid_token" | "insufficient_scope", resourceMetadataUrl: string, requiredScopes?: string[] | undefined);
25
- }
26
- /**
27
- * Extract Bearer token from Authorization header.
28
- *
29
- * @param request - HTTP Request
30
- * @returns Token string or null if not present/invalid format
31
- */
32
- export declare function extractBearerToken(request: Request): string | null;
33
- /**
34
- * Create a 401 Unauthorized response with WWW-Authenticate header.
35
- *
36
- * @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
37
- * @param error - OAuth error code
38
- * @param errorDescription - Human-readable error description
39
- */
40
- export declare function createUnauthorizedResponse(resourceMetadataUrl: string, error?: string, errorDescription?: string): Response;
41
- /**
42
- * Create a 403 Forbidden response for insufficient scopes.
43
- *
44
- * @param requiredScopes - Scopes that were required but missing
45
- * @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
46
- */
47
- export declare function createForbiddenResponse(requiredScopes: string[], resourceMetadataUrl: string): Response;
48
- export declare function freezeAuthInfo(authInfo: AuthInfo): AuthInfo;
49
- /**
50
- * Create an authentication middleware for the MCP pipeline.
51
- *
52
- * Extracts the Bearer token from the HTTP request, validates it
53
- * via the AuthProvider, and injects `authInfo` into the context.
54
- *
55
- * For STDIO transport (no `ctx.request`), the middleware is skipped
56
- * since STDIO is a local transport with no auth needed.
57
- *
58
- * @param provider - AuthProvider implementation
59
- */
60
- export declare function createAuthMiddleware(provider: AuthProvider): Middleware;
61
- //# sourceMappingURL=middleware.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/src/auth/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAuBzD,qDAAqD;AACrD,eAAO,MAAM,oBAAoB,SAAS,CAAC;AAE3C,kEAAkE;AAClE,eAAO,MAAM,iBAAiB,SAAS,CAAC;AAMxC;;;GAGG;AACH,qBAAa,SAAU,SAAQ,KAAK;aAEhB,IAAI,EAChB,eAAe,GACf,eAAe,GACf,oBAAoB;aACR,mBAAmB,EAAE,MAAM;aAC3B,cAAc,CAAC,EAAE,MAAM,EAAE;gBALzB,IAAI,EAChB,eAAe,GACf,eAAe,GACf,oBAAoB,EACR,mBAAmB,EAAE,MAAM,EAC3B,cAAc,CAAC,EAAE,MAAM,EAAE,YAAA;CAW5C;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAKlE;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,mBAAmB,EAAE,MAAM,EAC3B,KAAK,CAAC,EAAE,MAAM,EACd,gBAAgB,CAAC,EAAE,MAAM,GACxB,QAAQ,CA8BV;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,cAAc,EAAE,MAAM,EAAE,EACxB,mBAAmB,EAAE,MAAM,GAC1B,QAAQ,CA2BV;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAgB3D;AAUD;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,YAAY,GAAG,UAAU,CAyDvE"}
@@ -1,209 +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
- import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
10
- // ── Auth error codes ────────────────────────────────────────────────────────
11
- //
12
- // Both codes moved OUT of the JSON-RPC reserved range (`-32768`..`-32000`) for
13
- // spec 2026-07-28, which is stricter than earlier readings of it suggested:
14
- //
15
- // * `-32002` — "Implementations of this protocol version **MUST NOT** emit
16
- // these codes", because 2025-11-25 and earlier used it for resource-not-found
17
- // (now `-32602`). Keeping it for 403 was a conformance violation, not a
18
- // grandfathered liberty. Two prior reviews, including one of this file, read
19
- // the allocation policy as permitting it. It does not.
20
- // * `-32001` — inside `-32000`..`-32019`, where "new implementations
21
- // **SHOULD NOT** use codes from this sub-range at all" and receivers "**MUST
22
- // NOT** assume any specific meaning".
23
- //
24
- // The spec's own guidance for codes it does not define: "**SHOULD** be allocated
25
- // outside the JSON-RPC reserved range". Hence `-31401` / `-31403`, mnemonic for
26
- // the HTTP statuses they accompany.
27
- //
28
- // BREAKING for anything matching on the old numbers — see the changelog.
29
- /** 401 Unauthorized: no token, or an invalid one. */
30
- export const JSONRPC_UNAUTHORIZED = -31401;
31
- /** 403 Forbidden: authenticated, but missing a required scope. */
32
- export const JSONRPC_FORBIDDEN = -31403;
33
- function escapeAuthenticateParam(s) {
34
- return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
35
- }
36
- /**
37
- * Authentication error with structured information
38
- * for generating proper HTTP error responses.
39
- */
40
- export class AuthError extends Error {
41
- code;
42
- resourceMetadataUrl;
43
- requiredScopes;
44
- constructor(code, resourceMetadataUrl, requiredScopes) {
45
- super(code === "missing_token"
46
- ? "Authorization header with Bearer token required"
47
- : code === "invalid_token"
48
- ? "Invalid or expired token"
49
- : `Insufficient scope: requires ${requiredScopes?.join(", ")}`);
50
- this.code = code;
51
- this.resourceMetadataUrl = resourceMetadataUrl;
52
- this.requiredScopes = requiredScopes;
53
- this.name = "AuthError";
54
- }
55
- }
56
- /**
57
- * Extract Bearer token from Authorization header.
58
- *
59
- * @param request - HTTP Request
60
- * @returns Token string or null if not present/invalid format
61
- */
62
- export function extractBearerToken(request) {
63
- const auth = request.headers.get("Authorization");
64
- if (!auth?.startsWith("Bearer "))
65
- return null;
66
- const token = auth.slice(7).trim();
67
- return token.length > 0 ? token : null;
68
- }
69
- /**
70
- * Create a 401 Unauthorized response with WWW-Authenticate header.
71
- *
72
- * @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
73
- * @param error - OAuth error code
74
- * @param errorDescription - Human-readable error description
75
- */
76
- export function createUnauthorizedResponse(resourceMetadataUrl, error, errorDescription) {
77
- const parts = [
78
- `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
79
- ];
80
- if (error)
81
- parts.push(`error="${escapeAuthenticateParam(error)}"`);
82
- if (errorDescription) {
83
- parts.push(`error_description="${escapeAuthenticateParam(errorDescription)}"`);
84
- }
85
- return new Response(JSON.stringify({
86
- jsonrpc: "2.0",
87
- id: null,
88
- error: {
89
- code: JSONRPC_UNAUTHORIZED,
90
- message: errorDescription ?? "Unauthorized",
91
- },
92
- }), {
93
- status: 401,
94
- headers: {
95
- "Content-Type": "application/json",
96
- "WWW-Authenticate": parts.join(", "),
97
- },
98
- });
99
- }
100
- /**
101
- * Create a 403 Forbidden response for insufficient scopes.
102
- *
103
- * @param requiredScopes - Scopes that were required but missing
104
- * @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
105
- */
106
- export function createForbiddenResponse(requiredScopes, resourceMetadataUrl) {
107
- const requiredScopesDescription = requiredScopes.join(", ");
108
- const parts = [
109
- `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
110
- `error="insufficient_scope"`,
111
- `error_description="${escapeAuthenticateParam(requiredScopesDescription)}"`,
112
- ];
113
- return new Response(JSON.stringify({
114
- jsonrpc: "2.0",
115
- id: null,
116
- error: {
117
- code: JSONRPC_FORBIDDEN,
118
- message: `Forbidden: requires scopes ${requiredScopes.join(", ")}`,
119
- },
120
- }), {
121
- status: 403,
122
- headers: {
123
- "Content-Type": "application/json",
124
- "WWW-Authenticate": parts.join(", "),
125
- },
126
- });
127
- }
128
- export function freezeAuthInfo(authInfo) {
129
- const scopes = Object.freeze([...authInfo.scopes]);
130
- const frozen = {
131
- ...authInfo,
132
- scopes,
133
- ...(authInfo.claims
134
- ? {
135
- claims: deepFreezeJson(structuredClone(authInfo.claims)),
136
- }
137
- : {}),
138
- };
139
- return Object.freeze(frozen);
140
- }
141
- function deepFreezeJson(value) {
142
- if (typeof value !== "object" || value === null)
143
- return value;
144
- for (const nested of Object.values(value)) {
145
- deepFreezeJson(nested);
146
- }
147
- return Object.freeze(value);
148
- }
149
- /**
150
- * Create an authentication middleware for the MCP pipeline.
151
- *
152
- * Extracts the Bearer token from the HTTP request, validates it
153
- * via the AuthProvider, and injects `authInfo` into the context.
154
- *
155
- * For STDIO transport (no `ctx.request`), the middleware is skipped
156
- * since STDIO is a local transport with no auth needed.
157
- *
158
- * @param provider - AuthProvider implementation
159
- */
160
- export function createAuthMiddleware(provider) {
161
- return async (ctx, next) => {
162
- // STDIO transport: no request, skip auth
163
- if (!ctx.request) {
164
- return next();
165
- }
166
- // 0.15.0+: provider's getResourceMetadata() always returns a valid
167
- // absolute URL in resource_metadata_url (type system guarantees it).
168
- // No derivation needed at the middleware level anymore.
169
- const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
170
- // Already authenticated by the HTTP-level gate (verifyHttpAuth).
171
- // Skip the redundant verifyToken call to avoid JWKS race conditions
172
- // when concurrent requests arrive on a cold cache.
173
- if (ctx.authInfo) {
174
- ctx.resourceMetadataUrl = metadataUrl;
175
- return next();
176
- }
177
- const token = extractBearerToken(ctx.request);
178
- if (!token) {
179
- if (isOtelEnabled()) {
180
- recordAuthEvent("reject", {
181
- reason: "missing_token",
182
- tool: ctx.toolName ?? "",
183
- });
184
- }
185
- throw new AuthError("missing_token", metadataUrl);
186
- }
187
- const authInfo = await provider.verifyToken(token);
188
- if (!authInfo) {
189
- if (isOtelEnabled()) {
190
- recordAuthEvent("reject", {
191
- reason: "invalid_token",
192
- tool: ctx.toolName ?? "",
193
- });
194
- }
195
- throw new AuthError("invalid_token", metadataUrl);
196
- }
197
- if (isOtelEnabled()) {
198
- recordAuthEvent("verify", {
199
- subject: authInfo.subject ?? "",
200
- tool: ctx.toolName ?? "",
201
- });
202
- }
203
- // Deep-freeze authInfo to prevent mutation by downstream middlewares
204
- ctx.authInfo = freezeAuthInfo(authInfo);
205
- // Propagate resourceMetadataUrl for downstream middlewares (scope-middleware)
206
- ctx.resourceMetadataUrl = metadataUrl;
207
- return next();
208
- };
209
- }
@@ -1,23 +0,0 @@
1
- /**
2
- * Auth module for McpApp.
3
- *
4
- * @module lib/server/auth
5
- */
6
- export type { AuthInfo, AuthOptions, HttpsUrl, ProtectedResourceMetadata, } from "./types.js";
7
- export { httpsUrl, tryHttpsUrl } from "./types.js";
8
- export { AuthProvider } from "./provider.js";
9
- export { AuthError, createAuthMiddleware, createForbiddenResponse, createUnauthorizedResponse, extractBearerToken, } from "./middleware.js";
10
- export { createScopeMiddleware } from "./scope-middleware.js";
11
- export { createMultiTenantMiddleware } from "./multi-tenant-middleware.js";
12
- export type { MultiTenantMiddlewareOptions, TenantResolution, TenantResolver, } from "./multi-tenant-middleware.js";
13
- export { JwtAuthProvider } from "./jwt-provider.js";
14
- export type { JwtAuthProviderOptions, JwtAuthProviderOptionsOpaqueResource, JwtAuthProviderOptionsUrlResource, } from "./jwt-provider.js";
15
- export { buildJwtAuthProvider, createAuth0AuthProvider, createGitHubAuthProvider, createGoogleAuthProvider, createOIDCAuthProvider, } from "./presets.js";
16
- export type { BuildJwtAuthProviderOptions, OIDCPresetOptions, PresetOptions, } from "./presets.js";
17
- export { createAsMetadataHandler } from "./as-metadata-proxy.js";
18
- export type { AsMetadataProxyOptions } from "./as-metadata-proxy.js";
19
- export { createAuthProviderFromConfig, loadAuthConfig } from "./config.js";
20
- export type { Auth0AuthConfig, AuthConfig, AuthProviderName, GitHubAuthConfig, GoogleAuthConfig, OIDCAuthConfig, } from "./config.js";
21
- export { createStaticTokenAuthProvider, StaticTokenAuthProvider, } from "./static-token-provider.js";
22
- export type { StaticTokenAuthProviderOptions, StaticTokenCredential, } from "./static-token-provider.js";
23
- //# sourceMappingURL=mod.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../src/src/auth/mod.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,YAAY,EACV,QAAQ,EACR,WAAW,EACX,QAAQ,EACR,yBAAyB,GAC1B,MAAM,YAAY,CAAC;AAIpB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAGnD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAG7C,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,uBAAuB,EACvB,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,YAAY,EACV,4BAA4B,EAC5B,gBAAgB,EAChB,cAAc,GACf,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIpD,YAAY,EACV,sBAAsB,EACtB,oCAAoC,EACpC,iCAAiC,GAClC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,cAAc,CAAC;AACtB,YAAY,EACV,2BAA2B,EAC3B,iBAAiB,EACjB,aAAa,GACd,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,YAAY,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAGrE,OAAO,EAAE,4BAA4B,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAG3E,YAAY,EACV,eAAe,EACf,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,GACf,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,6BAA6B,EAC7B,uBAAuB,GACxB,MAAM,4BAA4B,CAAC;AACpC,YAAY,EACV,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,4BAA4B,CAAC"}
@@ -1,27 +0,0 @@
1
- /**
2
- * Auth module for McpApp.
3
- *
4
- * @module lib/server/auth
5
- */
6
- // HttpsUrl brand factories (0.16.0) — construct branded URL values for
7
- // `JwtAuthProviderOptions`, `ProtectedResourceMetadata`, and anywhere else
8
- // that requires a validated absolute HTTP(S) URL.
9
- export { httpsUrl, tryHttpsUrl } from "./types.js";
10
- // Provider base class
11
- export { AuthProvider } from "./provider.js";
12
- // Middleware and utilities
13
- export { AuthError, createAuthMiddleware, createForbiddenResponse, createUnauthorizedResponse, extractBearerToken, } from "./middleware.js";
14
- // Scope enforcement
15
- export { createScopeMiddleware } from "./scope-middleware.js";
16
- // Multi-tenant resolution (tenant enforcement on top of auth)
17
- export { createMultiTenantMiddleware } from "./multi-tenant-middleware.js";
18
- // JWT Provider
19
- export { JwtAuthProvider } from "./jwt-provider.js";
20
- // OIDC Presets
21
- export { buildJwtAuthProvider, createAuth0AuthProvider, createGitHubAuthProvider, createGoogleAuthProvider, createOIDCAuthProvider, } from "./presets.js";
22
- // AS Metadata Proxy (DCR discovery for IdPs without native RFC 7591)
23
- export { createAsMetadataHandler } from "./as-metadata-proxy.js";
24
- // Config loader (YAML + env)
25
- export { createAuthProviderFromConfig, loadAuthConfig } from "./config.js";
26
- // Static Token Provider (opaque pre-shared bearer tokens; no OIDC/JWT infra)
27
- export { createStaticTokenAuthProvider, StaticTokenAuthProvider, } from "./static-token-provider.js";
@@ -1,131 +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
- import type { Middleware, MiddlewareContext } from "../middleware/types.js";
28
- /**
29
- * Result of a tenant resolution attempt.
30
- *
31
- * Use `{ ok: true, tenantId }` when the request is valid and the tenant
32
- * has been identified. Use `{ ok: false, reason }` to reject the request
33
- * (the reason is passed to `onRejection` for logging but NEVER returned
34
- * to the client, to avoid leaking tenant topology).
35
- */
36
- export type TenantResolution = {
37
- ok: true;
38
- tenantId: string;
39
- } | {
40
- ok: false;
41
- reason: string;
42
- };
43
- /**
44
- * Resolves and validates the tenant for an incoming MCP request.
45
- *
46
- * Implementations typically:
47
- * 1. Read a tenant hint from the request (subdomain, path, header, …)
48
- * 2. Read the authoritative tenant from `ctx.authInfo.claims`
49
- * 3. Validate they match
50
- * 4. Return the tenant identifier, or a rejection reason
51
- *
52
- * @example Subdomain + JWT claim matching
53
- * ```typescript
54
- * class SubdomainTenantResolver implements TenantResolver {
55
- * async resolve(ctx: MiddlewareContext): Promise<TenantResolution> {
56
- * const host = ctx.request!.headers.get("host") ?? "";
57
- * const subdomain = host.split(".")[0];
58
- *
59
- * const authInfo = ctx.authInfo as AuthInfo;
60
- * const claim = authInfo.claims?.["urn:my-app:tenant_id"];
61
- *
62
- * if (typeof claim !== "string") {
63
- * return { ok: false, reason: "tenant_id claim missing or not a string" };
64
- * }
65
- * if (claim !== subdomain) {
66
- * return { ok: false, reason: `subdomain=${subdomain} claim=${claim}` };
67
- * }
68
- * return { ok: true, tenantId: subdomain };
69
- * }
70
- * }
71
- * ```
72
- */
73
- export interface TenantResolver {
74
- /**
75
- * Resolve the tenant for this request.
76
- *
77
- * @param ctx - Middleware context with `ctx.request` and `ctx.authInfo` populated
78
- * @returns A successful resolution with the tenant id, or a rejection with a reason
79
- * @throws May throw — throwing is treated identically to returning `{ ok: false }`
80
- */
81
- resolve(ctx: MiddlewareContext): Promise<TenantResolution>;
82
- }
83
- /**
84
- * Options for {@link createMultiTenantMiddleware}.
85
- */
86
- export interface MultiTenantMiddlewareOptions {
87
- /**
88
- * Called whenever a request is rejected — either because the resolver
89
- * returned `{ ok: false }`, threw an exception, or returned an empty
90
- * `tenantId`.
91
- *
92
- * Typical use: write an audit log entry for compliance / forensics.
93
- * The `reason` string may contain sensitive details (tenant ids, claim
94
- * values) — log it server-side but never expose it to clients.
95
- *
96
- * Awaited before the client receives the 401 response, so audit writes
97
- * are guaranteed to land before the error is observable. Keep it fast —
98
- * slow callbacks delay the rejection.
99
- *
100
- * If this hook itself throws, the exception is **caught and logged to
101
- * stderr** but NOT rethrown — the client still receives the standard
102
- * generic `invalid_token` AuthError. A crashing audit hook must never
103
- * change client-visible behaviour, otherwise a buggy audit path becomes
104
- * an observable oracle for attackers probing tenant topology.
105
- */
106
- onRejection?: (ctx: MiddlewareContext, reason: string) => void | Promise<void>;
107
- }
108
- /**
109
- * Create a tenant resolution middleware.
110
- *
111
- * Pipeline behaviour:
112
- *
113
- * - **STDIO transport** (no `ctx.request`) → pass through unchanged. STDIO
114
- * is a local trusted transport with no meaningful notion of tenant.
115
- *
116
- * - **HTTP without `ctx.authInfo`** → throws a configuration error. This
117
- * indicates the auth middleware is missing from the pipeline. Fail fast
118
- * rather than silently skipping tenant enforcement.
119
- *
120
- * - **HTTP with `ctx.authInfo`** → calls `resolver.resolve(ctx)`:
121
- * - On success with a non-empty `tenantId`: copies `authInfo`, injects
122
- * `tenantId`, re-freezes, continues.
123
- * - On rejection (`ok: false`, thrown, or empty `tenantId`): calls
124
- * `onRejection`, then throws {@link AuthError}`("invalid_token")` —
125
- * the client sees a generic 401 with no tenant details leaked.
126
- *
127
- * @param resolver - Implementation that maps requests to tenant ids
128
- * @param options - Optional hooks (notably `onRejection` for audit logging)
129
- */
130
- export declare function createMultiTenantMiddleware(resolver: TenantResolver, options?: MultiTenantMiddlewareOptions): Middleware;
131
- //# sourceMappingURL=multi-tenant-middleware.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"multi-tenant-middleware.d.ts","sourceRoot":"","sources":["../../../src/src/auth/multi-tenant-middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI5E;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;OAMG;IACH,OAAO,CAAC,GAAG,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAC5D;AAED;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC3C;;;;;;;;;;;;;;;;;;OAkBG;IACH,WAAW,CAAC,EAAE,CACZ,GAAG,EAAE,iBAAiB,EACtB,MAAM,EAAE,MAAM,KACX,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,cAAc,EACxB,OAAO,GAAE,4BAAiC,GACzC,UAAU,CAuDZ"}