@forinda/kickjs 10.14.2 → 10.15.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.
- package/dist/{adapter-B64IOivZ.d.mts → adapter-D_nUmKEQ.d.mts} +172 -34
- package/dist/adapter-D_nUmKEQ.d.mts.map +1 -0
- package/dist/{allowed-hosts-U12_gESr.d.mts → allowed-hosts-BQlQFt-1.d.mts} +6 -1
- package/dist/allowed-hosts-BQlQFt-1.d.mts.map +1 -0
- package/dist/{app-module-EmIojM4d.d.mts → app-module-BmViGLgj.d.mts} +5 -5
- package/dist/{app-module-EmIojM4d.d.mts.map → app-module-BmViGLgj.d.mts.map} +1 -1
- package/dist/application-B16ltRnC.mjs +14 -0
- package/dist/application-B16ltRnC.mjs.map +1 -0
- package/dist/{application-CGcY8SZZ.d.mts → application-ClCq0AgY.d.mts} +190 -53
- package/dist/application-ClCq0AgY.d.mts.map +1 -0
- package/dist/{body-policy-Be3Y0hjq.mjs → body-policy-D8LveWmO.mjs} +2 -2
- package/dist/{body-policy-Be3Y0hjq.mjs.map → body-policy-D8LveWmO.mjs.map} +1 -1
- package/dist/{bootstrap-Bvk3BWJX.mjs → bootstrap-C5NvsxHQ.mjs} +3 -3
- package/dist/bootstrap-C5NvsxHQ.mjs.map +1 -0
- package/dist/{bounded-counters-Bh5jeT9I.mjs → bounded-counters-BtvB2daV.mjs} +2 -2
- package/dist/{bounded-counters-Bh5jeT9I.mjs.map → bounded-counters-BtvB2daV.mjs.map} +1 -1
- package/dist/{breach-padding-DfT9MXGb.d.mts → breach-padding-BUuc21Eu.d.mts} +6 -1
- package/dist/breach-padding-BUuc21Eu.d.mts.map +1 -0
- package/dist/{cache-DMIt3c6M.d.mts → cache-ByX5O2Hp.d.mts} +26 -1
- package/dist/{cache-DMIt3c6M.d.mts.map → cache-ByX5O2Hp.d.mts.map} +1 -1
- package/dist/{client-ip-CGH_IvnC.mjs → client-ip-CWvyHmqt.mjs} +2 -2
- package/dist/{client-ip-CGH_IvnC.mjs.map → client-ip-CWvyHmqt.mjs.map} +1 -1
- package/dist/config/index.d.mts +6 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-CjFxvh0v.mjs → config-BIQoDNil.mjs} +3 -3
- package/dist/{config-CjFxvh0v.mjs.map → config-BIQoDNil.mjs.map} +1 -1
- package/dist/container-DtdUiRwr.d.mts +3 -0
- package/dist/{context-BvZLaTeE.mjs → context-BzFNflxV.mjs} +3 -3
- package/dist/context-BzFNflxV.mjs.map +1 -0
- package/dist/{context-errors-BZVS0B1O.mjs → context-errors-BmaG4vwd.mjs} +2 -2
- package/dist/context-errors-BmaG4vwd.mjs.map +1 -0
- package/dist/{contributor-runner-fdKy6Tme.mjs → contributor-runner-BnJzu2GI.mjs} +3 -3
- package/dist/contributor-runner-BnJzu2GI.mjs.map +1 -0
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.d.mts +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.d.mts +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.d.mts +1 -1
- package/dist/core/cron.mjs +2 -2
- package/dist/core/cron.mjs.map +1 -1
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.d.mts +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/errors.mjs.map +1 -1
- package/dist/core/interfaces.d.mts +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.d.mts +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.d.mts +1 -1
- package/dist/core/reactivity.mjs +2 -2
- package/dist/core/reactivity.mjs.map +1 -1
- package/dist/core-Dqzah_BX.mjs +12 -0
- package/dist/core-Dqzah_BX.mjs.map +1 -0
- package/dist/{cors-J-q6PuSU.d.mts → cors-u1OwTxQ8.d.mts} +6 -1
- package/dist/cors-u1OwTxQ8.d.mts.map +1 -0
- package/dist/{cron-DGV1AE0R.d.mts → cron-Bxm2MY8u.d.mts} +10 -1
- package/dist/cron-Bxm2MY8u.d.mts.map +1 -0
- package/dist/{csrf-DjtJPgA3.d.mts → csrf-8-Jknvmc.d.mts} +12 -2
- package/dist/csrf-8-Jknvmc.d.mts.map +1 -0
- package/dist/{decorate-DRbXCNQz.mjs → decorate-C3to8dG-.mjs} +3 -3
- package/dist/{decorate-DRbXCNQz.mjs.map → decorate-C3to8dG-.mjs.map} +1 -1
- package/dist/{decorators-BAD8qjuq.d.mts → decorators-Bflncyz6.d.mts} +122 -6
- package/dist/decorators-Bflncyz6.d.mts.map +1 -0
- package/dist/{define-adapter-DMo6og81.mjs → define-adapter-DCjNTP6m.mjs} +2 -2
- package/dist/define-adapter-DCjNTP6m.mjs.map +1 -0
- package/dist/{di-hooks-DCqt2yJ9.mjs → di-hooks-DTDy7ABs.mjs} +2 -2
- package/dist/di-hooks-DTDy7ABs.mjs.map +1 -0
- package/dist/{disposables-BsdVu69-.mjs → disposables-BC291ukb.mjs} +1 -1
- package/dist/{driver-oZBQDJZz.mjs → driver-D59oWDec.mjs} +3 -3
- package/dist/{driver-oZBQDJZz.mjs.map → driver-D59oWDec.mjs.map} +1 -1
- package/dist/{error-handler-Dl_gZRNK.d.mts → error-handler-gZLQFHeE.d.mts} +2 -2
- package/dist/{error-handler-Dl_gZRNK.d.mts.map → error-handler-gZLQFHeE.d.mts.map} +1 -1
- package/dist/{errors-DZGuPLoZ.d.mts → errors-CppqPy0A.d.mts} +2 -1
- package/dist/errors-CppqPy0A.d.mts.map +1 -0
- package/dist/{express-f9CTA8qO.mjs → express-JAXx9MK0.mjs} +3 -3
- package/dist/{express-f9CTA8qO.mjs.map → express-JAXx9MK0.mjs.map} +1 -1
- package/dist/{express-lazy-DMxcLBpT.mjs → express-lazy-jIFBeDpY.mjs} +3 -3
- package/dist/{express-lazy-DMxcLBpT.mjs.map → express-lazy-jIFBeDpY.mjs.map} +1 -1
- package/dist/{handler-B66laQY0.mjs → handler-C8iAD_xz.mjs} +3 -3
- package/dist/{handler-B66laQY0.mjs.map → handler-C8iAD_xz.mjs.map} +1 -1
- package/dist/{helmet-Rwkbp9IS.d.mts → helmet-1H0LKr6y.d.mts} +6 -1
- package/dist/helmet-1H0LKr6y.d.mts.map +1 -0
- package/dist/{host-DalMsn5Z.mjs → host-Crxmi91N.mjs} +2 -2
- package/dist/{host-DalMsn5Z.mjs.map → host-Crxmi91N.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.d.mts +1 -1
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
- package/dist/http/middleware/breach-padding.d.mts +1 -1
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/breach-padding.mjs.map +1 -1
- package/dist/http/middleware/cors.d.mts +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.d.mts +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.d.mts +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.d.mts +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/request-logger.mjs.map +1 -1
- package/dist/http/middleware/session.d.mts +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.d.mts +2 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.d.mts +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +3 -2
- package/dist/http/runtimes/express.d.mts.map +1 -1
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +3 -3
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-ZbCnCyQx.d.mts → index-CtjmSXFy.d.mts} +11 -1
- package/dist/index-CtjmSXFy.d.mts.map +1 -0
- package/dist/{index-CFTwnev9.d.mts → index-DoukvKwh.d.mts} +2 -2
- package/dist/{index-CFTwnev9.d.mts.map → index-DoukvKwh.d.mts.map} +1 -1
- package/dist/index.d.mts +34 -28
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{interfaces-BQhYh3lL.d.mts → interfaces-CvO9sAea.d.mts} +3 -3
- package/dist/{interfaces-BQhYh3lL.d.mts.map → interfaces-CvO9sAea.d.mts.map} +1 -1
- package/dist/{is-production-9QzMIRuO.mjs → is-production-LziEMGrc.mjs} +2 -2
- package/dist/{is-production-9QzMIRuO.mjs.map → is-production-LziEMGrc.mjs.map} +1 -1
- package/dist/{jobs-CuZqVDDG.mjs → jobs-D7ToA0yF.mjs} +3 -3
- package/dist/jobs-D7ToA0yF.mjs.map +1 -0
- package/dist/{kv-stores-wTD3VDPB.d.mts → kv-stores-DdGPLXQG.d.mts} +32 -7
- package/dist/kv-stores-DdGPLXQG.d.mts.map +1 -0
- package/dist/{kv-stores-C9CJ3xCB.mjs → kv-stores-DpM57Xr5.mjs} +3 -3
- package/dist/kv-stores-DpM57Xr5.mjs.map +1 -0
- package/dist/{lazy-serve-static-DVWmKM7Z.mjs → lazy-serve-static-DxI2K-zs.mjs} +3 -3
- package/dist/{lazy-serve-static-DVWmKM7Z.mjs.map → lazy-serve-static-DxI2K-zs.mjs.map} +1 -1
- package/dist/{logger-BL8MiSrm.d.mts → logger-ByJsVwqY.d.mts} +3 -3
- package/dist/{logger-BL8MiSrm.d.mts.map → logger-ByJsVwqY.d.mts.map} +1 -1
- package/dist/{metadata-BZRtQog3.mjs → metadata-nTTSnVTO.mjs} +1 -1
- package/dist/{observers-B4VnKAHK.mjs → observers-fQtCIKLq.mjs} +2 -2
- package/dist/observers-fQtCIKLq.mjs.map +1 -0
- package/dist/{precompressed-AxF66Ls0.mjs → precompressed-BtwmgzyS.mjs} +2 -2
- package/dist/{precompressed-AxF66Ls0.mjs.map → precompressed-BtwmgzyS.mjs.map} +1 -1
- package/dist/{query-BwUR-ssX.mjs → query-Dr28oT30.mjs} +2 -2
- package/dist/query-Dr28oT30.mjs.map +1 -0
- package/dist/{rate-limit-DMiV6bAq.d.mts → rate-limit-BQx_P6gG.d.mts} +11 -1
- package/dist/rate-limit-BQx_P6gG.d.mts.map +1 -0
- package/dist/{reactivity-Dski64km.d.mts → reactivity-KZOrwVeK.d.mts} +32 -1
- package/dist/reactivity-KZOrwVeK.d.mts.map +1 -0
- package/dist/{reply-B5kZ6VGv.mjs → reply-ChoI5SvM.mjs} +3 -3
- package/dist/{reply-B5kZ6VGv.mjs.map → reply-ChoI5SvM.mjs.map} +1 -1
- package/dist/{request-id-B_n-3A16.d.mts → request-id-B9Myiv75.d.mts} +2 -1
- package/dist/request-id-B9Myiv75.d.mts.map +1 -0
- package/dist/{request-logger-BV1C5r5q.d.mts → request-logger-CYyAuPmo.d.mts} +6 -1
- package/dist/request-logger-CYyAuPmo.d.mts.map +1 -0
- package/dist/{request-scope-D2WQwatk.mjs → request-scope-BfSNdmz9.mjs} +3 -3
- package/dist/{request-scope-D2WQwatk.mjs.map → request-scope-BfSNdmz9.mjs.map} +1 -1
- package/dist/{respond-C6ohI69y.mjs → respond-1BjaDME9.mjs} +2 -2
- package/dist/{respond-C6ohI69y.mjs.map → respond-1BjaDME9.mjs.map} +1 -1
- package/dist/rolldown-runtime-B5KeNctS.mjs +11 -0
- package/dist/{route-flag-CHiMvgar.mjs → route-flag-B6ZmhkfI.mjs} +3 -3
- package/dist/{route-flag-CHiMvgar.mjs.map → route-flag-B6ZmhkfI.mjs.map} +1 -1
- package/dist/{route-policy-ckK7N1eN.mjs → route-policy-BG--gAcF.mjs} +2 -2
- package/dist/route-policy-BG--gAcF.mjs.map +1 -0
- package/dist/{router-builder-Dtyya4qP.d.mts → router-builder-BkIW_qjz.d.mts} +3 -2
- package/dist/router-builder-BkIW_qjz.d.mts.map +1 -0
- package/dist/{router-builder-D2cly8Wt.mjs → router-builder-DHKtp4I8.mjs} +3 -3
- package/dist/router-builder-DHKtp4I8.mjs.map +1 -0
- package/dist/{runtime-D9TN6CpL.mjs → runtime-CUfFIHiC.mjs} +3 -3
- package/dist/runtime-CUfFIHiC.mjs.map +1 -0
- package/dist/{session-CXWu2rXW.d.mts → session-DPTbfwKO.d.mts} +40 -1
- package/dist/session-DPTbfwKO.d.mts.map +1 -0
- package/dist/{settings-v2N3V8Bl.mjs → settings-I7GUX5ps.mjs} +3 -3
- package/dist/{settings-v2N3V8Bl.mjs.map → settings-I7GUX5ps.mjs.map} +1 -1
- package/dist/{token-DtW16tw3.mjs → token-uWfhVlfe.mjs} +1 -1
- package/dist/{upload-eNNueUxR.d.mts → upload-O3VTcODy.d.mts} +3 -3
- package/dist/{upload-eNNueUxR.d.mts.map → upload-O3VTcODy.d.mts.map} +1 -1
- package/dist/{upload-config-BXjBiNjC.mjs → upload-config-BXqBuyza.mjs} +2 -2
- package/dist/{upload-config-BXjBiNjC.mjs.map → upload-config-BXqBuyza.mjs.map} +1 -1
- package/dist/url-for-CuMaQ2wS.mjs +12 -0
- package/dist/url-for-CuMaQ2wS.mjs.map +1 -0
- package/dist/{validate-BbthfLBb.d.mts → validate-CTgfm7oE.d.mts} +2 -2
- package/dist/{validate-BbthfLBb.d.mts.map → validate-CTgfm7oE.d.mts.map} +1 -1
- package/dist/{view-renderer-C4sMEruA.mjs → view-renderer-Bf1Wy-DQ.mjs} +3 -3
- package/dist/view-renderer-Bf1Wy-DQ.mjs.map +1 -0
- package/dist/{web-crypto-SXVOPDxW.mjs → web-crypto-JzoGmiG0.mjs} +2 -2
- package/dist/{web-crypto-SXVOPDxW.mjs.map → web-crypto-JzoGmiG0.mjs.map} +1 -1
- package/dist/web.d.mts +6 -6
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +10 -10
- package/dist/adapter-B64IOivZ.d.mts.map +0 -1
- package/dist/allowed-hosts-U12_gESr.d.mts.map +0 -1
- package/dist/application-BzimU62Q.mjs +0 -14
- package/dist/application-BzimU62Q.mjs.map +0 -1
- package/dist/application-CGcY8SZZ.d.mts.map +0 -1
- package/dist/bootstrap-Bvk3BWJX.mjs.map +0 -1
- package/dist/breach-padding-DfT9MXGb.d.mts.map +0 -1
- package/dist/container-4iJdDkRH.d.mts +0 -3
- package/dist/context-BvZLaTeE.mjs.map +0 -1
- package/dist/context-errors-BZVS0B1O.mjs.map +0 -1
- package/dist/contributor-runner-fdKy6Tme.mjs.map +0 -1
- package/dist/core-CCIpjo6g.mjs +0 -12
- package/dist/core-CCIpjo6g.mjs.map +0 -1
- package/dist/cors-J-q6PuSU.d.mts.map +0 -1
- package/dist/cron-DGV1AE0R.d.mts.map +0 -1
- package/dist/csrf-DjtJPgA3.d.mts.map +0 -1
- package/dist/decorators-BAD8qjuq.d.mts.map +0 -1
- package/dist/define-adapter-DMo6og81.mjs.map +0 -1
- package/dist/di-hooks-DCqt2yJ9.mjs.map +0 -1
- package/dist/errors-DZGuPLoZ.d.mts.map +0 -1
- package/dist/helmet-Rwkbp9IS.d.mts.map +0 -1
- package/dist/index-ZbCnCyQx.d.mts.map +0 -1
- package/dist/jobs-CuZqVDDG.mjs.map +0 -1
- package/dist/kv-stores-C9CJ3xCB.mjs.map +0 -1
- package/dist/kv-stores-wTD3VDPB.d.mts.map +0 -1
- package/dist/observers-B4VnKAHK.mjs.map +0 -1
- package/dist/query-BwUR-ssX.mjs.map +0 -1
- package/dist/rate-limit-DMiV6bAq.d.mts.map +0 -1
- package/dist/reactivity-Dski64km.d.mts.map +0 -1
- package/dist/request-id-B_n-3A16.d.mts.map +0 -1
- package/dist/request-logger-BV1C5r5q.d.mts.map +0 -1
- package/dist/rolldown-runtime-DuhQYUab.mjs +0 -11
- package/dist/route-policy-ckK7N1eN.mjs.map +0 -1
- package/dist/router-builder-D2cly8Wt.mjs.map +0 -1
- package/dist/router-builder-Dtyya4qP.d.mts.map +0 -1
- package/dist/runtime-D9TN6CpL.mjs.map +0 -1
- package/dist/session-CXWu2rXW.d.mts.map +0 -1
- package/dist/url-for-C4Eomib7.mjs +0 -12
- package/dist/url-for-C4Eomib7.mjs.map +0 -1
- package/dist/view-renderer-C4sMEruA.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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{HttpException}from"./core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,i as formFields,l as readBodyBytes,o as parseByteSize,p as unsupportedMediaTypeError,r as classifyMediaType,s as parseForm,u as readBodyText}from"./body-policy-
|
|
12
|
-
//# sourceMappingURL=handler-
|
|
11
|
+
import{HttpException}from"./core/errors.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,i as formFields,l as readBodyBytes,o as parseByteSize,p as unsupportedMediaTypeError,r as classifyMediaType,s as parseForm,u as readBodyText}from"./body-policy-D8LveWmO.mjs";import{t as RequestContext}from"./context-BzFNflxV.mjs";import{n as publishMatchedRoute}from"./runtime-CUfFIHiC.mjs";import{n as applyHandlerResult}from"./reply-ChoI5SvM.mjs";import{f as requestStore}from"./view-renderer-Bf1Wy-DQ.mjs";import{n as disposeRequestStore,t as createRequestStore}from"./request-scope-BfSNdmz9.mjs";import{validate}from"./http/middleware/validate.mjs";import{c as tooManyFiles,l as uploadLimits,r as applyUploadConfig}from"./upload-config-BXqBuyza.mjs";import{n as WebResponseDriver,t as WebRequestShim}from"./driver-D59oWDec.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";const NOOP_NEXT=()=>{},BODY_METHODS=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]),builtInError=errorHandler(),builtInNotFound=notFoundHandler();function decodeParams(params){let decoded={};for(let key in params){let value=params[key];decoded[key]=value.includes(`%`)?decodeURIComponent(value):value}return decoded}function readThrough(shim,carry){return new Proxy(shim,{get(target,prop,receiver){let own=Reflect.get(target,prop,receiver);return own===void 0?Reflect.get(carry,prop,carry):own},has(target,prop){return Reflect.has(target,prop)||Reflect.has(carry,prop)}})}function compileWebRoute(entry,hooks,options={}){let bodyLimit=options.bodyLimit??parseByteSize(`1mb`),validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0,upload=entry.meta.upload&&entry.meta.upload.mode!==`none`?entry.meta.upload:null;return async({request,url,params,carry})=>{let shim=new WebRequestShim(request,url),req=carry?readThrough(shim,carry):shim,bodyError;try{req.params=decodeParams(params)}catch{req.params=params,bodyError=HttpException.badRequest(`Malformed URL parameter`)}if(upload){let limits=uploadLimits(upload),form;try{let bytes=await readBodyBytes(request,limits.total),type=request.headers.get(`content-type`)??``;form=await new Response(bytes,{headers:{"content-type":type}}).formData().catch(()=>void 0)}catch(err){err instanceof HttpException&&(bodyError=err)}if(form){let rawParts=[],fields=[];for(let[name,value]of form.entries())typeof value==`string`?fields.push([name,value]):rawParts.push({fieldname:name,filename:value.name??``,mimetype:value.type||`application/octet-stream`,buffer:typeof Buffer==`function`?Buffer.from(await value.arrayBuffer()):new Uint8Array(await value.arrayBuffer())});if(req.body=formFields(fields),rawParts.length>limits.files)bodyError=tooManyFiles(limits.files);else try{let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);req.file=file,req.files=files}catch(err){bodyError=err}}}else if(BODY_METHODS.has(request.method)){let raw=``;try{raw=await readBodyText(request,bodyLimit)}catch(err){err instanceof HttpException&&(bodyError=err)}let kind=classifyMediaType(req.headers[`content-type`]);if(raw!==``&&kind===`unsupported`)bodyError=unsupportedMediaTypeError(req.headers[`content-type`]);else if(raw!==``&&kind!==`multipart`){if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){bodyError=HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`)}else req.body=kind===`urlencoded`?parseForm(raw):raw}}!bodyError&&hasPrototypeKey(req.body)&&(bodyError=prototypeKeyError());let store=createRequestStore(req.requestId||req.headers[`x-request-id`]);req.requestId=store.requestId;let driver=new WebResponseDriver(request.signal);driver.setHeader(`x-request-id`,store.requestId),publishMatchedRoute(req,entry),carry&&publishMatchedRoute(carry,entry);let pipeline=requestStore.run(store,async()=>{if(bodyError)throw bodyError;let ctx=new RequestContext(req,driver,NOOP_NEXT,driver);if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),driver.settled))return;validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||driver.settled)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),driver.settled)return;let result=await entry.handler(ctx);driver.settled||await applyHandlerResult(ctx,result)});try{try{await Promise.race([pipeline,driver.ready])}catch(err){driver.settled||await requestStore.run(store,async()=>{hooks?.onError&&await hooks.onError(err,req,driver),driver.settled||await builtInError(err,req,driver,NOOP_NEXT)})}return driver.settled||builtInNotFound(req,driver,NOOP_NEXT),await driver.ready}finally{Promise.resolve(pipeline).catch(()=>{}).then(()=>disposeRequestStore(store))}}}async function headFromGet(response){let res=await response;return res.body?.cancel().catch(()=>{}),new Response(null,{status:res.status,statusText:res.statusText,headers:res.headers})}export{headFromGet as n,readThrough as r,compileWebRoute as t};
|
|
12
|
+
//# sourceMappingURL=handler-C8iAD_xz.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler-B66laQY0.mjs","names":[],"sources":["../src/http/web/handler.ts"],"sourcesContent":["// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n readBodyBytes,\n readBodyText,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport {\n applyUploadConfig,\n tooManyFiles,\n uploadLimits,\n type RawUploadPart,\n} from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n // Bounded before anything is parsed: the route's file budget plus room\n // for fields. Past it is a 413, held like a parse failure below.\n const limits = uploadLimits(upload)\n let form: FormData | undefined\n try {\n const bytes = await readBodyBytes(request, limits.total)\n const type = request.headers.get('content-type') ?? ''\n form = await new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], {\n headers: { 'content-type': type },\n })\n .formData()\n .catch(() => undefined)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields.push([name, value])\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n req.body = formFields(fields)\n // A refused type (415), an oversized file or too many (413) is held like\n // a parse failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n if (rawParts.length > limits.files) {\n bodyError = tooManyFiles(limits.files)\n } else {\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\n }\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (!bodyError && hasPrototypeKey(req.body)) bodyError = prototypeKeyError()\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n // Inside the request's store: an error page renders with the same\n // context and REQUEST-scoped services the route had.\n if (!driver.settled) {\n await requestStore.run(store, async () => {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n })\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n\n/**\n * HEAD for a GET route: run the route and answer with its status and\n * headers, without the body — what Express and Fastify do for every GET.\n */\nexport async function headFromGet(response: Promise<Response> | Response): Promise<Response> {\n const res = await response\n // A streamed GET (SSE) would otherwise keep producing for nobody.\n res.body?.cancel().catch(() => {})\n return new Response(null, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n })\n}\n"],"mappings":";;;;;;;;;;A,04BAkCA,MAAM,cAAwB,CAAC,EACzB,6BAAe,IAAI,IAAI,CAAC,OAAQ,MAAO,QAAS,QAAQ,CAAC,EA6BzD,aAAe,aAAa,EAC5B,gBAAkB,gBAAgB,EAExC,SAAS,aAAa,OAAwD,CAC5E,IAAM,QAAkC,CAAC,EACzC,IAAK,IAAM,OAAO,OAAQ,CACxB,IAAM,MAAQ,OAAO,KACrB,QAAQ,KAAO,MAAM,SAAS,GAAG,EAAI,mBAAmB,KAAK,EAAI,KACnE,CACA,OAAO,OACT,CAYA,SAAgB,YAAY,KAAsB,MAA+B,CAC/E,OAAO,IAAI,MAAM,KAAM,CACrB,IAAI,OAAQ,KAAM,SAAU,CAC1B,IAAM,IAAM,QAAQ,IAAI,OAAQ,KAAM,QAAQ,EAC9C,OAAO,MAAQ,IAAA,GAAkB,QAAQ,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,SAA2D,CAC3F,IAAM,IAAM,MAAM,SAGlB,OADA,IAAI,MAAM,OAAO,CAAC,CAAC,UAAY,CAAC,CAAC,EAC1B,IAAI,SAAS,KAAM,CACxB,OAAQ,IAAI,OACZ,WAAY,IAAI,WAChB,QAAS,IAAI,OACf,CAAC,CACH,C"}
|
|
1
|
+
{"version":3,"file":"handler-C8iAD_xz.mjs","names":[],"sources":["../src/http/web/handler.ts"],"sourcesContent":["// Engine-neutral web pipeline: run one KickJS RouteEntry against a WHATWG\n// Request and produce a WHATWG Response. Shared by the h3 v2 runtime\n// (node bootstrap) and the `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n// Edge-safe: no node imports beyond the sanctioned ALS request store.\n\nimport { HttpException } from '../../core/errors'\nimport {\n DEFAULT_BODY_LIMIT,\n classifyMediaType,\n parseByteSize,\n formFields,\n hasPrototypeKey,\n parseForm,\n prototypeKeyError,\n readBodyBytes,\n readBodyText,\n unsupportedMediaTypeError,\n} from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport {\n applyUploadConfig,\n tooManyFiles,\n uploadLimits,\n type RawUploadPart,\n} from '../middleware/upload-config'\nimport type { RouteEntry, RuntimeResponse } from '../runtime'\nimport { WebRequestShim, WebResponseDriver } from './driver'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport interface WebRouteInvocation {\n request: Request\n url: URL\n params: Record<string, string>\n /**\n * The request object the app's connect middleware wrote to — the node\n * `req` behind a node server, the per-event shim on the fetch path.\n * Whatever it set (`session`, `user`, `requestId`, an adapter's symbol)\n * reads through on the route's request.\n */\n carry?: object\n}\n\nexport interface WebRouteHooks {\n /**\n * Error bridge — receives pipeline rejections (validation failures,\n * handler throws) with the shim + driver so an engine can dispatch the\n * framework's connect-style error handler. When absent (or when it\n * doesn't settle the driver), a minimal JSON error is produced from\n * `err.status`/`err.statusCode` (500 default).\n */\n onError?: (err: unknown, req: WebRequestShim, res: WebResponseDriver) => void | Promise<void>\n}\n\n// The same handlers Express and Fastify answer with, so an error or a request\n// nothing answered has one shape on every engine: RFC 9457 problem details,\n// the error's own headers, `requestId` on a 500.\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\n\nfunction decodeParams(params: Record<string, string>): Record<string, string> {\n const decoded: Record<string, string> = {}\n for (const key in params) {\n const value = params[key]\n decoded[key] = value.includes('%') ? decodeURIComponent(value) : value\n }\n return decoded\n}\n\n/**\n * Compile a RouteEntry into a `(invocation) => Promise<Response>` function.\n * Everything derivable at route-build time (validator, upload config) is\n * hoisted here — per-request work is shim + store + pipeline only.\n */\n/**\n * The route's request, with anything it does not set itself read from\n * `carry` — the object connect middleware wrote to. Writes stay on the route's\n * own request. A declared-but-unset field (`requestId`) counts as not set.\n */\nexport function readThrough(shim: WebRequestShim, carry: object): WebRequestShim {\n return new Proxy(shim, {\n get(target, prop, receiver) {\n const own = Reflect.get(target, prop, receiver)\n return own !== undefined ? own : Reflect.get(carry, prop, carry)\n },\n has(target, prop) {\n return Reflect.has(target, prop) || Reflect.has(carry, prop)\n },\n })\n}\n\nexport function compileWebRoute(\n entry: RouteEntry,\n hooks?: WebRouteHooks,\n options: { bodyLimit?: number } = {},\n): (invocation: WebRouteInvocation) => Promise<Response> {\n const bodyLimit = options.bodyLimit ?? parseByteSize(DEFAULT_BODY_LIMIT)\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n const upload = entry.meta.upload && entry.meta.upload.mode !== 'none' ? entry.meta.upload : null\n\n return async ({ request, url, params, carry }) => {\n const shim = new WebRequestShim(request, url)\n const req = carry ? readThrough(shim, carry) : shim\n let bodyError: unknown\n // h3 hands params over still percent-encoded; Express and Fastify decode\n // them, so `/users/a%20b` must reach the handler as `'a b'` here too.\n try {\n req.params = decodeParams(params)\n } catch {\n req.params = params\n bodyError = HttpException.badRequest('Malformed URL parameter')\n }\n\n // Body: uploads consume the stream as FormData; everything else parses\n // by content-type.\n if (upload) {\n // Bounded before anything is parsed: the route's file budget plus room\n // for fields. Past it is a 413, held like a parse failure below.\n const limits = uploadLimits(upload)\n let form: FormData | undefined\n try {\n const bytes = await readBodyBytes(request, limits.total)\n const type = request.headers.get('content-type') ?? ''\n form = await new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], {\n headers: { 'content-type': type },\n })\n .formData()\n .catch(() => undefined)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n if (form) {\n const rawParts: RawUploadPart[] = []\n const fields: Array<[string, string]> = []\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n fields.push([name, value])\n } else {\n rawParts.push({\n fieldname: name,\n filename: value.name ?? '',\n mimetype: value.type || 'application/octet-stream',\n // A real Buffer where the runtime has one (Node, Bun, Deno), so\n // `file.buffer.toString()` is the content as on every other\n // engine — a bare Uint8Array stringifies as \"80,78,71,…\".\n buffer: (typeof Buffer === 'function'\n ? Buffer.from(await value.arrayBuffer())\n : new Uint8Array(await value.arrayBuffer())) as unknown as Buffer,\n })\n }\n }\n req.body = formFields(fields)\n // A refused type (415), an oversized file or too many (413) is held like\n // a parse failure — thrown before the driver exists, it would escape the\n // route and reach the client as the host's bare error, not kick's.\n if (rawParts.length > limits.files) {\n bodyError = tooManyFiles(limits.files)\n } else {\n try {\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload!)\n req.file = file\n req.files = files\n } catch (err) {\n bodyError = err\n }\n }\n }\n } else if (BODY_METHODS.has(request.method)) {\n // Read once — a Request body is a stream and cannot be consumed twice.\n // A read that fails (client aborted mid-flight) is treated as an absent\n // body: there is nobody left to answer, and it is not a malformed one.\n // Past the limit is a 413, held like a parse failure below.\n let raw = ''\n try {\n raw = await readBodyText(request, bodyLimit)\n } catch (err) {\n if (err instanceof HttpException) bodyError = err\n }\n\n // An empty body is ABSENT, not unparseable — the same call the node h3\n // runtime makes on `content-length: 0`. Distinguishing the two is the\n // whole point: `.catch(() => undefined)` around the parse could not,\n // so a malformed payload answered 200 with the handler running against\n // `undefined` (#605), the defect #586 removed from the node runtime.\n const kind = classifyMediaType(req.headers['content-type'])\n if (raw !== '' && kind === 'unsupported') {\n // Held for the same reason as a parse failure: no driver yet.\n bodyError = unsupportedMediaTypeError(req.headers['content-type'])\n } else if (raw !== '' && kind !== 'multipart') {\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n // Held, not thrown: the driver that turns an error into a response\n // does not exist yet, so throwing here escapes the route entirely\n // and surfaces as a 500. Rethrown as the pipeline's first act.\n bodyError = HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = parseForm(raw)\n } else {\n req.body = raw\n }\n }\n }\n\n // A key that could rewrite a prototype — refused before any of the app's code sees it.\n if (!bodyError && hasPrototypeKey(req.body)) bodyError = prototypeKeyError()\n\n // Reuse the id `requestId()` middleware already gave the request, so the\n // response header, the route's ctx and observers agree on one id.\n const store = createRequestStore(req.requestId || req.headers['x-request-id'])\n req.requestId = store.requestId\n\n const driver = new WebResponseDriver(request.signal)\n driver.setHeader('x-request-id', store.requestId)\n\n publishMatchedRoute(req, entry)\n // Middleware that reports after the response (observers, request logger)\n // reads the route off the request it was handed — the carried one.\n if (carry) publishMatchedRoute(carry, entry)\n\n const pipeline = requestStore.run(store, async () => {\n if (bodyError) throw bodyError\n\n const ctx = new RequestContext(\n req as never,\n driver as never,\n NOOP_NEXT,\n driver as RuntimeResponse,\n )\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (driver.settled) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || driver.settled) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (driver.settled) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // `undefined` falls through to the canonical 404 below.\n if (!driver.settled) await applyHandlerResult(ctx, result)\n })\n\n try {\n // Streaming responses resolve `ready` mid-pipeline (SSE); buffered ones\n // resolve at the terminal ctx call. Race so both shapes return promptly.\n try {\n await Promise.race([pipeline, driver.ready])\n } catch (err) {\n // Inside the request's store: an error page renders with the same\n // context and REQUEST-scoped services the route had.\n if (!driver.settled) {\n await requestStore.run(store, async () => {\n if (hooks?.onError) await hooks.onError(err, req, driver)\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n })\n }\n }\n if (!driver.settled) {\n // Pipeline finished without responding — the catch-all's 404.\n builtInNotFound(req, driver, NOOP_NEXT)\n }\n return await driver.ready\n } finally {\n // @PreDestroy teardown. For buffered responses this runs post-response;\n // for streams it runs when the pipeline (not the stream) completes —\n // stream lifetime is governed by the client abort signal.\n void Promise.resolve(pipeline)\n .catch(() => {})\n .then(() => disposeRequestStore(store))\n }\n }\n}\n\n/**\n * HEAD for a GET route: run the route and answer with its status and\n * headers, without the body — what Express and Fastify do for every GET.\n */\nexport async function headFromGet(response: Promise<Response> | Response): Promise<Response> {\n const res = await response\n // A streamed GET (SSE) would otherwise keep producing for nobody.\n res.body?.cancel().catch(() => {})\n return new Response(null, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n })\n}\n"],"mappings":";;;;;;;;;;A,04BAkCA,MAAM,cAAwB,CAAC,EACzB,6BAAe,IAAI,IAAI,CAAC,OAAQ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AM,QAAQ,KAAK,CAAC,SAAU,OAAO,KAAK,CAAC,CAC7C,OAAS,IAAK,CAGP,OAAO,SACV,MAAM,aAAa,IAAI,MAAO,SAAY,CACpC,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAK,IAAK,MAAM,EACnD,OAAO,SAAS,MAAM,aAAa,IAAK,IAAK,OAAQ,SAAS,CACrE,CAAC,CAEL,CAKA,OAJK,OAAO,SAEV,gBAAgB,IAAK,OAAQ,SAAS,EAEjC,MAAM,OAAO,KACtB,QAAU,CAIH,QAAQ,QAAQ,QAAQ,CAAC,CAC3B,UAAY,CAAC,CAAC,CAAC,CACf,SAAW,oBAAoB,KAAK,CAAC,CAC1C,CACF,CACF,CAMA,eAAsB,YAAY,SAA2D,CAC3F,IAAM,IAAM,MAAM,SAGlB,OADA,IAAI,MAAM,OAAO,CAAC,CAAC,UAAY,CAAC,CAAC,EAC1B,IAAI,SAAS,KAAM,CACxB,OAAQ,IAAI,OACZ,WAAY,IAAI,WAChB,QAAS,IAAI,OACf,CAAC,CACH,C"}
|
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-DamOelO8.mjs";
|
|
3
3
|
/** Brand identifying a `helmet()` handler, so auto-injection can stand down. */
|
|
4
4
|
declare const HELMET_MIDDLEWARE: unique symbol;
|
|
5
|
+
/**
|
|
6
|
+
* Options for {@link helmet}: which security headers to set, and their values.
|
|
7
|
+
*
|
|
8
|
+
* @see https://kickjs.app/guide/security-headers
|
|
9
|
+
*/
|
|
5
10
|
interface HelmetOptions {
|
|
6
11
|
/** Set Content-Security-Policy header (default: self-only policy) */
|
|
7
12
|
contentSecurityPolicy?: boolean | Record<string, string[]>;
|
|
@@ -40,4 +45,4 @@ interface HelmetOptions {
|
|
|
40
45
|
*/
|
|
41
46
|
declare function helmet(options?: HelmetOptions): (req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => void;
|
|
42
47
|
export { HelmetOptions as n, helmet as r, HELMET_MIDDLEWARE as t };
|
|
43
|
-
//# sourceMappingURL=helmet-
|
|
48
|
+
//# sourceMappingURL=helmet-1H0LKr6y.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helmet-1H0LKr6y.d.mts","names":["Request","Response","NextFunction"],"sources":["../src/http/middleware/helmet.ts"],"mappings":";;;cAOa;;;;;;UAOI;;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.
|
|
2
|
+
* @forinda/kickjs v10.15.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-
|
|
12
|
+
//# sourceMappingURL=host-Crxmi91N.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-
|
|
1
|
+
{"version":3,"file":"host-Crxmi91N.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,C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as ConfigDescription, c as MiddlewareEntry, d as ShutdownOptions, f as describeRoutes, i as ApplicationOptions, l as MountedRouteInfo, n as AppStatus, o as ConfigOrigins, r as Application, s as ManagementOptions, t as APPLICATION, u as ServerOptions } from "../application-
|
|
2
|
+
import { a as ConfigDescription, c as MiddlewareEntry, d as ShutdownOptions, f as describeRoutes, i as ApplicationOptions, l as MountedRouteInfo, n as AppStatus, o as ConfigOrigins, r as Application, s as ManagementOptions, t as APPLICATION, u as ServerOptions } from "../application-ClCq0AgY.mjs";
|
|
3
3
|
export { APPLICATION, AppStatus, Application, ApplicationOptions, ConfigDescription, ConfigOrigins, ManagementOptions, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions, describeRoutes };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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,r as describeRoutes}from"../application-
|
|
11
|
+
export{t as APPLICATION,n as Application,r as describeRoutes}from"../application-B16ltRnC.mjs";
|
package/dist/http/bootstrap.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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-
|
|
11
|
+
export{t as bootstrap}from"../bootstrap-C5NvsxHQ.mjs";
|
package/dist/http/context.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
import { D as RouteShape, E as RequestContext, O as SseHandler, T as DeepReadonly, k as contentDisposition, w as Ctx } from "../adapter-
|
|
3
|
-
import { b as ContextMeta } from "../app-module-
|
|
2
|
+
import { D as RouteShape, E as RequestContext, O as SseHandler, T as DeepReadonly, k as contentDisposition, w as Ctx } from "../adapter-D_nUmKEQ.mjs";
|
|
3
|
+
import { b as ContextMeta } from "../app-module-BmViGLgj.mjs";
|
|
4
4
|
export { type ContextMeta, Ctx, DeepReadonly, RequestContext, RouteShape, SseHandler, contentDisposition };
|
package/dist/http/context.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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-
|
|
11
|
+
export{t as RequestContext,n as contentDisposition}from"../context-BzFNflxV.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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-
|
|
11
|
+
import{r as parseHttpUrl,t as HOST_GRAMMAR}from"../../host-Crxmi91N.mjs";import{n as resolvePathname}from"../../client-ip-CWvyHmqt.mjs";import{i as sendJson}from"../../respond-1BjaDME9.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 {\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":";;;;;;;;;;A,
|
|
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\n/**\n * Options for {@link allowedHosts}.\n *\n * @see https://kickjs.app/guide/security-headers\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":";;;;;;;;;;A,8LA4CA,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,G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,EAErD,OAAO,KAAK,EAGd,IAAI,UAAU,eAAgB,0BAA0B,EACxD,SAAS,IAAK,IAAK,QAAQ,CAC7B,CACF,C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as breachPadding, r as padGzipHeader, t as BreachPaddingOptions } from "../../breach-padding-
|
|
2
|
+
import { n as breachPadding, r as padGzipHeader, t as BreachPaddingOptions } from "../../breach-padding-BUuc21Eu.mjs";
|
|
3
3
|
export { BreachPaddingOptions, breachPadding, padGzipHeader };
|
|
@@ -1 +1 @@
|
|
|
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":";;;;;;;;;;
|
|
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\n/**\n * Options for {@link breachPadding}.\n *\n * @see https://kickjs.app/guide/middleware\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":";;;;;;;;;;AAuBA,SAAS,YAAY,IAAqB,CACxC,GAAI,KAAO,EAAG,MAAO,GACrB,GAAM,CAAC,OAAS,OAAO,gCAAgB,IAAI,YAAY,CAAC,CAAC,EACzD,OAAO,MAAQ,GACjB,CASA,SAAgB,cAAc,MAAmB,SAA8B,CAC7E,GACE,MAAM,OAAS,IACf,MAAM,KAAO,IACb,MAAM,KAAO,KACb,MAAM,KAAO,GACb,MAAM,KAAO,EAEb,OAAO,MAET,IAAM,OAAS,YAAY,QAAQ,EAC7B,OAAS,IAAI,WAAW,MAAM,OAAS,OAAS,CAAC,EAMvD,OALA,OAAO,IAAI,MAAM,SAAS,EAAG,EAAW,CAAC,EACzC,OAAO,GAAK,EACZ,OAAO,KAAK,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AAG,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,C"}
|
|
@@ -1 +1 @@
|
|
|
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":";;;;;;;;;;
|
|
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\n/**\n * Options for {@link cors}.\n *\n * @see https://kickjs.app/guide/security-headers\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":";;;;;;;;;;AA4BA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AkB,GAAG,EACnC,IAAI,IAAI,CAEV,MAEA,KAAK,CACP,CACF,C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as csrfToken, i as csrfGuard, n as CsrfOptions, o as isAllowedOrigin, r as csrf, t as CsrfGuardOptions } from "../../csrf-
|
|
2
|
+
import { a as csrfToken, i as csrfGuard, n as CsrfOptions, o as isAllowedOrigin, r as csrf, t as CsrfGuardOptions } from "../../csrf-8-Jknvmc.mjs";
|
|
3
3
|
export { CsrfGuardOptions, CsrfOptions, csrf, csrfGuard, csrfToken, isAllowedOrigin };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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{a as setCookie,i as sendJson,n as readCookies}from"../../respond-
|
|
11
|
+
import{a as setCookie,i as sendJson,n as readCookies}from"../../respond-1BjaDME9.mjs";import{n as resolvePathname}from"../../client-ip-CWvyHmqt.mjs";import{n as randomHex,r as safeEqual}from"../../web-crypto-JzoGmiG0.mjs";import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-B6ZmhkfI.mjs";import{t as isProduction}from"../../is-production-LziEMGrc.mjs";import{n as canonicalHost,r as parseHttpUrl}from"../../host-Crxmi91N.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`},TOKEN=Symbol.for(`kickjs.csrfToken`);function csrfToken(ctx){return ctx?.req?.[TOKEN]}function isOwnToken(value,bytes){return value!==void 0&&value.length===bytes*2&&/^[0-9a-f]+$/.test(value)}function sentToken(headers,body,header,field){if(headers[header]!==void 0)return headerOf(headers,header);let fromBody=body&&typeof body==`object`?body[field]:void 0;return typeof fromBody==`string`?fromBody:void 0}function csrf(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,fieldName=options.field??`_csrf`,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(isOwnToken(token,tokenLength)||(token=randomHex(tokenLength),setCookie(res,cookieName,token,cookieOpts)),req[TOKEN]=token,!protectedMethods.has(req.method.toUpperCase())||ignorePaths.has(resolvePathname(req)))return next();if(checkOrigin&&!isAllowedOrigin(req.headers,trusted))return sendJson(res,403,ORIGIN_REJECTED);let sent=sentToken(req.headers,req.body,headerName,fieldName);if(sent===void 0||!safeEqual(sent,token))return sendJson(res,403,{message:`CSRF token mismatch`});next()}}function csrfGuard(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,fieldName=options.field??`_csrf`,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];isOwnToken(token,tokenLength)||(token=randomHex(tokenLength),setCookie(ctx.res,cookieName,token,cookieOpts)),ctx.req[TOKEN]=token;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 sent=sentToken(ctx.headers,ctx.req.body,headerName,fieldName);sent===void 0||!safeEqual(sent,token)?ctx.json({message:`CSRF token mismatch`},403):next()}}export{csrf,csrfGuard,csrfToken,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 {\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 /**\n * Form field that carries the token when the header is absent, for plain\n * HTML forms (default: '_csrf'). Read from the parsed body, so `csrf()` must\n * come after the body parser; `csrfGuard()` always runs after it.\n */\n field?: 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/** Where the middleware leaves this request's token, for {@link csrfToken}. */\nconst TOKEN = Symbol.for('kickjs.csrfToken')\n\n/**\n * This request's CSRF token, for a page to put in its forms\n * (`<input type=\"hidden\" name=\"_csrf\" value=\"…\">`) or a `<meta>` tag. Set by\n * `csrf()` or `csrfGuard()`, including on the first visit, before the\n * browser has the cookie. `undefined` when neither ran.\n */\nexport function csrfToken(ctx: { req: unknown } | undefined): string | undefined {\n return (ctx?.req as { [TOKEN]?: string } | undefined)?.[TOKEN]\n}\n\n/**\n * A cookie value shaped like a token this middleware issues. Anything else\n * (set by a sibling subdomain, or by hand) is replaced, so {@link csrfToken}\n * only ever hands a page hex.\n */\nfunction isOwnToken(value: string | undefined, bytes: number): value is string {\n return value !== undefined && value.length === bytes * 2 && /^[0-9a-f]+$/.test(value)\n}\n\n/** The token a mutating request sent: the header, else the form field. */\nfunction sentToken(headers: HeaderBag, body: unknown, header: string, field: string) {\n // Any header, even sent as a list, is the answer: a form field never overrides it.\n if (headers[header] !== undefined) return headerOf(headers, header)\n const fromBody =\n body && typeof body === 'object' ? (body as Record<string, unknown>)[field] : undefined\n return typeof fromBody === 'string' ? fromBody : undefined\n}\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 fieldName = options.field ?? '_csrf'\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 (!isOwnToken(token, tokenLength)) {\n token = randomHex(tokenLength)\n setCookie(res, cookieName, token, cookieOpts)\n }\n ;(req as { [TOKEN]?: string })[TOKEN] = token\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: the header (or form field) token must match the cookie token\n const sent = sentToken(\n req.headers as HeaderBag,\n (req as { body?: unknown }).body,\n headerName,\n fieldName,\n )\n\n if (sent === undefined || !safeEqual(sent, 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 fieldName = options.field ?? '_csrf'\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 (!isOwnToken(token, tokenLength)) {\n token = randomHex(tokenLength)\n setCookie(ctx.res, cookieName, token, cookieOpts)\n }\n ;(ctx.req as { [TOKEN]?: string })[TOKEN] = token\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 sent = sentToken(ctx.headers as HeaderBag, ctx.req.body, headerName, fieldName)\n if (sent === undefined || !safeEqual(sent, token)) {\n ctx.json({ message: 'CSRF token mismatch' }, 403)\n return\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;A,4bAgEA,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/C,CAEA,SAAS,WAAW,QAA4C,CAC9D,OAAO,IAAI,KACR,SAAW,CAAC,EAAA,CAAG,IAAK,GAAM,CACzB,IAAM,IAAM,aAAa,CAAC,EAG1B,GAAI,CAAC,KAAO,IAAI,WAAa,KAAO,IAAI,QAAU,IAAI,MAAQ,IAAI,UAAY,IAAI,SACh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AAgB,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,KAAO,UAAU,IAAI,QAAsB,IAAI,IAAI,KAAM,WAAY,SAAS,EAChF,OAAS,IAAA,IAAa,CAAC,UAAU,KAAM,KAAK,EAC9C,IAAI,KAAK,CAAE,QAAS,qBAAsB,EAAG,GAAG,EAIlD,KAAK,CACP,CACF,C"}
|
|
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\n/**\n * Options for {@link csrf}.\n *\n * @see https://kickjs.app/guide/csrf\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 /**\n * Form field that carries the token when the header is absent, for plain\n * HTML forms (default: '_csrf'). Read from the parsed body, so `csrf()` must\n * come after the body parser; `csrfGuard()` always runs after it.\n */\n field?: 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/** Where the middleware leaves this request's token, for {@link csrfToken}. */\nconst TOKEN = Symbol.for('kickjs.csrfToken')\n\n/**\n * This request's CSRF token, for a page to put in its forms\n * (`<input type=\"hidden\" name=\"_csrf\" value=\"…\">`) or a `<meta>` tag. Set by\n * `csrf()` or `csrfGuard()`, including on the first visit, before the\n * browser has the cookie. `undefined` when neither ran.\n */\nexport function csrfToken(ctx: { req: unknown } | undefined): string | undefined {\n return (ctx?.req as { [TOKEN]?: string } | undefined)?.[TOKEN]\n}\n\n/**\n * A cookie value shaped like a token this middleware issues. Anything else\n * (set by a sibling subdomain, or by hand) is replaced, so {@link csrfToken}\n * only ever hands a page hex.\n */\nfunction isOwnToken(value: string | undefined, bytes: number): value is string {\n return value !== undefined && value.length === bytes * 2 && /^[0-9a-f]+$/.test(value)\n}\n\n/** The token a mutating request sent: the header, else the form field. */\nfunction sentToken(headers: HeaderBag, body: unknown, header: string, field: string) {\n // Any header, even sent as a list, is the answer: a form field never overrides it.\n if (headers[header] !== undefined) return headerOf(headers, header)\n const fromBody =\n body && typeof body === 'object' ? (body as Record<string, unknown>)[field] : undefined\n return typeof fromBody === 'string' ? fromBody : undefined\n}\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 fieldName = options.field ?? '_csrf'\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 (!isOwnToken(token, tokenLength)) {\n token = randomHex(tokenLength)\n setCookie(res, cookieName, token, cookieOpts)\n }\n ;(req as { [TOKEN]?: string })[TOKEN] = token\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: the header (or form field) token must match the cookie token\n const sent = sentToken(\n req.headers as HeaderBag,\n (req as { body?: unknown }).body,\n headerName,\n fieldName,\n )\n\n if (sent === undefined || !safeEqual(sent, token)) {\n return sendJson(res, 403, {\n message: 'CSRF token mismatch',\n })\n }\n\n next()\n }\n}\n\n/**\n * Options for {@link csrfGuard}: the {@link csrf} options plus route-flag exemptions.\n *\n * @see https://kickjs.app/guide/csrf\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 fieldName = options.field ?? '_csrf'\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 (!isOwnToken(token, tokenLength)) {\n token = randomHex(tokenLength)\n setCookie(ctx.res, cookieName, token, cookieOpts)\n }\n ;(ctx.req as { [TOKEN]?: string })[TOKEN] = token\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 sent = sentToken(ctx.headers as HeaderBag, ctx.req.body, headerName, fieldName)\n if (sent === undefined || !safeEqual(sent, token)) {\n ctx.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,IAAI,QAAsB,IAAI,IAAI,KAAM,WAAY,SAAS,EAChF,OAAS,IAAA,IAAa,CAAC,UAAU,KAAM,KAAK,EAC9C,IAAI,KAAK,CAAE,QAAS,qBAAsB,EAAG,GAAG,EAIlD,KAAK,CACP,CACF,C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as errorHandler, r as notFoundHandler, t as MountedRoute } from "../../error-handler-
|
|
2
|
+
import { n as errorHandler, r as notFoundHandler, t as MountedRoute } from "../../error-handler-gZLQFHeE.mjs";
|
|
3
3
|
export { MountedRoute, errorHandler, notFoundHandler };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.15.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{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{createLogger,describeError}from"../../core/logger.mjs";import{t as isProduction}from"../../is-production-
|
|
11
|
+
import{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{createLogger,describeError}from"../../core/logger.mjs";import{t as isProduction}from"../../is-production-LziEMGrc.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
|