@forinda/kickjs 10.4.0 → 10.6.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 (209) hide show
  1. package/dist/{adapter-BZ1WzN1z.d.mts → adapter-9sPr_5xt.d.mts} +123 -35
  2. package/dist/adapter-9sPr_5xt.d.mts.map +1 -0
  3. package/dist/{allowed-hosts-D6qcuK5I.d.mts → allowed-hosts-BpKwviq5.d.mts} +3 -3
  4. package/dist/allowed-hosts-BpKwviq5.d.mts.map +1 -0
  5. package/dist/{application-D5Iiy7rt.d.mts → application-BD9LQ2s4.d.mts} +83 -43
  6. package/dist/application-BD9LQ2s4.d.mts.map +1 -0
  7. package/dist/application-DwYTFctU.mjs +14 -0
  8. package/dist/application-DwYTFctU.mjs.map +1 -0
  9. package/dist/background-DSztbyc4.mjs +12 -0
  10. package/dist/background-DSztbyc4.mjs.map +1 -0
  11. package/dist/bootstrap-DdTHtS8P.mjs +12 -0
  12. package/dist/{bootstrap-B_sGJNSz.mjs.map → bootstrap-DdTHtS8P.mjs.map} +1 -1
  13. package/dist/{bounded-counters-DS-IbDW9.mjs → bounded-counters-Bd7X3eI5.mjs} +2 -2
  14. package/dist/{bounded-counters-DS-IbDW9.mjs.map → bounded-counters-Bd7X3eI5.mjs.map} +1 -1
  15. package/dist/{breach-padding-C-Dnq8CS.d.mts → breach-padding-FBVGmcBb.d.mts} +3 -3
  16. package/dist/breach-padding-FBVGmcBb.d.mts.map +1 -0
  17. package/dist/{client-ip-BLkoQTIR.mjs → client-ip-DxEVqZP-.mjs} +2 -2
  18. package/dist/{client-ip-BLkoQTIR.mjs.map → client-ip-DxEVqZP-.mjs.map} +1 -1
  19. package/dist/config/index.mjs +2 -2
  20. package/dist/{config-B6EeAw4P.mjs → config-_YTqZtnE.mjs} +3 -3
  21. package/dist/{config-B6EeAw4P.mjs.map → config-_YTqZtnE.mjs.map} +1 -1
  22. package/dist/connect-BlIamapT.d.mts +41 -0
  23. package/dist/connect-BlIamapT.d.mts.map +1 -0
  24. package/dist/context-UaQ6cv0K.mjs +12 -0
  25. package/dist/context-UaQ6cv0K.mjs.map +1 -0
  26. package/dist/{context-errors-CR5NCXfl.mjs → context-errors-DcPmDybm.mjs} +2 -2
  27. package/dist/{context-errors-CR5NCXfl.mjs.map → context-errors-DcPmDybm.mjs.map} +1 -1
  28. package/dist/{contributor-runner--ofCRZ0d.mjs → contributor-runner-BHjr6qSE.mjs} +3 -3
  29. package/dist/{contributor-runner--ofCRZ0d.mjs.map → contributor-runner-BHjr6qSE.mjs.map} +1 -1
  30. package/dist/core/adapter.d.mts +1 -1
  31. package/dist/core/adapter.mjs +1 -1
  32. package/dist/core/app-module.mjs +1 -1
  33. package/dist/core/cache.mjs +1 -1
  34. package/dist/core/container.mjs +2 -2
  35. package/dist/core/cron.mjs +2 -2
  36. package/dist/core/decorators.mjs +2 -2
  37. package/dist/core/errors.mjs +1 -1
  38. package/dist/core/interfaces.mjs +1 -1
  39. package/dist/core/logger.mjs +1 -1
  40. package/dist/core/path.mjs +1 -1
  41. package/dist/core/plugin.d.mts +1 -1
  42. package/dist/core/plugin.mjs +1 -1
  43. package/dist/core/reactivity.mjs +1 -1
  44. package/dist/core-Ddq8b9hi.mjs +12 -0
  45. package/dist/{core-CsMDdzNE.mjs.map → core-Ddq8b9hi.mjs.map} +1 -1
  46. package/dist/{cors-2Bwhyhpt.d.mts → cors-BlR_b0Qb.d.mts} +3 -3
  47. package/dist/cors-BlR_b0Qb.d.mts.map +1 -0
  48. package/dist/{csrf-BDAZK2mm.d.mts → csrf-ZFOrJZhJ.d.mts} +3 -3
  49. package/dist/csrf-ZFOrJZhJ.d.mts.map +1 -0
  50. package/dist/decorate-wrAUzCjW.mjs +13 -0
  51. package/dist/{decorate-CLeX6hbL.mjs.map → decorate-wrAUzCjW.mjs.map} +1 -1
  52. package/dist/{define-adapter-RbKRSG3i.mjs → define-adapter-Ce1FDvEo.mjs} +2 -2
  53. package/dist/{define-adapter-RbKRSG3i.mjs.map → define-adapter-Ce1FDvEo.mjs.map} +1 -1
  54. package/dist/{di-hooks-CiNaIu12.mjs → di-hooks-MFthA-Fs.mjs} +9 -4
  55. package/dist/di-hooks-MFthA-Fs.mjs.map +1 -0
  56. package/dist/{disposables-DYTkgNiG.mjs → disposables-BgUIg4s1.mjs} +1 -1
  57. package/dist/{error-handler-CbP7hKdJ.d.mts → error-handler-CH4PPZCK.d.mts} +2 -2
  58. package/dist/{error-handler-CbP7hKdJ.d.mts.map → error-handler-CH4PPZCK.d.mts.map} +1 -1
  59. package/dist/express-BcfJgvBP.mjs +12 -0
  60. package/dist/express-BcfJgvBP.mjs.map +1 -0
  61. package/dist/express-lazy-DCYWtKZx.mjs +12 -0
  62. package/dist/express-lazy-DCYWtKZx.mjs.map +1 -0
  63. package/dist/handler-CS1BhG0C.mjs +12 -0
  64. package/dist/{handler-Cw4mr3ls.mjs.map → handler-CS1BhG0C.mjs.map} +1 -1
  65. package/dist/{helmet-CEOmo516.d.mts → helmet-BVuVBl-D.d.mts} +3 -3
  66. package/dist/helmet-BVuVBl-D.d.mts.map +1 -0
  67. package/dist/{host-H7CIkHNB.mjs → host-lMSIGnh7.mjs} +2 -2
  68. package/dist/{host-H7CIkHNB.mjs.map → host-lMSIGnh7.mjs.map} +1 -1
  69. package/dist/http/application.d.mts +2 -2
  70. package/dist/http/application.mjs +2 -2
  71. package/dist/http/bootstrap.d.mts +1 -1
  72. package/dist/http/bootstrap.mjs +2 -2
  73. package/dist/http/context.d.mts +1 -1
  74. package/dist/http/context.mjs +2 -2
  75. package/dist/http/middleware/allowed-hosts.d.mts +1 -1
  76. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  77. package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
  78. package/dist/http/middleware/breach-padding.d.mts +1 -1
  79. package/dist/http/middleware/breach-padding.mjs +1 -1
  80. package/dist/http/middleware/breach-padding.mjs.map +1 -1
  81. package/dist/http/middleware/cors.d.mts +1 -1
  82. package/dist/http/middleware/cors.mjs +1 -1
  83. package/dist/http/middleware/cors.mjs.map +1 -1
  84. package/dist/http/middleware/csrf.d.mts +1 -1
  85. package/dist/http/middleware/csrf.mjs +2 -2
  86. package/dist/http/middleware/csrf.mjs.map +1 -1
  87. package/dist/http/middleware/error-handler.d.mts +1 -1
  88. package/dist/http/middleware/error-handler.mjs +2 -2
  89. package/dist/http/middleware/helmet.d.mts +1 -1
  90. package/dist/http/middleware/helmet.mjs +1 -1
  91. package/dist/http/middleware/helmet.mjs.map +1 -1
  92. package/dist/http/middleware/rate-limit.d.mts +1 -1
  93. package/dist/http/middleware/rate-limit.mjs +2 -2
  94. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  95. package/dist/http/middleware/request-id.d.mts +1 -1
  96. package/dist/http/middleware/request-id.mjs +1 -1
  97. package/dist/http/middleware/request-id.mjs.map +1 -1
  98. package/dist/http/middleware/request-logger.mjs +2 -2
  99. package/dist/http/middleware/session.d.mts +1 -1
  100. package/dist/http/middleware/session.mjs +2 -2
  101. package/dist/http/middleware/session.mjs.map +1 -1
  102. package/dist/http/middleware/spa.d.mts +1 -1
  103. package/dist/http/middleware/spa.mjs +2 -2
  104. package/dist/http/middleware/upload.d.mts +3 -2
  105. package/dist/http/middleware/upload.mjs +2 -2
  106. package/dist/http/middleware/upload.mjs.map +1 -1
  107. package/dist/http/middleware/validate.d.mts +1 -1
  108. package/dist/http/middleware/validate.mjs +1 -1
  109. package/dist/http/middleware/validate.mjs.map +1 -1
  110. package/dist/http/middleware/views.d.mts +1 -1
  111. package/dist/http/middleware/views.mjs +2 -2
  112. package/dist/http/middleware/views.mjs.map +1 -1
  113. package/dist/http/query/index.mjs +2 -2
  114. package/dist/http/router-builder.d.mts +1 -1
  115. package/dist/http/router-builder.mjs +2 -2
  116. package/dist/http/runtimes/express.d.mts +47 -0
  117. package/dist/http/runtimes/express.d.mts.map +1 -0
  118. package/dist/http/runtimes/express.mjs +11 -0
  119. package/dist/http/runtimes/fastify.d.mts +1 -1
  120. package/dist/http/runtimes/fastify.mjs +2 -2
  121. package/dist/http/runtimes/fastify.mjs.map +1 -1
  122. package/dist/http/runtimes/h3-web.mjs +1 -1
  123. package/dist/http/runtimes/h3.d.mts +1 -1
  124. package/dist/http/runtimes/h3.mjs +2 -2
  125. package/dist/index.d.mts +17 -16
  126. package/dist/index.mjs +3 -3
  127. package/dist/index.mjs.map +1 -1
  128. package/dist/{is-production-BTroGhp5.mjs → is-production-MYGnN2Nv.mjs} +2 -2
  129. package/dist/{is-production-BTroGhp5.mjs.map → is-production-MYGnN2Nv.mjs.map} +1 -1
  130. package/dist/{jobs-xqoMmdr4.mjs → jobs-ANHUk_Ht.mjs} +3 -3
  131. package/dist/{jobs-xqoMmdr4.mjs.map → jobs-ANHUk_Ht.mjs.map} +1 -1
  132. package/dist/{kv-stores-DXFBEYYu.d.mts → kv-stores-C1sQs2Rb.d.mts} +4 -4
  133. package/dist/{kv-stores-DXFBEYYu.d.mts.map → kv-stores-C1sQs2Rb.d.mts.map} +1 -1
  134. package/dist/{kv-stores-0-6blGzh.mjs → kv-stores-Cro8JwAF.mjs} +3 -3
  135. package/dist/{kv-stores-0-6blGzh.mjs.map → kv-stores-Cro8JwAF.mjs.map} +1 -1
  136. package/dist/lazy-serve-static-Zge6_pKo.mjs +12 -0
  137. package/dist/lazy-serve-static-Zge6_pKo.mjs.map +1 -0
  138. package/dist/{metadata-Bm65Y-5O.mjs → metadata-_LqQme8p.mjs} +1 -1
  139. package/dist/{observers-BAXkwMx0.mjs → observers-Oedvuzit.mjs} +2 -2
  140. package/dist/{observers-BAXkwMx0.mjs.map → observers-Oedvuzit.mjs.map} +1 -1
  141. package/dist/precompressed-B6wz_5tz.mjs +12 -0
  142. package/dist/precompressed-B6wz_5tz.mjs.map +1 -0
  143. package/dist/{query-CGyw7vNi.mjs → query-KMR84Kwu.mjs} +2 -2
  144. package/dist/{query-CGyw7vNi.mjs.map → query-KMR84Kwu.mjs.map} +1 -1
  145. package/dist/{rate-limit-BgoeahE5.d.mts → rate-limit-DQDk6bAH.d.mts} +5 -5
  146. package/dist/rate-limit-DQDk6bAH.d.mts.map +1 -0
  147. package/dist/reply-BQTif5Iu.mjs +12 -0
  148. package/dist/reply-BQTif5Iu.mjs.map +1 -0
  149. package/dist/{request-id-CVzJ1uHD.d.mts → request-id-Dn64nEHK.d.mts} +3 -3
  150. package/dist/request-id-Dn64nEHK.d.mts.map +1 -0
  151. package/dist/request-scope-L71-nmRe.mjs +12 -0
  152. package/dist/request-scope-L71-nmRe.mjs.map +1 -0
  153. package/dist/{respond-BOlh-baJ.mjs → respond-DR7zkOUf.mjs} +2 -2
  154. package/dist/{respond-BOlh-baJ.mjs.map → respond-DR7zkOUf.mjs.map} +1 -1
  155. package/dist/rolldown-runtime-DouoOEDq.mjs +11 -0
  156. package/dist/{route-flag-BPSq2JCs.mjs → route-flag-DCOS_F5A.mjs} +3 -3
  157. package/dist/{route-flag-BPSq2JCs.mjs.map → route-flag-DCOS_F5A.mjs.map} +1 -1
  158. package/dist/{route-policy-DDszB6dQ.mjs → route-policy-Cy-oSUro.mjs} +2 -2
  159. package/dist/{route-policy-DDszB6dQ.mjs.map → route-policy-Cy-oSUro.mjs.map} +1 -1
  160. package/dist/{router-builder-BewIsj7V.d.mts → router-builder-BfbEdxew.d.mts} +2 -2
  161. package/dist/{router-builder-BewIsj7V.d.mts.map → router-builder-BfbEdxew.d.mts.map} +1 -1
  162. package/dist/{router-builder-DoaDAmK8.mjs → router-builder-U-kiHlqo.mjs} +3 -3
  163. package/dist/{router-builder-DoaDAmK8.mjs.map → router-builder-U-kiHlqo.mjs.map} +1 -1
  164. package/dist/{session-ChXx7jG5.d.mts → session-8uNRCplB.d.mts} +3 -3
  165. package/dist/session-8uNRCplB.d.mts.map +1 -0
  166. package/dist/{settings-CRkMOwcz.mjs → settings-CrEgdXc0.mjs} +3 -3
  167. package/dist/{settings-CRkMOwcz.mjs.map → settings-CrEgdXc0.mjs.map} +1 -1
  168. package/dist/{token-2CJq89za.mjs → token-B1FRPTVt.mjs} +1 -1
  169. package/dist/upload-Jgs9BFC4.d.mts +55 -0
  170. package/dist/upload-Jgs9BFC4.d.mts.map +1 -0
  171. package/dist/{upload-config-Be7w0Dfx.mjs → upload-config-DEnNEwL4.mjs} +2 -2
  172. package/dist/upload-config-DEnNEwL4.mjs.map +1 -0
  173. package/dist/{url-for-EQsmb3yi.mjs → url-for-CLtZIeYd.mjs} +3 -3
  174. package/dist/{url-for-EQsmb3yi.mjs.map → url-for-CLtZIeYd.mjs.map} +1 -1
  175. package/dist/{validate-CzjCbRUn.d.mts → validate-D4Poe2EE.d.mts} +3 -3
  176. package/dist/validate-D4Poe2EE.d.mts.map +1 -0
  177. package/dist/{web-crypto-G-m6c6w2.mjs → web-crypto-B6iM0yYx.mjs} +2 -2
  178. package/dist/{web-crypto-G-m6c6w2.mjs.map → web-crypto-B6iM0yYx.mjs.map} +1 -1
  179. package/dist/web.d.mts +3 -3
  180. package/dist/web.mjs +2 -2
  181. package/dist/web.mjs.map +1 -1
  182. package/package.json +9 -2
  183. package/dist/adapter-BZ1WzN1z.d.mts.map +0 -1
  184. package/dist/allowed-hosts-D6qcuK5I.d.mts.map +0 -1
  185. package/dist/application-Bs30gJF1.mjs +0 -14
  186. package/dist/application-Bs30gJF1.mjs.map +0 -1
  187. package/dist/application-D5Iiy7rt.d.mts.map +0 -1
  188. package/dist/bootstrap-B_sGJNSz.mjs +0 -12
  189. package/dist/breach-padding-C-Dnq8CS.d.mts.map +0 -1
  190. package/dist/context-CRJzl_Mj.mjs +0 -12
  191. package/dist/context-CRJzl_Mj.mjs.map +0 -1
  192. package/dist/core-CsMDdzNE.mjs +0 -12
  193. package/dist/cors-2Bwhyhpt.d.mts.map +0 -1
  194. package/dist/csrf-BDAZK2mm.d.mts.map +0 -1
  195. package/dist/decorate-CLeX6hbL.mjs +0 -13
  196. package/dist/di-hooks-CiNaIu12.mjs.map +0 -1
  197. package/dist/handler-Cw4mr3ls.mjs +0 -12
  198. package/dist/helmet-CEOmo516.d.mts.map +0 -1
  199. package/dist/lazy-serve-static-D94xvah5.mjs +0 -12
  200. package/dist/lazy-serve-static-D94xvah5.mjs.map +0 -1
  201. package/dist/rate-limit-BgoeahE5.d.mts.map +0 -1
  202. package/dist/reply-tlUaowib.mjs +0 -12
  203. package/dist/reply-tlUaowib.mjs.map +0 -1
  204. package/dist/request-id-CVzJ1uHD.d.mts.map +0 -1
  205. package/dist/session-ChXx7jG5.d.mts.map +0 -1
  206. package/dist/upload-DkT2p1gd.d.mts +0 -104
  207. package/dist/upload-DkT2p1gd.d.mts.map +0 -1
  208. package/dist/upload-config-Be7w0Dfx.mjs.map +0 -1
  209. package/dist/validate-CzjCbRUn.d.mts.map +0 -1
@@ -1,5 +1,5 @@
1
1
 
2
- import { NextFunction, Request, Response } from "express";
2
+ import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-BlIamapT.mjs";
3
3
  //#region src/http/middleware/helmet.d.ts
4
4
  /** Brand identifying a `helmet()` handler, so auto-injection can stand down. */
5
5
  declare const HELMET_MIDDLEWARE: unique symbol;
@@ -39,7 +39,7 @@ interface HelmetOptions {
39
39
  * Options are read once, when the middleware is created: changing the options
40
40
  * object afterwards does not change the headers. Create a new middleware instead.
41
41
  */
42
- declare function helmet(options?: HelmetOptions): (req: Request, res: Response, next: NextFunction) => void;
42
+ declare function helmet(options?: HelmetOptions): (req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => void;
43
43
  //#endregion
44
44
  export { HelmetOptions as n, helmet as r, HELMET_MIDDLEWARE as t };
45
- //# sourceMappingURL=helmet-CEOmo516.d.mts.map
45
+ //# sourceMappingURL=helmet-BVuVBl-D.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helmet-BVuVBl-D.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/helmet.ts"],"mappings":";;;;cAOa;UAEI;;EAEf,kCAAkC;;EAElC;;EAEA;;EAEA;IAAiB;IAAiB;IAA6B;;;EAE/D;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;iBAiBc,OAAO,UAAS,iBAAkB,KA0B1BA,gBAAO,KAAOC,iBAAQ,MAAQC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  function parseHttpUrl(value){try{let url=new URL(value);return url.protocol===`http:`||url.protocol===`https:`?url:void 0}catch{return}}const HOST_GRAMMAR=/^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::\d{1,5})?$/;function canonicalHost(host,protocol){if(host&&HOST_GRAMMAR.test(host))return parseHttpUrl(`${protocol}//${host}`)?.host}export{canonicalHost as n,parseHttpUrl as r,HOST_GRAMMAR as t};
12
- //# sourceMappingURL=host-H7CIkHNB.mjs.map
12
+ //# sourceMappingURL=host-lMSIGnh7.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"host-H7CIkHNB.mjs","names":[],"sources":["../src/http/host.ts"],"sourcesContent":["/**\n * Host header parsing shared by the middleware that trusts it (CSRF origin\n * check, allowed hosts). One grammar and one canonical form, so two checks\n * never disagree about what host a request named.\n *\n * @module @forinda/kickjs/http/host\n */\n\n/** An http(s) URL, or undefined for anything else (`null`, `file:`, garbage). */\nexport function parseHttpUrl(value: string): URL | undefined {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * RFC 9110 `Host`: a hostname or bracketed IPv6 literal, optional port. Checked\n * before parsing, so the URL parser never sees userinfo, a path or whitespace —\n * `x@a.test` would otherwise parse to the host `a.test`.\n */\nexport const HOST_GRAMMAR = /^(?:[A-Za-z0-9.-]+|\\[[0-9A-Fa-f:.]+\\])(?::\\d{1,5})?$/\n\n/**\n * The request's host, canonicalized the way `URL` canonicalizes the origin it\n * is compared with (case, IDN, default port for that scheme) — comparing two\n * strings parsed by different rules is how checks like this get bypassed.\n */\nexport function canonicalHost(host: string | undefined, protocol: string): string | undefined {\n if (!host || !HOST_GRAMMAR.test(host)) return undefined\n return parseHttpUrl(`${protocol}//${host}`)?.host\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,aAAa,MAAgC,CAC3D,GAAI,CACF,IAAM,IAAM,IAAI,IAAI,KAAK,EACzB,OAAO,IAAI,WAAa,SAAW,IAAI,WAAa,SAAW,IAAM,IAAA,EACvE,MAAQ,CACN,MACF,CACF,CAOA,MAAa,aAAe,uDAO5B,SAAgB,cAAc,KAA0B,SAAsC,CAC5F,GAAK,MAAS,aAAa,KAAK,IAAI,EACpC,OAAO,aAAa,GAAG,SAAS,IAAI,MAAM,CAAC,EAAE,IAC/C"}
1
+ {"version":3,"file":"host-lMSIGnh7.mjs","names":[],"sources":["../src/http/host.ts"],"sourcesContent":["/**\n * Host header parsing shared by the middleware that trusts it (CSRF origin\n * check, allowed hosts). One grammar and one canonical form, so two checks\n * never disagree about what host a request named.\n *\n * @module @forinda/kickjs/http/host\n */\n\n/** An http(s) URL, or undefined for anything else (`null`, `file:`, garbage). */\nexport function parseHttpUrl(value: string): URL | undefined {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * RFC 9110 `Host`: a hostname or bracketed IPv6 literal, optional port. Checked\n * before parsing, so the URL parser never sees userinfo, a path or whitespace —\n * `x@a.test` would otherwise parse to the host `a.test`.\n */\nexport const HOST_GRAMMAR = /^(?:[A-Za-z0-9.-]+|\\[[0-9A-Fa-f:.]+\\])(?::\\d{1,5})?$/\n\n/**\n * The request's host, canonicalized the way `URL` canonicalizes the origin it\n * is compared with (case, IDN, default port for that scheme) — comparing two\n * strings parsed by different rules is how checks like this get bypassed.\n */\nexport function canonicalHost(host: string | undefined, protocol: string): string | undefined {\n if (!host || !HOST_GRAMMAR.test(host)) return undefined\n return parseHttpUrl(`${protocol}//${host}`)?.host\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,aAAa,MAAgC,CAC3D,GAAI,CACF,IAAM,IAAM,IAAI,IAAI,KAAK,EACzB,OAAO,IAAI,WAAa,SAAW,IAAI,WAAa,SAAW,IAAM,IAAA,EACvE,MAAQ,CACN,MACF,CACF,CAOA,MAAa,aAAe,uDAO5B,SAAgB,cAAc,KAA0B,SAAsC,CAC5F,GAAK,MAAS,aAAa,KAAK,IAAI,EACpC,OAAO,aAAa,GAAG,SAAS,IAAI,MAAM,CAAC,EAAE,IAC/C"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as ConfigOrigins, c as ServerOptions, i as ConfigDescription, l as ShutdownOptions, n as Application, o as MiddlewareEntry, r as ApplicationOptions, s as MountedRouteInfo, t as APPLICATION } from "../application-D5Iiy7rt.mjs";
3
- export { APPLICATION, Application, ApplicationOptions, ConfigDescription, ConfigOrigins, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions };
2
+ import { a as ConfigOrigins, c as MountedRouteInfo, i as ConfigDescription, l as ServerOptions, n as Application, o as ManagementOptions, r as ApplicationOptions, s as MiddlewareEntry, t as APPLICATION, u as ShutdownOptions } from "../application-BD9LQ2s4.mjs";
3
+ export { APPLICATION, Application, ApplicationOptions, ConfigDescription, ConfigOrigins, ManagementOptions, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as APPLICATION,n as Application}from"../application-Bs30gJF1.mjs";
11
+ export{t as APPLICATION,n as Application}from"../application-DwYTFctU.mjs";
@@ -1,3 +1,3 @@
1
1
 
2
- import { Z as bootstrap } from "../application-D5Iiy7rt.mjs";
2
+ import { Q as bootstrap } from "../application-BD9LQ2s4.mjs";
3
3
  export { bootstrap };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as bootstrap}from"../bootstrap-B_sGJNSz.mjs";
11
+ export{t as bootstrap}from"../bootstrap-DdTHtS8P.mjs";
@@ -1,4 +1,4 @@
1
1
 
2
- import { A as SseHandler, D as DeepReadonly, E as Ctx, O as RequestContext, j as contentDisposition, k as RouteShape } from "../adapter-BZ1WzN1z.mjs";
2
+ import { D as RouteShape, E as RequestContext, O as SseHandler, T as DeepReadonly, k as contentDisposition, w as Ctx } from "../adapter-9sPr_5xt.mjs";
3
3
  import { b as ContextMeta } from "../app-module-Cuu-Ma_E.mjs";
4
4
  export { type ContextMeta, Ctx, DeepReadonly, RequestContext, RouteShape, SseHandler, contentDisposition };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as RequestContext,n as contentDisposition}from"../context-CRJzl_Mj.mjs";
11
+ export{t as RequestContext,n as contentDisposition}from"../context-UaQ6cv0K.mjs";
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as allowedHosts, t as AllowedHostsOptions } from "../../allowed-hosts-D6qcuK5I.mjs";
2
+ import { n as allowedHosts, t as AllowedHostsOptions } from "../../allowed-hosts-BpKwviq5.mjs";
3
3
  export { AllowedHostsOptions, allowedHosts };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{r as parseHttpUrl,t as HOST_GRAMMAR}from"../../host-H7CIkHNB.mjs";import{n as resolvePathname}from"../../client-ip-BLkoQTIR.mjs";import{i as sendJson}from"../../respond-BOlh-baJ.mjs";function headerOf(headers,name){let value=headers[name];return Array.isArray(value)?value[0]:value}function hostnameOf(host){if(host&&HOST_GRAMMAR.test(host))return parseHttpUrl(`http://${host}`)?.hostname}function compile(patterns){if(patterns.length===0)throw Error(`allowedHosts(): list at least one host`);if(patterns.includes(`*`))return()=>!0;let exact=/* @__PURE__ */ new Set,suffixes=[];for(let pattern of patterns){let wildcard=pattern.startsWith(`.`),hostname=hostnameOf(wildcard?pattern.slice(1):pattern);if(!hostname)throw Error(`allowedHosts(): '${pattern}' is not a host name`);wildcard?suffixes.push(hostname):exact.add(hostname)}return hostname=>exact.has(hostname)||suffixes.some(s=>hostname===s||hostname.endsWith(`.${s}`))}const REJECTED={type:`about:blank`,title:`Bad Request`,status:400,detail:`This host is not served here.`};function allowedHosts(options){let{hosts,trustForwardedHost=!1,ignorePaths=[]}=Array.isArray(options)?{hosts:options}:options,allowed=compile(hosts),ignored=new Set(ignorePaths);return(req,res,next)=>{let headers=req.headers,forwardedHeader=headerOf(headers,`x-forwarded-host`),candidates;if(trustForwardedHost&&forwardedHeader!==void 0?candidates=forwardedHeader.split(`,`).map(h=>h.trim()):(forwardedHeader!==void 0&&delete headers[`x-forwarded-host`],candidates=[headerOf(headers,`host`)??headerOf(headers,`:authority`)]),candidates.every(host=>{let hostname=hostnameOf(host);return hostname!==void 0&&allowed(hostname)}))return next();let method=req.method?.toUpperCase();if(ignored.size>0&&(method===`GET`||method===`HEAD`)&&ignored.has(resolvePathname(req)))return next();res.setHeader(`content-type`,`application/problem+json`),sendJson(res,400,REJECTED)}}export{allowedHosts};
11
+ import{r as parseHttpUrl,t as HOST_GRAMMAR}from"../../host-lMSIGnh7.mjs";import{n as resolvePathname}from"../../client-ip-DxEVqZP-.mjs";import{i as sendJson}from"../../respond-DR7zkOUf.mjs";function headerOf(headers,name){let value=headers[name];return Array.isArray(value)?value[0]:value}function hostnameOf(host){if(host&&HOST_GRAMMAR.test(host))return parseHttpUrl(`http://${host}`)?.hostname}function compile(patterns){if(patterns.length===0)throw Error(`allowedHosts(): list at least one host`);if(patterns.includes(`*`))return()=>!0;let exact=/* @__PURE__ */ new Set,suffixes=[];for(let pattern of patterns){let wildcard=pattern.startsWith(`.`),hostname=hostnameOf(wildcard?pattern.slice(1):pattern);if(!hostname)throw Error(`allowedHosts(): '${pattern}' is not a host name`);wildcard?suffixes.push(hostname):exact.add(hostname)}return hostname=>exact.has(hostname)||suffixes.some(s=>hostname===s||hostname.endsWith(`.${s}`))}const REJECTED={type:`about:blank`,title:`Bad Request`,status:400,detail:`This host is not served here.`};function allowedHosts(options){let{hosts,trustForwardedHost=!1,ignorePaths=[]}=Array.isArray(options)?{hosts:options}:options,allowed=compile(hosts),ignored=new Set(ignorePaths);return(req,res,next)=>{let headers=req.headers,forwardedHeader=headerOf(headers,`x-forwarded-host`),candidates;if(trustForwardedHost&&forwardedHeader!==void 0?candidates=forwardedHeader.split(`,`).map(h=>h.trim()):(forwardedHeader!==void 0&&delete headers[`x-forwarded-host`],candidates=[headerOf(headers,`host`)??headerOf(headers,`:authority`)]),candidates.every(host=>{let hostname=hostnameOf(host);return hostname!==void 0&&allowed(hostname)}))return next();let method=req.method?.toUpperCase();if(ignored.size>0&&(method===`GET`||method===`HEAD`)&&ignored.has(resolvePathname(req)))return next();res.setHeader(`content-type`,`application/problem+json`),sendJson(res,400,REJECTED)}}export{allowedHosts};
12
12
  //# sourceMappingURL=allowed-hosts.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"allowed-hosts.mjs","names":[],"sources":["../../../src/http/middleware/allowed-hosts.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport { HOST_GRAMMAR, parseHttpUrl } from '../host'\nimport { resolvePathname, type ClientRequestLike } from '../client-ip'\nimport { sendJson } from './respond'\n\nexport interface AllowedHostsOptions {\n /**\n * Hosts this app answers for. `'example.com'` matches exactly;\n * `'.example.com'` matches it and every subdomain; `'*'` matches anything\n * (turns the check off). Ports are ignored. Compared case-insensitively,\n * internationalized names in either form.\n */\n hosts: string[]\n /**\n * Read the host from `X-Forwarded-Host` instead of `Host`. Only behind a\n * proxy that sets it — a client can send the header too. Every value in it\n * must be allowed: a proxy that appends leaves the client's own value first,\n * and that first value is what Express's `req.hostname` reads.\n *\n * Without this option the header is removed from the request, so nothing\n * downstream (Express under `trust proxy`, your own code) reads a host this\n * check never saw. Default `false`.\n */\n trustForwardedHost?: boolean\n /**\n * Exact paths answered whatever the host, for `GET` and `HEAD` only — e.g.\n * probes that a platform sends to the instance's IP.\n * `bootstrap({ security: { allowedHosts } })` adds `/health/live` and\n * `/health/ready`.\n */\n ignorePaths?: string[]\n}\n\ntype HeaderBag = Record<string, string | string[] | undefined>\n\nfunction headerOf(headers: HeaderBag, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value[0] : value\n}\n\n/** The hostname a `Host`-shaped value names, canonical, or undefined if malformed. */\nfunction hostnameOf(host: string | undefined): string | undefined {\n if (!host || !HOST_GRAMMAR.test(host)) return undefined\n return parseHttpUrl(`http://${host}`)?.hostname\n}\n\nfunction compile(patterns: string[]): (hostname: string) => boolean {\n if (patterns.length === 0) throw new Error('allowedHosts(): list at least one host')\n if (patterns.includes('*')) return () => true\n const exact = new Set<string>()\n const suffixes: string[] = []\n for (const pattern of patterns) {\n const wildcard = pattern.startsWith('.')\n const hostname = hostnameOf(wildcard ? pattern.slice(1) : pattern)\n if (!hostname) {\n throw new Error(`allowedHosts(): '${pattern}' is not a host name`)\n }\n if (wildcard) suffixes.push(hostname)\n else exact.add(hostname)\n }\n return (hostname) =>\n exact.has(hostname) || suffixes.some((s) => hostname === s || hostname.endsWith(`.${s}`))\n}\n\nconst REJECTED = {\n type: 'about:blank',\n title: 'Bad Request',\n status: 400,\n // The host itself is not echoed: it is attacker-chosen text.\n detail: 'This host is not served here.',\n}\n\n/**\n * Refuse requests whose `Host` is not one this app serves.\n *\n * Code that builds absolute URLs from the request — password-reset and\n * verification links, redirects, `Location` headers — trusts `Host`, and a\n * client chooses it. Without a check, a reset email can carry a link to the\n * attacker's domain, and a shared cache can store a response built for it.\n *\n * ```ts\n * bootstrap({ security: { allowedHosts: ['example.com', '.example.com'] } })\n * ```\n */\nexport function allowedHosts(options: string[] | AllowedHostsOptions) {\n const {\n hosts,\n trustForwardedHost = false,\n ignorePaths = [],\n } = Array.isArray(options) ? { hosts: options } : options\n const allowed = compile(hosts)\n const ignored = new Set(ignorePaths)\n\n return (req: Request, res: Response, next: NextFunction) => {\n const headers = req.headers as HeaderBag\n // Check every host a consumer could read, not one chosen by a rule that a\n // consumer may not share — which value of a list wins differs between\n // proxies and frameworks.\n const forwardedHeader = headerOf(headers, 'x-forwarded-host')\n let candidates: Array<string | undefined>\n if (trustForwardedHost && forwardedHeader !== undefined) {\n candidates = forwardedHeader.split(',').map((h) => h.trim())\n } else {\n // Not trusted: drop it, so it can't be read past this point.\n if (forwardedHeader !== undefined) delete headers['x-forwarded-host']\n candidates = [headerOf(headers, 'host') ?? headerOf(headers, ':authority')]\n }\n const passes = candidates.every((host) => {\n const hostname = hostnameOf(host)\n return hostname !== undefined && allowed(hostname)\n })\n if (passes) return next()\n // Probes read; nothing that changes state is exempt.\n const method = req.method?.toUpperCase()\n if (\n ignored.size > 0 &&\n (method === 'GET' || method === 'HEAD') &&\n ignored.has(resolvePathname(req as ClientRequestLike))\n ) {\n return next()\n }\n\n res.setHeader('content-type', 'application/problem+json')\n sendJson(res, 400, REJECTED)\n }\n}\n"],"mappings":";;;;;;;;;;8LAmCA,SAAS,SAAS,QAAoB,KAAkC,CACtE,IAAM,MAAQ,QAAQ,MACtB,OAAO,MAAM,QAAQ,KAAK,EAAI,MAAM,GAAK,KAC3C,CAGA,SAAS,WAAW,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W,WAAW,IAAI,EAChC,OAAO,WAAa,IAAA,IAAa,QAAQ,QAAQ,CACnD,CACS,EAAG,OAAO,KAAK,EAExB,IAAM,OAAS,IAAI,QAAQ,YAAY,EACvC,GACE,QAAQ,KAAO,IACd,SAAW,OAAS,SAAW,SAChC,QAAQ,IAAI,gBAAgB,GAAwB,CAAC,EAErD,OAAO,KAAK,EAGd,IAAI,UAAU,eAAgB,0BAA0B,EACxD,SAAS,IAAK,IAAK,QAAQ,CAC7B,CACF"}
1
+ {"version":3,"file":"allowed-hosts.mjs","names":[],"sources":["../../../src/http/middleware/allowed-hosts.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\nimport { HOST_GRAMMAR, parseHttpUrl } from '../host'\nimport { resolvePathname, type ClientRequestLike } from '../client-ip'\nimport { sendJson } from './respond'\n\nexport interface AllowedHostsOptions {\n /**\n * Hosts this app answers for. `'example.com'` matches exactly;\n * `'.example.com'` matches it and every subdomain; `'*'` matches anything\n * (turns the check off). Ports are ignored. Compared case-insensitively,\n * internationalized names in either form.\n */\n hosts: string[]\n /**\n * Read the host from `X-Forwarded-Host` instead of `Host`. Only behind a\n * proxy that sets it — a client can send the header too. Every value in it\n * must be allowed: a proxy that appends leaves the client's own value first,\n * and that first value is what Express's `req.hostname` reads.\n *\n * Without this option the header is removed from the request, so nothing\n * downstream (Express under `trust proxy`, your own code) reads a host this\n * check never saw. Default `false`.\n */\n trustForwardedHost?: boolean\n /**\n * Exact paths answered whatever the host, for `GET` and `HEAD` only — e.g.\n * probes that a platform sends to the instance's IP.\n * `bootstrap({ security: { allowedHosts } })` adds `/health/live` and\n * `/health/ready`.\n */\n ignorePaths?: string[]\n}\n\ntype HeaderBag = Record<string, string | string[] | undefined>\n\nfunction headerOf(headers: HeaderBag, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value[0] : value\n}\n\n/** The hostname a `Host`-shaped value names, canonical, or undefined if malformed. */\nfunction hostnameOf(host: string | undefined): string | undefined {\n if (!host || !HOST_GRAMMAR.test(host)) return undefined\n return parseHttpUrl(`http://${host}`)?.hostname\n}\n\nfunction compile(patterns: string[]): (hostname: string) => boolean {\n if (patterns.length === 0) throw new Error('allowedHosts(): list at least one host')\n if (patterns.includes('*')) return () => true\n const exact = new Set<string>()\n const suffixes: string[] = []\n for (const pattern of patterns) {\n const wildcard = pattern.startsWith('.')\n const hostname = hostnameOf(wildcard ? pattern.slice(1) : pattern)\n if (!hostname) {\n throw new Error(`allowedHosts(): '${pattern}' is not a host name`)\n }\n if (wildcard) suffixes.push(hostname)\n else exact.add(hostname)\n }\n return (hostname) =>\n exact.has(hostname) || suffixes.some((s) => hostname === s || hostname.endsWith(`.${s}`))\n}\n\nconst REJECTED = {\n type: 'about:blank',\n title: 'Bad Request',\n status: 400,\n // The host itself is not echoed: it is attacker-chosen text.\n detail: 'This host is not served here.',\n}\n\n/**\n * Refuse requests whose `Host` is not one this app serves.\n *\n * Code that builds absolute URLs from the request — password-reset and\n * verification links, redirects, `Location` headers — trusts `Host`, and a\n * client chooses it. Without a check, a reset email can carry a link to the\n * attacker's domain, and a shared cache can store a response built for it.\n *\n * ```ts\n * bootstrap({ security: { allowedHosts: ['example.com', '.example.com'] } })\n * ```\n */\nexport function allowedHosts(options: string[] | AllowedHostsOptions) {\n const {\n hosts,\n trustForwardedHost = false,\n ignorePaths = [],\n } = Array.isArray(options) ? { hosts: options } : options\n const allowed = compile(hosts)\n const ignored = new Set(ignorePaths)\n\n return (req: Request, res: Response, next: NextFunction) => {\n const headers = req.headers as HeaderBag\n // Check every host a consumer could read, not one chosen by a rule that a\n // consumer may not share — which value of a list wins differs between\n // proxies and frameworks.\n const forwardedHeader = headerOf(headers, 'x-forwarded-host')\n let candidates: Array<string | undefined>\n if (trustForwardedHost && forwardedHeader !== undefined) {\n candidates = forwardedHeader.split(',').map((h) => h.trim())\n } else {\n // Not trusted: drop it, so it can't be read past this point.\n if (forwardedHeader !== undefined) delete headers['x-forwarded-host']\n candidates = [headerOf(headers, 'host') ?? headerOf(headers, ':authority')]\n }\n const passes = candidates.every((host) => {\n const hostname = hostnameOf(host)\n return hostname !== undefined && allowed(hostname)\n })\n if (passes) return next()\n // Probes read; nothing that changes state is exempt.\n const method = req.method?.toUpperCase()\n if (\n ignored.size > 0 &&\n (method === 'GET' || method === 'HEAD') &&\n ignored.has(resolvePathname(req as ClientRequestLike))\n ) {\n return next()\n }\n\n res.setHeader('content-type', 'application/problem+json')\n sendJson(res, 400, REJECTED)\n }\n}\n"],"mappings":";;;;;;;;;;8LAuCA,SAAS,SAAS,QAAoB,KAAkC,CACtE,IAAM,MAAQ,QAAQ,MACtB,OAAO,MAAM,QAAQ,KAAK,EAAI,MAAM,GAAK,KAC3C,CAGA,SAAS,WAAW,KAA8C,CAChE,GAAK,MAAS,aAAa,KAAK,IAAI,EACpC,OAAO,aAAa,UAAU,MAAM,CAAC,EAAE,QACzC,CAEA,SAAS,QAAQ,SAAmD,CAClE,GAAI,SAAS,SAAW,EAAG,MAAU,MAAM,wCAAwC,EACnF,GAAI,SAAS,SAAS,GAAG,EAAG,UAAa,GACzC,IAAM,sBAAQ,IAAI,IACZ,SAAqB,CAAC,EAC5B,IAAK,IAAM,WAAW,SAAU,CAC9B,IAAM,SAAW,QAAQ,WAAW,GAAG,EACjC,SAAW,WAAW,SAAW,QAAQ,MAAM,CAAC,EAAI,OAAO,EACjE,GAAI,CAAC,SACH,MAAU,MAAM,oBAAoB,QAAQ,qBAAqB,EAE/D,SAAU,SAAS,KAAK,QAAQ,EAC/B,MAAM,IAAI,QAAQ,CACzB,CACA,MAAQ,WACN,MAAM,IAAI,QAAQ,GAAK,SAAS,KAAM,GAAM,WAAa,GAAK,SAAS,SAAS,IAAI,GAAG,CAAC,CAC5F,CAEA,MAAM,SAAW,CACf,KAAM,cACN,MAAO,cACP,OAAQ,IAER,OAAQ,+BACV,EAcA,SAAgB,aAAa,QAAyC,CACpE,GAAM,CACJ,MACA,mBAAqB,GACrB,YAAc,CAAC,GACb,MAAM,QAAQ,OAAO,EAAI,CAAE,MAAO,OAAQ,EAAI,QAC5C,QAAU,QAAQ,KAAK,EACvB,QAAU,IAAI,IAAI,WAAW,EAEnC,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,QAAU,IAAI,QAId,gBAAkB,SAAS,QAAS,kBAAkB,EACxD,WAYJ,GAXI,oBAAsB,kBAAoB,IAAA,GAC5C,WAAa,gBAAgB,MAAM,GAAG,CAAC,CAAC,IAAK,GAAM,EAAE,KAAK,CAAC,GAGvD,kBAAoB,IAAA,IAAW,OAAO,QAAQ,oBAClD,WAAa,CAAC,SAAS,QAAS,MAAM,GAAK,SAAS,QAAS,YAAY,CAAC,GAE7D,WAAW,MAAO,MAAS,CACxC,IAAM,SAAW,WAAW,IAAI,EAChC,OAAO,WAAa,IAAA,IAAa,QAAQ,QAAQ,CACnD,CACS,EAAG,OAAO,KAAK,EAExB,IAAM,OAAS,IAAI,QAAQ,YAAY,EACvC,GACE,QAAQ,KAAO,IACd,SAAW,OAAS,SAAW,SAChC,QAAQ,IAAI,gBAAgB,GAAwB,CAAC,EAErD,OAAO,KAAK,EAGd,IAAI,UAAU,eAAgB,0BAA0B,EACxD,SAAS,IAAK,IAAK,QAAQ,CAC7B,CACF"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as breachPadding, r as padGzipHeader, t as BreachPaddingOptions } from "../../breach-padding-C-Dnq8CS.mjs";
2
+ import { n as breachPadding, r as padGzipHeader, t as BreachPaddingOptions } from "../../breach-padding-FBVGmcBb.mjs";
3
3
  export { BreachPaddingOptions, breachPadding, padGzipHeader };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"breach-padding.mjs","names":[],"sources":["../../../src/http/middleware/breach-padding.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport interface BreachPaddingOptions {\n /**\n * Padding added to each compressed response is 0 to `maxBytes - 1` bytes,\n * drawn fresh every time. Default 100, as Django's `GZipMiddleware`.\n */\n maxBytes?: number\n}\n\nconst GZIP_HEADER = 10\nconst FNAME = 0x08\n\n/** A random `0 … max-1`, from Web Crypto. */\nfunction randomBelow(max: number): number {\n if (max <= 1) return 0\n const [value] = crypto.getRandomValues(new Uint32Array(1))\n return value % max\n}\n\n/**\n * Pad a complete gzip member's header with a random-length file name (the\n * gzip `FNAME` field, which decompressors ignore). Returns `chunk` unchanged\n * unless it starts with a plain gzip header — magic, deflate, no flags set —\n * so anything else (plaintext, another encoding, a header already carrying\n * fields) passes through untouched.\n */\nexport function padGzipHeader(chunk: Uint8Array, maxBytes: number): Uint8Array {\n if (\n chunk.length < GZIP_HEADER ||\n chunk[0] !== 0x1f ||\n chunk[1] !== 0x8b ||\n chunk[2] !== 0x08 ||\n chunk[3] !== 0\n ) {\n return chunk\n }\n const length = randomBelow(maxBytes)\n const padded = new Uint8Array(chunk.length + length + 1)\n padded.set(chunk.subarray(0, GZIP_HEADER))\n padded[3] = FNAME\n padded.fill(0x61, GZIP_HEADER, GZIP_HEADER + length) // 'a' × length\n padded[GZIP_HEADER + length] = 0 // name terminator\n padded.set(chunk.subarray(GZIP_HEADER), GZIP_HEADER + length + 1)\n return padded\n}\n\ntype Writer = (chunk?: unknown, ...rest: unknown[]) => unknown\n\n/**\n * BREACH mitigation for `compression()`: makes the size of every gzip response\n * vary by a random amount, so an attacker watching encrypted traffic cannot\n * learn a secret in the page from how well their guesses compress (Django's\n * \"Heal The Breach\"). Opt-in — it costs some compression ratio.\n *\n * Mount it **before** `compression()`, so it sees the compressed bytes:\n *\n * ```ts\n * bootstrap({ middlewares: [breachPadding(), compression(), …] })\n * ```\n *\n * Padding lives in the gzip header, which Brotli does not have, so this also\n * removes `br` and `zstd` from the request's `Accept-Encoding` — browsers then\n * get gzip, and the padding applies. Not for the web entry: Netlify, Vercel\n * and Cloudflare compress at the edge.\n */\nexport function breachPadding(options: BreachPaddingOptions = {}) {\n const maxBytes = options.maxBytes ?? 100\n\n return (req: Request, res: Response, next: NextFunction) => {\n const accept = req.headers['accept-encoding']\n if (typeof accept === 'string') {\n req.headers['accept-encoding'] = accept\n .split(',')\n .filter((part) => !/^\\s*(br|zstd)\\s*(;|$)/i.test(part))\n .join(',')\n }\n\n // compression() captures res.write / res.end when it runs, after this, so\n // its compressed output comes through these. The gzip header is in the\n // first bytes; collect until there are enough of them, pad, then pass the\n // rest through as it comes.\n const write = res.write.bind(res) as Writer\n const end = res.end.bind(res) as Writer\n let pending: Uint8Array | null = new Uint8Array(0)\n\n const isGzip = () => /\\bgzip\\b/i.test(String(res.getHeader('content-encoding') ?? ''))\n const take = (chunk: unknown): Uint8Array | null => {\n if (pending === null) return null\n if (!isGzip() || !(chunk instanceof Uint8Array)) {\n pending = null\n return null\n }\n const joined = new Uint8Array(pending.length + chunk.length)\n joined.set(pending)\n joined.set(chunk, pending.length)\n if (joined.length < GZIP_HEADER) {\n pending = joined\n return new Uint8Array(0)\n }\n pending = null\n return padGzipHeader(joined, maxBytes)\n }\n\n // Bytes held back while waiting for a full header. Whenever padding is\n // abandoned — the next chunk is a string, the encoding changed, the\n // response ends early — they go out first, so nothing is lost.\n const held = () => (pending && pending.length > 0 ? pending : null)\n\n ;(res as unknown as { write: Writer }).write = (chunk, ...rest) => {\n const before = held()\n const out = take(chunk)\n if (out === null) {\n if (before) write(Buffer.from(before))\n return write(chunk, ...rest)\n }\n return out.length > 0 ? write(Buffer.from(out), ...rest) : true\n }\n ;(res as unknown as { end: Writer }).end = (chunk, ...rest) => {\n const before = held()\n // end() / end(callback): no more data — send what was held, unpadded.\n if (chunk === undefined || typeof chunk === 'function') {\n pending = null\n if (before) write(Buffer.from(before))\n return end(chunk, ...rest)\n }\n const out = take(chunk)\n pending = null\n if (out === null) {\n if (before) write(Buffer.from(before))\n return end(chunk, ...r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WAAW,QAAQ,OAAS,MAAM,MAAM,EAQ3D,OAPA,OAAO,IAAI,OAAO,EAClB,OAAO,IAAI,MAAO,QAAQ,MAAM,EAC5B,OAAO,OAAS,IAClB,QAAU,uBACH,IAAI,aAEb,QAAU,KACH,cAAc,OAAQ,QAAQ,EACvC,EAKM,SAAc,SAAW,QAAQ,OAAS,EAAI,QAAU,KAE7D,IAAsC,OAAS,MAAO,GAAG,OAAS,CACjE,IAAM,OAAS,KAAK,EACd,IAAM,KAAK,KAAK,EAKtB,OAJI,MAAQ,MACN,QAAQ,MAAM,OAAO,KAAK,MAAM,CAAC,EAC9B,MAAM,MAAO,GAAG,IAAI,GAEtB,IAAI,OAAS,EAAI,MAAM,OAAO,KAAK,GAAG,EAAG,GAAG,IAAI,EAAI,EAC7D,EACC,IAAoC,KAAO,MAAO,GAAG,OAAS,CAC7D,IAAM,OAAS,KAAK,EAEpB,GAAI,QAAU,IAAA,IAAa,OAAO,OAAU,WAG1C,MAFA,SAAU,KACN,QAAQ,MAAM,OAAO,KAAK,MAAM,CAAC,EAC9B,IAAI,MAAO,GAAG,IAAI,EAE3B,IAAM,IAAM,KAAK,KAAK,EAMtB,MALA,SAAU,KACN,MAAQ,MACN,QAAQ,MAAM,OAAO,KAAK,MAAM,CAAC,EAC9B,IAAI,MAAO,GAAG,IAAI,GAEpB,IAAI,OAAO,KAAK,GAAG,EAAG,GAAG,IAAI,CACtC,EACA,KAAK,CACP,CACF"}
1
+ {"version":3,"file":"breach-padding.mjs","names":[],"sources":["../../../src/http/middleware/breach-padding.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\nexport interface BreachPaddingOptions {\n /**\n * Padding added to each compressed response is 0 to `maxBytes - 1` bytes,\n * drawn fresh every time. Default 100, as Django's `GZipMiddleware`.\n */\n maxBytes?: number\n}\n\nconst GZIP_HEADER = 10\nconst FNAME = 0x08\n\n/** A random `0 … max-1`, from Web Crypto. */\nfunction randomBelow(max: number): number {\n if (max <= 1) return 0\n const [value] = crypto.getRandomValues(new Uint32Array(1))\n return value % max\n}\n\n/**\n * Pad a complete gzip member's header with a random-length file name (the\n * gzip `FNAME` field, which decompressors ignore). Returns `chunk` unchanged\n * unless it starts with a plain gzip header — magic, deflate, no flags set —\n * so anything else (plaintext, another encoding, a header already carrying\n * fields) passes through untouched.\n */\nexport function padGzipHeader(chunk: Uint8Array, maxBytes: number): Uint8Array {\n if (\n chunk.length < GZIP_HEADER ||\n chunk[0] !== 0x1f ||\n chunk[1] !== 0x8b ||\n chunk[2] !== 0x08 ||\n chunk[3] !== 0\n ) {\n return chunk\n }\n const length = randomBelow(maxBytes)\n const padded = new Uint8Array(chunk.length + length + 1)\n padded.set(chunk.subarray(0, GZIP_HEADER))\n padded[3] = FNAME\n padded.fill(0x61, GZIP_HEADER, GZIP_HEADER + length) // 'a' × length\n padded[GZIP_HEADER + length] = 0 // name terminator\n padded.set(chunk.subarray(GZIP_HEADER), GZIP_HEADER + length + 1)\n return padded\n}\n\ntype Writer = (chunk?: unknown, ...rest: unknown[]) => unknown\n\n/**\n * BREACH mitigation for `compression()`: makes the size of every gzip response\n * vary by a random amount, so an attacker watching encrypted traffic cannot\n * learn a secret in the page from how well their guesses compress (Django's\n * \"Heal The Breach\"). Opt-in — it costs some compression ratio.\n *\n * Mount it **before** `compression()`, so it sees the compressed bytes:\n *\n * ```ts\n * bootstrap({ middlewares: [breachPadding(), compression(), …] })\n * ```\n *\n * Padding lives in the gzip header, which Brotli does not have, so this also\n * removes `br` and `zstd` from the request's `Accept-Encoding` — browsers then\n * get gzip, and the padding applies. Not for the web entry: Netlify, Vercel\n * and Cloudflare compress at the edge.\n */\nexport function breachPadding(options: BreachPaddingOptions = {}) {\n const maxBytes = options.maxBytes ?? 100\n\n return (req: Request, res: Response, next: NextFunction) => {\n const accept = req.headers['accept-encoding']\n if (typeof accept === 'string') {\n req.headers['accept-encoding'] = accept\n .split(',')\n .filter((part) => !/^\\s*(br|zstd)\\s*(;|$)/i.test(part))\n .join(',')\n }\n\n // compression() captures res.write / res.end when it runs, after this, so\n // its compressed output comes through these. The gzip header is in the\n // first bytes; collect until there are enough of them, pad, then pass the\n // rest through as it comes.\n const write = res.write.bind(res) as Writer\n const end = res.end.bind(res) as Writer\n let pending: Uint8Array | null = new Uint8Array(0)\n\n const isGzip = () => /\\bgzip\\b/i.test(String(res.getHeader('content-encoding') ?? ''))\n const take = (chunk: unknown): Uint8Array | null => {\n if (pending === null) return null\n if (!isGzip() || !(chunk instanceof Uint8Array)) {\n pending = null\n return null\n }\n const joined = new Uint8Array(pending.length + chunk.length)\n joined.set(pending)\n joined.set(chunk, pending.length)\n if (joined.length < GZIP_HEADER) {\n pending = joined\n return new Uint8Array(0)\n }\n pending = null\n return padGzipHeader(joined, maxBytes)\n }\n\n // Bytes held back while waiting for a full header. Whenever padding is\n // abandoned — the next chunk is a string, the encoding changed, the\n // response ends early — they go out first, so nothing is lost.\n const held = () => (pending && pending.length > 0 ? pending : null)\n\n ;(res as unknown as { write: Writer }).write = (chunk, ...rest) => {\n const before = held()\n const out = take(chunk)\n if (out === null) {\n if (before) write(Buffer.from(before))\n return write(chunk, ...rest)\n }\n return out.length > 0 ? write(Buffer.from(out), ...rest) : true\n }\n ;(res as unknown as { end: Writer }).end = (chunk, ...rest) => {\n const before = held()\n // end() / end(callback): no more data — send what was held, unpadded.\n if (chunk === undefined || typeof chunk === 'function') {\n pending = null\n if (before) write(Buffer.from(before))\n return end(chunk, ...rest)\n }\n const out = take(chunk)\n pending = null\n if (out === null) {\n if (before) write(Buffer.from(before))\n return end(chunk, ...rest)\n }\n return end(Buffer.from(out), ...rest)\n }\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAkBA,SAAS,YAAY,IAAqB,CACxC,GAAI,KAAO,EAAG,MAAO,GACrB,GAAM,CAAC,OAAS,OAAO,gCAAgB,IAAI,YAAY,CAAC,CAAC,EACzD,OAAO,MAAQ,GACjB,CASA,SA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,EAAI,QAAU,KAE7D,IAAsC,OAAS,MAAO,GAAG,OAAS,CACjE,IAAM,OAAS,KAAK,EACd,IAAM,KAAK,KAAK,EAKtB,OAJI,MAAQ,MACN,QAAQ,MAAM,OAAO,KAAK,MAAM,CAAC,EAC9B,MAAM,MAAO,GAAG,IAAI,GAEtB,IAAI,OAAS,EAAI,MAAM,OAAO,KAAK,GAAG,EAAG,GAAG,IAAI,EAAI,EAC7D,EACC,IAAoC,KAAO,MAAO,GAAG,OAAS,CAC7D,IAAM,OAAS,KAAK,EAEpB,GAAI,QAAU,IAAA,IAAa,OAAO,OAAU,WAG1C,MAFA,SAAU,KACN,QAAQ,MAAM,OAAO,KAAK,MAAM,CAAC,EAC9B,IAAI,MAAO,GAAG,IAAI,EAE3B,IAAM,IAAM,KAAK,KAAK,EAMtB,MALA,SAAU,KACN,MAAQ,MACN,QAAQ,MAAM,OAAO,KAAK,MAAM,CAAC,EAC9B,IAAI,MAAO,GAAG,IAAI,GAEpB,IAAI,OAAO,KAAK,GAAG,EAAG,GAAG,IAAI,CACtC,EACA,KAAK,CACP,CACF"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as cors, t as CorsOptions } from "../../cors-2Bwhyhpt.mjs";
2
+ import { n as cors, t as CorsOptions } from "../../cors-BlR_b0Qb.mjs";
3
3
  export { CorsOptions, cors };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cors.mjs","names":[],"sources":["../../../src/http/middleware/cors.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport interface CorsOptions {\n /** Allowed origin(s). `true` reflects request origin, `'*'` allows all, `false` rejects all. Default: `false` (restrictive) */\n origin?: boolean | string | RegExp | (string | RegExp)[]\n /** Allowed HTTP methods. Default: `['GET','HEAD','PUT','PATCH','POST','DELETE']` */\n methods?: string[]\n /** Allowed request headers. Default: reflects `Access-Control-Request-Headers` */\n allowedHeaders?: string[]\n /** Headers exposed to the browser. Default: none */\n exposedHeaders?: string[]\n /** Allow credentials (cookies, authorization). Default: false */\n credentials?: boolean\n /** Preflight cache duration in seconds. Default: 86400 (24h) */\n maxAge?: number\n /** Handle preflight OPTIONS requests. Default: true */\n preflight?: boolean\n}\n\nconst DEFAULT_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE']\n\nfunction isOriginAllowed(requestOrigin: string, allowed: CorsOptions['origin']): boolean {\n if (allowed === true || allowed === '*') return true\n if (typeof allowed === 'string') return requestOrigin === allowed\n if (allowed instanceof RegExp) return allowed.test(requestOrigin)\n if (Array.isArray(allowed)) {\n return allowed.some((pattern) =>\n typeof pattern === 'string' ? requestOrigin === pattern : pattern.test(requestOrigin),\n )\n }\n return false\n}\n\n/**\n * CORS middleware with correct spec behavior.\n *\n * - Reflects origin from allowlist (sets `Vary: Origin`)\n * - Handles preflight `OPTIONS` with `204 No Content`\n * - Supports string, regex, and array origin matching\n *\n * @example\n * ```ts\n * // Allow all origins\n * bootstrap({ middlewares: [cors(), express.json()] })\n *\n * // Allowlist specific origins\n * bootstrap({\n * middlewares: [\n * cors({\n * origin: ['https://app.example.com', /\\.example\\.com$/],\n * credentials: true,\n * }),\n * express.json(),\n * ],\n * })\n * ```\n *\n * Options are read once, when the middleware is created: changing the options\n * object afterwards does not change the headers. Create a new middleware instead.\n */\nexport function cors(options: CorsOptions = {}) {\n const {\n origin = false,\n methods = DEFAULT_METHODS,\n allowedHeaders,\n exposedHeaders,\n credentials = false,\n maxAge = 86400,\n preflight = true,\n } = options\n\n // Header values depend only on the options — joined once, not per request.\n const exposeValue = exposedHeaders?.length ? exposedHeaders.join(', ') : undefined\n const methodsValue = methods.join(', ')\n const allowedValue = allowedHeaders?.join(', ')\n const maxAgeValue = maxAge ? String(maxAge) : undefined\n\n return (req: Request, res: Response, next: NextFunction) => {\n const requestOrigin = req.headers.origin\n\n // Determine the Access-Control-Allow-Origin value\n if (origin === '*' && !credentials) {\n res.setHeader('Access-Control-Allow-Origin', '*')\n } else if (requestOrigin) {\n if (isOriginAllowed(requestOrigin, origin)) {\n res.setHeader('Access-Control-Allow-Origin', requestOrigin)\n // Must vary by Origin when reflecting — CDN/proxy correctness\n res.setHeader('Vary', 'Origin')\n }\n }\n\n if (credentials) {\n res.setHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n if (exposeValue) res.setHeader('Access-Control-Expose-Headers', exposeValue)\n\n // Preflight handling\n if (preflight && req.method === 'OPTIONS') {\n res.setHeader('Access-Control-Allow-Methods', methodsValue)\n\n const reqHeaders = allowedValue ?? req.headers['access-control-request-headers']\n if (reqHeaders) {\n const value = Array.isArray(reqHeaders) ? reqHeaders.join(', ') : reqHeaders\n res.setHeader('Access-Control-Allow-Headers', value)\n }\n\n if (maxAgeValue) res.setHeader('Access-Control-Max-Age', maxAgeValue)\n\n res.statusCode = 204\n res.setHeader('Content-Length', '0')\n res.end()\n return\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAmBA,MAAM,gBAAkB,CAAC,MAAO,OAAQ,MAAO,QAAS,OAAQ,QAAQ,EAExE,SAAS,gBAAgB,cAAuB,QAAyC,CASvF,OARI,UAAY,IAAQ,UAAY,IAAY,GAC5C,OAAO,SAAY,SAAiB,gBAAkB,QACtD,mBAAmB,OAAe,QAAQ,KAAK,aAAa,EAC5D,MAAM,QAAQ,OAAO,EAChB,QAAQ,KAAM,SACnB,OAAO,SAAY,SAAW,gBAAkB,QAAU,QAAQ,KAAK,aAAa,CACtF,EAEK,EACT,CA6BA,SAAgB,KAAK,QAAuB,CAAC,EAAG,CAC9C,GAAM,CACJ,OAAS,GACT,QAAU,gBACV,eACA,eACA,YAAc,GACd,OAAS,MACT,UAAY,IACV,QAGE,YAAc,gBAAgB,OAAS,eAAe,KAAK,IAAI,EAAI,IAAA,GACnE,aAAe,QAAQ,KAAK,IAAI,EAChC,aAAe,gBAAgB,KAAK,IAAI,EACxC,YAAc,OAAS,OAAO,MAAM,EAAI,IAAA,GAE9C,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,cAAgB,IAAI,QAAQ,OAoBlC,GAjBI,SAAW,KAAO,CAAC,YACrB,IAAI,UAAU,8BAA+B,GAAG,EACvC,eACL,gBAAgB,cAAe,MAAM,IACvC,IAAI,UAAU,8BAA+B,aAAa,EAE1D,IAAI,UAAU,OAAQ,QAAQ,GAI9B,aACF,IAAI,UAAU,mCAAoC,MAAM,EAGtD,aAAa,IAAI,UAAU,gCAAiC,WAAW,EAGvE,WAAa,IAAI,SAAW,UAAW,CACzC,IAAI,UAAU,+BAAgC,YAAY,EAE1D,IAAM,WAAa,cAAgB,IAAI,QAAQ,kCAC/C,GAAI,WAAY,CACd,IAAM,MAAQ,MAAM,QAAQ,UAAU,EAAI,WAAW,KAAK,IAAI,EAAI,WAClE,IAAI,UAAU,+BAAgC,KAAK,CACrD,CAEI,aAAa,IAAI,UAAU,yBAA0B,WAAW,EAEpE,IAAI,WAAa,IACjB,IAAI,UAAU,iBAAkB,GAAG,EACnC,IAAI,IAAI,CAEV,MAEA,KAAK,CACP,CACF"}
1
+ {"version":3,"file":"cors.mjs","names":[],"sources":["../../../src/http/middleware/cors.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\nexport interface CorsOptions {\n /** Allowed origin(s). `true` reflects request origin, `'*'` allows all, `false` rejects all. Default: `false` (restrictive) */\n origin?: boolean | string | RegExp | (string | RegExp)[]\n /** Allowed HTTP methods. Default: `['GET','HEAD','PUT','PATCH','POST','DELETE']` */\n methods?: string[]\n /** Allowed request headers. Default: reflects `Access-Control-Request-Headers` */\n allowedHeaders?: string[]\n /** Headers exposed to the browser. Default: none */\n exposedHeaders?: string[]\n /** Allow credentials (cookies, authorization). Default: false */\n credentials?: boolean\n /** Preflight cache duration in seconds. Default: 86400 (24h) */\n maxAge?: number\n /** Handle preflight OPTIONS requests. Default: true */\n preflight?: boolean\n}\n\nconst DEFAULT_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE']\n\nfunction isOriginAllowed(requestOrigin: string, allowed: CorsOptions['origin']): boolean {\n if (allowed === true || allowed === '*') return true\n if (typeof allowed === 'string') return requestOrigin === allowed\n if (allowed instanceof RegExp) return allowed.test(requestOrigin)\n if (Array.isArray(allowed)) {\n return allowed.some((pattern) =>\n typeof pattern === 'string' ? requestOrigin === pattern : pattern.test(requestOrigin),\n )\n }\n return false\n}\n\n/**\n * CORS middleware with correct spec behavior.\n *\n * - Reflects origin from allowlist (sets `Vary: Origin`)\n * - Handles preflight `OPTIONS` with `204 No Content`\n * - Supports string, regex, and array origin matching\n *\n * @example\n * ```ts\n * // Allow all origins\n * bootstrap({ middlewares: [cors(), express.json()] })\n *\n * // Allowlist specific origins\n * bootstrap({\n * middlewares: [\n * cors({\n * origin: ['https://app.example.com', /\\.example\\.com$/],\n * credentials: true,\n * }),\n * express.json(),\n * ],\n * })\n * ```\n *\n * Options are read once, when the middleware is created: changing the options\n * object afterwards does not change the headers. Create a new middleware instead.\n */\nexport function cors(options: CorsOptions = {}) {\n const {\n origin = false,\n methods = DEFAULT_METHODS,\n allowedHeaders,\n exposedHeaders,\n credentials = false,\n maxAge = 86400,\n preflight = true,\n } = options\n\n // Header values depend only on the options — joined once, not per request.\n const exposeValue = exposedHeaders?.length ? exposedHeaders.join(', ') : undefined\n const methodsValue = methods.join(', ')\n const allowedValue = allowedHeaders?.join(', ')\n const maxAgeValue = maxAge ? String(maxAge) : undefined\n\n return (req: Request, res: Response, next: NextFunction) => {\n const requestOrigin = req.headers.origin\n\n // Determine the Access-Control-Allow-Origin value\n if (origin === '*' && !credentials) {\n res.setHeader('Access-Control-Allow-Origin', '*')\n } else if (requestOrigin) {\n if (isOriginAllowed(requestOrigin, origin)) {\n res.setHeader('Access-Control-Allow-Origin', requestOrigin)\n // Must vary by Origin when reflecting — CDN/proxy correctness\n res.setHeader('Vary', 'Origin')\n }\n }\n\n if (credentials) {\n res.setHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n if (exposeValue) res.setHeader('Access-Control-Expose-Headers', exposeValue)\n\n // Preflight handling\n if (preflight && req.method === 'OPTIONS') {\n res.setHeader('Access-Control-Allow-Methods', methodsValue)\n\n const reqHeaders = allowedValue ?? req.headers['access-control-request-headers']\n if (reqHeaders) {\n const value = Array.isArray(reqHeaders) ? reqHeaders.join(', ') : reqHeaders\n res.setHeader('Access-Control-Allow-Headers', value)\n }\n\n if (maxAgeValue) res.setHeader('Access-Control-Max-Age', maxAgeValue)\n\n res.statusCode = 204\n res.setHeader('Content-Length', '0')\n res.end()\n return\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,gBAAkB,CAAC,MAAO,OAAQ,MAAO,QAAS,OAAQ,QAAQ,EAExE,SAAS,gBAAgB,cAAuB,QAAyC,CASvF,OARI,UAAY,IAAQ,UAAY,IAAY,GAC5C,OAAO,SAAY,SAAiB,gBAAkB,QACtD,mBAAmB,OAAe,QAAQ,KAAK,aAAa,EAC5D,MAAM,QAAQ,OAAO,EAChB,QAAQ,KAAM,SACnB,OAAO,SAAY,SAAW,gBAAkB,QAAU,QAAQ,KAAK,aAAa,CACtF,EAEK,EACT,CA6BA,SAAgB,KAAK,QAAuB,CAAC,EAAG,CAC9C,GAAM,CACJ,OAAS,GACT,QAAU,gBACV,eACA,eACA,YAAc,GACd,OAAS,MACT,UAAY,IACV,QAGE,YAAc,gBAAgB,OAAS,eAAe,KAAK,IAAI,EAAI,IAAA,GACnE,aAAe,QAAQ,KAAK,IAAI,EAChC,aAAe,gBAAgB,KAAK,IAAI,EACxC,YAAc,OAAS,OAAO,MAAM,EAAI,IAAA,GAE9C,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,cAAgB,IAAI,QAAQ,OAoBlC,GAjBI,SAAW,KAAO,CAAC,YACrB,IAAI,UAAU,8BAA+B,GAAG,EACvC,eACL,gBAAgB,cAAe,MAAM,IACvC,IAAI,UAAU,8BAA+B,aAAa,EAE1D,IAAI,UAAU,OAAQ,QAAQ,GAI9B,aACF,IAAI,UAAU,mCAAoC,MAAM,EAGtD,aAAa,IAAI,UAAU,gCAAiC,WAAW,EAGvE,WAAa,IAAI,SAAW,UAAW,CACzC,IAAI,UAAU,+BAAgC,YAAY,EAE1D,IAAM,WAAa,cAAgB,IAAI,QAAQ,kCAC/C,GAAI,WAAY,CACd,IAAM,MAAQ,MAAM,QAAQ,UAAU,EAAI,WAAW,KAAK,IAAI,EAAI,WAClE,IAAI,UAAU,+BAAgC,KAAK,CACrD,CAEI,aAAa,IAAI,UAAU,yBAA0B,WAAW,EAEpE,IAAI,WAAa,IACjB,IAAI,UAAU,iBAAkB,GAAG,EACnC,IAAI,IAAI,CAEV,MAEA,KAAK,CACP,CACF"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as isAllowedOrigin, i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "../../csrf-BDAZK2mm.mjs";
2
+ import { a as isAllowedOrigin, i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "../../csrf-ZFOrJZhJ.mjs";
3
3
  export { CsrfGuardOptions, CsrfOptions, csrf, csrfGuard, isAllowedOrigin };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-BPSq2JCs.mjs";import{t as isProduction}from"../../is-production-BTroGhp5.mjs";import{n as randomHex,r as safeEqual}from"../../web-crypto-G-m6c6w2.mjs";import{n as canonicalHost,r as parseHttpUrl}from"../../host-H7CIkHNB.mjs";import{n as resolvePathname}from"../../client-ip-BLkoQTIR.mjs";import{a as setCookie,i as sendJson,n as readCookies}from"../../respond-BOlh-baJ.mjs";function headerOf(headers,name){let value=headers[name];return Array.isArray(value)?value[0]:value}function originOfUrl(url){if(url)try{return new URL(url).origin}catch{return}}function isAllowedOrigin(headers,trusted){let site=headerOf(headers,`sec-fetch-site`);if(site===`same-origin`)return!0;let declared=headerOf(headers,`origin`)??originOfUrl(headerOf(headers,`referer`));if(declared===void 0)return site===void 0||site===`none`;let origin=parseHttpUrl(declared);if(!origin)return!1;if(trusted.has(origin.origin))return!0;let host=canonicalHost(headerOf(headers,`host`)??headerOf(headers,`:authority`),origin.protocol);return host!==void 0&&host===origin.host}function trustedSet(origins){return new Set((origins??[]).map(o=>{let url=parseHttpUrl(o);if(!url||url.pathname!==`/`||url.search||url.hash||url.username||url.password)throw Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`);return url.origin}))}const ORIGIN_REJECTED={message:`CSRF origin not allowed`};function csrf(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(req,res,next)=>{let token=readCookies(req)[cookieName];if(token||(token=randomHex(tokenLength),setCookie(res,cookieName,token,cookieOpts)),!protectedMethods.has(req.method.toUpperCase())||ignorePaths.has(resolvePathname(req)))return next();if(checkOrigin&&!isAllowedOrigin(req.headers,trusted))return sendJson(res,403,ORIGIN_REJECTED);let headerToken=req.headers[headerName];if(typeof headerToken!=`string`||!safeEqual(headerToken,token))return sendJson(res,403,{message:`CSRF token mismatch`});next()}}function csrfGuard(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`csrfGuard({ exemptWhen })`);let checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(ctx,next)=>{let token=readCookies(ctx.req)[cookieName];token||(token=randomHex(tokenLength),setCookie(ctx.res,cookieName,token,cookieOpts));let method=ctx.route?.method??ctx.req.method??`GET`;if(!protectedMethods.has(method.toUpperCase())||exemptWhen!==void 0&&matchesFlagTest(exemptWhen,ctx.route?.flags,ctx.route)||ignorePaths.has(resolvePathname(ctx.req)))return next();if(checkOrigin&&!isAllowedOrigin(ctx.headers,trusted)){ctx.json(ORIGIN_REJECTED,403);return}let headerToken=ctx.headers[headerName];typeof headerToken!=`string`||!safeEqual(headerToken,token)?ctx.json({message:`CSRF token mismatch`},403):next()}}export{csrf,csrfGuard,isAllowedOrigin};
11
+ import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-DCOS_F5A.mjs";import{t as isProduction}from"../../is-production-MYGnN2Nv.mjs";import{n as randomHex,r as safeEqual}from"../../web-crypto-B6iM0yYx.mjs";import{n as canonicalHost,r as parseHttpUrl}from"../../host-lMSIGnh7.mjs";import{n as resolvePathname}from"../../client-ip-DxEVqZP-.mjs";import{a as setCookie,i as sendJson,n as readCookies}from"../../respond-DR7zkOUf.mjs";function headerOf(headers,name){let value=headers[name];return Array.isArray(value)?value[0]:value}function originOfUrl(url){if(url)try{return new URL(url).origin}catch{return}}function isAllowedOrigin(headers,trusted){let site=headerOf(headers,`sec-fetch-site`);if(site===`same-origin`)return!0;let declared=headerOf(headers,`origin`)??originOfUrl(headerOf(headers,`referer`));if(declared===void 0)return site===void 0||site===`none`;let origin=parseHttpUrl(declared);if(!origin)return!1;if(trusted.has(origin.origin))return!0;let host=canonicalHost(headerOf(headers,`host`)??headerOf(headers,`:authority`),origin.protocol);return host!==void 0&&host===origin.host}function trustedSet(origins){return new Set((origins??[]).map(o=>{let url=parseHttpUrl(o);if(!url||url.pathname!==`/`||url.search||url.hash||url.username||url.password)throw Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`);return url.origin}))}const ORIGIN_REJECTED={message:`CSRF origin not allowed`};function csrf(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(req,res,next)=>{let token=readCookies(req)[cookieName];if(token||(token=randomHex(tokenLength),setCookie(res,cookieName,token,cookieOpts)),!protectedMethods.has(req.method.toUpperCase())||ignorePaths.has(resolvePathname(req)))return next();if(checkOrigin&&!isAllowedOrigin(req.headers,trusted))return sendJson(res,403,ORIGIN_REJECTED);let headerToken=req.headers[headerName];if(typeof headerToken!=`string`||!safeEqual(headerToken,token))return sendJson(res,403,{message:`CSRF token mismatch`});next()}}function csrfGuard(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`csrfGuard({ exemptWhen })`);let checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(ctx,next)=>{let token=readCookies(ctx.req)[cookieName];token||(token=randomHex(tokenLength),setCookie(ctx.res,cookieName,token,cookieOpts));let method=ctx.route?.method??ctx.req.method??`GET`;if(!protectedMethods.has(method.toUpperCase())||exemptWhen!==void 0&&matchesFlagTest(exemptWhen,ctx.route?.flags,ctx.route)||ignorePaths.has(resolvePathname(ctx.req)))return next();if(checkOrigin&&!isAllowedOrigin(ctx.headers,trusted)){ctx.json(ORIGIN_REJECTED,403);return}let headerToken=ctx.headers[headerName];typeof headerToken!=`string`||!safeEqual(headerToken,token)?ctx.json({message:`CSRF token mismatch`},403):next()}}export{csrf,csrfGuard,isAllowedOrigin};
12
12
  //# sourceMappingURL=csrf.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"csrf.mjs","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"sourcesContent":["import { readCookies, sendJson, setCookie } from './respond'\nimport type { Request, Response, NextFunction } from 'express'\nimport { resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { randomHex, safeEqual } from '../../core/web-crypto'\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport { isProduction } from '../../core/is-production'\nimport { canonicalHost, parseHttpUrl } from '../host'\n\nexport interface CsrfOptions {\n /** Cookie name for the CSRF token (default: '_csrf') */\n cookie?: string\n /** Header name to check for the token (default: 'x-csrf-token') */\n header?: string\n /** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */\n methods?: string[]\n /** Paths to exclude from CSRF checks (e.g. webhooks) */\n ignorePaths?: string[]\n /** Token byte length before hex encoding (default: 32 = 64 hex chars) */\n tokenLength?: number\n /**\n * Origins, besides the request's own host, allowed to send state-changing\n * requests — e.g. `['https://app.example.com']` when the frontend lives on\n * another subdomain. Compared against the `Origin` (or `Referer`) header.\n */\n trustedOrigins?: string[]\n /**\n * Check where an unsafe request came from before the token (default `true`).\n * `Sec-Fetch-Site: same-origin` passes; otherwise the `Origin` (or `Referer`)\n * must match the request's `Host` or a {@link trustedOrigins} entry, and a\n * browser request that says it is cross-site with neither is refused. A\n * request with no such headers at all (a server, curl) goes on to the token\n * check. Turn off only behind a proxy that rewrites `Host` and when you\n * cannot list the origins.\n */\n checkOrigin?: boolean\n /** Cookie options */\n cookieOptions?: {\n /**\n * Default `false`, because double-submit CSRF needs the page to read the\n * token and echo it in a header. Set `true` only if the client receives\n * the token another way — server-rendered, or from your own endpoint.\n */\n httpOnly?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n secure?: boolean\n path?: string\n }\n}\n\ntype HeaderBag = Record<string, string | string[] | undefined>\n\nfunction headerOf(headers: HeaderBag, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value[0] : value\n}\n\n/** `scheme://host[:port]` of a URL, or undefined when it doesn't parse. */\nfunction originOfUrl(url: string | undefined): string | undefined {\n if (!url) return undefined\n try {\n return new URL(url).origin\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether an unsafe request came from somewhere allowed to send it — the\n * origin half of CSRF protection, ahead of the token. The token alone (double\n * submit) can be planted by a sibling subdomain that sets cookies on the\n * parent domain; the browser's own origin headers cannot.\n */\nexport function isAllowedOrigin(headers: HeaderBag, trusted: ReadonlySet<string>): boolean {\n const site = headerOf(headers, 'sec-fetch-site')\n if (site === 'same-origin') return true\n\n const declared = headerOf(headers, 'origin') ?? originOfUrl(headerOf(headers, 'referer'))\n if (declared === undefined) {\n // No browser origin headers: not a browser cross-site request (or a very\n // old browser). Left to the token. A browser that says cross-site or\n // same-site but sends no origin is refused.\n return site === undefined || site === 'none'\n }\n // `Origin: null` (sandboxed frames, some redirects) and non-http schemes\n // don't parse: refused.\n const origin = parseHttpUrl(declared)\n if (!origin) return false\n if (trusted.has(origin.origin)) return true\n // The scheme is not compared: behind a TLS-terminating proxy the app cannot\n // know it reliably. The host (with port) is what an attacker cannot match.\n // HTTP/2 carries it as `:authority`.\n const host = canonicalHost(\n headerOf(headers, 'host') ?? headerOf(headers, ':authority'),\n origin.protocol,\n )\n return host !== undefined && host === origin.host\n}\n\nfunction trustedSet(origins: string[] | undefined): Set<string> {\n return new Set(\n (origins ?? []).map((o) => {\n const url = parseHttpUrl(o)\n // An origin is scheme + host + port: a path, query or credentials here\n // means the entry was meant as something else.\n if (!url || url.pathname !== '/' || url.search || url.hash || url.username || url.password) {\n throw new Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`)\n }\n return url.origin\n }),\n )\n}\n\nconst ORIGIN_REJECTED = { message: 'CSRF origin not allowed' }\n\n/**\n * Double-submit cookie CSRF protection middleware.\n *\n * On every request, sets a CSRF token cookie. For state-changing methods\n * (POST, PUT, PATCH, DELETE), validates that the request header matches\n * the cookie value.\n *\n * @example\n * ```ts\n * import { csrf } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * cookieParser(),\n * csrf(),\n * // ... other middleware\n * ],\n * })\n * ```\n *\n * Client usage:\n * 1. Read the `_csrf` cookie value\n * 2. Send it in the `x-csrf-token` header on every mutating request\n */\nexport function csrf(options: CsrfOptions = {}) {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // `false`, not `true`: double-submit CSRF requires the PAGE to read this\n // cookie and echo it in a header. Under `httpOnly: true` `document.cookie`\n // returns nothing, no header is sent, and every mutating request answers\n // 403 — the documented client flow could not work. The token is not a\n // credential; a token an attacker cannot read is also one your own page\n // cannot send. Set `cookieOptions: { httpOnly: true }` only when the token\n // reaches the client some other way (server-rendered, or your own endpoint).\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Generate or reuse CSRF token\n // NOT `req.cookies` alone: that is populated only by an upstream parser,\n // which Fastify and h3 never have and Express only has if the app mounts\n // one. Without this the middleware never saw the token it had just issued.\n const cookies = readCookies(req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(res, cookieName, token, cookieOpts)\n }\n\n // Skip validation for safe methods and ignored paths\n if (!protectedMethods.has(req.method.toUpperCase())) {\n return next()\n }\n\n // `req.path` is Express-only, so `has(undefined)` never matched and\n // configured exemptions were silently ignored on Fastify / h3.\n if (ignorePaths.has(resolvePathname(req as ClientRequestLike))) {\n return next()\n }\n\n if (checkOrigin && !isAllowedOrigin(req.headers as HeaderBag, trusted)) {\n return sendJson(res, 403, ORIGIN_REJECTED)\n }\n\n // Validate: header token must match cookie token\n const headerToken = req.headers[headerName] as string | undefined\n\n if (typeof headerToken !== 'string' || !safeEqual(headerToken, token)) {\n return sendJson(res, 403, {\n message: 'CSRF token mismatch',\n })\n }\n\n next()\n }\n}\n\nexport interface CsrfGuardOptions extends CsrfOptions {\n /**\n * Skip the token check on routes carrying a route flag — a name, a list of\n * names (any-of), or a predicate.\n *\n * This is the reason the guard exists. `csrf()` runs before route matching,\n * so its only handle on \"not this endpoint\" is {@link CsrfOptions.ignorePaths}\n * — an exact pathname string that cannot express `/webhooks/:provider` and\n * keeps parsing after an `apiPrefix` change that voids it. A flag is declared\n * on the route itself:\n *\n * ```ts\n * const CsrfExempt = defineRouteFlag('csrf.exempt')\n *\n * @CsrfExempt\n * @Controller()\n * class WebhooksController {\n * @Post('/:provider') receive(ctx: RequestContext) {}\n * }\n * ```\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Double-submit cookie CSRF protection as a `(ctx, next)` middleware.\n *\n * The ctx-style counterpart of {@link csrf}: it runs inside the matched route,\n * so it can read `ctx.route.flags` and be exempted per route, and it works on\n * every runtime including the `@forinda/kickjs/web` fetch entry.\n *\n * ```ts\n * // per controller — the flag-aware form\n * @Middleware(csrfGuard({ exemptWhen: 'csrf.exempt' }))\n * @Controller()\n * class BillingController {}\n *\n * // edge, app-wide\n * createWebApp({ h3, modules, middleware: [csrfGuard()] })\n * ```\n *\n * Mount `csrf()` instead when you want one app-wide connect middleware that\n * also covers requests matching no route — nothing to exempt, nothing to read.\n */\nexport function csrfGuard(options: CsrfGuardOptions = {}): MiddlewareHandler {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'csrfGuard({ exemptWhen })')\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // Same default as `csrf()` above, and for the same reason.\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (ctx: RequestContext, next: () => void): void => {\n const cookies = readCookies(ctx.req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(ctx.res, cookieName, token, cookieOpts)\n }\n\n // Safe methods only ever issue the token.\n const method = ctx.route?.method ?? (ctx.req as { method?: string }).method ?? 'GET'\n if (!protectedMethods.has(method.toUpperCase())) return next()\n\n // Flag first: it is the declared exemption, and cheaper than the path set.\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n if (ignorePaths.has(resolvePathname(ctx.req as unknown as ClientRequestLike))) return next()\n\n if (checkOrigin && !isAllowedOrigin(ctx.headers as HeaderBag, trusted)) {\n ctx.json(ORIGIN_REJECTED, 403)\n return\n }\n\n const headerToken = ctx.headers[headerName] as string | undefined\n if (typeof headerToken !== 'string' || !safe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AM,YAAc,QAAQ,aAAe,GACrC,QAAU,WAAW,QAAQ,cAAc,EAC3C,WAAa,CAEjB,SAAU,GACV,SAAU,SACV,OAAQ,aAAa,EACrB,KAAM,IACN,GAAG,QAAQ,aACb,EAEA,OAAQ,IAAqB,OAA2B,CAEtD,IAAI,MADY,YAAY,IAAI,GACd,CAAC,CAAC,YAEf,QACH,MAAQ,UAAU,WAAW,EAC7B,UAAU,IAAI,IAAK,WAAY,MAAO,UAAU,GAIlD,IAAM,OAAS,IAAI,OAAO,QAAW,IAAI,IAA4B,QAAU,MAQ/E,GAPI,CAAC,iBAAiB,IAAI,OAAO,YAAY,CAAC,GAG1C,aAAe,IAAA,IAAa,gBAAgB,WAAY,IAAI,OAAO,MAAO,IAAI,KAAK,GAInF,YAAY,IAAI,gBAAgB,IAAI,GAAmC,CAAC,EAAG,OAAO,KAAK,EAE3F,GAAI,aAAe,CAAC,gBAAgB,IAAI,QAAsB,OAAO,EAAG,CACtE,IAAI,KAAK,gBAAiB,GAAG,EAC7B,MACF,CAEA,IAAM,YAAc,IAAI,QAAQ,YAC5B,OAAO,aAAgB,UAAY,CAAC,UAAU,YAAa,KAAK,EAClE,IAAI,KAAK,CAAE,QAAS,qBAAsB,EAAG,GAAG,EAIlD,KAAK,CACP,CACF"}
1
+ {"version":3,"file":"csrf.mjs","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"sourcesContent":["import { readCookies, sendJson, setCookie } from './respond'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\nimport { resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { randomHex, safeEqual } from '../../core/web-crypto'\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport { isProduction } from '../../core/is-production'\nimport { canonicalHost, parseHttpUrl } from '../host'\n\nexport interface CsrfOptions {\n /** Cookie name for the CSRF token (default: '_csrf') */\n cookie?: string\n /** Header name to check for the token (default: 'x-csrf-token') */\n header?: string\n /** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */\n methods?: string[]\n /** Paths to exclude from CSRF checks (e.g. webhooks) */\n ignorePaths?: string[]\n /** Token byte length before hex encoding (default: 32 = 64 hex chars) */\n tokenLength?: number\n /**\n * Origins, besides the request's own host, allowed to send state-changing\n * requests — e.g. `['https://app.example.com']` when the frontend lives on\n * another subdomain. Compared against the `Origin` (or `Referer`) header.\n */\n trustedOrigins?: string[]\n /**\n * Check where an unsafe request came from before the token (default `true`).\n * `Sec-Fetch-Site: same-origin` passes; otherwise the `Origin` (or `Referer`)\n * must match the request's `Host` or a {@link trustedOrigins} entry, and a\n * browser request that says it is cross-site with neither is refused. A\n * request with no such headers at all (a server, curl) goes on to the token\n * check. Turn off only behind a proxy that rewrites `Host` and when you\n * cannot list the origins.\n */\n checkOrigin?: boolean\n /** Cookie options */\n cookieOptions?: {\n /**\n * Default `false`, because double-submit CSRF needs the page to read the\n * token and echo it in a header. Set `true` only if the client receives\n * the token another way — server-rendered, or from your own endpoint.\n */\n httpOnly?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n secure?: boolean\n path?: string\n }\n}\n\ntype HeaderBag = Record<string, string | string[] | undefined>\n\nfunction headerOf(headers: HeaderBag, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value[0] : value\n}\n\n/** `scheme://host[:port]` of a URL, or undefined when it doesn't parse. */\nfunction originOfUrl(url: string | undefined): string | undefined {\n if (!url) return undefined\n try {\n return new URL(url).origin\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether an unsafe request came from somewhere allowed to send it — the\n * origin half of CSRF protection, ahead of the token. The token alone (double\n * submit) can be planted by a sibling subdomain that sets cookies on the\n * parent domain; the browser's own origin headers cannot.\n */\nexport function isAllowedOrigin(headers: HeaderBag, trusted: ReadonlySet<string>): boolean {\n const site = headerOf(headers, 'sec-fetch-site')\n if (site === 'same-origin') return true\n\n const declared = headerOf(headers, 'origin') ?? originOfUrl(headerOf(headers, 'referer'))\n if (declared === undefined) {\n // No browser origin headers: not a browser cross-site request (or a very\n // old browser). Left to the token. A browser that says cross-site or\n // same-site but sends no origin is refused.\n return site === undefined || site === 'none'\n }\n // `Origin: null` (sandboxed frames, some redirects) and non-http schemes\n // don't parse: refused.\n const origin = parseHttpUrl(declared)\n if (!origin) return false\n if (trusted.has(origin.origin)) return true\n // The scheme is not compared: behind a TLS-terminating proxy the app cannot\n // know it reliably. The host (with port) is what an attacker cannot match.\n // HTTP/2 carries it as `:authority`.\n const host = canonicalHost(\n headerOf(headers, 'host') ?? headerOf(headers, ':authority'),\n origin.protocol,\n )\n return host !== undefined && host === origin.host\n}\n\nfunction trustedSet(origins: string[] | undefined): Set<string> {\n return new Set(\n (origins ?? []).map((o) => {\n const url = parseHttpUrl(o)\n // An origin is scheme + host + port: a path, query or credentials here\n // means the entry was meant as something else.\n if (!url || url.pathname !== '/' || url.search || url.hash || url.username || url.password) {\n throw new Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`)\n }\n return url.origin\n }),\n )\n}\n\nconst ORIGIN_REJECTED = { message: 'CSRF origin not allowed' }\n\n/**\n * Double-submit cookie CSRF protection middleware.\n *\n * On every request, sets a CSRF token cookie. For state-changing methods\n * (POST, PUT, PATCH, DELETE), validates that the request header matches\n * the cookie value.\n *\n * @example\n * ```ts\n * import { csrf } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * cookieParser(),\n * csrf(),\n * // ... other middleware\n * ],\n * })\n * ```\n *\n * Client usage:\n * 1. Read the `_csrf` cookie value\n * 2. Send it in the `x-csrf-token` header on every mutating request\n */\nexport function csrf(options: CsrfOptions = {}) {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // `false`, not `true`: double-submit CSRF requires the PAGE to read this\n // cookie and echo it in a header. Under `httpOnly: true` `document.cookie`\n // returns nothing, no header is sent, and every mutating request answers\n // 403 — the documented client flow could not work. The token is not a\n // credential; a token an attacker cannot read is also one your own page\n // cannot send. Set `cookieOptions: { httpOnly: true }` only when the token\n // reaches the client some other way (server-rendered, or your own endpoint).\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Generate or reuse CSRF token\n // NOT `req.cookies` alone: that is populated only by an upstream parser,\n // which Fastify and h3 never have and Express only has if the app mounts\n // one. Without this the middleware never saw the token it had just issued.\n const cookies = readCookies(req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(res, cookieName, token, cookieOpts)\n }\n\n // Skip validation for safe methods and ignored paths\n if (!protectedMethods.has(req.method.toUpperCase())) {\n return next()\n }\n\n // `req.path` is Express-only, so `has(undefined)` never matched and\n // configured exemptions were silently ignored on Fastify / h3.\n if (ignorePaths.has(resolvePathname(req as ClientRequestLike))) {\n return next()\n }\n\n if (checkOrigin && !isAllowedOrigin(req.headers as HeaderBag, trusted)) {\n return sendJson(res, 403, ORIGIN_REJECTED)\n }\n\n // Validate: header token must match cookie token\n const headerToken = req.headers[headerName] as string | undefined\n\n if (typeof headerToken !== 'string' || !safeEqual(headerToken, token)) {\n return sendJson(res, 403, {\n message: 'CSRF token mismatch',\n })\n }\n\n next()\n }\n}\n\nexport interface CsrfGuardOptions extends CsrfOptions {\n /**\n * Skip the token check on routes carrying a route flag — a name, a list of\n * names (any-of), or a predicate.\n *\n * This is the reason the guard exists. `csrf()` runs before route matching,\n * so its only handle on \"not this endpoint\" is {@link CsrfOptions.ignorePaths}\n * — an exact pathname string that cannot express `/webhooks/:provider` and\n * keeps parsing after an `apiPrefix` change that voids it. A flag is declared\n * on the route itself:\n *\n * ```ts\n * const CsrfExempt = defineRouteFlag('csrf.exempt')\n *\n * @CsrfExempt\n * @Controller()\n * class WebhooksController {\n * @Post('/:provider') receive(ctx: RequestContext) {}\n * }\n * ```\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Double-submit cookie CSRF protection as a `(ctx, next)` middleware.\n *\n * The ctx-style counterpart of {@link csrf}: it runs inside the matched route,\n * so it can read `ctx.route.flags` and be exempted per route, and it works on\n * every runtime including the `@forinda/kickjs/web` fetch entry.\n *\n * ```ts\n * // per controller — the flag-aware form\n * @Middleware(csrfGuard({ exemptWhen: 'csrf.exempt' }))\n * @Controller()\n * class BillingController {}\n *\n * // edge, app-wide\n * createWebApp({ h3, modules, middleware: [csrfGuard()] })\n * ```\n *\n * Mount `csrf()` instead when you want one app-wide connect middleware that\n * also covers requests matching no route — nothing to exempt, nothing to read.\n */\nexport function csrfGuard(options: CsrfGuardOptions = {}): MiddlewareHandler {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'csrfGuard({ exemptWhen })')\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // Same default as `csrf()` above, and for the same reason.\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (ctx: RequestContext, next: () => void): void => {\n const cookies = readCookies(ctx.req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(ctx.res, cookieName, token, cookieOpts)\n }\n\n // Safe methods only ever issue the token.\n const method = ctx.route?.method ?? (ctx.req as { method?: string }).method ?? 'GET'\n if (!protectedMethods.has(method.toUpperCase())) return next()\n\n // Flag first: it is the declared exemption, and cheaper than the path set.\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n if (ignorePaths.has(resolvePathname(ctx.req as unknown as ClientRequestLike))) return next()\n\n if (checkOrigin && !isAllowedOrigin(ctx.headers as HeaderBag, trusted)) {\n ctx.json(ORIGIN_REJECTED, 403)\n return\n }\n\n const headerToken = ctx.headers[headerName] as string | undefined\n if (typeof headerToken !== 'string' || !safeEqual(headerToken, token)) {\n ctx.json({ message: 'CSRF token mismatch' }, 403)\n return\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;4bA0DA,SAAS,SAAS,QAAoB,KAAkC,CACtE,IAAM,MAAQ,QAAQ,MACtB,OAAO,MAAM,QAAQ,KAAK,EAAI,MAAM,GAAK,KAC3C,CAGA,SAAS,YAAY,IAA6C,CAChE,GAAK,IACL,GAAI,CACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC,MACtB,MAAQ,CACN,MACF,CACF,CAQA,SAAgB,gBAAgB,QAAoB,QAAuC,CACzF,IAAM,KAAO,SAAS,QAAS,gBAAgB,EAC/C,GAAI,OAAS,cAAe,MAAO,GAEnC,IAAM,SAAW,SAAS,QAAS,QAAQ,GAAK,YAAY,SAAS,QAAS,SAAS,CAAC,EACxF,GAAI,WAAa,IAAA,GAIf,OAAO,OAAS,IAAA,IAAa,OAAS,OAIxC,IAAM,OAAS,aAAa,QAAQ,EACpC,GAAI,CAAC,OAAQ,MAAO,GACpB,GAAI,QAAQ,IAAI,OAAO,MAAM,EAAG,MAAO,GAIvC,IAAM,KAAO,cACX,SAAS,QAAS,MAAM,GAAK,SAAS,QAAS,YAAY,EAC3D,OAAO,QACT,EACA,OAAO,OAAS,IAAA,IAAa,OAAS,OAAO,IAC/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@@
1
1
 
2
- import { n as errorHandler, r as notFoundHandler, t as MountedRoute } from "../../error-handler-CbP7hKdJ.mjs";
2
+ import { n as errorHandler, r as notFoundHandler, t as MountedRoute } from "../../error-handler-CH4PPZCK.mjs";
3
3
  export { MountedRoute, errorHandler, notFoundHandler };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger,describeError}from"../../core/logger.mjs";import{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{t as isProduction}from"../../is-production-BTroGhp5.mjs";const log=createLogger(`ErrorHandler`);function patternToRegExp(pattern){let source=pattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\/:[^/]+/g,`/[^/]+`).replace(/\*/g,`.*`);return RegExp(`^${source}/?$`)}function pathOf(req){let url=req.originalUrl??req.url??`/`,cut=url.search(/[?#]/);return cut===-1?url:url.slice(0,cut)}function notFoundHandler(routes=[]){let matchers=routes.map(route=>({method:route.method.toUpperCase(),matches:patternToRegExp(route.path)}));return(req,res,_next)=>{let path=pathOf(req),method=(req.method??`GET`).toUpperCase(),allowed=[...new Set(matchers.filter(m=>m.matches.test(path)).map(m=>m.method))];if(allowed.length>0&&!allowed.includes(method)){let verbs=allowed.toSorted().join(`, `);return res.setHeader(`Allow`,verbs),res.setHeader(`Content-Type`,`application/problem+json`),res.status(405).json(normalizeProblem({status:405,detail:`${method} is not supported for this resource. Allowed: ${verbs}.`}))}return res.setHeader(`Content-Type`,`application/problem+json`),res.status(404).json(normalizeProblem({status:404}))}}function fieldErrors(details){if(Array.isArray(details)&&details.length!==0)return details.every(d=>typeof d?.field==`string`&&typeof d?.message==`string`)?details.map(d=>({field:d.field,message:d.message})):void 0}function errorHandler(){return(err,req,res,_next)=>{let isProduction$1=isProduction();if(res.headersSent){log.warn(`Error after headers sent: ${err?.message||`Unknown`}`);return}if(err instanceof ProblemException){if(err.problem.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let body=normalizeProblem(err.problem);return res.setHeader(`Content-Type`,`application/problem+json`),res.status(body.status).json(body)}if(err?.name===`ZodError`){let firstIssue=err.issues?.[0];return res.status(422).json({message:firstIssue?.message||`Validation failed`,...isProduction$1?{}:{errors:err.issues}})}if(err instanceof HttpException){if(err.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let errors=isProduction$1?err.status===422?fieldErrors(err.details):void 0:err.details;return res.setHeader(`Content-Type`,`application/problem+json`),res.status(err.status).json(normalizeProblem({status:err.status,detail:err.message,...errors===void 0?{}:{errors}}))}let requestId=req.requestId??req.headers[`x-request-id`],declared=Number(err.status??err.statusCode);if(Number.isInteger(declared)&&declared>=400&&declared<500)return log.warn(`${req.method} ${req.originalUrl??req.url} — ${declared} ${describeError(err)}`),res.setHeader(`Content-Type`,`application/problem+json`),res.status(declared).json(normalizeProblem({status:declared,detail:err.message||void 0,...requestId?{requestId}:{}}));let status=Number.isInteger(declared)&&declared>=500&&declared<600?declared:500;log.error(err,`${req.method} ${req.originalUrl??req.url} — ${describeError(err)}${requestId?` [${requestId}]`:``}`),res.status(status).json({message:`Internal Server Error`,...requestId?{requestId}:{},...isProduction$1?{}:{error:describeError(err),...typeof err?.stack==`string`?{stack:err.stack.split(`
11
+ import{createLogger,describeError}from"../../core/logger.mjs";import{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{t as isProduction}from"../../is-production-MYGnN2Nv.mjs";const log=createLogger(`ErrorHandler`);function patternToRegExp(pattern){let source=pattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\/:[^/]+/g,`/[^/]+`).replace(/\*/g,`.*`);return RegExp(`^${source}/?$`)}function pathOf(req){let url=req.originalUrl??req.url??`/`,cut=url.search(/[?#]/);return cut===-1?url:url.slice(0,cut)}function notFoundHandler(routes=[]){let matchers=routes.map(route=>({method:route.method.toUpperCase(),matches:patternToRegExp(route.path)}));return(req,res,_next)=>{let path=pathOf(req),method=(req.method??`GET`).toUpperCase(),allowed=[...new Set(matchers.filter(m=>m.matches.test(path)).map(m=>m.method))];if(allowed.length>0&&!allowed.includes(method)){let verbs=allowed.toSorted().join(`, `);return res.setHeader(`Allow`,verbs),res.setHeader(`Content-Type`,`application/problem+json`),res.status(405).json(normalizeProblem({status:405,detail:`${method} is not supported for this resource. Allowed: ${verbs}.`}))}return res.setHeader(`Content-Type`,`application/problem+json`),res.status(404).json(normalizeProblem({status:404}))}}function fieldErrors(details){if(Array.isArray(details)&&details.length!==0)return details.every(d=>typeof d?.field==`string`&&typeof d?.message==`string`)?details.map(d=>({field:d.field,message:d.message})):void 0}function errorHandler(){return(err,req,res,_next)=>{let isProduction$1=isProduction();if(res.headersSent){log.warn(`Error after headers sent: ${err?.message||`Unknown`}`);return}if(err instanceof ProblemException){if(err.problem.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let body=normalizeProblem(err.problem);return res.setHeader(`Content-Type`,`application/problem+json`),res.status(body.status).json(body)}if(err?.name===`ZodError`){let firstIssue=err.issues?.[0];return res.status(422).json({message:firstIssue?.message||`Validation failed`,...isProduction$1?{}:{errors:err.issues}})}if(err instanceof HttpException){if(err.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let errors=isProduction$1?err.status===422?fieldErrors(err.details):void 0:err.details;return res.setHeader(`Content-Type`,`application/problem+json`),res.status(err.status).json(normalizeProblem({status:err.status,detail:err.message,...errors===void 0?{}:{errors}}))}let requestId=req.requestId??req.headers[`x-request-id`],declared=Number(err.status??err.statusCode);if(Number.isInteger(declared)&&declared>=400&&declared<500)return log.warn(`${req.method} ${req.originalUrl??req.url} — ${declared} ${describeError(err)}`),res.setHeader(`Content-Type`,`application/problem+json`),res.status(declared).json(normalizeProblem({status:declared,detail:err.message||void 0,...requestId?{requestId}:{}}));let status=Number.isInteger(declared)&&declared>=500&&declared<600?declared:500;log.error(err,`${req.method} ${req.originalUrl??req.url} — ${describeError(err)}${requestId?` [${requestId}]`:``}`),res.status(status).json({message:`Internal Server Error`,...requestId?{requestId}:{},...isProduction$1?{}:{error:describeError(err),...typeof err?.stack==`string`?{stack:err.stack.split(`
12
12
  `)}:{}}})}}export{errorHandler,notFoundHandler};
13
13
  //# sourceMappingURL=error-handler.mjs.map
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as HelmetOptions, r as helmet, t as HELMET_MIDDLEWARE } from "../../helmet-CEOmo516.mjs";
2
+ import { n as HelmetOptions, r as helmet, t as HELMET_MIDDLEWARE } from "../../helmet-BVuVBl-D.mjs";
3
3
  export { HELMET_MIDDLEWARE, HelmetOptions, helmet };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"helmet.mjs","names":[],"sources":["../../../src/http/middleware/helmet.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\n/** Brand identifying a `helmet()` handler, so auto-injection can stand down. */\nexport const HELMET_MIDDLEWARE = Symbol.for('kick/http/helmet')\n\nexport interface HelmetOptions {\n /** Set Content-Security-Policy header (default: self-only policy) */\n contentSecurityPolicy?: boolean | Record<string, string[]>\n /** Set X-Content-Type-Options: nosniff (default: true) */\n noSniff?: boolean\n /** Set X-Frame-Options (default: 'DENY') */\n frameguard?: false | 'DENY' | 'SAMEORIGIN'\n /** Set Strict-Transport-Security (default: max-age=31536000; includeSubDomains) */\n hsts?: false | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }\n /** Set X-DNS-Prefetch-Control (default: off) */\n dnsPrefetch?: boolean\n /** Remove X-Powered-By header (default: true) */\n hidePoweredBy?: boolean\n /** Set Referrer-Policy (default: 'no-referrer') */\n referrerPolicy?: false | string\n /** Set X-XSS-Protection: 0 (default: true — disables legacy XSS auditor) */\n xssFilter?: boolean\n}\n\n/**\n * Security headers middleware. Lightweight alternative to the `helmet` npm package\n * with sensible defaults for API servers.\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [helmet(), requestId(), express.json()],\n * })\n * ```\n *\n * Options are read once, when the middleware is created: changing the options\n * object afterwards does not change the headers. Create a new middleware instead.\n */\nexport function helmet(options: HelmetOptions = {}) {\n const {\n noSniff = true,\n frameguard = 'DENY',\n hsts = { maxAge: 31536000, includeSubDomains: true },\n dnsPrefetch = false,\n hidePoweredBy = true,\n referrerPolicy = 'no-referrer',\n xssFilter = true,\n contentSecurityPolicy = false,\n } = options\n\n // Header values depend only on the options — built once, not per request.\n const hstsValue = hsts\n ? `max-age=${hsts.maxAge ?? 31536000}${hsts.includeSubDomains ? '; includeSubDomains' : ''}${\n hsts.preload ? '; preload' : ''\n }`\n : undefined\n const cspValue = !contentSecurityPolicy\n ? undefined\n : typeof contentSecurityPolicy === 'object'\n ? Object.entries(contentSecurityPolicy)\n .map(([key, values]) => `${key} ${values.join(' ')}`)\n .join('; ')\n : \"default-src 'self'\"\n\n const handler = (req: Request, res: Response, next: NextFunction) => {\n if (hidePoweredBy) res.removeHeader('X-Powered-By')\n if (noSniff) res.setHeader('X-Content-Type-Options', 'nosniff')\n if (frameguard) res.setHeader('X-Frame-Options', frameguard)\n if (xssFilter) res.setHeader('X-XSS-Protection', '0')\n if (referrerPolicy) res.setHeader('Referrer-Policy', referrerPolicy)\n if (!dnsPrefetch) res.setHeader('X-DNS-Prefetch-Control', 'off')\n\n if (hstsValue) res.setHeader('Strict-Transport-Security', hstsValue)\n if (cspValue) res.setHeader('Content-Security-Policy', cspValue)\n\n next()\n }\n\n // Brand the handler so the Application skips its own auto-injection. Without\n // that, auto-helmet runs first with defaults and a user helmet can only ADD\n // headers — an explicit `frameguard: false` would leave the auto-injected\n // `X-Frame-Options: DENY` standing.\n return Object.defineProperty(handler, HELMET_MIDDLEWARE, { value: true })\n}\n"],"mappings":";;;;;;;;;;AAGA,MAAa,kBAAoB,OAAO,IAAI,kBAAkB,EAmC9D,SAAgB,OAAO,QAAyB,CAAC,EAAG,CAClD,GAAM,CACJ,QAAU,GACV,WAAa,OACb,KAAO,CAAE,OAAQ,QAAU,kBAAmB,EAAK,EACnD,YAAc,GACd,cAAgB,GAChB,eAAiB,cACjB,UAAY,GACZ,sBAAwB,IACtB,QAGE,UAAY,KACd,WAAW,KAAK,QAAU,UAAW,KAAK,kBAAoB,sBAAwB,KACpF,KAAK,QAAU,YAAc,KAE/B,IAAA,GACE,SAAY,sBAEd,OAAO,uBAA0B,SAC/B,OAAO,QAAQ,qBAAqB,CAAC,CAClC,KAAK,CAAC,IAAK,UAAY,GAAG,IAAI,GAAG,OAAO,KAAK,GAAG,GAAG,CAAC,CACpD,KAAK,IAAI,EACZ,qBALF,IAAA,GAyBJ,OAAO,OAAO,gBAlBG,IAAc,IAAe,OAAuB,CAC/D,eAAe,IAAI,aAAa,cAAc,EAC9C,SAAS,IAAI,UAAU,yBAA0B,SAAS,EAC1D,YAAY,IAAI,UAAU,kBAAmB,UAAU,EACvD,WAAW,IAAI,UAAU,mBAAoB,GAAG,EAChD,gBAAgB,IAAI,UAAU,kBAAmB,cAAc,EAC9D,aAAa,IAAI,UAAU,yBAA0B,KAAK,EAE3D,WAAW,IAAI,UAAU,4BAA6B,SAAS,EAC/D,UAAU,IAAI,UAAU,0BAA2B,QAAQ,EAE/D,KAAK,CACP,EAMsC,kBAAmB,CAAE,MAAO,EAAK,CAAC,CAC1E"}
1
+ {"version":3,"file":"helmet.mjs","names":[],"sources":["../../../src/http/middleware/helmet.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\n/** Brand identifying a `helmet()` handler, so auto-injection can stand down. */\nexport const HELMET_MIDDLEWARE = Symbol.for('kick/http/helmet')\n\nexport interface HelmetOptions {\n /** Set Content-Security-Policy header (default: self-only policy) */\n contentSecurityPolicy?: boolean | Record<string, string[]>\n /** Set X-Content-Type-Options: nosniff (default: true) */\n noSniff?: boolean\n /** Set X-Frame-Options (default: 'DENY') */\n frameguard?: false | 'DENY' | 'SAMEORIGIN'\n /** Set Strict-Transport-Security (default: max-age=31536000; includeSubDomains) */\n hsts?: false | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }\n /** Set X-DNS-Prefetch-Control (default: off) */\n dnsPrefetch?: boolean\n /** Remove X-Powered-By header (default: true) */\n hidePoweredBy?: boolean\n /** Set Referrer-Policy (default: 'no-referrer') */\n referrerPolicy?: false | string\n /** Set X-XSS-Protection: 0 (default: true — disables legacy XSS auditor) */\n xssFilter?: boolean\n}\n\n/**\n * Security headers middleware. Lightweight alternative to the `helmet` npm package\n * with sensible defaults for API servers.\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [helmet(), requestId(), express.json()],\n * })\n * ```\n *\n * Options are read once, when the middleware is created: changing the options\n * object afterwards does not change the headers. Create a new middleware instead.\n */\nexport function helmet(options: HelmetOptions = {}) {\n const {\n noSniff = true,\n frameguard = 'DENY',\n hsts = { maxAge: 31536000, includeSubDomains: true },\n dnsPrefetch = false,\n hidePoweredBy = true,\n referrerPolicy = 'no-referrer',\n xssFilter = true,\n contentSecurityPolicy = false,\n } = options\n\n // Header values depend only on the options — built once, not per request.\n const hstsValue = hsts\n ? `max-age=${hsts.maxAge ?? 31536000}${hsts.includeSubDomains ? '; includeSubDomains' : ''}${\n hsts.preload ? '; preload' : ''\n }`\n : undefined\n const cspValue = !contentSecurityPolicy\n ? undefined\n : typeof contentSecurityPolicy === 'object'\n ? Object.entries(contentSecurityPolicy)\n .map(([key, values]) => `${key} ${values.join(' ')}`)\n .join('; ')\n : \"default-src 'self'\"\n\n const handler = (req: Request, res: Response, next: NextFunction) => {\n if (hidePoweredBy) res.removeHeader('X-Powered-By')\n if (noSniff) res.setHeader('X-Content-Type-Options', 'nosniff')\n if (frameguard) res.setHeader('X-Frame-Options', frameguard)\n if (xssFilter) res.setHeader('X-XSS-Protection', '0')\n if (referrerPolicy) res.setHeader('Referrer-Policy', referrerPolicy)\n if (!dnsPrefetch) res.setHeader('X-DNS-Prefetch-Control', 'off')\n\n if (hstsValue) res.setHeader('Strict-Transport-Security', hstsValue)\n if (cspValue) res.setHeader('Content-Security-Policy', cspValue)\n\n next()\n }\n\n // Brand the handler so the Application skips its own auto-injection. Without\n // that, auto-helmet runs first with defaults and a user helmet can only ADD\n // headers — an explicit `frameguard: false` would leave the auto-injected\n // `X-Frame-Options: DENY` standing.\n return Object.defineProperty(handler, HELMET_MIDDLEWARE, { value: true })\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,kBAAoB,OAAO,IAAI,kBAAkB,EAmC9D,SAAgB,OAAO,QAAyB,CAAC,EAAG,CAClD,GAAM,CACJ,QAAU,GACV,WAAa,OACb,KAAO,CAAE,OAAQ,QAAU,kBAAmB,EAAK,EACnD,YAAc,GACd,cAAgB,GAChB,eAAiB,cACjB,UAAY,GACZ,sBAAwB,IACtB,QAGE,UAAY,KACd,WAAW,KAAK,QAAU,UAAW,KAAK,kBAAoB,sBAAwB,KACpF,KAAK,QAAU,YAAc,KAE/B,IAAA,GACE,SAAY,sBAEd,OAAO,uBAA0B,SAC/B,OAAO,QAAQ,qBAAqB,CAAC,CAClC,KAAK,CAAC,IAAK,UAAY,GAAG,IAAI,GAAG,OAAO,KAAK,GAAG,GAAG,CAAC,CACpD,KAAK,IAAI,EACZ,qBALF,IAAA,GAyBJ,OAAO,OAAO,gBAlBG,IAAc,IAAe,OAAuB,CAC/D,eAAe,IAAI,aAAa,cAAc,EAC9C,SAAS,IAAI,UAAU,yBAA0B,SAAS,EAC1D,YAAY,IAAI,UAAU,kBAAmB,UAAU,EACvD,WAAW,IAAI,UAAU,mBAAoB,GAAG,EAChD,gBAAgB,IAAI,UAAU,kBAAmB,cAAc,EAC9D,aAAa,IAAI,UAAU,yBAA0B,KAAK,EAE3D,WAAW,IAAI,UAAU,4BAA6B,SAAS,EAC/D,UAAU,IAAI,UAAU,0BAA2B,QAAQ,EAE/D,KAAK,CACP,EAMsC,kBAAmB,CAAE,MAAO,EAAK,CAAC,CAC1E"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { i as rateLimit, n as RateLimitOptions, r as RateLimitStore, t as MemoryStore } from "../../rate-limit-BgoeahE5.mjs";
2
+ import { i as rateLimit, n as RateLimitOptions, r as RateLimitStore, t as MemoryStore } from "../../rate-limit-DQDk6bAH.mjs";
3
3
  export { MemoryStore, RateLimitOptions, RateLimitStore, rateLimit };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{r as registerDisposable}from"../../disposables-DYTkgNiG.mjs";import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-BPSq2JCs.mjs";import{n as bindRoutePolicy}from"../../route-policy-DDszB6dQ.mjs";import{n as resolvePathname,t as resolveClientIp}from"../../client-ip-BLkoQTIR.mjs";import{i as sendJson}from"../../respond-BOlh-baJ.mjs";import{t as BoundedCounters}from"../../bounded-counters-DS-IbDW9.mjs";var MemoryStore=class{counters;cleanupTimer;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit),this.cleanupTimer=setInterval(()=>this.counters.sweep(),windowMs),this.cleanupTimer.unref&&this.cleanupTimer.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupTimer),this.counters.clear()}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function rateLimit(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??(req=>resolveClientIp(req)??`global`),sendHeaders=options.headers??!0,store=options.store??new MemoryStore(windowMs,max),skip=options.skip,skipPaths=new Set(options.skipPaths??[]),exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimit({ exemptWhen })`);let policy;return bindRoutePolicy(async(req,res,next)=>{let pathname=resolvePathname(req);if(skipPaths.has(pathname))return next();if(exemptWhen!==void 0&&policy){let{originalUrl}=req,routePath=originalUrl?resolvePathname({url:originalUrl}):pathname,flags=policy.lookup(String(req.method??`GET`),routePath);if(matchesFlagTest(exemptWhen,flags))return next()}if(skip&&skip(req))return next();let key=keyGenerator(req),{totalHits,resetTime}=await store.increment(key),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(res.setHeader(`RateLimit-Limit`,max),res.setHeader(`RateLimit-Remaining`,remaining),res.setHeader(`RateLimit-Reset`,Math.ceil(resetTime.getTime()/1e3))),totalHits>max)return sendJson(res,statusCode,{message});next()},table=>{policy=table})}export{MemoryStore,rateLimit};
11
+ import{r as registerDisposable}from"../../disposables-BgUIg4s1.mjs";import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-DCOS_F5A.mjs";import{n as bindRoutePolicy}from"../../route-policy-Cy-oSUro.mjs";import{n as resolvePathname,t as resolveClientIp}from"../../client-ip-DxEVqZP-.mjs";import{i as sendJson}from"../../respond-DR7zkOUf.mjs";import{t as BoundedCounters}from"../../bounded-counters-Bd7X3eI5.mjs";var MemoryStore=class{counters;cleanupTimer;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit),this.cleanupTimer=setInterval(()=>this.counters.sweep(),windowMs),this.cleanupTimer.unref&&this.cleanupTimer.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupTimer),this.counters.clear()}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function rateLimit(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??(req=>resolveClientIp(req)??`global`),sendHeaders=options.headers??!0,store=options.store??new MemoryStore(windowMs,max),skip=options.skip,skipPaths=new Set(options.skipPaths??[]),exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimit({ exemptWhen })`);let policy;return bindRoutePolicy(async(req,res,next)=>{let pathname=resolvePathname(req);if(skipPaths.has(pathname))return next();if(exemptWhen!==void 0&&policy){let{originalUrl}=req,routePath=originalUrl?resolvePathname({url:originalUrl}):pathname,flags=policy.lookup(String(req.method??`GET`),routePath);if(matchesFlagTest(exemptWhen,flags))return next()}if(skip&&skip(req))return next();let key=keyGenerator(req),{totalHits,resetTime}=await store.increment(key),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(res.setHeader(`RateLimit-Limit`,max),res.setHeader(`RateLimit-Remaining`,remaining),res.setHeader(`RateLimit-Reset`,Math.ceil(resetTime.getTime()/1e3))),totalHits>max)return sendJson(res,statusCode,{message});next()},table=>{policy=table})}export{MemoryStore,rateLimit};
12
12
  //# sourceMappingURL=rate-limit.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../../src/http/middleware/rate-limit.ts"],"sourcesContent":["import { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport { bindRoutePolicy, type RoutePolicyTable } from '../../core/route-policy'\nimport { sendJson } from './respond'\nimport type { Request, Response, NextFunction } from 'express'\nimport { resolveClientIp, resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitStore {\n increment(key: string): Promise<{ totalHits: number; resetTime: Date }>\n decrement(key: string): Promise<void>\n reset(key: string): Promise<void>\n}\n\nexport interface RateLimitOptions {\n /** Maximum number of requests per window (default: 100) */\n max?: number\n /** Time window in milliseconds (default: 60_000) */\n windowMs?: number\n /** Response message when rate limit is exceeded (default: 'Too Many Requests') */\n message?: string\n /** HTTP status code when rate limit is exceeded (default: 429) */\n statusCode?: number\n /** Function to generate the key for rate limiting (default: req.ip) */\n keyGenerator?: (req: Request) => string\n /** Whether to send rate limit headers (default: true) */\n headers?: boolean\n /** Custom store implementation (default: in-memory Map) */\n store?: RateLimitStore\n /** Function to skip rate limiting for certain requests */\n skip?: (req: Request) => boolean\n /** Paths to exclude from rate limiting */\n skipPaths?: string[]\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate.\n *\n * This middleware runs before route matching, so it has no `ctx.route` to\n * read. Instead the Application hands it a table of every mounted route's\n * flags at boot, and the incoming method + pathname is looked up against it.\n * Requests matching no route match no flags — which is the point of limiting\n * here rather than in a route-scoped guard.\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * bootstrap({ middlewares: [rateLimit({ max: 60, exemptWhen: 'auth.public' })] })\n * ```\n *\n * Prefer `skipPaths` only for paths that are not routes at all (a static\n * mount, a proxied prefix); a flag cannot describe those.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/** @internal Exported for tests. Bounded: see {@link BoundedCounters}. */\nexport class MemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n private cleanupTimer: ReturnType<typeof setInterval>\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n this.cleanupTimer = setInterval(() => this.counters.sweep(), windowMs)\n // Allow the process to exit without waiting for the timer\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref()\n }\n // Symmetric teardown: Application.shutdown() drains the disposables\n // registry — without this, every in-process app re-create (tests, HMR)\n // leaked one live interval + its hits Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all hit counters. */\n dispose(): void {\n clearInterval(this.cleanupTimer)\n this.counters.clear()\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\n/**\n * Rate limiting middleware.\n *\n * Limits the number of requests a client can make within a time window.\n * Uses an in-memory store by default, but accepts a custom store for\n * distributed deployments (e.g. Redis).\n *\n * @example\n * ```ts\n * import { rateLimit } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * rateLimit({ max: 100, windowMs: 60_000 }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function rateLimit(options: RateLimitOptions = {}) {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n // `req.ip` is Express-only. Under Fastify and h3 it is undefined, so EVERY\n // caller fell back to the same `'127.0.0.1'` literal — one shared bucket,\n // letting a single client exhaust the limit for everyone.\n const keyGenerator =\n options.keyGenerator ??\n ((req: Request) => resolveClientIp(req as ClientRequestLike) ?? 'global')\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new MemoryStore(windowMs, max)\n const skip = options.skip\n const skipPaths = new Set(options.skipPaths ?? [])\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimit({ exemptWhen })')\n\n // Filled in by the Application once routes are mounted, via the slot\n // declared below. Absent when this middleware runs outside an Application\n // (a bare connect stack, a unit test) — `exemptWhen` then matches nothing,\n // which fails closed: everything stays limited.\n let policy: RoutePolicyTable | undefined\n\n const handler = async (req: Request, res: Response, next: NextFunction) => {\n // Skip if path is in the skip list\n // `req.path` is Express-only; `has(undefined)` never matched, so\n // configured skips were silently dead on the other runtimes.\n const pathname = resolvePathname(req as ClientRequestLike)\n if (skipPaths.has(pathname)) {\n return next()\n }\n\n // Flag exemption: ask the table what flags the matched route WOULD carry.\n // A request matching no route matches no flags and stays limited.\n // Routes are registered by their full path; mounted at a path, `req.url`\n // is relative to the mount, so look the route up by `originalUrl`.\n if (exemptWhen !== undefined && policy) {\n const { originalUrl } = req as ClientRequestLike\n const routePath = originalUrl ? resolvePathname({ url: originalUrl }) : pathname\n const flags = policy.lookup(String(req.method ?? 'GET'), routePath)\n if (matchesFlagTest(exemptWhen, flags)) {\n return next()\n }\n }\n\n // Skip if the skip function returns true\n if (skip && skip(req)) {\n return next()\n }\n\n const key = keyGenerator(req)\n const { totalHits, resetTime } = await store.increment(key)\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n res.setHeader('RateLimit-Limit', max)\n res.setHeader('RateLimit-Remaining', remaining)\n res.setHeader('RateLimit-Reset', Math.ceil(resetTime.getTime() / 1000))\n }\n\n if (totalHits > max) {\n return sendJson(res, statusCode, { message })\n }\n\n next()\n }\n\n return bindRoutePolicy(handler, (table) => {\n policy = table\n })\n}\n"],"mappings":";;;;;;;;;;0aAwDA,IAAa,YAAb,KAAmD,CACjD,SACA,aAGA,YAAY,SAAkB,MAAgB,CAC5C,KAAK,SAAW,IAAI,gBAAgB,SAAU,KAAK,EACnD,KAAK,aAAe,gBAAkB,KAAK,SAAS,MAAM,EAAG,QAAQ,EAEjE,KAAK,aAAa,OACpB,KAAK,aAAa,MAAM,EAK1B,uBAAyB,KAAK,QAAQ,CAAC,CACzC,CAGA,SAAgB,CACd,cAAc,KAAK,YAAY,EAC/B,KAAK,SAAS,MAAM,CACtB,CAEA,MAAM,UAAU,IAA8D,CAC5E,OAAO,KAAK,SAAS,UAAU,GAAG,CACpC,CAEA,MAAM,UAAU,IAA4B,CAC1C,KAAK,SAAS,UAAU,GAAG,CAC7B,CAEA,MAAM,MAAM,IAA4B,CACtC,KAAK,SAAS,MAAM,GAAG,CACzB,CACF,EAsBA,SAAgB,UAAU,QAA4B,CAAC,EAAG,CACxD,IAAM,IAAM,QAAQ,KAAO,IACrB,SAAW,QAAQ,UAAY,IAC/B,QAAU,QAAQ,SAAW,oBAC7B,WAAa,QAAQ,YAAc,IAInC,aACJ,QAAQ,eACN,KAAiB,gBAAgB,GAAwB,GAAK,UAC5D,YAAc,QAAQ,SAAW,GACjC,MAAQ,QAAQ,OAAS,IAAI,YAAY,SAAU,GAAG,EACtD,KAAO,QAAQ,KACf,UAAY,IAAI,IAAI,QAAQ,WAAa,CAAC,CAAC,EAC3C,WAAa,QAAQ,WACvB,aAAe,IAAA,IAAW,eAAe,WAAY,2BAA2B,EAMpF,IAAI,OA8CJ,OAAO,gBAAgB,MA5CA,IAAc,IAAe,OAAuB,CAIzE,IAAM,SAAW,gBAAgB,GAAwB,EACzD,GAAI,UAAU,IAAI,QAAQ,EACxB,OAAO,KAAK,EAOd,GAAI,aAAe,IAAA,IAAa,OAAQ,CACtC,GAAM,CAAE,aAAgB,IAClB,UAAY,YAAc,gBAAgB,CAAE,IAAK,WAAY,CAAC,EAAI,SAClE,MAAQ,OAAO,OAAO,OAAO,IAAI,QAAU,KAAK,EAAG,SAAS,EAClE,GAAI,gBAAgB,WAAY,KAAK,EACnC,OAAO,KAAK,CAEhB,CAGA,GAAI,MAAQ,KAAK,GAAG,EAClB,OAAO,KAAK,EAGd,IAAM,IAAM,aAAa,GAAG,EACtB,CAAE,UAAW,WAAc,MAAM,MAAM,UAAU,GAAG,EACpD,UAAY,KAAK,IAAI,EAAG,IAAM,SAAS,EAQ7C,GANI,cACF,IAAI,UAAU,kBAAmB,GAAG,EACpC,IAAI,UAAU,sBAAuB,SAAS,EAC9C,IAAI,UAAU,kBAAmB,KAAK,KAAK,UAAU,QAAQ,EAAI,GAAI,CAAC,GAGpE,UAAY,IACd,OAAO,SAAS,IAAK,WAAY,CAAE,OAAQ,CAAC,EAG9C,KAAK,CACP,EAEiC,OAAU,CACzC,OAAS,KACX,CAAC,CACH"}
1
+ {"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../../src/http/middleware/rate-limit.ts"],"sourcesContent":["import { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport { bindRoutePolicy, type RoutePolicyTable } from '../../core/route-policy'\nimport { sendJson } from './respond'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\nimport { resolveClientIp, resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { BoundedCounters } from './bounded-counters'\n\nexport interface RateLimitStore {\n increment(key: string): Promise<{ totalHits: number; resetTime: Date }>\n decrement(key: string): Promise<void>\n reset(key: string): Promise<void>\n}\n\nexport interface RateLimitOptions {\n /** Maximum number of requests per window (default: 100) */\n max?: number\n /** Time window in milliseconds (default: 60_000) */\n windowMs?: number\n /** Response message when rate limit is exceeded (default: 'Too Many Requests') */\n message?: string\n /** HTTP status code when rate limit is exceeded (default: 429) */\n statusCode?: number\n /** Function to generate the key for rate limiting (default: req.ip) */\n keyGenerator?: (req: Request) => string\n /** Whether to send rate limit headers (default: true) */\n headers?: boolean\n /** Custom store implementation (default: in-memory Map) */\n store?: RateLimitStore\n /** Function to skip rate limiting for certain requests */\n skip?: (req: Request) => boolean\n /** Paths to exclude from rate limiting */\n skipPaths?: string[]\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate.\n *\n * This middleware runs before route matching, so it has no `ctx.route` to\n * read. Instead the Application hands it a table of every mounted route's\n * flags at boot, and the incoming method + pathname is looked up against it.\n * Requests matching no route match no flags — which is the point of limiting\n * here rather than in a route-scoped guard.\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * bootstrap({ middlewares: [rateLimit({ max: 60, exemptWhen: 'auth.public' })] })\n * ```\n *\n * Prefer `skipPaths` only for paths that are not routes at all (a static\n * mount, a proxied prefix); a flag cannot describe those.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/** @internal Exported for tests. Bounded: see {@link BoundedCounters}. */\nexport class MemoryStore implements RateLimitStore {\n private readonly counters: BoundedCounters\n private cleanupTimer: ReturnType<typeof setInterval>\n\n /** @param limit The `max` it enforces, so it never evicts a counter at the limit. */\n constructor(windowMs: number, limit?: number) {\n this.counters = new BoundedCounters(windowMs, limit)\n this.cleanupTimer = setInterval(() => this.counters.sweep(), windowMs)\n // Allow the process to exit without waiting for the timer\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref()\n }\n // Symmetric teardown: Application.shutdown() drains the disposables\n // registry — without this, every in-process app re-create (tests, HMR)\n // leaked one live interval + its hits Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all hit counters. */\n dispose(): void {\n clearInterval(this.cleanupTimer)\n this.counters.clear()\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n return this.counters.increment(key)\n }\n\n async decrement(key: string): Promise<void> {\n this.counters.decrement(key)\n }\n\n async reset(key: string): Promise<void> {\n this.counters.reset(key)\n }\n}\n\n/**\n * Rate limiting middleware.\n *\n * Limits the number of requests a client can make within a time window.\n * Uses an in-memory store by default, but accepts a custom store for\n * distributed deployments (e.g. Redis).\n *\n * @example\n * ```ts\n * import { rateLimit } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * rateLimit({ max: 100, windowMs: 60_000 }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function rateLimit(options: RateLimitOptions = {}) {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n // `req.ip` is Express-only. Under Fastify and h3 it is undefined, so EVERY\n // caller fell back to the same `'127.0.0.1'` literal — one shared bucket,\n // letting a single client exhaust the limit for everyone.\n const keyGenerator =\n options.keyGenerator ??\n ((req: Request) => resolveClientIp(req as ClientRequestLike) ?? 'global')\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new MemoryStore(windowMs, max)\n const skip = options.skip\n const skipPaths = new Set(options.skipPaths ?? [])\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimit({ exemptWhen })')\n\n // Filled in by the Application once routes are mounted, via the slot\n // declared below. Absent when this middleware runs outside an Application\n // (a bare connect stack, a unit test) — `exemptWhen` then matches nothing,\n // which fails closed: everything stays limited.\n let policy: RoutePolicyTable | undefined\n\n const handler = async (req: Request, res: Response, next: NextFunction) => {\n // Skip if path is in the skip list\n // `req.path` is Express-only; `has(undefined)` never matched, so\n // configured skips were silently dead on the other runtimes.\n const pathname = resolvePathname(req as ClientRequestLike)\n if (skipPaths.has(pathname)) {\n return next()\n }\n\n // Flag exemption: ask the table what flags the matched route WOULD carry.\n // A request matching no route matches no flags and stays limited.\n // Routes are registered by their full path; mounted at a path, `req.url`\n // is relative to the mount, so look the route up by `originalUrl`.\n if (exemptWhen !== undefined && policy) {\n const { originalUrl } = req as ClientRequestLike\n const routePath = originalUrl ? resolvePathname({ url: originalUrl }) : pathname\n const flags = policy.lookup(String(req.method ?? 'GET'), routePath)\n if (matchesFlagTest(exemptWhen, flags)) {\n return next()\n }\n }\n\n // Skip if the skip function returns true\n if (skip && skip(req)) {\n return next()\n }\n\n const key = keyGenerator(req)\n const { totalHits, resetTime } = await store.increment(key)\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n res.setHeader('RateLimit-Limit', max)\n res.setHeader('RateLimit-Remaining', remaining)\n res.setHeader('RateLimit-Reset', Math.ceil(resetTime.getTime() / 1000))\n }\n\n if (totalHits > max) {\n return sendJson(res, statusCode, { message })\n }\n\n next()\n }\n\n return bindRoutePolicy(handler, (table) => {\n policy = table\n })\n}\n"],"mappings":";;;;;;;;;;0aA4DA,IAAa,YAAb,KAAmD,CACjD,SACA,aAGA,YAAY,SAAkB,MAAgB,CAC5C,KAAK,SAAW,IAAI,gBAAgB,SAAU,KAAK,EACnD,KAAK,aAAe,gBAAkB,KAAK,SAAS,MAAM,EAAG,QAAQ,EAEjE,KAAK,aAAa,OACpB,KAAK,aAAa,MAAM,EAK1B,uBAAyB,KAAK,QAAQ,CAAC,CACzC,CAGA,SAAgB,CACd,cAAc,KAAK,YAAY,EAC/B,KAAK,SAAS,MAAM,CACt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BAAuB,SAAS,EAC9C,IAAI,UAAU,kBAAmB,KAAK,KAAK,UAAU,QAAQ,EAAI,GAAI,CAAC,GAGpE,UAAY,IACd,OAAO,SAAS,IAAK,WAAY,CAAE,OAAQ,CAAC,EAG9C,KAAK,CACP,EAEiC,OAAU,CACzC,OAAS,KACX,CAAC,CACH"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as requestId, t as REQUEST_ID_HEADER } from "../../request-id-CVzJ1uHD.mjs";
2
+ import { n as requestId, t as REQUEST_ID_HEADER } from "../../request-id-Dn64nEHK.mjs";
3
3
  export { REQUEST_ID_HEADER, requestId };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"request-id.mjs","names":[],"sources":["../../../src/http/middleware/request-id.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport const REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Middleware that generates or propagates a unique request ID.\n *\n * Idempotent: if `req.requestId` is already set (e.g. by\n * `requestScopeMiddleware` earlier in the pipeline), this middleware reuses\n * it instead of generating a divergent second value. Keeps the\n * X-Request-Id response header, the ALS store's `requestId`, and\n * `RequestContext.requestId` in agreement for every request, regardless of\n * mounting order.\n */\nexport function requestId() {\n return (req: Request, res: Response, next: NextFunction) => {\n const existing = (req as Request & { requestId?: string }).requestId\n // globalThis.crypto (Web Crypto) — portable across node/bun/deno/workers,\n // unlike node:crypto. Node ≥ 19 exposes it globally; engines pin ≥ 20.\n const header = req.headers[REQUEST_ID_HEADER]\n const id = existing || (Array.isArray(header) ? header[0] : header) || crypto.randomUUID()\n ;(req as any).requestId = id\n res.setHeader(REQUEST_ID_HEADER, id)\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAEA,MAAa,kBAAoB,eAYjC,SAAgB,WAAY,CAC1B,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,SAAY,IAAyC,UAGrD,OAAS,IAAI,QAAQ,mBACrB,GAAK,WAAa,MAAM,QAAQ,MAAM,EAAI,OAAO,GAAK,SAAW,OAAO,WAAW,EACxF,IAAa,UAAY,GAC1B,IAAI,UAAU,kBAAmB,EAAE,EACnC,KAAK,CACP,CACF"}
1
+ {"version":3,"file":"request-id.mjs","names":[],"sources":["../../../src/http/middleware/request-id.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\nexport const REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Middleware that generates or propagates a unique request ID.\n *\n * Idempotent: if `req.requestId` is already set (e.g. by\n * `requestScopeMiddleware` earlier in the pipeline), this middleware reuses\n * it instead of generating a divergent second value. Keeps the\n * X-Request-Id response header, the ALS store's `requestId`, and\n * `RequestContext.requestId` in agreement for every request, regardless of\n * mounting order.\n */\nexport function requestId() {\n return (req: Request, res: Response, next: NextFunction) => {\n const existing = (req as Request & { requestId?: string }).requestId\n // globalThis.crypto (Web Crypto) — portable across node/bun/deno/workers,\n // unlike node:crypto. Node ≥ 19 exposes it globally; engines pin ≥ 20.\n const header = req.headers[REQUEST_ID_HEADER]\n const id = existing || (Array.isArray(header) ? header[0] : header) || crypto.randomUUID()\n ;(req as any).requestId = id\n res.setHeader(REQUEST_ID_HEADER, id)\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAMA,MAAa,kBAAoB,eAYjC,SAAgB,WAAY,CAC1B,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,SAAY,IAAyC,UAGrD,OAAS,IAAI,QAAQ,mBACrB,GAAK,WAAa,MAAM,QAAQ,MAAM,EAAI,OAAO,GAAK,SAAW,OAAO,WAAW,EACxF,IAAa,UAAY,GAC1B,IAAI,UAAU,kBAAmB,EAAE,EACnC,KAAK,CACP,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.4.0
2
+ * @forinda/kickjs v10.6.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"../../core/logger.mjs";import"../../core-CsMDdzNE.mjs";function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}function requestLogger(options={}){let log=createLogger(options.name??`HTTP`),level=options.level??`info`,skip=options.skip??[];return(req,res,next)=>{let pathname=req.path??pathnameOf(req.url);if(skip.some(prefix=>pathname.startsWith(prefix)))return next();let start=Date.now();res.on(`finish`,()=>{let duration=Date.now()-start,requestId=req.requestId||req.headers[`x-request-id`]||`-`,status=res.statusCode,path=req.originalUrl??req.url??`/`;log.child({method:req.method,path,status,ms:duration,requestId})[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)}),next()}}export{requestLogger};
11
+ import{createLogger}from"../../core/logger.mjs";import"../../core-Ddq8b9hi.mjs";function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}function requestLogger(options={}){let log=createLogger(options.name??`HTTP`),level=options.level??`info`,skip=options.skip??[];return(req,res,next)=>{let pathname=req.path??pathnameOf(req.url);if(skip.some(prefix=>pathname.startsWith(prefix)))return next();let start=Date.now();res.on(`finish`,()=>{let duration=Date.now()-start,requestId=req.requestId||req.headers[`x-request-id`]||`-`,status=res.statusCode,path=req.originalUrl??req.url??`/`;log.child({method:req.method,path,status,ms:duration,requestId})[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)}),next()}}export{requestLogger};
12
12
  //# sourceMappingURL=request-logger.mjs.map
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData, t as MemoryStore } from "../../session-ChXx7jG5.mjs";
2
+ import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData, t as MemoryStore } from "../../session-8uNRCplB.mjs";
3
3
  export { MemoryStore, Session, SessionData, SessionOptions, SessionStore, session };