@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
@@ -0,0 +1,62 @@
1
+ /**
2
+ * File-based token store.
3
+ *
4
+ * Stores OAuth credentials as JSON files with restrictive permissions (0o600).
5
+ * One file per MCP server, keyed by SHA-256 hash of the server URL.
6
+ *
7
+ * @module lib/server/client-auth/token-store/file-store
8
+ */
9
+ import { mkdir, readDir, readTextFile, remove, writeTextFile, } from "../../runtime/runtime.js";
10
+ async function sha256hex(input) {
11
+ const data = new TextEncoder().encode(input);
12
+ const hash = await crypto.subtle.digest("SHA-256", data);
13
+ return Array.from(new Uint8Array(hash))
14
+ .map((b) => b.toString(16).padStart(2, "0"))
15
+ .join("");
16
+ }
17
+ export class FileTokenStore {
18
+ baseDir;
19
+ constructor(baseDir) {
20
+ this.baseDir = baseDir;
21
+ }
22
+ async filePath(serverUrl) {
23
+ const hash = await sha256hex(serverUrl);
24
+ return `${this.baseDir}/${hash}.json`;
25
+ }
26
+ async ensureDir() {
27
+ await mkdir(this.baseDir, { recursive: true, mode: 0o700 });
28
+ }
29
+ async get(serverUrl) {
30
+ const path = await this.filePath(serverUrl);
31
+ const content = await readTextFile(path);
32
+ return content === null ? null : JSON.parse(content);
33
+ }
34
+ async set(serverUrl, credentials) {
35
+ await this.ensureDir();
36
+ const path = await this.filePath(serverUrl);
37
+ const content = JSON.stringify(credentials, null, 2);
38
+ await writeTextFile(path, content, { mode: 0o600 });
39
+ }
40
+ async delete(serverUrl) {
41
+ const path = await this.filePath(serverUrl);
42
+ await remove(path);
43
+ }
44
+ async list() {
45
+ const urls = [];
46
+ for (const name of await readDir(this.baseDir)) {
47
+ if (name.endsWith(".json")) {
48
+ try {
49
+ const content = await readTextFile(`${this.baseDir}/${name}`);
50
+ if (content === null)
51
+ continue;
52
+ const creds = JSON.parse(content);
53
+ urls.push(creds.serverUrl);
54
+ }
55
+ catch {
56
+ // Corrupted file, skip
57
+ }
58
+ }
59
+ }
60
+ return urls;
61
+ }
62
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * In-memory token store for testing and ephemeral use.
3
+ *
4
+ * @module lib/server/client-auth/token-store/memory-store
5
+ */
6
+ import type { StoredCredentials, TokenStore } from "../types.js";
7
+ export declare class MemoryTokenStore implements TokenStore {
8
+ private store;
9
+ get(serverUrl: string): Promise<StoredCredentials | null>;
10
+ set(serverUrl: string, credentials: StoredCredentials): Promise<void>;
11
+ delete(serverUrl: string): Promise<void>;
12
+ list(): Promise<string[]>;
13
+ }
14
+ //# sourceMappingURL=memory-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-store.d.ts","sourceRoot":"","sources":["../../../../src/src/client-auth/token-store/memory-store.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEjE,qBAAa,gBAAiB,YAAW,UAAU;IACjD,OAAO,CAAC,KAAK,CAAwC;IAKrD,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAIzD,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrE,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKxC,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;CAG1B"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * In-memory token store for testing and ephemeral use.
3
+ *
4
+ * @module lib/server/client-auth/token-store/memory-store
5
+ */
6
+ export class MemoryTokenStore {
7
+ store = new Map();
8
+ // Not `async`: the Map operations are synchronous. The interface returns
9
+ // Promises so a real store can be I/O-backed; `Promise.resolve` satisfies it
10
+ // without claiming an await point that does not exist.
11
+ get(serverUrl) {
12
+ return Promise.resolve(this.store.get(serverUrl) ?? null);
13
+ }
14
+ set(serverUrl, credentials) {
15
+ this.store.set(serverUrl, credentials);
16
+ return Promise.resolve();
17
+ }
18
+ delete(serverUrl) {
19
+ this.store.delete(serverUrl);
20
+ return Promise.resolve();
21
+ }
22
+ list() {
23
+ return Promise.resolve([...this.store.keys()]);
24
+ }
25
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * OAuth client auth types.
3
+ *
4
+ * Interfaces for token storage and OAuth client configuration.
5
+ * Used by OAuthClientProviderImpl to authenticate against
6
+ * OAuth-protected MCP servers.
7
+ *
8
+ * @module lib/server/client-auth/types
9
+ */
10
+ import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
11
+ /** Stored OAuth credentials for one MCP server */
12
+ export interface StoredCredentials {
13
+ /** The MCP server URL these credentials are for */
14
+ serverUrl: string;
15
+ /** OAuth tokens (access_token, refresh_token, etc.) */
16
+ tokens: OAuthTokens;
17
+ /** When the tokens were obtained (Unix epoch ms) */
18
+ obtainedAt: number;
19
+ /**
20
+ * Issuer that minted these credentials (SEP-2352).
21
+ *
22
+ * Absent on records written before the binding existed; `tokens()` treats
23
+ * that as unusable, since nothing proves who minted them.
24
+ */
25
+ authServerUrl?: string;
26
+ }
27
+ /** Abstract token storage — consumers provide the implementation */
28
+ export interface TokenStore {
29
+ /** Retrieve stored credentials for a server, or null if none */
30
+ get(serverUrl: string): Promise<StoredCredentials | null>;
31
+ /** Store credentials for a server */
32
+ set(serverUrl: string, credentials: StoredCredentials): Promise<void>;
33
+ /** Delete credentials for a server */
34
+ delete(serverUrl: string): Promise<void>;
35
+ /** List all server URLs with stored credentials */
36
+ list(): Promise<string[]>;
37
+ }
38
+ /** Fields shared by all OAuth client registration modes. */
39
+ export interface OAuthClientConfigBase {
40
+ /** Client name shown in consent screen */
41
+ clientName?: string;
42
+ /** Scopes to request (space-separated in OAuth, array here) */
43
+ scopes?: string[];
44
+ /** Token storage backend */
45
+ tokenStore: TokenStore;
46
+ /** Callback to open browser — injected by consumer (platform-specific) */
47
+ openBrowser: (url: string) => Promise<void>;
48
+ /** Callback server port (0 = OS auto-assign, default: 0) */
49
+ callbackPort?: number;
50
+ /** Timeout for user to complete OAuth flow (ms, default: 120_000) */
51
+ authTimeout?: number;
52
+ /**
53
+ * Optional sink for credential-lifecycle events.
54
+ *
55
+ * Notably an authorization-server change (SEP-2352): the client silently
56
+ * drops its stored credentials and re-authorizes, and an operator debugging
57
+ * an unexpected login prompt has no other way to see why.
58
+ */
59
+ logger?: (message: string) => void;
60
+ }
61
+ /** Static OAuth client registration (default, backwards-compatible mode). */
62
+ export interface StaticClientConfig extends OAuthClientConfigBase {
63
+ /** OAuth Client ID (public — embedded in consumer binary) */
64
+ clientId: string;
65
+ /** Absence of clientRegistration selects static client-id behavior. */
66
+ clientRegistration?: undefined;
67
+ }
68
+ /** CIMD client registration (explicit opt-in). */
69
+ export interface CimdClientConfig extends OAuthClientConfigBase {
70
+ /** In CIMD mode, client_id is derived from clientIdMetadataUrl. */
71
+ clientId?: never;
72
+ clientRegistration: {
73
+ method: "client_id_metadata";
74
+ /** HTTPS URL of the hosted Client ID Metadata Document; also the client_id. */
75
+ clientIdMetadataUrl: string;
76
+ /** Runtime redirect URI published in the metadata document. */
77
+ redirectUri: string;
78
+ /** Optional display and extension metadata for the hosted document. */
79
+ metadata?: {
80
+ client_uri?: string;
81
+ logo_uri?: string;
82
+ contacts?: string[];
83
+ extra?: Record<string, unknown>;
84
+ };
85
+ };
86
+ }
87
+ /** Configuration for creating an OAuthClientProvider */
88
+ export type OAuthClientConfig = StaticClientConfig | CimdClientConfig;
89
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/src/client-auth/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0CAA0C,CAAC;AAE5E,kDAAkD;AAClD,MAAM,WAAW,iBAAiB;IAChC,mDAAmD;IACnD,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,MAAM,EAAE,WAAW,CAAC;IACpB,oDAAoD;IACpD,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,oEAAoE;AACpE,MAAM,WAAW,UAAU;IACzB,gEAAgE;IAChE,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAAC;IAC1D,qCAAqC;IACrC,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACtE,sCAAsC;IACtC,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,mDAAmD;IACnD,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;CAC3B;AAED,4DAA4D;AAC5D,MAAM,WAAW,qBAAqB;IACpC,0CAA0C;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,+DAA+D;IAC/D,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,4BAA4B;IAC5B,UAAU,EAAE,UAAU,CAAC;IACvB,0EAA0E;IAC1E,WAAW,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5C,4DAA4D;IAC5D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACpC;AAED,6EAA6E;AAC7E,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAC/D,6DAA6D;IAC7D,QAAQ,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,kBAAkB,CAAC,EAAE,SAAS,CAAC;CAChC;AAED,kDAAkD;AAClD,MAAM,WAAW,gBAAiB,SAAQ,qBAAqB;IAC7D,mEAAmE;IACnE,QAAQ,CAAC,EAAE,KAAK,CAAC;IACjB,kBAAkB,EAAE;QAClB,MAAM,EAAE,oBAAoB,CAAC;QAC7B,+EAA+E;QAC/E,mBAAmB,EAAE,MAAM,CAAC;QAC5B,+DAA+D;QAC/D,WAAW,EAAE,MAAM,CAAC;QACpB,uEAAuE;QACvE,QAAQ,CAAC,EAAE;YACT,UAAU,CAAC,EAAE,MAAM,CAAC;YACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;YAClB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;YACpB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACjC,CAAC;KACH,CAAC;CACH;AAED,wDAAwD;AACxD,MAAM,MAAM,iBAAiB,GAAG,kBAAkB,GAAG,gBAAgB,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * OAuth client auth types.
3
+ *
4
+ * Interfaces for token storage and OAuth client configuration.
5
+ * Used by OAuthClientProviderImpl to authenticate against
6
+ * OAuth-protected MCP servers.
7
+ *
8
+ * @module lib/server/client-auth/types
9
+ */
10
+ export {};
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Rate Limiter
3
+ *
4
+ * Sliding window rate limiter for per-client request throttling.
5
+ * Prevents server overload by limiting requests per time window.
6
+ *
7
+ * @module lib/server/rate-limiter
8
+ */
9
+ /**
10
+ * Sliding window rate limiter
11
+ *
12
+ * Features:
13
+ * - Per-key rate limiting (client ID, IP, etc.)
14
+ * - Sliding window for smooth rate enforcement
15
+ * - Automatic cleanup of old timestamps
16
+ * - Backoff waiting when limit exceeded
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * const limiter = new RateLimiter({ maxRequests: 100, windowMs: 60000 });
21
+ *
22
+ * if (await limiter.checkLimit("client-123")) {
23
+ * // Execute request
24
+ * } else {
25
+ * // Rate limited
26
+ * }
27
+ * ```
28
+ */
29
+ export declare class RateLimiter {
30
+ private requestCounts;
31
+ private readonly windowMs;
32
+ private readonly maxRequests;
33
+ private operationsSinceLastPurge;
34
+ private static readonly PURGE_EVERY_N_OPS;
35
+ constructor(options: {
36
+ maxRequests: number;
37
+ windowMs: number;
38
+ });
39
+ /**
40
+ * Check if request is allowed for the given key
41
+ *
42
+ * @param key - Identifier (client ID, IP, etc.)
43
+ * @returns true if allowed, false if rate limited
44
+ */
45
+ checkLimit(key: string): boolean;
46
+ /**
47
+ * Remove all keys with no active requests in the current window.
48
+ * Called automatically every PURGE_EVERY_N_OPS operations.
49
+ */
50
+ purgeExpiredKeys(): number;
51
+ /**
52
+ * Wait until request slot is available (with exponential backoff)
53
+ *
54
+ * @param key - Identifier (client ID, IP, etc.)
55
+ * @throws Error if max wait time exceeded (defaults to windowMs)
56
+ */
57
+ waitForSlot(key: string): Promise<void>;
58
+ /**
59
+ * Get current request count for a key
60
+ */
61
+ getCurrentCount(key: string): number;
62
+ /**
63
+ * Get remaining requests for a key
64
+ */
65
+ getRemainingRequests(key: string): number;
66
+ /**
67
+ * Get time until next slot is available (in ms)
68
+ * Returns 0 if a slot is available now
69
+ */
70
+ getTimeUntilSlot(key: string): number;
71
+ /**
72
+ * Clear rate limit history for a key
73
+ */
74
+ clear(key: string): void;
75
+ /**
76
+ * Clear all rate limit history
77
+ */
78
+ clearAll(): void;
79
+ /**
80
+ * Get metrics for monitoring
81
+ */
82
+ getMetrics(): {
83
+ keys: number;
84
+ totalRequests: number;
85
+ };
86
+ }
87
+ //# sourceMappingURL=rate-limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limiter.d.ts","sourceRoot":"","sources":["../../../src/src/concurrency/rate-limiter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,aAAa,CAA+B;IACpD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,wBAAwB,CAAK;IACrC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAQ;gBAErC,OAAO,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE;IAK9D;;;;;OAKG;IACH,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IA+BhC;;;OAGG;IACH,gBAAgB,IAAI,MAAM;IAgB1B;;;;;OAKG;IACG,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAmB7C;;OAEG;IACH,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAMpC;;OAEG;IACH,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAIzC;;;OAGG;IACH,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAcrC;;OAEG;IACH,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIxB;;OAEG;IACH,QAAQ,IAAI,IAAI;IAIhB;;OAEG;IACH,UAAU,IAAI;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM,CAAA;KAAE;CAetD"}
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Rate Limiter
3
+ *
4
+ * Sliding window rate limiter for per-client request throttling.
5
+ * Prevents server overload by limiting requests per time window.
6
+ *
7
+ * @module lib/server/rate-limiter
8
+ */
9
+ /**
10
+ * Sliding window rate limiter
11
+ *
12
+ * Features:
13
+ * - Per-key rate limiting (client ID, IP, etc.)
14
+ * - Sliding window for smooth rate enforcement
15
+ * - Automatic cleanup of old timestamps
16
+ * - Backoff waiting when limit exceeded
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * const limiter = new RateLimiter({ maxRequests: 100, windowMs: 60000 });
21
+ *
22
+ * if (await limiter.checkLimit("client-123")) {
23
+ * // Execute request
24
+ * } else {
25
+ * // Rate limited
26
+ * }
27
+ * ```
28
+ */
29
+ export class RateLimiter {
30
+ requestCounts = new Map();
31
+ windowMs;
32
+ maxRequests;
33
+ operationsSinceLastPurge = 0;
34
+ static PURGE_EVERY_N_OPS = 1000;
35
+ constructor(options) {
36
+ this.maxRequests = options.maxRequests;
37
+ this.windowMs = options.windowMs;
38
+ }
39
+ /**
40
+ * Check if request is allowed for the given key
41
+ *
42
+ * @param key - Identifier (client ID, IP, etc.)
43
+ * @returns true if allowed, false if rate limited
44
+ */
45
+ checkLimit(key) {
46
+ const now = Date.now();
47
+ const requests = this.requestCounts.get(key) || [];
48
+ // Remove old requests outside the sliding window
49
+ const validRequests = requests.filter((time) => now - time < this.windowMs);
50
+ if (validRequests.length === 0) {
51
+ // No active requests for this key — remove from map to prevent unbounded growth
52
+ this.requestCounts.delete(key);
53
+ }
54
+ if (validRequests.length >= this.maxRequests) {
55
+ // Update with cleaned list
56
+ this.requestCounts.set(key, validRequests);
57
+ return false;
58
+ }
59
+ // Add current request timestamp
60
+ validRequests.push(now);
61
+ this.requestCounts.set(key, validRequests);
62
+ // Periodic full purge to catch keys that haven't been checked recently
63
+ this.operationsSinceLastPurge++;
64
+ if (this.operationsSinceLastPurge >= RateLimiter.PURGE_EVERY_N_OPS) {
65
+ this.purgeExpiredKeys();
66
+ }
67
+ return true;
68
+ }
69
+ /**
70
+ * Remove all keys with no active requests in the current window.
71
+ * Called automatically every PURGE_EVERY_N_OPS operations.
72
+ */
73
+ purgeExpiredKeys() {
74
+ const now = Date.now();
75
+ let purged = 0;
76
+ for (const [key, requests] of this.requestCounts) {
77
+ const active = requests.filter((time) => now - time < this.windowMs);
78
+ if (active.length === 0) {
79
+ this.requestCounts.delete(key);
80
+ purged++;
81
+ }
82
+ else {
83
+ this.requestCounts.set(key, active);
84
+ }
85
+ }
86
+ this.operationsSinceLastPurge = 0;
87
+ return purged;
88
+ }
89
+ /**
90
+ * Wait until request slot is available (with exponential backoff)
91
+ *
92
+ * @param key - Identifier (client ID, IP, etc.)
93
+ * @throws Error if max wait time exceeded (defaults to windowMs)
94
+ */
95
+ async waitForSlot(key) {
96
+ let retries = 0;
97
+ const baseDelay = 100;
98
+ const maxWaitMs = this.windowMs;
99
+ const startTime = Date.now();
100
+ while (!this.checkLimit(key)) {
101
+ if (Date.now() - startTime >= maxWaitMs) {
102
+ throw new Error(`Rate limit wait timeout: waited ${maxWaitMs}ms for key "${key}"`);
103
+ }
104
+ // Exponential backoff: 100ms, 200ms, 400ms, 800ms, cap at 1000ms
105
+ const delay = Math.min(baseDelay * Math.pow(2, retries), 1000);
106
+ await new Promise((resolve) => setTimeout(resolve, delay));
107
+ retries++;
108
+ }
109
+ }
110
+ /**
111
+ * Get current request count for a key
112
+ */
113
+ getCurrentCount(key) {
114
+ const now = Date.now();
115
+ const requests = this.requestCounts.get(key) || [];
116
+ return requests.filter((time) => now - time < this.windowMs).length;
117
+ }
118
+ /**
119
+ * Get remaining requests for a key
120
+ */
121
+ getRemainingRequests(key) {
122
+ return Math.max(0, this.maxRequests - this.getCurrentCount(key));
123
+ }
124
+ /**
125
+ * Get time until next slot is available (in ms)
126
+ * Returns 0 if a slot is available now
127
+ */
128
+ getTimeUntilSlot(key) {
129
+ const now = Date.now();
130
+ const requests = this.requestCounts.get(key) || [];
131
+ const validRequests = requests.filter((time) => now - time < this.windowMs);
132
+ if (validRequests.length < this.maxRequests) {
133
+ return 0;
134
+ }
135
+ // Find oldest request in window - when it expires, a slot opens
136
+ const oldest = Math.min(...validRequests);
137
+ return Math.max(0, oldest + this.windowMs - now);
138
+ }
139
+ /**
140
+ * Clear rate limit history for a key
141
+ */
142
+ clear(key) {
143
+ this.requestCounts.delete(key);
144
+ }
145
+ /**
146
+ * Clear all rate limit history
147
+ */
148
+ clearAll() {
149
+ this.requestCounts.clear();
150
+ }
151
+ /**
152
+ * Get metrics for monitoring
153
+ */
154
+ getMetrics() {
155
+ let totalRequests = 0;
156
+ const now = Date.now();
157
+ for (const requests of this.requestCounts.values()) {
158
+ totalRequests += requests.filter((time) => now - time < this.windowMs).length;
159
+ }
160
+ return {
161
+ keys: this.requestCounts.size,
162
+ totalRequests,
163
+ };
164
+ }
165
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Request Queue with Concurrency Control and Backpressure
3
+ *
4
+ * Limits the number of concurrent requests to prevent resource exhaustion
5
+ * and implements backpressure strategies when at capacity.
6
+ *
7
+ * @module lib/server/request-queue
8
+ */
9
+ import type { QueueMetrics, QueueOptions } from "../types.js";
10
+ /**
11
+ * RequestQueue manages concurrent request execution with backpressure
12
+ *
13
+ * Features:
14
+ * - Limits max concurrent requests (default: 10)
15
+ * - Multiple backpressure strategies: sleep, queue, reject
16
+ * - Metrics for monitoring (inFlight, queued)
17
+ * - Graceful degradation under load
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const queue = new RequestQueue({
22
+ * maxConcurrent: 5,
23
+ * strategy: 'queue',
24
+ * sleepMs: 10
25
+ * });
26
+ *
27
+ * await queue.acquire();
28
+ * try {
29
+ * // Execute request
30
+ * } finally {
31
+ * queue.release();
32
+ * }
33
+ * ```
34
+ */
35
+ export declare class RequestQueue {
36
+ private inFlight;
37
+ private maxConcurrent;
38
+ private strategy;
39
+ private sleepMs;
40
+ private waitQueue;
41
+ constructor(options: QueueOptions);
42
+ /**
43
+ * Acquire a slot for request execution
44
+ * Blocks until a slot is available based on backpressure strategy
45
+ *
46
+ * @throws {Error} If strategy is 'reject' and queue is at capacity
47
+ */
48
+ acquire(): Promise<void>;
49
+ /**
50
+ * Release a slot after request completion
51
+ * Notifies next waiting request if using queue strategy
52
+ */
53
+ release(): void;
54
+ /**
55
+ * Get current queue metrics for monitoring
56
+ */
57
+ getMetrics(): QueueMetrics;
58
+ /**
59
+ * Check if queue is at capacity
60
+ */
61
+ isAtCapacity(): boolean;
62
+ /**
63
+ * Get current in-flight request count
64
+ */
65
+ getInFlight(): number;
66
+ /**
67
+ * Get current queued request count
68
+ */
69
+ getQueued(): number;
70
+ }
71
+ //# sourceMappingURL=request-queue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-queue.d.ts","sourceRoot":"","sources":["../../../src/src/concurrency/request-queue.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAA+B;IAC/C,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,SAAS,CAAyB;gBAE9B,OAAO,EAAE,YAAY;IAMjC;;;;;OAKG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAsC9B;;;OAGG;IACH,OAAO,IAAI,IAAI;IAYf;;OAEG;IACH,UAAU,IAAI,YAAY;IAO1B;;OAEG;IACH,YAAY,IAAI,OAAO;IAIvB;;OAEG;IACH,WAAW,IAAI,MAAM;IAIrB;;OAEG;IACH,SAAS,IAAI,MAAM;CAGpB"}
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Request Queue with Concurrency Control and Backpressure
3
+ *
4
+ * Limits the number of concurrent requests to prevent resource exhaustion
5
+ * and implements backpressure strategies when at capacity.
6
+ *
7
+ * @module lib/server/request-queue
8
+ */
9
+ /**
10
+ * RequestQueue manages concurrent request execution with backpressure
11
+ *
12
+ * Features:
13
+ * - Limits max concurrent requests (default: 10)
14
+ * - Multiple backpressure strategies: sleep, queue, reject
15
+ * - Metrics for monitoring (inFlight, queued)
16
+ * - Graceful degradation under load
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * const queue = new RequestQueue({
21
+ * maxConcurrent: 5,
22
+ * strategy: 'queue',
23
+ * sleepMs: 10
24
+ * });
25
+ *
26
+ * await queue.acquire();
27
+ * try {
28
+ * // Execute request
29
+ * } finally {
30
+ * queue.release();
31
+ * }
32
+ * ```
33
+ */
34
+ export class RequestQueue {
35
+ inFlight = 0;
36
+ maxConcurrent;
37
+ strategy;
38
+ sleepMs;
39
+ waitQueue = [];
40
+ constructor(options) {
41
+ this.maxConcurrent = options.maxConcurrent;
42
+ this.strategy = options.strategy;
43
+ this.sleepMs = options.sleepMs;
44
+ }
45
+ /**
46
+ * Acquire a slot for request execution
47
+ * Blocks until a slot is available based on backpressure strategy
48
+ *
49
+ * @throws {Error} If strategy is 'reject' and queue is at capacity
50
+ */
51
+ async acquire() {
52
+ if (this.strategy === "reject") {
53
+ // Fail fast - reject immediately if at capacity
54
+ if (this.inFlight >= this.maxConcurrent) {
55
+ throw new Error(`Server at capacity (${this.maxConcurrent} concurrent requests)`);
56
+ }
57
+ this.inFlight++;
58
+ return;
59
+ }
60
+ if (this.strategy === "queue") {
61
+ // Queue-based backpressure - wait in FIFO queue.
62
+ // Claim the slot BEFORE awaiting to prevent TOCTOU race:
63
+ // without this, two waiters woken back-to-back could both see
64
+ // inFlight < maxConcurrent and both increment past the limit.
65
+ if (this.inFlight >= this.maxConcurrent) {
66
+ await new Promise((resolve) => {
67
+ this.waitQueue.push(resolve);
68
+ });
69
+ // Slot was pre-claimed by release() before waking us
70
+ }
71
+ else {
72
+ this.inFlight++;
73
+ }
74
+ return;
75
+ }
76
+ // Sleep-based backpressure (default) - busy-wait with sleep.
77
+ // The check + increment is safe here because JS is single-threaded
78
+ // for synchronous code: after the while loop exits, no other code
79
+ // runs before inFlight++ (no await between check and increment).
80
+ while (this.inFlight >= this.maxConcurrent) {
81
+ await new Promise((resolve) => setTimeout(resolve, this.sleepMs));
82
+ }
83
+ this.inFlight++;
84
+ }
85
+ /**
86
+ * Release a slot after request completion
87
+ * Notifies next waiting request if using queue strategy
88
+ */
89
+ release() {
90
+ if (this.strategy === "queue" && this.waitQueue.length > 0) {
91
+ // Transfer the slot directly to the next waiter without decrementing.
92
+ // This prevents the TOCTOU race: the waiter wakes up with
93
+ // the slot already claimed (inFlight unchanged).
94
+ const next = this.waitQueue.shift();
95
+ next();
96
+ }
97
+ else {
98
+ this.inFlight--;
99
+ }
100
+ }
101
+ /**
102
+ * Get current queue metrics for monitoring
103
+ */
104
+ getMetrics() {
105
+ return {
106
+ inFlight: this.inFlight,
107
+ queued: this.waitQueue.length,
108
+ };
109
+ }
110
+ /**
111
+ * Check if queue is at capacity
112
+ */
113
+ isAtCapacity() {
114
+ return this.inFlight >= this.maxConcurrent;
115
+ }
116
+ /**
117
+ * Get current in-flight request count
118
+ */
119
+ getInFlight() {
120
+ return this.inFlight;
121
+ }
122
+ /**
123
+ * Get current queued request count
124
+ */
125
+ getQueued() {
126
+ return this.waitQueue.length;
127
+ }
128
+ }