@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.
Files changed (299) hide show
  1. package/CHANGELOG.md +1779 -0
  2. package/LICENSE +21 -0
  3. package/README.md +19 -5
  4. package/esm/_dnt.polyfills.d.ts +12 -0
  5. package/esm/_dnt.polyfills.d.ts.map +1 -0
  6. package/esm/_dnt.polyfills.js +15 -0
  7. package/esm/_dnt.shims.d.ts +2 -0
  8. package/esm/_dnt.shims.d.ts.map +1 -0
  9. package/esm/_dnt.shims.js +57 -0
  10. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +33 -0
  11. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +1 -0
  12. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +48 -0
  13. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +106 -0
  14. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +1 -0
  15. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +636 -0
  16. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +67 -0
  17. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +1 -0
  18. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +1393 -0
  19. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +44 -0
  20. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +1 -0
  21. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +117 -0
  22. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +3 -0
  23. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +1 -0
  24. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +103 -0
  25. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +3 -0
  26. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +1 -0
  27. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +32 -0
  28. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +3 -0
  29. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +1 -0
  30. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +96 -0
  31. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +3 -0
  32. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +1 -0
  33. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +159 -0
  34. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +3 -0
  35. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +1 -0
  36. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +14 -0
  37. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +3 -0
  38. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +1 -0
  39. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +10 -0
  40. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +3 -0
  41. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +1 -0
  42. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +22 -0
  43. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +3 -0
  44. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +1 -0
  45. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +29 -0
  46. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +3 -0
  47. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +1 -0
  48. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +19 -0
  49. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +3 -0
  50. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +1 -0
  51. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +30 -0
  52. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +3 -0
  53. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +1 -0
  54. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +10 -0
  55. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +3 -0
  56. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +1 -0
  57. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +14 -0
  58. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +3 -0
  59. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +1 -0
  60. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +9 -0
  61. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +3 -0
  62. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +1 -0
  63. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +81 -0
  64. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +3 -0
  65. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +1 -0
  66. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +20 -0
  67. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +32 -0
  68. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +1 -0
  69. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +6 -0
  70. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +4 -0
  71. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +1 -0
  72. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +13 -0
  73. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +51 -0
  74. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +1 -0
  75. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +53 -0
  76. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +79 -0
  77. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +1 -0
  78. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +91 -0
  79. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +100 -0
  80. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +1 -0
  81. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +33 -0
  82. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +111 -0
  83. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +1 -0
  84. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +104 -0
  85. package/esm/mod.d.ts +102 -0
  86. package/esm/mod.d.ts.map +1 -0
  87. package/esm/mod.js +103 -0
  88. package/esm/package.json +3 -0
  89. package/esm/src/auth/as-metadata-proxy.d.ts +112 -0
  90. package/esm/src/auth/as-metadata-proxy.d.ts.map +1 -0
  91. package/esm/src/auth/as-metadata-proxy.js +171 -0
  92. package/esm/src/auth/config.d.ts +117 -0
  93. package/esm/src/auth/config.d.ts.map +1 -0
  94. package/esm/src/auth/config.js +219 -0
  95. package/esm/src/auth/jwt-provider.d.ts +157 -0
  96. package/esm/src/auth/jwt-provider.d.ts.map +1 -0
  97. package/esm/src/auth/jwt-provider.js +187 -0
  98. package/esm/src/auth/middleware.d.ts +61 -0
  99. package/esm/src/auth/middleware.d.ts.map +1 -0
  100. package/esm/src/auth/middleware.js +209 -0
  101. package/esm/src/auth/mod.d.ts +23 -0
  102. package/esm/src/auth/mod.d.ts.map +1 -0
  103. package/esm/src/auth/mod.js +27 -0
  104. package/esm/src/auth/multi-tenant-middleware.d.ts +131 -0
  105. package/esm/src/auth/multi-tenant-middleware.d.ts.map +1 -0
  106. package/esm/src/auth/multi-tenant-middleware.js +128 -0
  107. package/esm/src/auth/presets.d.ts +231 -0
  108. package/esm/src/auth/presets.d.ts.map +1 -0
  109. package/esm/src/auth/presets.js +223 -0
  110. package/{src/auth/provider.ts → esm/src/auth/provider.d.ts} +13 -15
  111. package/esm/src/auth/provider.d.ts.map +1 -0
  112. package/esm/src/auth/provider.js +34 -0
  113. package/esm/src/auth/scope-middleware.d.ts +30 -0
  114. package/esm/src/auth/scope-middleware.d.ts.map +1 -0
  115. package/esm/src/auth/scope-middleware.js +48 -0
  116. package/esm/src/auth/static-token-provider.d.ts +155 -0
  117. package/esm/src/auth/static-token-provider.d.ts.map +1 -0
  118. package/esm/src/auth/static-token-provider.js +256 -0
  119. package/esm/src/auth/types.d.ts +151 -0
  120. package/esm/src/auth/types.d.ts.map +1 -0
  121. package/esm/src/auth/types.js +64 -0
  122. package/esm/src/client-auth/callback-server.d.ts +34 -0
  123. package/esm/src/client-auth/callback-server.d.ts.map +1 -0
  124. package/esm/src/client-auth/callback-server.js +141 -0
  125. package/esm/src/client-auth/client-id-metadata.d.ts +29 -0
  126. package/esm/src/client-auth/client-id-metadata.d.ts.map +1 -0
  127. package/esm/src/client-auth/client-id-metadata.js +149 -0
  128. package/esm/src/client-auth/connect.d.ts +32 -0
  129. package/esm/src/client-auth/connect.d.ts.map +1 -0
  130. package/esm/src/client-auth/connect.js +47 -0
  131. package/esm/src/client-auth/mod.d.ts +19 -0
  132. package/esm/src/client-auth/mod.d.ts.map +1 -0
  133. package/{src/client-auth/mod.ts → esm/src/client-auth/mod.js} +1 -26
  134. package/esm/src/client-auth/provider.d.ts +78 -0
  135. package/esm/src/client-auth/provider.d.ts.map +1 -0
  136. package/esm/src/client-auth/provider.js +246 -0
  137. package/esm/src/client-auth/token-store/file-store.d.ts +20 -0
  138. package/esm/src/client-auth/token-store/file-store.d.ts.map +1 -0
  139. package/esm/src/client-auth/token-store/file-store.js +62 -0
  140. package/esm/src/client-auth/token-store/memory-store.d.ts +14 -0
  141. package/esm/src/client-auth/token-store/memory-store.d.ts.map +1 -0
  142. package/esm/src/client-auth/token-store/memory-store.js +25 -0
  143. package/esm/src/client-auth/types.d.ts +89 -0
  144. package/esm/src/client-auth/types.d.ts.map +1 -0
  145. package/esm/src/client-auth/types.js +10 -0
  146. package/esm/src/concurrency/rate-limiter.d.ts +87 -0
  147. package/esm/src/concurrency/rate-limiter.d.ts.map +1 -0
  148. package/esm/src/concurrency/rate-limiter.js +165 -0
  149. package/esm/src/concurrency/request-queue.d.ts +71 -0
  150. package/esm/src/concurrency/request-queue.d.ts.map +1 -0
  151. package/esm/src/concurrency/request-queue.js +128 -0
  152. package/esm/src/http/body.d.ts +20 -0
  153. package/esm/src/http/body.d.ts.map +1 -0
  154. package/esm/src/http/body.js +63 -0
  155. package/esm/src/http/request-guards.d.ts +54 -0
  156. package/esm/src/http/request-guards.d.ts.map +1 -0
  157. package/esm/src/http/request-guards.js +114 -0
  158. package/esm/src/http/wire.d.ts +26 -0
  159. package/esm/src/http/wire.d.ts.map +1 -0
  160. package/{src/http/wire.ts → esm/src/http/wire.js} +13 -19
  161. package/esm/src/inspector/launcher.d.ts +48 -0
  162. package/esm/src/inspector/launcher.d.ts.map +1 -0
  163. package/esm/src/inspector/launcher.js +100 -0
  164. package/esm/src/mcp-app.d.ts +728 -0
  165. package/esm/src/mcp-app.d.ts.map +1 -0
  166. package/esm/src/mcp-app.js +3530 -0
  167. package/{src/middleware/backpressure.ts → esm/src/middleware/backpressure.d.ts} +2 -14
  168. package/esm/src/middleware/backpressure.d.ts.map +1 -0
  169. package/esm/src/middleware/backpressure.js +31 -0
  170. package/esm/src/middleware/mod.d.ts +11 -0
  171. package/esm/src/middleware/mod.d.ts.map +1 -0
  172. package/{src/middleware/mod.ts → esm/src/middleware/mod.js} +0 -10
  173. package/{src/middleware/rate-limit.ts → esm/src/middleware/rate-limit.d.ts} +2 -25
  174. package/esm/src/middleware/rate-limit.d.ts.map +1 -0
  175. package/esm/src/middleware/rate-limit.js +33 -0
  176. package/esm/src/middleware/runner.d.ts +32 -0
  177. package/esm/src/middleware/runner.d.ts.map +1 -0
  178. package/esm/src/middleware/runner.js +49 -0
  179. package/esm/src/middleware/types.d.ts +76 -0
  180. package/esm/src/middleware/types.d.ts.map +1 -0
  181. package/esm/src/middleware/types.js +9 -0
  182. package/esm/src/middleware/validation.d.ts +24 -0
  183. package/esm/src/middleware/validation.d.ts.map +1 -0
  184. package/esm/src/middleware/validation.js +30 -0
  185. package/esm/src/mrtr/capability-check.d.ts +75 -0
  186. package/esm/src/mrtr/capability-check.d.ts.map +1 -0
  187. package/esm/src/mrtr/capability-check.js +233 -0
  188. package/esm/src/mrtr/mod.d.ts +18 -0
  189. package/esm/src/mrtr/mod.d.ts.map +1 -0
  190. package/esm/src/mrtr/mod.js +12 -0
  191. package/esm/src/mrtr/replay-store.d.ts +50 -0
  192. package/esm/src/mrtr/replay-store.d.ts.map +1 -0
  193. package/esm/src/mrtr/replay-store.js +61 -0
  194. package/esm/src/mrtr/request-state.d.ts +181 -0
  195. package/esm/src/mrtr/request-state.d.ts.map +1 -0
  196. package/esm/src/mrtr/request-state.js +313 -0
  197. package/esm/src/mrtr/retry-guard.d.ts +61 -0
  198. package/esm/src/mrtr/retry-guard.d.ts.map +1 -0
  199. package/esm/src/mrtr/retry-guard.js +53 -0
  200. package/esm/src/mrtr/types.d.ts +99 -0
  201. package/esm/src/mrtr/types.d.ts.map +1 -0
  202. package/esm/src/mrtr/types.js +14 -0
  203. package/esm/src/observability/metrics.d.ts +104 -0
  204. package/esm/src/observability/metrics.d.ts.map +1 -0
  205. package/esm/src/observability/metrics.js +207 -0
  206. package/{src/observability/mod.ts → esm/src/observability/mod.d.ts} +2 -11
  207. package/esm/src/observability/mod.d.ts.map +1 -0
  208. package/esm/src/observability/mod.js +11 -0
  209. package/esm/src/observability/otel.d.ts +73 -0
  210. package/esm/src/observability/otel.d.ts.map +1 -0
  211. package/esm/src/observability/otel.js +260 -0
  212. package/esm/src/runtime/runtime.d.ts +10 -0
  213. package/esm/src/runtime/runtime.d.ts.map +1 -0
  214. package/esm/src/runtime/runtime.deno.d.ts +50 -0
  215. package/esm/src/runtime/runtime.deno.d.ts.map +1 -0
  216. package/esm/src/runtime/runtime.deno.js +120 -0
  217. package/{src/runtime/runtime.ts → esm/src/runtime/runtime.js} +5 -14
  218. package/esm/src/runtime/runtime.node.d.ts +51 -0
  219. package/esm/src/runtime/runtime.node.d.ts.map +1 -0
  220. package/esm/src/runtime/runtime.node.js +268 -0
  221. package/{src/runtime/types.ts → esm/src/runtime/types.d.ts} +28 -51
  222. package/esm/src/runtime/types.d.ts.map +1 -0
  223. package/esm/src/runtime/types.js +12 -0
  224. package/esm/src/security/channel-hmac.d.ts +43 -0
  225. package/esm/src/security/channel-hmac.d.ts.map +1 -0
  226. package/{src/security/channel-hmac.ts → esm/src/security/channel-hmac.js} +12 -17
  227. package/esm/src/security/csp.d.ts +50 -0
  228. package/esm/src/security/csp.d.ts.map +1 -0
  229. package/esm/src/security/csp.js +63 -0
  230. package/esm/src/security/message-signer.d.ts +88 -0
  231. package/esm/src/security/message-signer.d.ts.map +1 -0
  232. package/esm/src/security/message-signer.js +166 -0
  233. package/esm/src/subscriptions/subscription-registry.d.ts +256 -0
  234. package/esm/src/subscriptions/subscription-registry.d.ts.map +1 -0
  235. package/esm/src/subscriptions/subscription-registry.js +406 -0
  236. package/{src/tasks/mod.ts → esm/src/tasks/mod.d.ts} +3 -23
  237. package/esm/src/tasks/mod.d.ts.map +1 -0
  238. package/esm/src/tasks/mod.js +11 -0
  239. package/esm/src/tasks/task-store.d.ts +342 -0
  240. package/esm/src/tasks/task-store.d.ts.map +1 -0
  241. package/esm/src/tasks/task-store.js +649 -0
  242. package/esm/src/transport/request-headers.d.ts +145 -0
  243. package/esm/src/transport/request-headers.d.ts.map +1 -0
  244. package/esm/src/transport/request-headers.js +525 -0
  245. package/esm/src/types.d.ts +776 -0
  246. package/esm/src/types.d.ts.map +1 -0
  247. package/esm/src/types.js +92 -0
  248. package/esm/src/ui/viewer-utils.d.ts +45 -0
  249. package/esm/src/ui/viewer-utils.d.ts.map +1 -0
  250. package/esm/src/ui/viewer-utils.js +97 -0
  251. package/esm/src/validation/schema-validator.d.ts +115 -0
  252. package/esm/src/validation/schema-validator.d.ts.map +1 -0
  253. package/esm/src/validation/schema-validator.js +249 -0
  254. package/package.json +35 -23
  255. package/mod.ts +0 -302
  256. package/src/auth/as-metadata-proxy.ts +0 -288
  257. package/src/auth/config.ts +0 -368
  258. package/src/auth/jwt-provider.ts +0 -327
  259. package/src/auth/middleware.ts +0 -257
  260. package/src/auth/mod.ts +0 -89
  261. package/src/auth/multi-tenant-middleware.ts +0 -236
  262. package/src/auth/presets.ts +0 -351
  263. package/src/auth/scope-middleware.ts +0 -59
  264. package/src/auth/static-token-provider.ts +0 -197
  265. package/src/auth/types.ts +0 -207
  266. package/src/client-auth/callback-server.ts +0 -166
  267. package/src/client-auth/client-id-metadata.ts +0 -260
  268. package/src/client-auth/connect.ts +0 -72
  269. package/src/client-auth/provider.ts +0 -300
  270. package/src/client-auth/token-store/file-store.ts +0 -73
  271. package/src/client-auth/token-store/memory-store.ts +0 -32
  272. package/src/client-auth/types.ts +0 -95
  273. package/src/concurrency/rate-limiter.ts +0 -190
  274. package/src/concurrency/request-queue.ts +0 -140
  275. package/src/http/body.ts +0 -72
  276. package/src/http/request-guards.ts +0 -137
  277. package/src/inspector/launcher.ts +0 -131
  278. package/src/mcp-app.ts +0 -4426
  279. package/src/middleware/runner.ts +0 -63
  280. package/src/middleware/types.ts +0 -104
  281. package/src/middleware/validation.ts +0 -28
  282. package/src/mrtr/capability-check.ts +0 -303
  283. package/src/mrtr/mod.ts +0 -46
  284. package/src/mrtr/replay-store.ts +0 -103
  285. package/src/mrtr/request-state.ts +0 -435
  286. package/src/mrtr/types.ts +0 -107
  287. package/src/observability/metrics.ts +0 -336
  288. package/src/observability/otel.ts +0 -330
  289. package/src/runtime/runtime.deno.ts +0 -149
  290. package/src/runtime/runtime.node.ts +0 -324
  291. package/src/security/csp.ts +0 -89
  292. package/src/security/message-signer.ts +0 -223
  293. package/src/subscriptions/subscription-registry.ts +0 -558
  294. package/src/tasks/task-store.ts +0 -1014
  295. package/src/testdata/stdio-e2e-server.ts +0 -110
  296. package/src/transport/request-headers.ts +0 -661
  297. package/src/types.ts +0 -907
  298. package/src/ui/viewer-utils.ts +0 -117
  299. package/src/validation/schema-validator.ts +0 -307
@@ -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
- }