@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,368 +0,0 @@
1
- /**
2
- * Auth configuration loader.
3
- *
4
- * Loads auth config from YAML file with env var overrides.
5
- * Priority: env vars > YAML > (nothing = no auth)
6
- *
7
- * @module lib/server/auth/config
8
- */
9
-
10
- import { parse as parseYaml } from "yaml";
11
- import { env, readTextFile } from "../runtime/runtime.js";
12
- import type { AuthProvider } from "./provider.js";
13
- import {
14
- createAuth0AuthProvider,
15
- createGitHubAuthProvider,
16
- createGoogleAuthProvider,
17
- createOIDCAuthProvider,
18
- } from "./presets.js";
19
-
20
- /** Supported auth provider names */
21
- export type AuthProviderName = "github" | "google" | "auth0" | "oidc";
22
-
23
- const VALID_PROVIDERS: AuthProviderName[] = [
24
- "github",
25
- "google",
26
- "auth0",
27
- "oidc",
28
- ];
29
-
30
- /**
31
- * Fields shared by all {@link AuthConfig} variants.
32
- */
33
- interface AuthConfigBase {
34
- /** JWT audience (aud claim) */
35
- audience: string;
36
- /** RFC 9728 § 2 resource identifier (HTTP(S) URL or opaque URI) */
37
- resource: string;
38
- /** Scopes supported by this server */
39
- scopesSupported?: string[];
40
- /**
41
- * Absolute HTTP(S) URL where the `/.well-known/oauth-protected-resource`
42
- * metadata document is served publicly (RFC 9728 § 3).
43
- *
44
- * Required when `resource` is an opaque URI (e.g., an OIDC project ID used
45
- * as JWT audience per RFC 9728 § 2) — otherwise preset factories will
46
- * throw at construction. When `resource` is itself an HTTP(S) URL, this
47
- * field is optional and auto-derived by the preset bridge layer. Mirrors
48
- * `JwtAuthProviderOptions.resourceMetadataUrl`.
49
- */
50
- resourceMetadataUrl?: string;
51
- }
52
-
53
- /** Auth config for GitHub Actions OIDC (no provider-specific fields). */
54
- export interface GitHubAuthConfig extends AuthConfigBase {
55
- provider: "github";
56
- }
57
-
58
- /** Auth config for Google OIDC (no provider-specific fields). */
59
- export interface GoogleAuthConfig extends AuthConfigBase {
60
- provider: "google";
61
- }
62
-
63
- /** Auth config for Auth0 — `domain` is REQUIRED at the type level. */
64
- export interface Auth0AuthConfig extends AuthConfigBase {
65
- provider: "auth0";
66
- /** Auth0 tenant domain (e.g., `"my-tenant.auth0.com"`). */
67
- domain: string;
68
- }
69
-
70
- /** Auth config for generic OIDC — `issuer` is REQUIRED at the type level. */
71
- export interface OIDCAuthConfig extends AuthConfigBase {
72
- provider: "oidc";
73
- /** OIDC issuer URL (used as both JWT `iss` and JWKS discovery root). */
74
- issuer: string;
75
- /** JWKS URI, optional — derived from `issuer` if absent. */
76
- jwksUri?: string;
77
- }
78
-
79
- /**
80
- * Parsed auth configuration (after YAML + env merge).
81
- *
82
- * 0.17.0: discriminated union on `provider` tag. Each variant encodes
83
- * its provider-specific required fields at the type level:
84
- * - `"github"` / `"google"`: base only
85
- * - `"auth0"`: base + required `domain`
86
- * - `"oidc"`: base + required `issuer`, optional `jwksUri`
87
- *
88
- * TypeScript narrows on `config.provider`, so `createAuthProviderFromConfig`
89
- * no longer needs non-null assertions (`config.domain!`) — the required
90
- * fields are typed correctly in each branch.
91
- *
92
- * The runtime checks in `loadAuthConfig()` stay as defense-in-depth for
93
- * YAML/env input (untyped), but TS callers constructing `AuthConfig` literals
94
- * directly now get compile-time safety.
95
- *
96
- * BREAKING from 0.16.x: callers who constructed `AuthConfig` literals with
97
- * optional `domain`/`issuer` and relied on runtime validation now get a
98
- * compile error if they don't match a variant's required fields. Migration:
99
- * ensure the literal satisfies the discriminated variant (e.g.,
100
- * `provider: "auth0"` requires `domain`). See
101
- * `Casys-AI/mcp-server#11`.
102
- */
103
- export type AuthConfig =
104
- | GitHubAuthConfig
105
- | GoogleAuthConfig
106
- | Auth0AuthConfig
107
- | OIDCAuthConfig;
108
-
109
- /**
110
- * YAML file schema (top-level has `auth` key).
111
- */
112
- interface ConfigFile {
113
- auth?: {
114
- provider?: string;
115
- audience?: string;
116
- resource?: string;
117
- domain?: string;
118
- issuer?: string;
119
- jwksUri?: string;
120
- scopesSupported?: string[];
121
- resourceMetadataUrl?: string;
122
- };
123
- }
124
-
125
- /**
126
- * Load auth configuration from YAML file + env var overrides.
127
- *
128
- * 1. Reads YAML file (if it exists)
129
- * 2. Overlays env vars (MCP_AUTH_* take precedence)
130
- * 3. Validates the merged config
131
- * 4. Returns null if no auth is configured
132
- *
133
- * Env var mapping:
134
- * - MCP_AUTH_PROVIDER → auth.provider
135
- * - MCP_AUTH_AUDIENCE → auth.audience
136
- * - MCP_AUTH_RESOURCE → auth.resource
137
- * - MCP_AUTH_DOMAIN → auth.domain
138
- * - MCP_AUTH_ISSUER → auth.issuer
139
- * - MCP_AUTH_JWKS_URI → auth.jwksUri
140
- * - MCP_AUTH_SCOPES → auth.scopesSupported (space-separated)
141
- * - MCP_AUTH_RESOURCE_METADATA_URL → auth.resourceMetadataUrl
142
- *
143
- * @param configPath - Path to YAML config file. Defaults to "mcp-server.yaml" in cwd.
144
- * @returns AuthConfig or null if no auth configured
145
- * @throws Error if config is invalid (fail-fast)
146
- */
147
- export async function loadAuthConfig(
148
- configPath?: string,
149
- ): Promise<AuthConfig | null> {
150
- // 1. Load YAML (optional - file may not exist)
151
- const yamlAuth = await loadYamlAuth(configPath ?? "mcp-server.yaml");
152
-
153
- // 2. Read env vars
154
- const envProvider = env("MCP_AUTH_PROVIDER");
155
- const envAudience = env("MCP_AUTH_AUDIENCE");
156
- const envResource = env("MCP_AUTH_RESOURCE");
157
- const envDomain = env("MCP_AUTH_DOMAIN");
158
- const envIssuer = env("MCP_AUTH_ISSUER");
159
- const envJwksUri = env("MCP_AUTH_JWKS_URI");
160
- const envScopes = env("MCP_AUTH_SCOPES");
161
- const envResourceMetadataUrl = env("MCP_AUTH_RESOURCE_METADATA_URL");
162
-
163
- // 3. Merge: env overrides YAML
164
- const providerRaw = envProvider ?? yamlAuth?.provider;
165
-
166
- // No provider configured anywhere → no auth
167
- if (!providerRaw) return null;
168
-
169
- // Validate provider name — untyped YAML/env input requires a runtime check
170
- // even after 0.17.0's compile-time DU. This is the defense-in-depth layer.
171
- if (!VALID_PROVIDERS.includes(providerRaw as AuthProviderName)) {
172
- throw new Error(
173
- `[AuthConfig] Unknown auth provider: "${providerRaw}". ` +
174
- `Valid values: ${VALID_PROVIDERS.join(", ")}`,
175
- );
176
- }
177
- const provider = providerRaw as AuthProviderName;
178
-
179
- const audience = envAudience ?? yamlAuth?.audience;
180
- const resource = envResource ?? yamlAuth?.resource;
181
-
182
- if (!audience) {
183
- throw new Error(
184
- `[AuthConfig] "audience" is required when provider="${provider}". ` +
185
- "Set auth.audience in YAML or MCP_AUTH_AUDIENCE env var.",
186
- );
187
- }
188
- if (!resource) {
189
- throw new Error(
190
- `[AuthConfig] "resource" is required when provider="${provider}". ` +
191
- "Set auth.resource in YAML or MCP_AUTH_RESOURCE env var.",
192
- );
193
- }
194
-
195
- const base: AuthConfigBase = {
196
- audience,
197
- resource,
198
- scopesSupported: envScopes
199
- ? envScopes.split(" ").filter(Boolean)
200
- : yamlAuth?.scopesSupported,
201
- resourceMetadataUrl: envResourceMetadataUrl ??
202
- yamlAuth?.resourceMetadataUrl,
203
- };
204
-
205
- // 4. Construct the correct DU variant, enforcing provider-specific
206
- // required fields at runtime. The runtime checks mirror the type-level
207
- // constraints in the DU variants (Auth0AuthConfig.domain, OIDCAuthConfig.issuer).
208
- //
209
- // The `issuer` / `domain` fields are URL-shaped at runtime even though the
210
- // DU variants type them as `string`. 0.17.0 runs them through `new URL()`
211
- // here (at the YAML/env boundary) to catch typos like
212
- // `MCP_AUTH_ISSUER=not-a-url` with a clear error naming the offending field,
213
- // instead of surfacing a confusing `authorizationServers[0]` error deep
214
- // inside the preset bridge later (pre-existing issue caught during 0.17.0
215
- // review, code-reviewer finding).
216
- switch (provider) {
217
- case "github":
218
- return { provider: "github", ...base };
219
- case "google":
220
- return { provider: "google", ...base };
221
- case "auth0": {
222
- const domain = envDomain ?? yamlAuth?.domain;
223
- if (!domain) {
224
- throw new Error(
225
- '[AuthConfig] "domain" is required for auth0 provider. ' +
226
- "Set auth.domain in YAML or MCP_AUTH_DOMAIN env var.",
227
- );
228
- }
229
- return { provider: "auth0", ...base, domain };
230
- }
231
- case "oidc": {
232
- const issuer = envIssuer ?? yamlAuth?.issuer;
233
- if (!issuer) {
234
- throw new Error(
235
- '[AuthConfig] "issuer" is required for oidc provider. ' +
236
- "Set auth.issuer in YAML or MCP_AUTH_ISSUER env var.",
237
- );
238
- }
239
- try {
240
- const parsed = new URL(issuer);
241
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
242
- throw new Error(
243
- `[AuthConfig] "issuer" for oidc provider must use http(s):// ` +
244
- `scheme, got ${JSON.stringify(parsed.protocol)} in ` +
245
- `${JSON.stringify(issuer)}.`,
246
- );
247
- }
248
- } catch (err) {
249
- // If new URL() threw, re-wrap with AuthConfig-labelled error.
250
- // If our explicit scheme check threw, re-throw as-is (already labelled).
251
- if (err instanceof Error && err.message.startsWith("[AuthConfig]")) {
252
- throw err;
253
- }
254
- throw new Error(
255
- `[AuthConfig] "issuer" for oidc provider is not a valid URL: ` +
256
- `${JSON.stringify(issuer)}. Set auth.issuer in YAML or ` +
257
- `MCP_AUTH_ISSUER env var to an absolute http(s)://... URL.`,
258
- );
259
- }
260
- const jwksUri = envJwksUri ?? yamlAuth?.jwksUri;
261
- return { provider: "oidc", ...base, issuer, jwksUri };
262
- }
263
- default: {
264
- // Exhaustiveness guard: future provider additions land here as a TS
265
- // error at this function. Runtime throw is belt-and-suspenders — the
266
- // earlier `VALID_PROVIDERS.includes` check at line ~130 already
267
- // eliminates unknown provider strings.
268
- const _exhaustive: never = provider;
269
- throw new Error(
270
- `[AuthConfig] Unreachable — unhandled provider ${
271
- JSON.stringify(_exhaustive)
272
- }`,
273
- );
274
- }
275
- }
276
- }
277
-
278
- /**
279
- * Create an AuthProvider from a loaded AuthConfig.
280
- *
281
- * 0.17.0: `config` is a discriminated union on `provider`, so TypeScript
282
- * narrows `config.domain`/`config.issuer` as required (non-optional) in
283
- * their respective branches. No more non-null assertions (`config.domain!`)
284
- * or defensive runtime checks here — the type system guarantees them.
285
- *
286
- * @param config - Validated auth config
287
- * @returns AuthProvider instance
288
- */
289
- export function createAuthProviderFromConfig(config: AuthConfig): AuthProvider {
290
- const base = {
291
- audience: config.audience,
292
- resource: config.resource,
293
- scopesSupported: config.scopesSupported,
294
- resourceMetadataUrl: config.resourceMetadataUrl,
295
- };
296
-
297
- switch (config.provider) {
298
- case "github":
299
- return createGitHubAuthProvider(base);
300
- case "google":
301
- return createGoogleAuthProvider(base);
302
- case "auth0":
303
- return createAuth0AuthProvider({ ...base, domain: config.domain });
304
- case "oidc":
305
- return createOIDCAuthProvider({
306
- ...base,
307
- issuer: config.issuer,
308
- jwksUri: config.jwksUri,
309
- authorizationServers: [config.issuer],
310
- });
311
- default: {
312
- // Exhaustiveness guard matching the one in loadAuthConfig — when a
313
- // 5th variant is added to AuthConfig, TS flags this function as
314
- // incomplete before any caller is affected.
315
- const _exhaustive: never = config;
316
- throw new Error(
317
- `[AuthConfig] Unreachable — unhandled variant ${
318
- JSON.stringify(_exhaustive)
319
- }`,
320
- );
321
- }
322
- }
323
- }
324
-
325
- /**
326
- * Load the auth section from a YAML config file.
327
- * Returns null if file doesn't exist (not an error).
328
- */
329
- async function loadYamlAuth(
330
- path: string,
331
- ): Promise<ConfigFile["auth"] | null> {
332
- // readTextFile returns null if file doesn't exist
333
- const text = await readTextFile(path);
334
- if (text === null) return null;
335
-
336
- const parsed = parseYaml(text);
337
-
338
- // Validate parsed YAML is an object (not string, array, null, etc.)
339
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
340
- return null;
341
- }
342
-
343
- const configFile = parsed as Record<string, unknown>;
344
- if (
345
- !configFile.auth || typeof configFile.auth !== "object" ||
346
- Array.isArray(configFile.auth)
347
- ) {
348
- return null;
349
- }
350
-
351
- const auth = configFile.auth as Record<string, unknown>;
352
- return {
353
- provider: typeof auth.provider === "string" ? auth.provider : undefined,
354
- audience: typeof auth.audience === "string" ? auth.audience : undefined,
355
- resource: typeof auth.resource === "string" ? auth.resource : undefined,
356
- domain: typeof auth.domain === "string" ? auth.domain : undefined,
357
- issuer: typeof auth.issuer === "string" ? auth.issuer : undefined,
358
- jwksUri: typeof auth.jwksUri === "string" ? auth.jwksUri : undefined,
359
- scopesSupported: Array.isArray(auth.scopesSupported)
360
- ? auth.scopesSupported.filter((s: unknown): s is string =>
361
- typeof s === "string"
362
- )
363
- : undefined,
364
- resourceMetadataUrl: typeof auth.resourceMetadataUrl === "string"
365
- ? auth.resourceMetadataUrl
366
- : undefined,
367
- };
368
- }
@@ -1,327 +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
-
10
- import { createRemoteJWKSet, jwtVerify } from "jose";
11
- import { AuthProvider } from "./provider.js";
12
- import {
13
- type AuthInfo,
14
- type HttpsUrl,
15
- httpsUrl,
16
- type ProtectedResourceMetadata,
17
- } from "./types.js";
18
- import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
19
-
20
- // ============================================================================
21
- // JwtAuthProviderOptions — tagged discriminated union (0.17.0)
22
- // ============================================================================
23
-
24
- /**
25
- * Fields shared by both branches of {@link JwtAuthProviderOptions}.
26
- */
27
- interface JwtAuthProviderOptionsBase {
28
- /** JWT issuer (iss claim) */
29
- issuer: string;
30
- /** JWT audience (aud claim) */
31
- audience: string;
32
- /**
33
- * JWKS URI for signature validation. Defaults to
34
- * `{issuer}/.well-known/jwks.json` when omitted.
35
- */
36
- jwksUri?: string;
37
- /**
38
- * Authorization servers that issue valid tokens. Each entry is a branded
39
- * {@link HttpsUrl} — raw strings are rejected at compile time. Construct
40
- * via {@link httpsUrl}.
41
- */
42
- authorizationServers: HttpsUrl[];
43
- /** Scopes supported by this server */
44
- scopesSupported?: string[];
45
- }
46
-
47
- /**
48
- * Options where `resource` is a verified HTTP(S) URL. The metadata URL is
49
- * auto-derived when `resourceMetadataUrl` is omitted, by applying RFC 9728
50
- * § 3.1 insertion to `resource`.
51
- *
52
- * Tagged with `kind: "url"` so TypeScript narrowing is sound at the function
53
- * body level (see 0.17.0 CHANGELOG — this fixes finding C1 from the 0.16.0
54
- * review where narrowing on `resourceMetadataUrl === undefined` failed to
55
- * propagate because `HttpsUrl extends string` collapsed the union).
56
- */
57
- export interface JwtAuthProviderOptionsUrlResource
58
- extends JwtAuthProviderOptionsBase {
59
- /** Discriminant tag — MUST be `"url"` for this branch. */
60
- kind: "url";
61
- /** RFC 9728 § 2 resource identifier, pre-validated as HTTP(S) URL. */
62
- resource: HttpsUrl;
63
- /**
64
- * Metadata URL, optional — auto-derived from `resource` when omitted.
65
- */
66
- resourceMetadataUrl?: HttpsUrl;
67
- }
68
-
69
- /**
70
- * Options where `resource` is an opaque URI (per RFC 9728 § 2 — e.g., an
71
- * OIDC project ID used as JWT audience). The metadata URL is MANDATORY
72
- * because it cannot be derived from an opaque identifier.
73
- *
74
- * Tagged with `kind: "opaque"` to make the DU structurally disjoint (see
75
- * finding C2 from the 0.16.0 review — without the tag, `UrlResource` was
76
- * a structural subtype of `OpaqueResource` because `HttpsUrl extends
77
- * string`).
78
- */
79
- export interface JwtAuthProviderOptionsOpaqueResource
80
- extends JwtAuthProviderOptionsBase {
81
- /** Discriminant tag — MUST be `"opaque"` for this branch. */
82
- kind: "opaque";
83
- /** RFC 9728 § 2 opaque resource identifier (NOT an URL). */
84
- resource: string;
85
- /**
86
- * Metadata URL, REQUIRED — cannot be derived from opaque `resource`.
87
- * Construct via {@link httpsUrl}.
88
- */
89
- resourceMetadataUrl: HttpsUrl;
90
- }
91
-
92
- /**
93
- * Configuration for JwtAuthProvider.
94
- *
95
- * 0.17.0: tagged discriminated union on `kind: "url" | "opaque"`. TypeScript
96
- * narrowing is now structurally sound — `if (options.kind === "url")` truly
97
- * narrows `options.resource` to `HttpsUrl` at the constructor body level.
98
- * The tag also makes the branches strictly disjoint: a caller cannot
99
- * accidentally satisfy `OpaqueResource` with an `HttpsUrl`-branded `resource`
100
- * (as was possible in 0.16.x — finding C2 from the type-design review).
101
- *
102
- * - `kind: "url"` → {@link JwtAuthProviderOptionsUrlResource},
103
- * `resource: HttpsUrl` (wrap with {@link httpsUrl}),
104
- * `resourceMetadataUrl` optional (auto-derived).
105
- * - `kind: "opaque"` → {@link JwtAuthProviderOptionsOpaqueResource},
106
- * `resource: string` (raw opaque identifier),
107
- * `resourceMetadataUrl: HttpsUrl` REQUIRED.
108
- *
109
- * The preset factories and the public `buildJwtAuthProvider` bridge accept
110
- * raw string `resource` and set the `kind` tag automatically via detection
111
- * — only callers that construct `JwtAuthProvider` directly (not through the
112
- * bridge) need to supply `kind` themselves. Custom OIDC providers written
113
- * on top of `buildJwtAuthProvider` are unaffected.
114
- *
115
- * BREAKING from 0.16.x: every direct `new JwtAuthProvider(...)` site must
116
- * add `kind: "url"` or `kind: "opaque"`. Preset users are unaffected.
117
- * See `postmortems/phase8-deployment.md` § 7 and `CHANGELOG.md` 0.15.0 /
118
- * 0.15.1 / 0.16.0 for the bug-class history this refactor closes.
119
- */
120
- export type JwtAuthProviderOptions =
121
- | JwtAuthProviderOptionsUrlResource
122
- | JwtAuthProviderOptionsOpaqueResource;
123
-
124
- // ============================================================================
125
- // JwtAuthProvider
126
- // ============================================================================
127
-
128
- /**
129
- * Cached auth result with expiration
130
- */
131
- interface CachedAuth {
132
- authInfo: AuthInfo;
133
- expiresAt: number; // ms timestamp
134
- }
135
-
136
- /**
137
- * JWT Auth Provider with JWKS validation.
138
- *
139
- * @example URL resource (auto-derives metadata URL)
140
- * ```typescript
141
- * import { httpsUrl, JwtAuthProvider } from "@casys/mcp-server";
142
- *
143
- * const provider = new JwtAuthProvider({
144
- * kind: "url",
145
- * issuer: "https://accounts.google.com",
146
- * audience: "https://my-mcp.example.com",
147
- * resource: httpsUrl("https://my-mcp.example.com"),
148
- * authorizationServers: [httpsUrl("https://accounts.google.com")],
149
- * });
150
- * ```
151
- *
152
- * @example Opaque resource (explicit metadata URL required)
153
- * ```typescript
154
- * import { httpsUrl, JwtAuthProvider } from "@casys/mcp-server";
155
- *
156
- * // RFC 9728 § 2 Option B: OIDC project ID as JWT audience
157
- * const provider = new JwtAuthProvider({
158
- * kind: "opaque",
159
- * issuer: "https://my-tenant.zitadel.cloud",
160
- * audience: "367545125829670172",
161
- * resource: "367545125829670172",
162
- * resourceMetadataUrl: httpsUrl(
163
- * "https://my-mcp.example.com/.well-known/oauth-protected-resource",
164
- * ),
165
- * authorizationServers: [httpsUrl("https://my-tenant.zitadel.cloud")],
166
- * });
167
- * ```
168
- */
169
- export class JwtAuthProvider extends AuthProvider {
170
- private jwks: ReturnType<typeof createRemoteJWKSet>;
171
- private options: JwtAuthProviderOptions;
172
- private readonly resourceMetadataUrl: HttpsUrl;
173
-
174
- // Token verification cache: hash(token) → AuthInfo with TTL
175
- // Prevents redundant JWKS fetches (network round-trip per tool call)
176
- private tokenCache = new Map<string, CachedAuth>();
177
- private static readonly MAX_CACHE_SIZE = 1000;
178
- private static readonly DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
179
-
180
- constructor(options: JwtAuthProviderOptions) {
181
- super();
182
-
183
- if (!options.issuer) {
184
- throw new Error("[JwtAuthProvider] issuer is required");
185
- }
186
- if (!options.audience) {
187
- throw new Error("[JwtAuthProvider] audience is required");
188
- }
189
- if (!options.resource) {
190
- throw new Error("[JwtAuthProvider] resource is required");
191
- }
192
- if (!options.authorizationServers?.length) {
193
- throw new Error(
194
- "[JwtAuthProvider] at least one authorizationServer is required",
195
- );
196
- }
197
-
198
- // 0.17.0: narrow on the `kind` discriminant tag. TypeScript structurally
199
- // narrows the DU here — after `if (options.kind === "opaque")`, `options`
200
- // is `JwtAuthProviderOptionsOpaqueResource` and `resourceMetadataUrl` is
201
- // guaranteed non-undefined; after `else`, `options` is
202
- // `JwtAuthProviderOptionsUrlResource` and `options.resource` is
203
- // `HttpsUrl` (no widening, no runtime guess). This fixes finding C1 from
204
- // the 0.16.0 review — the previous narrowing on `resourceMetadataUrl !==
205
- // undefined` was unsound because `HttpsUrl extends string` collapsed the
206
- // union back to `string`. Tagging makes the branches strictly disjoint.
207
- //
208
- // URL branch derivation follows RFC 9728 § 3.1: when `resource` has a
209
- // path or query component, the well-known suffix is INSERTED between
210
- // the host and the path, not appended after it:
211
- //
212
- // resource = https://api.example.com/v1/mcp
213
- // metadata = https://api.example.com/.well-known/oauth-protected-resource/v1/mcp
214
- //
215
- // Fragments (`#...`) are intentionally dropped — they're client-side-only
216
- // per RFC 3986 § 3.5 and never part of a server-side metadata endpoint.
217
- if (options.kind === "opaque") {
218
- this.resourceMetadataUrl = options.resourceMetadataUrl;
219
- } else if (options.resourceMetadataUrl !== undefined) {
220
- this.resourceMetadataUrl = options.resourceMetadataUrl;
221
- } else {
222
- const parsed = new URL(options.resource);
223
- const pathPart = parsed.pathname === "/" ? "" : parsed.pathname;
224
- this.resourceMetadataUrl = httpsUrl(
225
- `${parsed.origin}/.well-known/oauth-protected-resource${pathPart}${parsed.search}`,
226
- );
227
- }
228
-
229
- this.options = options;
230
- const jwksUri = options.jwksUri ??
231
- `${options.issuer}/.well-known/jwks.json`;
232
- this.jwks = createRemoteJWKSet(new URL(jwksUri));
233
- }
234
-
235
- async verifyToken(token: string): Promise<AuthInfo | null> {
236
- // Check cache first (avoids JWKS network round-trip)
237
- const cacheKey = await this.hashToken(token);
238
- const cached = this.tokenCache.get(cacheKey);
239
- if (cached && Date.now() < cached.expiresAt) {
240
- if (isOtelEnabled()) {
241
- recordAuthEvent("cache_hit", {
242
- subject: cached.authInfo.subject ?? "",
243
- });
244
- }
245
- return cached.authInfo;
246
- }
247
- // Evict expired entry if present
248
- if (cached) this.tokenCache.delete(cacheKey);
249
-
250
- try {
251
- const { payload } = await jwtVerify(token, this.jwks, {
252
- issuer: this.options.issuer,
253
- audience: this.options.audience,
254
- });
255
-
256
- const authInfo: AuthInfo = {
257
- subject: payload.sub ?? "unknown",
258
- clientId: (payload.azp as string | undefined) ??
259
- (payload.client_id as string | undefined),
260
- scopes: this.extractScopes(payload),
261
- claims: payload as Record<string, unknown>,
262
- expiresAt: payload.exp,
263
- };
264
-
265
- // Cache with TTL = min(token remaining lifetime, 5 minutes)
266
- const tokenExpiresMs = payload.exp ? payload.exp * 1000 : Infinity;
267
- const cacheTtl = Math.min(
268
- tokenExpiresMs - Date.now(),
269
- JwtAuthProvider.DEFAULT_CACHE_TTL_MS,
270
- );
271
- if (cacheTtl > 0) {
272
- // Evict oldest entries if cache is full
273
- if (this.tokenCache.size >= JwtAuthProvider.MAX_CACHE_SIZE) {
274
- const oldestKey = this.tokenCache.keys().next().value;
275
- if (oldestKey) this.tokenCache.delete(oldestKey);
276
- }
277
- this.tokenCache.set(cacheKey, {
278
- authInfo: Object.freeze(authInfo) as AuthInfo,
279
- expiresAt: Date.now() + cacheTtl,
280
- });
281
- }
282
-
283
- return authInfo;
284
- } catch (err) {
285
- // Log the actual rejection reason so JWKS fetch failures, audience
286
- // mismatches, and expiration errors are distinguishable in logs.
287
- const msg = err instanceof Error ? err.message : String(err);
288
- console.error(`[JwtAuthProvider] Token rejected: ${msg}`);
289
- return null;
290
- }
291
- }
292
-
293
- /**
294
- * Hash a token for cache key (avoids storing raw tokens in memory)
295
- */
296
- private async hashToken(token: string): Promise<string> {
297
- const data = new TextEncoder().encode(token);
298
- const hash = await crypto.subtle.digest("SHA-256", data);
299
- return Array.from(new Uint8Array(hash)).map((b) =>
300
- b.toString(16).padStart(2, "0")
301
- ).join("");
302
- }
303
-
304
- getResourceMetadata(): ProtectedResourceMetadata {
305
- return {
306
- resource: this.options.resource,
307
- resource_metadata_url: this.resourceMetadataUrl,
308
- authorization_servers: this.options.authorizationServers,
309
- scopes_supported: this.options.scopesSupported,
310
- bearer_methods_supported: ["header"],
311
- };
312
- }
313
-
314
- /**
315
- * Extract scopes from JWT payload.
316
- * Supports: "scope" claim (space-separated string) and "scp" claim (array).
317
- */
318
- private extractScopes(payload: Record<string, unknown>): string[] {
319
- if (typeof payload.scope === "string") {
320
- return payload.scope.split(" ").filter(Boolean);
321
- }
322
- if (Array.isArray(payload.scp)) {
323
- return payload.scp.filter((s): s is string => typeof s === "string");
324
- }
325
- return [];
326
- }
327
- }