@forinda/kickjs 10.3.1 → 10.5.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-6fjmVVc2.d.mts → adapter-BZ1WzN1z.d.mts} +35 -5
- package/dist/{adapter-6fjmVVc2.d.mts.map → adapter-BZ1WzN1z.d.mts.map} +1 -1
- package/dist/{application-BuUWvaqp.d.mts → application-D5Iiy7rt.d.mts} +22 -11
- package/dist/{application-BuUWvaqp.d.mts.map → application-D5Iiy7rt.d.mts.map} +1 -1
- package/dist/{application-CYCvctQx.mjs → application-DtuQSky3.mjs} +4 -4
- package/dist/application-DtuQSky3.mjs.map +1 -0
- package/dist/{bootstrap-CfaYHbmd.mjs → bootstrap-B_6QfzXV.mjs} +3 -3
- package/dist/{bootstrap-CfaYHbmd.mjs.map → bootstrap-B_6QfzXV.mjs.map} +1 -1
- package/dist/{bounded-counters-BcA0f0bV.mjs → bounded-counters-C8PHfWEu.mjs} +2 -2
- package/dist/{bounded-counters-BcA0f0bV.mjs.map → bounded-counters-C8PHfWEu.mjs.map} +1 -1
- package/dist/{client-ip-BpauuVN_.mjs → client-ip-kxT2SHut.mjs} +2 -2
- package/dist/{client-ip-BpauuVN_.mjs.map → client-ip-kxT2SHut.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-DgMxtfcW.mjs → config-Dz-HnO4c.mjs} +3 -3
- package/dist/{config-DgMxtfcW.mjs.map → config-Dz-HnO4c.mjs.map} +1 -1
- package/dist/{context-errors-BGIOYMV5.mjs → context-errors-gitMJXxZ.mjs} +2 -2
- package/dist/{context-errors-BGIOYMV5.mjs.map → context-errors-gitMJXxZ.mjs.map} +1 -1
- package/dist/context-p-KpSsLy.mjs +12 -0
- package/dist/context-p-KpSsLy.mjs.map +1 -0
- package/dist/{contributor-runner-CJn1gZ8h.mjs → contributor-runner-CDlPrzai.mjs} +3 -3
- package/dist/{contributor-runner-CJn1gZ8h.mjs.map → contributor-runner-CDlPrzai.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- 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.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +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.mjs +1 -1
- package/dist/{core-YE-k8IrU.mjs → core-CSWR0hHJ.mjs} +3 -3
- package/dist/{core-YE-k8IrU.mjs.map → core-CSWR0hHJ.mjs.map} +1 -1
- package/dist/{csrf-ahBjt1ay.d.mts → csrf-BDAZK2mm.d.mts} +2 -2
- package/dist/{csrf-ahBjt1ay.d.mts.map → csrf-BDAZK2mm.d.mts.map} +1 -1
- package/dist/{decorate-CaEYam5J.mjs → decorate-D2oVJls5.mjs} +3 -3
- package/dist/{decorate-CaEYam5J.mjs.map → decorate-D2oVJls5.mjs.map} +1 -1
- package/dist/{decorators-deGmthGc.d.mts → decorators-Dvy0JZ5L.d.mts} +6 -2
- package/dist/{decorators-deGmthGc.d.mts.map → decorators-Dvy0JZ5L.d.mts.map} +1 -1
- package/dist/{define-adapter-C6H-I1og.mjs → define-adapter-oANmOi4a.mjs} +2 -2
- package/dist/{define-adapter-C6H-I1og.mjs.map → define-adapter-oANmOi4a.mjs.map} +1 -1
- package/dist/{di-hooks-BE0IOQk-.mjs → di-hooks-HI14rSja.mjs} +9 -4
- package/dist/di-hooks-HI14rSja.mjs.map +1 -0
- package/dist/{disposables-Cste73oY.mjs → disposables-CWNNe9HH.mjs} +1 -1
- package/dist/{error-handler-C6JJJct_.d.mts → error-handler-CbP7hKdJ.d.mts} +7 -7
- package/dist/{error-handler-C6JJJct_.d.mts.map → error-handler-CbP7hKdJ.d.mts.map} +1 -1
- package/dist/{handler-DUyRCpPw.mjs → handler-D23bJ6g1.mjs} +3 -3
- package/dist/{handler-DUyRCpPw.mjs.map → handler-D23bJ6g1.mjs.map} +1 -1
- package/dist/{host-fc-YQZnN.mjs → host-C2_vvcrO.mjs} +2 -2
- package/dist/{host-fc-YQZnN.mjs.map → host-C2_vvcrO.mjs.map} +1 -1
- package/dist/http/application.d.mts +2 -2
- 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 +1 -1
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +3 -2
- package/dist/http/middleware/csrf.mjs.map +1 -0
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -2
- 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/query/index.d.mts +2 -2
- 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/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- 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/{index-Dms8LzHG.d.mts → index-B4aOLoId.d.mts} +3 -3
- package/dist/{index-Dms8LzHG.d.mts.map → index-B4aOLoId.d.mts.map} +1 -1
- package/dist/{index-BfT5KZ-M.d.mts → index-Blgka75E.d.mts} +63 -4
- package/dist/index-Blgka75E.d.mts.map +1 -0
- package/dist/index.d.mts +11 -11
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/is-production-TSixl400.mjs +12 -0
- package/dist/is-production-TSixl400.mjs.map +1 -0
- package/dist/{jobs-DWi_Lwbe.mjs → jobs-DIddIoQs.mjs} +3 -3
- package/dist/{jobs-DWi_Lwbe.mjs.map → jobs-DIddIoQs.mjs.map} +1 -1
- package/dist/{kv-stores-BGXeNEDK.mjs → kv-stores-B9xLP0mg.mjs} +3 -3
- package/dist/{kv-stores-BGXeNEDK.mjs.map → kv-stores-B9xLP0mg.mjs.map} +1 -1
- package/dist/{kv-stores-BGXPKv15.d.mts → kv-stores-DXFBEYYu.d.mts} +30 -6
- package/dist/kv-stores-DXFBEYYu.d.mts.map +1 -0
- package/dist/{lazy-serve-static-Barg3__1.mjs → lazy-serve-static-BNM_5G_r.mjs} +2 -2
- package/dist/{lazy-serve-static-Barg3__1.mjs.map → lazy-serve-static-BNM_5G_r.mjs.map} +1 -1
- package/dist/{metadata-CnL9sQFa.mjs → metadata-CJRJvpAK.mjs} +1 -1
- package/dist/{observers-BNMQ7VLb.mjs → observers-DaIAahW4.mjs} +2 -2
- package/dist/{observers-BNMQ7VLb.mjs.map → observers-DaIAahW4.mjs.map} +1 -1
- package/dist/query-CUvSp-JT.mjs +12 -0
- package/dist/query-CUvSp-JT.mjs.map +1 -0
- package/dist/{reply-CMRk-Jp3.mjs → reply-C1CoxeQt.mjs} +3 -3
- package/dist/{reply-CMRk-Jp3.mjs.map → reply-C1CoxeQt.mjs.map} +1 -1
- package/dist/{respond-gPELdOSi.mjs → respond-Ius0bnxZ.mjs} +2 -2
- package/dist/{respond-gPELdOSi.mjs.map → respond-Ius0bnxZ.mjs.map} +1 -1
- package/dist/{route-flag-8Pi83-uw.mjs → route-flag-BP_jbhNy.mjs} +3 -3
- package/dist/{route-flag-8Pi83-uw.mjs.map → route-flag-BP_jbhNy.mjs.map} +1 -1
- package/dist/{route-policy-0LAfSzo-.mjs → route-policy-BF1hOoUO.mjs} +2 -2
- package/dist/{route-policy-0LAfSzo-.mjs.map → route-policy-BF1hOoUO.mjs.map} +1 -1
- package/dist/{router-builder-obSpg-Ub.d.mts → router-builder-BewIsj7V.d.mts} +2 -2
- package/dist/{router-builder-obSpg-Ub.d.mts.map → router-builder-BewIsj7V.d.mts.map} +1 -1
- package/dist/{router-builder-D0SDqFTr.mjs → router-builder-CBjQNcUy.mjs} +3 -3
- package/dist/{router-builder-D0SDqFTr.mjs.map → router-builder-CBjQNcUy.mjs.map} +1 -1
- package/dist/{settings-BW5gVm6c.mjs → settings-DlZtVJ3I.mjs} +3 -3
- package/dist/{settings-BW5gVm6c.mjs.map → settings-DlZtVJ3I.mjs.map} +1 -1
- package/dist/{token-Q2c8xwJE.mjs → token-9VtCdkUp.mjs} +1 -1
- package/dist/{upload-CyBSlnH_.d.mts → upload-DkT2p1gd.d.mts} +3 -3
- package/dist/{upload-CyBSlnH_.d.mts.map → upload-DkT2p1gd.d.mts.map} +1 -1
- package/dist/{upload-config-D22qKth8.mjs → upload-config-DYr3a8LW.mjs} +2 -2
- package/dist/{upload-config-D22qKth8.mjs.map → upload-config-DYr3a8LW.mjs.map} +1 -1
- package/dist/url-for-Cci2zH9d.mjs +12 -0
- package/dist/url-for-Cci2zH9d.mjs.map +1 -0
- package/dist/web-crypto-CWrgn2Yq.mjs +12 -0
- package/dist/web-crypto-CWrgn2Yq.mjs.map +1 -0
- package/dist/web.d.mts +4 -4
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/application-CYCvctQx.mjs.map +0 -1
- package/dist/context-DJvuLfrx.mjs +0 -12
- package/dist/context-DJvuLfrx.mjs.map +0 -1
- package/dist/csrf-C6Em76kH.mjs +0 -12
- package/dist/csrf-C6Em76kH.mjs.map +0 -1
- package/dist/di-hooks-BE0IOQk-.mjs.map +0 -1
- package/dist/index-BfT5KZ-M.d.mts.map +0 -1
- package/dist/is-production-0lB5MU1j.mjs +0 -12
- package/dist/is-production-0lB5MU1j.mjs.map +0 -1
- package/dist/kv-stores-BGXPKv15.d.mts.map +0 -1
- package/dist/query-mXPZYtQw.mjs +0 -12
- package/dist/query-mXPZYtQw.mjs.map +0 -1
- package/dist/url-for-UZ5kJjsG.mjs +0 -12
- package/dist/url-for-UZ5kJjsG.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-
|
|
1
|
+
{"version":3,"file":"host-C2_vvcrO.mjs","names":[],"sources":["../src/http/host.ts"],"sourcesContent":["/**\n * Host header parsing shared by the middleware that trusts it (CSRF origin\n * check, allowed hosts). One grammar and one canonical form, so two checks\n * never disagree about what host a request named.\n *\n * @module @forinda/kickjs/http/host\n */\n\n/** An http(s) URL, or undefined for anything else (`null`, `file:`, garbage). */\nexport function parseHttpUrl(value: string): URL | undefined {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * RFC 9110 `Host`: a hostname or bracketed IPv6 literal, optional port. Checked\n * before parsing, so the URL parser never sees userinfo, a path or whitespace —\n * `x@a.test` would otherwise parse to the host `a.test`.\n */\nexport const HOST_GRAMMAR = /^(?:[A-Za-z0-9.-]+|\\[[0-9A-Fa-f:.]+\\])(?::\\d{1,5})?$/\n\n/**\n * The request's host, canonicalized the way `URL` canonicalizes the origin it\n * is compared with (case, IDN, default port for that scheme) — comparing two\n * strings parsed by different rules is how checks like this get bypassed.\n */\nexport function canonicalHost(host: string | undefined, protocol: string): string | undefined {\n if (!host || !HOST_GRAMMAR.test(host)) return undefined\n return parseHttpUrl(`${protocol}//${host}`)?.host\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,aAAa,MAAgC,CAC3D,GAAI,CACF,IAAM,IAAM,IAAI,IAAI,KAAK,EACzB,OAAO,IAAI,WAAa,SAAW,IAAI,WAAa,SAAW,IAAM,IAAA,EACvE,MAAQ,CACN,MACF,CACF,CAOA,MAAa,aAAe,uDAO5B,SAAgB,cAAc,KAA0B,SAAsC,CAC5F,GAAK,MAAS,aAAa,KAAK,IAAI,EACpC,OAAO,aAAa,GAAG,SAAS,IAAI,MAAM,CAAC,EAAE,IAC/C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as
|
|
3
|
-
export { Application, ApplicationOptions, ConfigDescription, ConfigOrigins, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions };
|
|
2
|
+
import { a as ConfigOrigins, c as ServerOptions, i as ConfigDescription, l as ShutdownOptions, n as Application, o as MiddlewareEntry, r as ApplicationOptions, s as MountedRouteInfo, t as APPLICATION } from "../application-D5Iiy7rt.mjs";
|
|
3
|
+
export { APPLICATION, Application, ApplicationOptions, ConfigDescription, ConfigOrigins, MiddlewareEntry, MountedRouteInfo, ServerOptions, ShutdownOptions };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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}from"../application-
|
|
11
|
+
export{t as APPLICATION,n as Application}from"../application-DtuQSky3.mjs";
|
package/dist/http/bootstrap.mjs
CHANGED
package/dist/http/context.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as SseHandler, D as DeepReadonly, E as Ctx, O as RequestContext, j as contentDisposition, k as RouteShape } from "../adapter-
|
|
2
|
+
import { A as SseHandler, D as DeepReadonly, E as Ctx, O as RequestContext, j as contentDisposition, k as RouteShape } from "../adapter-BZ1WzN1z.mjs";
|
|
3
3
|
import { b as ContextMeta } from "../app-module-Cuu-Ma_E.mjs";
|
|
4
4
|
export { type ContextMeta, Ctx, DeepReadonly, RequestContext, RouteShape, SseHandler, contentDisposition };
|
package/dist/http/context.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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-p-KpSsLy.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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-C2_vvcrO.mjs";import{n as resolvePathname}from"../../client-ip-kxT2SHut.mjs";import{i as sendJson}from"../../respond-Ius0bnxZ.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,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as isAllowedOrigin, i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "../../csrf-
|
|
2
|
+
import { a as isAllowedOrigin, i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "../../csrf-BDAZK2mm.mjs";
|
|
3
3
|
export { CsrfGuardOptions, CsrfOptions, csrf, csrfGuard, isAllowedOrigin };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
|
|
11
|
+
import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-BP_jbhNy.mjs";import{t as isProduction}from"../../is-production-TSixl400.mjs";import{n as randomHex,r as safeEqual}from"../../web-crypto-CWrgn2Yq.mjs";import{n as canonicalHost,r as parseHttpUrl}from"../../host-C2_vvcrO.mjs";import{n as resolvePathname}from"../../client-ip-kxT2SHut.mjs";import{a as setCookie,i as sendJson,n as readCookies}from"../../respond-Ius0bnxZ.mjs";function headerOf(headers,name){let value=headers[name];return Array.isArray(value)?value[0]:value}function originOfUrl(url){if(url)try{return new URL(url).origin}catch{return}}function isAllowedOrigin(headers,trusted){let site=headerOf(headers,`sec-fetch-site`);if(site===`same-origin`)return!0;let declared=headerOf(headers,`origin`)??originOfUrl(headerOf(headers,`referer`));if(declared===void 0)return site===void 0||site===`none`;let origin=parseHttpUrl(declared);if(!origin)return!1;if(trusted.has(origin.origin))return!0;let host=canonicalHost(headerOf(headers,`host`)??headerOf(headers,`:authority`),origin.protocol);return host!==void 0&&host===origin.host}function trustedSet(origins){return new Set((origins??[]).map(o=>{let url=parseHttpUrl(o);if(!url||url.pathname!==`/`||url.search||url.hash||url.username||url.password)throw Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`);return url.origin}))}const ORIGIN_REJECTED={message:`CSRF origin not allowed`};function csrf(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(req,res,next)=>{let token=readCookies(req)[cookieName];if(token||(token=randomHex(tokenLength),setCookie(res,cookieName,token,cookieOpts)),!protectedMethods.has(req.method.toUpperCase())||ignorePaths.has(resolvePathname(req)))return next();if(checkOrigin&&!isAllowedOrigin(req.headers,trusted))return sendJson(res,403,ORIGIN_REJECTED);let headerToken=req.headers[headerName];if(typeof headerToken!=`string`||!safeEqual(headerToken,token))return sendJson(res,403,{message:`CSRF token mismatch`});next()}}function csrfGuard(options={}){let cookieName=options.cookie??`_csrf`,headerName=options.header??`x-csrf-token`,protectedMethods=new Set((options.methods??[`POST`,`PUT`,`PATCH`,`DELETE`]).map(m=>m.toUpperCase())),ignorePaths=new Set(options.ignorePaths??[]),tokenLength=options.tokenLength??32,exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`csrfGuard({ exemptWhen })`);let checkOrigin=options.checkOrigin??!0,trusted=trustedSet(options.trustedOrigins),cookieOpts={httpOnly:!1,sameSite:`strict`,secure:isProduction(),path:`/`,...options.cookieOptions};return(ctx,next)=>{let token=readCookies(ctx.req)[cookieName];token||(token=randomHex(tokenLength),setCookie(ctx.res,cookieName,token,cookieOpts));let method=ctx.route?.method??ctx.req.method??`GET`;if(!protectedMethods.has(method.toUpperCase())||exemptWhen!==void 0&&matchesFlagTest(exemptWhen,ctx.route?.flags,ctx.route)||ignorePaths.has(resolvePathname(ctx.req)))return next();if(checkOrigin&&!isAllowedOrigin(ctx.headers,trusted)){ctx.json(ORIGIN_REJECTED,403);return}let headerToken=ctx.headers[headerName];typeof headerToken!=`string`||!safeEqual(headerToken,token)?ctx.json({message:`CSRF token mismatch`},403):next()}}export{csrf,csrfGuard,isAllowedOrigin};
|
|
12
|
+
//# sourceMappingURL=csrf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csrf.mjs","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"sourcesContent":["import { readCookies, sendJson, setCookie } from './respond'\nimport type { Request, Response, NextFunction } from 'express'\nimport { resolvePathname, type ClientRequestLike } from '../client-ip'\n\nimport { randomHex, safeEqual } from '../../core/web-crypto'\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport { isProduction } from '../../core/is-production'\nimport { canonicalHost, parseHttpUrl } from '../host'\n\nexport interface CsrfOptions {\n /** Cookie name for the CSRF token (default: '_csrf') */\n cookie?: string\n /** Header name to check for the token (default: 'x-csrf-token') */\n header?: string\n /** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */\n methods?: string[]\n /** Paths to exclude from CSRF checks (e.g. webhooks) */\n ignorePaths?: string[]\n /** Token byte length before hex encoding (default: 32 = 64 hex chars) */\n tokenLength?: number\n /**\n * Origins, besides the request's own host, allowed to send state-changing\n * requests — e.g. `['https://app.example.com']` when the frontend lives on\n * another subdomain. Compared against the `Origin` (or `Referer`) header.\n */\n trustedOrigins?: string[]\n /**\n * Check where an unsafe request came from before the token (default `true`).\n * `Sec-Fetch-Site: same-origin` passes; otherwise the `Origin` (or `Referer`)\n * must match the request's `Host` or a {@link trustedOrigins} entry, and a\n * browser request that says it is cross-site with neither is refused. A\n * request with no such headers at all (a server, curl) goes on to the token\n * check. Turn off only behind a proxy that rewrites `Host` and when you\n * cannot list the origins.\n */\n checkOrigin?: boolean\n /** Cookie options */\n cookieOptions?: {\n /**\n * Default `false`, because double-submit CSRF needs the page to read the\n * token and echo it in a header. Set `true` only if the client receives\n * the token another way — server-rendered, or from your own endpoint.\n */\n httpOnly?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n secure?: boolean\n path?: string\n }\n}\n\ntype HeaderBag = Record<string, string | string[] | undefined>\n\nfunction headerOf(headers: HeaderBag, name: string): string | undefined {\n const value = headers[name]\n return Array.isArray(value) ? value[0] : value\n}\n\n/** `scheme://host[:port]` of a URL, or undefined when it doesn't parse. */\nfunction originOfUrl(url: string | undefined): string | undefined {\n if (!url) return undefined\n try {\n return new URL(url).origin\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether an unsafe request came from somewhere allowed to send it — the\n * origin half of CSRF protection, ahead of the token. The token alone (double\n * submit) can be planted by a sibling subdomain that sets cookies on the\n * parent domain; the browser's own origin headers cannot.\n */\nexport function isAllowedOrigin(headers: HeaderBag, trusted: ReadonlySet<string>): boolean {\n const site = headerOf(headers, 'sec-fetch-site')\n if (site === 'same-origin') return true\n\n const declared = headerOf(headers, 'origin') ?? originOfUrl(headerOf(headers, 'referer'))\n if (declared === undefined) {\n // No browser origin headers: not a browser cross-site request (or a very\n // old browser). Left to the token. A browser that says cross-site or\n // same-site but sends no origin is refused.\n return site === undefined || site === 'none'\n }\n // `Origin: null` (sandboxed frames, some redirects) and non-http schemes\n // don't parse: refused.\n const origin = parseHttpUrl(declared)\n if (!origin) return false\n if (trusted.has(origin.origin)) return true\n // The scheme is not compared: behind a TLS-terminating proxy the app cannot\n // know it reliably. The host (with port) is what an attacker cannot match.\n // HTTP/2 carries it as `:authority`.\n const host = canonicalHost(\n headerOf(headers, 'host') ?? headerOf(headers, ':authority'),\n origin.protocol,\n )\n return host !== undefined && host === origin.host\n}\n\nfunction trustedSet(origins: string[] | undefined): Set<string> {\n return new Set(\n (origins ?? []).map((o) => {\n const url = parseHttpUrl(o)\n // An origin is scheme + host + port: a path, query or credentials here\n // means the entry was meant as something else.\n if (!url || url.pathname !== '/' || url.search || url.hash || url.username || url.password) {\n throw new Error(`csrf: trustedOrigins entry '${o}' is not an http(s) origin`)\n }\n return url.origin\n }),\n )\n}\n\nconst ORIGIN_REJECTED = { message: 'CSRF origin not allowed' }\n\n/**\n * Double-submit cookie CSRF protection middleware.\n *\n * On every request, sets a CSRF token cookie. For state-changing methods\n * (POST, PUT, PATCH, DELETE), validates that the request header matches\n * the cookie value.\n *\n * @example\n * ```ts\n * import { csrf } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * cookieParser(),\n * csrf(),\n * // ... other middleware\n * ],\n * })\n * ```\n *\n * Client usage:\n * 1. Read the `_csrf` cookie value\n * 2. Send it in the `x-csrf-token` header on every mutating request\n */\nexport function csrf(options: CsrfOptions = {}) {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // `false`, not `true`: double-submit CSRF requires the PAGE to read this\n // cookie and echo it in a header. Under `httpOnly: true` `document.cookie`\n // returns nothing, no header is sent, and every mutating request answers\n // 403 — the documented client flow could not work. The token is not a\n // credential; a token an attacker cannot read is also one your own page\n // cannot send. Set `cookieOptions: { httpOnly: true }` only when the token\n // reaches the client some other way (server-rendered, or your own endpoint).\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Generate or reuse CSRF token\n // NOT `req.cookies` alone: that is populated only by an upstream parser,\n // which Fastify and h3 never have and Express only has if the app mounts\n // one. Without this the middleware never saw the token it had just issued.\n const cookies = readCookies(req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(res, cookieName, token, cookieOpts)\n }\n\n // Skip validation for safe methods and ignored paths\n if (!protectedMethods.has(req.method.toUpperCase())) {\n return next()\n }\n\n // `req.path` is Express-only, so `has(undefined)` never matched and\n // configured exemptions were silently ignored on Fastify / h3.\n if (ignorePaths.has(resolvePathname(req as ClientRequestLike))) {\n return next()\n }\n\n if (checkOrigin && !isAllowedOrigin(req.headers as HeaderBag, trusted)) {\n return sendJson(res, 403, ORIGIN_REJECTED)\n }\n\n // Validate: header token must match cookie token\n const headerToken = req.headers[headerName] as string | undefined\n\n if (typeof headerToken !== 'string' || !safeEqual(headerToken, token)) {\n return sendJson(res, 403, {\n message: 'CSRF token mismatch',\n })\n }\n\n next()\n }\n}\n\nexport interface CsrfGuardOptions extends CsrfOptions {\n /**\n * Skip the token check on routes carrying a route flag — a name, a list of\n * names (any-of), or a predicate.\n *\n * This is the reason the guard exists. `csrf()` runs before route matching,\n * so its only handle on \"not this endpoint\" is {@link CsrfOptions.ignorePaths}\n * — an exact pathname string that cannot express `/webhooks/:provider` and\n * keeps parsing after an `apiPrefix` change that voids it. A flag is declared\n * on the route itself:\n *\n * ```ts\n * const CsrfExempt = defineRouteFlag('csrf.exempt')\n *\n * @CsrfExempt\n * @Controller()\n * class WebhooksController {\n * @Post('/:provider') receive(ctx: RequestContext) {}\n * }\n * ```\n */\n exemptWhen?: RouteFlagTest\n}\n\n/**\n * Double-submit cookie CSRF protection as a `(ctx, next)` middleware.\n *\n * The ctx-style counterpart of {@link csrf}: it runs inside the matched route,\n * so it can read `ctx.route.flags` and be exempted per route, and it works on\n * every runtime including the `@forinda/kickjs/web` fetch entry.\n *\n * ```ts\n * // per controller — the flag-aware form\n * @Middleware(csrfGuard({ exemptWhen: 'csrf.exempt' }))\n * @Controller()\n * class BillingController {}\n *\n * // edge, app-wide\n * createWebApp({ h3, modules, middleware: [csrfGuard()] })\n * ```\n *\n * Mount `csrf()` instead when you want one app-wide connect middleware that\n * also covers requests matching no route — nothing to exempt, nothing to read.\n */\nexport function csrfGuard(options: CsrfGuardOptions = {}): MiddlewareHandler {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'csrfGuard({ exemptWhen })')\n const checkOrigin = options.checkOrigin ?? true\n const trusted = trustedSet(options.trustedOrigins)\n const cookieOpts = {\n // Same default as `csrf()` above, and for the same reason.\n httpOnly: false,\n sameSite: 'strict' as const,\n secure: isProduction(),\n path: '/',\n ...options.cookieOptions,\n }\n\n return (ctx: RequestContext, next: () => void): void => {\n const cookies = readCookies(ctx.req)\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomHex(tokenLength)\n setCookie(ctx.res, cookieName, token, cookieOpts)\n }\n\n // Safe methods only ever issue the token.\n const method = ctx.route?.method ?? (ctx.req as { method?: string }).method ?? 'GET'\n if (!protectedMethods.has(method.toUpperCase())) return next()\n\n // Flag first: it is the declared exemption, and cheaper than the path set.\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n if (ignorePaths.has(resolvePathname(ctx.req as unknown as ClientRequestLike))) return next()\n\n if (checkOrigin && !isAllowedOrigin(ctx.headers as HeaderBag, trusted)) {\n ctx.json(ORIGIN_REJECTED, 403)\n return\n }\n\n const headerToken = ctx.headers[headerName] as string | undefined\n if (typeof headerToken !== 'string' || !safeEqual(headerToken, token)) {\n ctx.json({ message: 'CSRF token mismatch' }, 403)\n return\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;4bAsDA,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,K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IAAI,OAAO,YAAY,CAAC,GAG1C,aAAe,IAAA,IAAa,gBAAgB,WAAY,IAAI,OAAO,MAAO,IAAI,KAAK,GAInF,YAAY,IAAI,gBAAgB,IAAI,GAAmC,CAAC,EAAG,OAAO,KAAK,EAE3F,GAAI,aAAe,CAAC,gBAAgB,IAAI,QAAsB,OAAO,EAAG,CACtE,IAAI,KAAK,gBAAiB,GAAG,EAC7B,MACF,CAEA,IAAM,YAAc,IAAI,QAAQ,YAC5B,OAAO,aAAgB,UAAY,CAAC,UAAU,YAAa,KAAK,EAClE,IAAI,KAAK,CAAE,QAAS,qBAAsB,EAAG,GAAG,EAIlD,KAAK,CACP,CACF"}
|
|
@@ -1,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-CbP7hKdJ.mjs";
|
|
3
3
|
export { MountedRoute, errorHandler, notFoundHandler };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger,describeError}from"../../core/logger.mjs";import{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{t as isProduction}from"../../is-production-
|
|
11
|
+
import{createLogger,describeError}from"../../core/logger.mjs";import{HttpException,ProblemException,normalizeProblem}from"../../core/errors.mjs";import{t as isProduction}from"../../is-production-TSixl400.mjs";const log=createLogger(`ErrorHandler`);function patternToRegExp(pattern){let source=pattern.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\/:[^/]+/g,`/[^/]+`).replace(/\*/g,`.*`);return RegExp(`^${source}/?$`)}function pathOf(req){let url=req.originalUrl??req.url??`/`,cut=url.search(/[?#]/);return cut===-1?url:url.slice(0,cut)}function notFoundHandler(routes=[]){let matchers=routes.map(route=>({method:route.method.toUpperCase(),matches:patternToRegExp(route.path)}));return(req,res,_next)=>{let path=pathOf(req),method=(req.method??`GET`).toUpperCase(),allowed=[...new Set(matchers.filter(m=>m.matches.test(path)).map(m=>m.method))];if(allowed.length>0&&!allowed.includes(method)){let verbs=allowed.toSorted().join(`, `);return res.setHeader(`Allow`,verbs),res.setHeader(`Content-Type`,`application/problem+json`),res.status(405).json(normalizeProblem({status:405,detail:`${method} is not supported for this resource. Allowed: ${verbs}.`}))}return res.setHeader(`Content-Type`,`application/problem+json`),res.status(404).json(normalizeProblem({status:404}))}}function fieldErrors(details){if(Array.isArray(details)&&details.length!==0)return details.every(d=>typeof d?.field==`string`&&typeof d?.message==`string`)?details.map(d=>({field:d.field,message:d.message})):void 0}function errorHandler(){return(err,req,res,_next)=>{let isProduction$1=isProduction();if(res.headersSent){log.warn(`Error after headers sent: ${err?.message||`Unknown`}`);return}if(err instanceof ProblemException){if(err.problem.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let body=normalizeProblem(err.problem);return res.setHeader(`Content-Type`,`application/problem+json`),res.status(body.status).json(body)}if(err?.name===`ZodError`){let firstIssue=err.issues?.[0];return res.status(422).json({message:firstIssue?.message||`Validation failed`,...isProduction$1?{}:{errors:err.issues}})}if(err instanceof HttpException){if(err.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let errors=isProduction$1?err.status===422?fieldErrors(err.details):void 0:err.details;return res.setHeader(`Content-Type`,`application/problem+json`),res.status(err.status).json(normalizeProblem({status:err.status,detail:err.message,...errors===void 0?{}:{errors}}))}let requestId=req.requestId??req.headers[`x-request-id`],declared=Number(err.status??err.statusCode);if(Number.isInteger(declared)&&declared>=400&&declared<500)return log.warn(`${req.method} ${req.originalUrl??req.url} — ${declared} ${describeError(err)}`),res.setHeader(`Content-Type`,`application/problem+json`),res.status(declared).json(normalizeProblem({status:declared,detail:err.message||void 0,...requestId?{requestId}:{}}));let status=Number.isInteger(declared)&&declared>=500&&declared<600?declared:500;log.error(err,`${req.method} ${req.originalUrl??req.url} — ${describeError(err)}${requestId?` [${requestId}]`:``}`),res.status(status).json({message:`Internal Server Error`,...requestId?{requestId}:{},...isProduction$1?{}:{error:describeError(err),...typeof err?.stack==`string`?{stack:err.stack.split(`
|
|
12
12
|
`)}:{}}})}}export{errorHandler,notFoundHandler};
|
|
13
13
|
//# sourceMappingURL=error-handler.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.mjs","names":["isProduction","isProductionEnv"],"sources":["../../../src/http/middleware/error-handler.ts"],"sourcesContent":["import type { RuntimeResponse } from '../runtime'\n\n/**\n * The slice of the request this handler reads, spelled from node's\n * `IncomingMessage` rather than Express's `Request`.\n *\n * Fastify and h3 hand the error handler `request.raw` — a plain\n * `IncomingMessage` — so anything Express-only is `undefined` there. This is\n * the default handler for EVERY runtime, so it must not assume Express.\n */\ninterface ErrorRequest {\n method?: string\n url?: string\n /** Express-only; absent on the raw node request the other runtimes pass. */\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n}\n// Module paths, not the core barrel: the web entry (edge runtimes) uses these\n// handlers too, and the barrel reaches node-only modules.\nimport { HttpException, ProblemException, normalizeProblem } from '../../core/errors'\nimport { createLogger, describeError } from '../../core/logger'\nimport { isProduction as isProductionEnv } from '../../core/is-production'\n\nconst log = createLogger('ErrorHandler')\n\n/** A mounted route, as the catch-all needs to see it. */\nexport interface MountedRoute {\n method: string\n /** Full path as mounted, `:param` segments included. */\n path: string\n}\n\n/** `/things/:id` → `^/things/[^/]+$`, so a concrete path can be matched. */\nfunction patternToRegExp(pattern: string): RegExp {\n const source = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/[^/]+')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\n/** Path without query string or hash. */\nfunction pathOf(req: ErrorRequest): string {\n const url = req.originalUrl ?? req.url ?? '/'\n const cut = url.search(/[?#]/)\n return cut === -1 ? url : url.slice(0, cut)\n}\n\n/**\n * Catch-all for unmatched routes.\n *\n * Answers RFC 9457 problem details, like every other error the framework\n * produces — the catch-all was the one path still emitting a bare\n * `{ message }`, so a client parsing `application/problem+json` had to special\n * case it.\n *\n * Distinguishes a path that does not exist from a path that does not accept\n * this method. `DELETE /things/1` where only `GET` is mounted is a **405** with\n * an `Allow` header, not a 404: the resource is there, the verb is not, and\n * 404 tells a client to stop looking for something that exists. Requires the\n * mounted route table, so an app that does not pass one keeps answering 404.\n */\nexport function notFoundHandler(routes: readonly MountedRoute[] = []) {\n const matchers = routes.map((route) => ({\n method: route.method.toUpperCase(),\n matches: patternToRegExp(route.path),\n }))\n\n return (req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const path = pathOf(req)\n const method = (req.method ?? 'GET').toUpperCase()\n const allowed = [...new Set(matchers.filter((m) => m.matches.test(path)).map((m) => m.method))]\n\n if (allowed.length > 0 && !allowed.includes(method)) {\n // Sorted once: the header and the detail must list the same verbs in the\n // same order, and `sort()` would mutate `allowed` under the second read.\n const verbs = allowed.toSorted().join(', ')\n // RFC 9110 §15.5.6 requires Allow on a 405.\n res.setHeader('Allow', verbs)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(405).json(\n normalizeProblem({\n status: 405,\n detail: `${method} is not supported for this resource. Allowed: ${verbs}.`,\n }),\n )\n }\n\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(404).json(normalizeProblem({ status: 404 }))\n }\n}\n\n/**\n * Global error handler.\n *\n * Default behavior strips error `details` from the response in production\n * (NODE_ENV === 'production') so internal context (DB errors, validation\n * issues, custom payloads) does not leak to clients. Apps that want to\n * expose details in production — for client-facing field-level validation,\n * for example — should pass their own `onError` to `bootstrap()` and decide\n * the policy explicitly.\n *\n * Unexpected 500s carry `requestId` in every environment (the correlation\n * handle back to the log line) and, outside production, the error summary\n * plus stack. Production bodies stay opaque.\n *\n * {@link ProblemException} and plain {@link HttpException} both emit\n * `application/problem+json` per RFC 9457. `ProblemException` carries a\n * caller-supplied `type` / `title` / extensions; an `HttpException`'s message\n * becomes `detail`, with `title` and `type` defaulted from the status. One\n * shape, so a client never has to branch on which one the app threw.\n */\nexport function errorHandler() {\n return (err: any, req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const isProduction = isProductionEnv()\n // Don't write after headers are already sent\n if (res.headersSent) {\n log.warn(`Error after headers sent: ${err?.message || 'Unknown'}`)\n return\n }\n\n // RFC 9457 Problem Details — checked before HttpException because\n // ProblemException extends HttpException; instanceof on the base\n // would otherwise swallow it.\n if (err instanceof ProblemException) {\n if (err.problem.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const body = normalizeProblem(err.problem)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(body.status).json(body)\n }\n\n // Zod validation errors\n if (err?.name === 'ZodError') {\n const firstIssue = err.issues?.[0]\n return res.status(422).json({\n message: firstIssue?.message || 'Validation failed',\n ...(isProduction ? {} : { errors: err.issues }),\n })\n }\n\n // HttpException (expected application errors) — RFC 9457, same as\n // ProblemException. It used to answer a bare `{ message }`, which made it\n // THE path a client parsing `application/problem+json` had to special-case\n // (#611) — the exact situation #587 removed from the catch-all. The\n // message becomes `detail`; `title` and `type` default from the status.\n if (err instanceof HttpException) {\n if (err.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const exposeDetails = !isProduction && err.details !== undefined\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(err.status).json(\n normalizeProblem({\n status: err.status,\n detail: err.message,\n // Extension member, permitted by RFC 9457 §3.2. Held back in\n // production for the same reason as before: `details` can carry the\n // shape of the request that failed.\n ...(exposeDetails ? { errors: err.details } : {}),\n }),\n )\n }\n\n const requestId = (req as any).requestId ?? req.headers['x-request-id']\n const declared = Number(err.status ?? err.statusCode)\n\n // Any error that says it's a client error — a database UniqueViolationError\n // (409), a BYO auth check's 401 — is answered like an HttpException: RFC\n // 9457, its message as `detail`, and a warning rather than an error log.\n // It used to fall through to the catch-all: logged at ERROR with a stack,\n // answered with a bare `{ message }` no problem+json client could parse.\n if (Number.isInteger(declared) && declared >= 400 && declared < 500) {\n log.warn(`${req.method} ${req.originalUrl ?? req.url} — ${declared} ${describeError(err)}`)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(declared).json(\n normalizeProblem({\n status: declared,\n detail: err.message || undefined,\n ...(requestId ? { requestId } : {}),\n }),\n )\n }\n\n // Unexpected errors — always log. A declared 5xx keeps its status but\n // gets the same guarded body as a 500.\n const status = Number.isInteger(declared) && declared >= 500 && declared < 600 ? declared : 500\n log.error(\n err,\n // `originalUrl` is Express-only. Fastify and h3 pass `request.raw`, so\n // this logged `GET undefined — <error>` on every error under those\n // runtimes — the path silently dropped from the one line meant to\n // identify the failing request.\n `${req.method} ${req.originalUrl ?? req.url} — ${describeError(err)}${\n requestId ? ` [${requestId}]` : ''\n }`,\n )\n\n // A 500 body must never carry the raw error in production — it can\n // contain table names, SQL, connection strings, or user data. But\n // returning a bare `{ message: 'Internal Server Error' }` in\n // development means the one place a developer is looking tells them\n // nothing, and the failure has to be re-diagnosed from the database.\n //\n // Development gets the full picture. Production gets the requestId,\n // which is the correlation handle back to the (now stack-carrying)\n // log line — without it an opaque 500 can't even be tied to its own\n // log entry.\n res.status(status).json({\n message: 'Internal Server Error',\n ...(requestId ? { requestId } : {}),\n ...(isProduction\n ? {}\n : {\n error: describeError(err),\n ...(typeof err?.stack === 'string' ? { stack: err.stack.split('\\n') } : {}),\n }),\n })\n }\n}\n"],"mappings":";;;;;;;;;;iNA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AAU,IAAI,UAAU,EAOpD,GAAI,OAAO,UAAU,QAAQ,GAAK,UAAY,KAAO,SAAW,IAG9D,OAFA,IAAI,KAAK,GAAG,IAAI,OAAO,GAAG,IAAI,aAAe,IAAI,IAAI,KAAK,SAAS,GAAG,cAAc,GAAG,GAAG,EAC1F,IAAI,UAAU,eAAgB,0BAA0B,EACjD,IAAI,OAAO,QAAQ,CAAC,CAAC,KAC1B,iBAAiB,CACf,OAAQ,SACR,OAAQ,IAAI,SAAW,IAAA,GACvB,GAAI,UAAY,CAAE,SAAU,EAAI,CAAC,CACnC,CAAC,CACH,EAKF,IAAM,OAAS,OAAO,UAAU,QAAQ,GAAK,UAAY,KAAO,SAAW,IAAM,SAAW,IAC5F,IAAI,MACF,IAKA,GAAG,IAAI,OAAO,GAAG,IAAI,aAAe,IAAI,IAAI,KAAK,cAAc,GAAG,IAChE,UAAY,KAAK,UAAU,GAAK,IAEpC,EAYA,IAAI,OAAO,MAAM,CAAC,CAAC,KAAK,CACtB,QAAS,wBACT,GAAI,UAAY,CAAE,SAAU,EAAI,CAAC,EACjC,GAAIA,eACA,CAAC,EACD,CACE,MAAO,cAAc,GAAG,EACxB,GAAI,OAAO,KAAK,OAAU,SAAW,CAAE,MAAO,IAAI,MAAM,MAAM;CAAI,CAAE,EAAI,CAAC,CAC3E,CACN,CAAC,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"error-handler.mjs","names":["isProduction","isProductionEnv"],"sources":["../../../src/http/middleware/error-handler.ts"],"sourcesContent":["import type { RuntimeResponse } from '../runtime'\n\n/**\n * The slice of the request this handler reads, spelled from node's\n * `IncomingMessage` rather than Express's `Request`.\n *\n * Fastify and h3 hand the error handler `request.raw` — a plain\n * `IncomingMessage` — so anything Express-only is `undefined` there. This is\n * the default handler for EVERY runtime, so it must not assume Express.\n */\ninterface ErrorRequest {\n method?: string\n url?: string\n /** Express-only; absent on the raw node request the other runtimes pass. */\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n}\n// Module paths, not the core barrel: the web entry (edge runtimes) uses these\n// handlers too, and the barrel reaches node-only modules.\nimport { HttpException, ProblemException, normalizeProblem } from '../../core/errors'\nimport { createLogger, describeError } from '../../core/logger'\nimport { isProduction as isProductionEnv } from '../../core/is-production'\n\nconst log = createLogger('ErrorHandler')\n\n/** A mounted route, as the catch-all needs to see it. */\nexport interface MountedRoute {\n method: string\n /** Full path as mounted, `:param` segments included. */\n path: string\n}\n\n/** `/things/:id` → `^/things/[^/]+$`, so a concrete path can be matched. */\nfunction patternToRegExp(pattern: string): RegExp {\n const source = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/[^/]+')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\n/** Path without query string or hash. */\nfunction pathOf(req: ErrorRequest): string {\n const url = req.originalUrl ?? req.url ?? '/'\n const cut = url.search(/[?#]/)\n return cut === -1 ? url : url.slice(0, cut)\n}\n\n/**\n * Catch-all for unmatched routes.\n *\n * Answers RFC 9457 problem details, like every other error the framework\n * produces — the catch-all was the one path still emitting a bare\n * `{ message }`, so a client parsing `application/problem+json` had to special\n * case it.\n *\n * Distinguishes a path that does not exist from a path that does not accept\n * this method. `DELETE /things/1` where only `GET` is mounted is a **405** with\n * an `Allow` header, not a 404: the resource is there, the verb is not, and\n * 404 tells a client to stop looking for something that exists. Requires the\n * mounted route table, so an app that does not pass one keeps answering 404.\n */\nexport function notFoundHandler(routes: readonly MountedRoute[] = []) {\n const matchers = routes.map((route) => ({\n method: route.method.toUpperCase(),\n matches: patternToRegExp(route.path),\n }))\n\n return (req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const path = pathOf(req)\n const method = (req.method ?? 'GET').toUpperCase()\n const allowed = [...new Set(matchers.filter((m) => m.matches.test(path)).map((m) => m.method))]\n\n if (allowed.length > 0 && !allowed.includes(method)) {\n // Sorted once: the header and the detail must list the same verbs in the\n // same order, and `sort()` would mutate `allowed` under the second read.\n const verbs = allowed.toSorted().join(', ')\n // RFC 9110 §15.5.6 requires Allow on a 405.\n res.setHeader('Allow', verbs)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(405).json(\n normalizeProblem({\n status: 405,\n detail: `${method} is not supported for this resource. Allowed: ${verbs}.`,\n }),\n )\n }\n\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(404).json(normalizeProblem({ status: 404 }))\n }\n}\n\n/**\n * A validation failure's `[{ field, message }]` with every other member\n * dropped — or `undefined` when `details` isn't that shape.\n */\nfunction fieldErrors(details: unknown): Array<{ field: string; message: string }> | undefined {\n if (!Array.isArray(details) || details.length === 0) return undefined\n const ok = details.every((d) => typeof d?.field === 'string' && typeof d?.message === 'string')\n return ok ? details.map((d) => ({ field: d.field, message: d.message })) : undefined\n}\n\n/**\n * Global error handler.\n *\n * Default behavior strips error `details` from the response in production\n * (any `NODE_ENV` but `development` / `test`, unset included) so internal\n * context (DB errors, custom payloads) does not leak to clients. A 422's\n * per-field `{ field, message }` list is kept — field names and messages are\n * what a form shows — with every other member dropped. Apps that want a\n * different policy pass their own `onError` to `bootstrap()`.\n *\n * Unexpected 500s carry `requestId` in every environment (the correlation\n * handle back to the log line) and, outside production, the error summary\n * plus stack. Production bodies stay opaque.\n *\n * {@link ProblemException} and plain {@link HttpException} both emit\n * `application/problem+json` per RFC 9457. `ProblemException` carries a\n * caller-supplied `type` / `title` / extensions; an `HttpException`'s message\n * becomes `detail`, with `title` and `type` defaulted from the status. One\n * shape, so a client never has to branch on which one the app threw.\n */\nexport function errorHandler() {\n return (err: any, req: ErrorRequest, res: RuntimeResponse, _next: () => void) => {\n const isProduction = isProductionEnv()\n // Don't write after headers are already sent\n if (res.headersSent) {\n log.warn(`Error after headers sent: ${err?.message || 'Unknown'}`)\n return\n }\n\n // RFC 9457 Problem Details — checked before HttpException because\n // ProblemException extends HttpException; instanceof on the base\n // would otherwise swallow it.\n if (err instanceof ProblemException) {\n if (err.problem.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const body = normalizeProblem(err.problem)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(body.status).json(body)\n }\n\n // A raw ZodError never comes from the framework's own validation (that\n // raises an HttpException 422 with `[{ field, message }]`). It is the app\n // parsing something — possibly internal data — so production shows no\n // field paths; route validation (`@Post('/', { body })`) or an explicit\n // `HttpException` is how a form gets its field errors.\n if (err?.name === 'ZodError') {\n const firstIssue = err.issues?.[0]\n return res.status(422).json({\n message: firstIssue?.message || 'Validation failed',\n ...(isProduction ? {} : { errors: err.issues }),\n })\n }\n\n // HttpException (expected application errors) — RFC 9457, same as\n // ProblemException. It used to answer a bare `{ message }`, which made it\n // THE path a client parsing `application/problem+json` had to special-case\n // (#611) — the exact situation #587 removed from the catch-all. The\n // message becomes `detail`; `title` and `type` default from the status.\n if (err instanceof HttpException) {\n if (err.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n // Extension member, permitted by RFC 9457 §3.2. Held back in production:\n // `details` can carry the shape of the request that failed. A 422's\n // per-field `{ field, message }` list is the exception — a form needs\n // it to say which field is wrong — so production keeps just those two.\n const errors = isProduction\n ? err.status === 422\n ? fieldErrors(err.details)\n : undefined\n : err.details\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(err.status).json(\n normalizeProblem({\n status: err.status,\n detail: err.message,\n ...(errors !== undefined ? { errors } : {}),\n }),\n )\n }\n\n const requestId = (req as any).requestId ?? req.headers['x-request-id']\n const declared = Number(err.status ?? err.statusCode)\n\n // Any error that says it's a client error — a database UniqueViolationError\n // (409), a BYO auth check's 401 — is answered like an HttpException: RFC\n // 9457, its message as `detail`, and a warning rather than an error log.\n // It used to fall through to the catch-all: logged at ERROR with a stack,\n // answered with a bare `{ message }` no problem+json client could parse.\n if (Number.isInteger(declared) && declared >= 400 && declared < 500) {\n log.warn(`${req.method} ${req.originalUrl ?? req.url} — ${declared} ${describeError(err)}`)\n res.setHeader('Content-Type', 'application/problem+json')\n return res.status(declared).json(\n normalizeProblem({\n status: declared,\n detail: err.message || undefined,\n ...(requestId ? { requestId } : {}),\n }),\n )\n }\n\n // Unexpected errors — always log. A declared 5xx keeps its status but\n // gets the same guarded body as a 500.\n const status = Number.isInteger(declared) && declared >= 500 && declared < 600 ? declared : 500\n log.error(\n err,\n // `originalUrl` is Express-only. Fastify and h3 pass `request.raw`, so\n // this logged `GET undefined — <error>` on every error under those\n // runtimes — the path silently dropped from the one line meant to\n // identify the failing request.\n `${req.method} ${req.originalUrl ?? req.url} — ${describeError(err)}${\n requestId ? ` [${requestId}]` : ''\n }`,\n )\n\n // A 500 body must never carry the raw error in production — it can\n // contain table names, SQL, connection strings, or user data. But\n // returning a bare `{ message: 'Internal Server Error' }` in\n // development means the one place a developer is looking tells them\n // nothing, and the failure has to be re-diagnosed from the database.\n //\n // Development gets the full picture. Production gets the requestId,\n // which is the correlation handle back to the (now stack-carrying)\n // log line — without it an opaque 500 can't even be tied to its own\n // log entry.\n res.status(status).json({\n message: 'Internal Server Error',\n ...(requestId ? { requestId } : {}),\n ...(isProduction\n ? {}\n : {\n error: describeError(err),\n ...(typeof err?.stack === 'string' ? { stack: err.stack.split('\\n') } : {}),\n }),\n })\n }\n}\n"],"mappings":";;;;;;;;;;iNAuBA,MAAM,IAAM,aAAa,cAAc,EAUvC,SAAS,gBAAgB,QAAyB,CAChD,IAAM,OAAS,QACZ,QAAQ,qBAAsB,MAAM,CAAC,CACrC,QAAQ,YAAa,QAAQ,CAAC,CAC9B,QAAQ,MAAO,IAAI,EACtB,OAAW,OAAO,IAAI,OAAO,IAAI,CACnC,CAGA,SAAS,OAAO,IAA2B,CACzC,IAAM,IAAM,IAAI,aAAe,IAAI,KAAO,IACpC,IAAM,IAAI,OAAO,MAAM,EAC7B,OAAO,MAAQ,GAAK,IAAM,IAAI,MAAM,EAAG,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,IAAI,KAAK,GAAG,IAAI,OAAO,GAAG,IAAI,aAAe,IAAI,IAAI,KAAK,SAAS,GAAG,cAAc,GAAG,GAAG,EAC1F,IAAI,UAAU,eAAgB,0BAA0B,EACjD,IAAI,OAAO,QAAQ,CAAC,CAAC,KAC1B,iBAAiB,CACf,OAAQ,SACR,OAAQ,IAAI,SAAW,IAAA,GACvB,GAAI,UAAY,CAAE,SAAU,EAAI,CAAC,CACnC,CAAC,CACH,EAKF,IAAM,OAAS,OAAO,UAAU,QAAQ,GAAK,UAAY,KAAO,SAAW,IAAM,SAAW,IAC5F,IAAI,MACF,IAKA,GAAG,IAAI,OAAO,GAAG,IAAI,aAAe,IAAI,IAAI,KAAK,cAAc,GAAG,IAChE,UAAY,KAAK,UAAU,GAAK,IAEpC,EAYA,IAAI,OAAO,MAAM,CAAC,CAAC,KAAK,CACtB,QAAS,wBACT,GAAI,UAAY,CAAE,SAAU,EAAI,CAAC,EACjC,GAAIA,eACA,CAAC,EACD,CACE,MAAO,cAAc,GAAG,EACxB,GAAI,OAAO,KAAK,OAAU,SAAW,CAAE,MAAO,IAAI,MAAM,MAAM;CAAI,CAAE,EAAI,CAAC,CAC3E,CACN,CAAC,CACH,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{r as registerDisposable}from"../../disposables-
|
|
11
|
+
import{r as registerDisposable}from"../../disposables-CWNNe9HH.mjs";import{n as assertFlagTest,s as matchesFlagTest}from"../../route-flag-BP_jbhNy.mjs";import{n as bindRoutePolicy}from"../../route-policy-BF1hOoUO.mjs";import{n as resolvePathname,t as resolveClientIp}from"../../client-ip-kxT2SHut.mjs";import{i as sendJson}from"../../respond-Ius0bnxZ.mjs";import{t as BoundedCounters}from"../../bounded-counters-C8PHfWEu.mjs";var MemoryStore=class{counters;cleanupTimer;constructor(windowMs,limit){this.counters=new BoundedCounters(windowMs,limit),this.cleanupTimer=setInterval(()=>this.counters.sweep(),windowMs),this.cleanupTimer.unref&&this.cleanupTimer.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupTimer),this.counters.clear()}async increment(key){return this.counters.increment(key)}async decrement(key){this.counters.decrement(key)}async reset(key){this.counters.reset(key)}};function rateLimit(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??(req=>resolveClientIp(req)??`global`),sendHeaders=options.headers??!0,store=options.store??new MemoryStore(windowMs,max),skip=options.skip,skipPaths=new Set(options.skipPaths??[]),exemptWhen=options.exemptWhen;exemptWhen!==void 0&&assertFlagTest(exemptWhen,`rateLimit({ exemptWhen })`);let policy;return bindRoutePolicy(async(req,res,next)=>{let pathname=resolvePathname(req);if(skipPaths.has(pathname))return next();if(exemptWhen!==void 0&&policy){let{originalUrl}=req,routePath=originalUrl?resolvePathname({url:originalUrl}):pathname,flags=policy.lookup(String(req.method??`GET`),routePath);if(matchesFlagTest(exemptWhen,flags))return next()}if(skip&&skip(req))return next();let key=keyGenerator(req),{totalHits,resetTime}=await store.increment(key),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(res.setHeader(`RateLimit-Limit`,max),res.setHeader(`RateLimit-Remaining`,remaining),res.setHeader(`RateLimit-Reset`,Math.ceil(resetTime.getTime()/1e3))),totalHits>max)return sendJson(res,statusCode,{message});next()},table=>{policy=table})}export{MemoryStore,rateLimit};
|
|
12
12
|
//# sourceMappingURL=rate-limit.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import"../../core-CSWR0hHJ.mjs";function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}function requestLogger(options={}){let log=createLogger(options.name??`HTTP`),level=options.level??`info`,skip=options.skip??[];return(req,res,next)=>{let pathname=req.path??pathnameOf(req.url);if(skip.some(prefix=>pathname.startsWith(prefix)))return next();let start=Date.now();res.on(`finish`,()=>{let duration=Date.now()-start,requestId=req.requestId||req.headers[`x-request-id`]||`-`,status=res.statusCode,path=req.originalUrl??req.url??`/`;log.child({method:req.method,path,status,ms:duration,requestId})[level](`${req.method} ${path} ${status} ${duration}ms ${requestId}`)}),next()}}export{requestLogger};
|
|
12
12
|
//# sourceMappingURL=request-logger.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"../../core/logger.mjs";import{r as registerDisposable}from"../../disposables-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import{r as registerDisposable}from"../../disposables-CWNNe9HH.mjs";import{t as isProduction}from"../../is-production-TSixl400.mjs";import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-Ius0bnxZ.mjs";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=/* @__PURE__ */ new Map;empty=/* @__PURE__ */ new Set;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear(),this.empty.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),this.empty.delete(sid),null):entry.data:null}async set(sid,data,maxAge){for(this.sessions.delete(sid),this.sessions.set(sid,{data,expires:Date.now()+maxAge}),this.empty.delete(sid),Object.keys(data).length===0&&this.empty.add(sid);this.sessions.size>1e4;){let victim=this.empty.values().next().value??this.sessions.keys().next().value;this.sessions.delete(victim),this.empty.delete(victim)}}async destroy(sid){this.sessions.delete(sid),this.empty.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge,this.sessions.delete(sid),this.sessions.set(sid,entry))}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&(this.sessions.delete(sid),this.empty.delete(sid))}};function secretList(secret){let list=Array.isArray(secret)?secret:[secret];if(list.length===0||list.some(s=>typeof s!=`string`||s.length===0))throw Error("session(): `secret` must be a non-empty string or list of strings");return list}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secrets){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),provided=Buffer.from(raw.slice(dotIndex+1));for(let[index,secret]of secrets.entries()){let expected=Buffer.from(createHmac(`sha256`,secret).update(value).digest(`base64url`));if(provided.length===expected.length&&timingSafeEqual(provided,expected))return{value,stale:index>0}}return!1}function session(options){if(options.store===`cookie`)return cookieSession(options);let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,secrets=secretList(options.secret),secret=secrets[0],store=options.store??new MemoryStore,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1,staleSignature=!1;if(signedCookie){let unsigned=unsign(signedCookie,secrets);unsigned&&(sid=unsigned.value,staleSignature=unsigned.stale,sessionData=await store.get(sid))}(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,setCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||(!isNew||saveUninitialized||Object.keys(currentData).length!==0)&&(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),!isNew&&(rolling||staleSignature)&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}const cookieLog=createLogger(`Session`);function sealer(secrets,cookieName){let keys=secrets.map(secret=>Buffer.from(hkdfSync(`sha256`,secret,`kick.session`,`cookie-store-v1`,32))),key=keys[0],aad=Buffer.from(cookieName);return{seal(payload){let iv=randomBytes(12),cipher=createCipheriv(`aes-256-gcm`,key,iv).setAAD(aad),body=Buffer.concat([cipher.update(JSON.stringify(payload),`utf8`),cipher.final()]);return`v1.${Buffer.concat([iv,cipher.getAuthTag(),body]).toString(`base64url`)}`},open(value){if(!value.startsWith(`v1.`))return null;let raw;try{raw=Buffer.from(value.slice(3),`base64url`)}catch{return null}if(raw.length<29)return null;for(let[index,k]of keys.entries())try{let decipher=createDecipheriv(`aes-256-gcm`,k,raw.subarray(0,12)).setAAD(aad).setAuthTag(raw.subarray(12,28)),json=Buffer.concat([decipher.update(raw.subarray(28)),decipher.final()]),payload=JSON.parse(json.toString(`utf8`));return typeof payload?.i!=`string`||typeof payload.e!=`number`||!payload.d||typeof payload.d!=`object`?null:payload.e>Date.now()?{payload,stale:index>0}:null}catch{}return null}}}function cookieSession(options){let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,{seal,open}=sealer(secretList(options.secret),cookieName),cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{}},warnedSize=!1;return(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let opened=cookies[cookieName]?open(cookies[cookieName]):null,existing=opened?.payload??null,isNew=!existing,id=existing?.i??randomUUID(),destroyed=!1,written=existing&&!opened?.stale?JSON.stringify(existing.d):void 0,write=(force=!1)=>{if(res.headersSent)return;if(destroyed){replaceCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)});return}let json=JSON.stringify(sessionObj.data);if(json===written&&!force&&(!rolling||isNew)||written===void 0&&json===`{}`&&!saveUninitialized&&!force)return;let value=seal({i:id,d:sessionObj.data,e:Date.now()+maxAge});value.length+cookieName.length>4e3&&!warnedSize&&(warnedSize=!0,cookieLog.warn(`session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, so this session will not be kept. Store less in it, or use a shared store.`)),replaceCookie(res,cookieName,value,{...cookieDefaults,maxAge}),written=json};for(let method of[`writeHead`,`flushHeaders`,`write`,`end`]){let original=res[method];typeof original==`function`&&(res[method]=function(...args){return write(),original.apply(this,args)})}res.on?.(`finish`,()=>write());let sessionObj={get id(){return id},data:existing?{...existing.d}:{},async regenerate(){id=randomUUID(),sessionObj.data={},written=void 0,write(!0)},async destroy(){destroyed=!0,sessionObj.data={},write()},async save(){write()}};req.session=sessionObj,next()}}export{MemoryStore,session};
|
|
12
12
|
//# sourceMappingURL=session.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { _ as
|
|
2
|
+
import { _ as SpaAdapterOptions, g as SpaAdapter, v as resolveClientDir } from "../../application-D5Iiy7rt.mjs";
|
|
3
3
|
export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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{Logger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import"../../core-CSWR0hHJ.mjs";import{t as defineAdapter}from"../../define-adapter-oANmOi4a.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=/* @__PURE__ */ new Set;function snapshotClientDir(){let paths=/* @__PURE__ */ new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return/* @__PURE__ */ new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);existsSync(indexPath)?(indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)):log.warn(`index.html not found in ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
|
|
12
12
|
//# sourceMappingURL=spa.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-
|
|
2
|
+
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-DkT2p1gd.mjs";
|
|
3
3
|
export { type RawUploadPart, UploadOptions, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-
|
|
11
|
+
import{HttpException,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-DYr3a8LW.mjs";import{unlink}from"node:fs/promises";let _multer;function loadMulter(){return _multer??=import(`multer`).then(mod=>mod.default??mod,()=>{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed. Add it to your dependencies.`)})}function translateMulterErrors(mw,options){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}next(err)})}}function createMulter(options){let limits={fileSize:options.maxSize??5242880},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}},built,lazy=pick=>{let handler;return(req,res,next)=>{handler??=(built??=loadMulter().then(multer=>multer(multerOptions))).then(pick),handler.then(run=>run(req,res,next),err=>{handler=built=_multer=void 0,next(err)})}};return{single:field=>lazy(m=>m.single(field)),array:(field,maxCount)=>lazy(m=>m.array(field,maxCount)),none:()=>lazy(m=>m.none())}}function bothConventions(handler){return((first,second,third)=>third===void 0&&typeof second==`function`&&typeof first==`object`&&first&&`req`in first&&`res`in first?new Promise((resolve,reject)=>{handler(first.req,first.res,err=>{if(err)return reject(err);resolve(),second()})}):handler(first,second,third))}function single(fieldName,options={}){return bothConventions(translateMulterErrors(createMulter(options).single(fieldName),options))}function array(fieldName,maxCount=10,options={}){return bothConventions(translateMulterErrors(createMulter(options).array(fieldName,maxCount),options))}function none(options={}){return bothConventions(translateMulterErrors(createMulter(options).none(),options))}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
|
|
12
12
|
//# sourceMappingURL=upload.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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{Logger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import"../../core-CSWR0hHJ.mjs";import{t as defineAdapter}from"../../define-adapter-oANmOi4a.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app}){let{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
|
|
12
12
|
//# sourceMappingURL=views.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { C as SortItem, S as
|
|
3
|
-
export { type ColumnQueryFieldConfig, FILTER_OPERATORS, type FieldsOf, type FilterItem, type FilterOperator, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, type SortItem, type StringQueryFieldConfig, type TypedParsedQuery, buildQueryParams, getQueryParsingDefaults, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, resetQueryParsingDefaults, setQueryParsingDefaults };
|
|
2
|
+
import { A as TypedParsedQuery, C as PaginatedResponse, D as QueryFieldConfig, E as QueryBuilderAdapter, O as SortItem, S as FilterOperator, T as ParsedQuery, _ as CursorQuery, a as getQueryParsingDefaults, b as FieldsOf, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as CursorPosition, h as CursorPaginatedResponse, i as buildQueryParams, k as StringQueryFieldConfig, l as parseSearchQuery, m as CursorPaginateOptions, n as QueryRejectReason, o as parseFilters, p as ColumnQueryFieldConfig, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as CursorValue, w as PaginationParams, x as FilterItem, y as FILTER_OPERATORS } from "../../index-Blgka75E.mjs";
|
|
3
|
+
export { type ColumnQueryFieldConfig, type CursorPaginateOptions, type CursorPaginatedResponse, type CursorPosition, type CursorQuery, type CursorValue, FILTER_OPERATORS, type FieldsOf, type FilterItem, type FilterOperator, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, type SortItem, type StringQueryFieldConfig, type TypedParsedQuery, buildQueryParams, getQueryParsingDefaults, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, resetQueryParsingDefaults, setQueryParsingDefaults };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-
|
|
11
|
+
export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-CUvSp-JT.mjs";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-
|
|
2
|
+
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-BewIsj7V.mjs";
|
|
3
3
|
export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.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 _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-
|
|
11
|
+
export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-CBjQNcUy.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"../../core/logger.mjs";import{HttpException}from"../../core/errors.mjs";import{_ as unsupportedMediaTypeError,m as parseForm,n as applyHandlerResult,o as createRequestStore,s as disposeRequestStore}from"../../reply-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import{HttpException}from"../../core/errors.mjs";import{_ as unsupportedMediaTypeError,m as parseForm,n as applyHandlerResult,o as createRequestStore,s as disposeRequestStore}from"../../reply-C1CoxeQt.mjs";import{f as requestStore,i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"../../context-p-KpSsLy.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-DYr3a8LW.mjs";import"../middleware/upload.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-BNM_5G_r.mjs";import Fastify from"fastify";const pluginOf=mod=>mod.default??mod,createFastify=Fastify,log=createLogger(`FastifyRuntime`),QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.headersSent?this.reply.raw.end(data):this.reply.send(data??``),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
|
|
12
12
|
Install it as a peer dependency: pnpm add @fastify/multipart.`);let rawParts=[],fields={};for await(let part of request.parts())part.type===`file`&&part.toBuffer?rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer:await part.toBuffer()}):fields[part.fieldname]=part.value;let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...fields}}let headerId=raw.headers[`x-request-id`],requestId=raw.requestId||(Array.isArray(headerId)?headerId[0]:headerId),store=createRequestStore(requestId);raw.requestId=store.requestId,reply.getHeader(`x-request-id`)||reply.header(`x-request-id`,store.requestId),reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(raw,entry);let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),reply.sent))return;validator&&await new Promise((resolve,reject)=>{validator(raw,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||reply.sent)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),reply.sent)return;let result=await entry.handler(ctx);!reply.sent&&!await applyHandlerResult(ctx,result)&&reply.callNotFound()})}}function hopTrust(hops){return(_ip,hopIndex)=>hopIndex<hops}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=createFastify({logger:!1,routerOptions:{ignoreTrailingSlash:!0},...options.bodyLimit===void 0?{}:{bodyLimit:options.bodyLimit},trustProxy:typeof options.trustProxy==`number`?hopTrust(options.trustProxy):options.trustProxy});app[QUEUE]=[];let addParser=app.addContentTypeParser?.bind(app);return addParser&&(addParser(/^application\/[\w.+-]+\+json$/,{parseAs:`string`},(_req,body,done)=>{if(body===``)return done(null,void 0);try{done(null,JSON.parse(body))}catch(err){done(HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`),void 0)}}),addParser(`application/x-www-form-urlencoded`,{parseAs:`string`},(_req,body,done)=>{done(null,parseForm(body))}),addParser(/^text\//,{parseAs:`string`},(_req,body,done)=>{done(null,body)}),addParser(`*`,{parseAs:`string`},(req,body,done)=>{if(!body)return done(null,void 0);done(unsupportedMediaTypeError(req.headers?.[`content-type`]),void 0)})),options.notFoundFallthrough===!1&&(app[NO_FALLTHROUGH]=!0),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=pluginOf(await import(`@fastify/multipart`));await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=pluginOf(await import(`@fastify/middie`));await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY],ready=!1;return readyP.then(()=>ready=!0,()=>{}),(req,res,next)=>{next&&(req[NEXT]=next),ready?app.routing(req,res):readyP.then(()=>app.routing(req,res)).catch(err=>{if(next)return next(err);log.error(err,`Fastify failed to start`),res.statusCode=500,res.end(`Internal Server Error`)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];next&&!app[NO_FALLTHROUGH]?(reply.hijack(),next()):settleOrFail(reply,mw(request.raw,replyDriver(reply),NOOP_NEXT))})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{settleOrFail(reply,mw(err,request.raw,replyDriver(reply),NOOP_NEXT))})},close(app){return app.close()},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{fastifyRuntime};
|
|
13
13
|
//# sourceMappingURL=fastify.mjs.map
|