@venizia/ignis-kernel 0.4.8-3 → 0.4.8-5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/esm/base/applications/body-limit.d.ts +29 -0
  2. package/dist/esm/base/applications/body-limit.js +49 -0
  3. package/dist/esm/base/applications/body-limit.js.map +1 -0
  4. package/dist/esm/base/applications/common/types/middlewares.d.ts +8 -2
  5. package/dist/esm/base/applications/common/types/middlewares.js.map +1 -1
  6. package/dist/esm/base/applications/cors.d.ts +19 -10
  7. package/dist/esm/base/applications/cors.js +51 -21
  8. package/dist/esm/base/applications/cors.js.map +1 -1
  9. package/dist/esm/base/applications/index.d.ts +1 -0
  10. package/dist/esm/base/applications/index.js +1 -0
  11. package/dist/esm/base/applications/index.js.map +1 -1
  12. package/dist/esm/base/applications/rest.d.ts +2 -0
  13. package/dist/esm/base/applications/rest.js +15 -14
  14. package/dist/esm/base/applications/rest.js.map +1 -1
  15. package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +57 -24
  16. package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
  17. package/dist/esm/base/auth/authenticate/common/types/service.d.ts +3 -0
  18. package/dist/esm/base/auth/authenticate/common/types/service.js.map +1 -1
  19. package/dist/esm/base/auth/authenticate/providers/authentication.provider.js +5 -0
  20. package/dist/esm/base/auth/authenticate/providers/authentication.provider.js.map +1 -1
  21. package/dist/esm/base/controllers/factory/controller.d.ts +7 -0
  22. package/dist/esm/base/controllers/factory/crud/abstract.d.ts +11 -0
  23. package/dist/esm/base/controllers/factory/crud/abstract.js +7 -0
  24. package/dist/esm/base/controllers/factory/crud/abstract.js.map +1 -1
  25. package/dist/esm/base/controllers/factory/crud/persistable.js +2 -0
  26. package/dist/esm/base/controllers/factory/crud/persistable.js.map +1 -1
  27. package/dist/esm/base/controllers/factory/crud/readable.js +5 -0
  28. package/dist/esm/base/controllers/factory/crud/readable.js.map +1 -1
  29. package/dist/esm/base/controllers/factory/definition.d.ts +16 -16
  30. package/dist/esm/base/middlewares/app-error/app-error.middleware.d.ts +14 -0
  31. package/dist/esm/base/middlewares/app-error/app-error.middleware.js +68 -2
  32. package/dist/esm/base/middlewares/app-error/app-error.middleware.js.map +1 -1
  33. package/dist/esm/base/middlewares/app-error/zod.handler.js +4 -1
  34. package/dist/esm/base/middlewares/app-error/zod.handler.js.map +1 -1
  35. package/dist/esm/base/repositories/common/index.d.ts +1 -0
  36. package/dist/esm/base/repositories/common/index.js +1 -0
  37. package/dist/esm/base/repositories/common/index.js.map +1 -1
  38. package/dist/esm/base/repositories/common/request-filter-guard.d.ts +68 -0
  39. package/dist/esm/base/repositories/common/request-filter-guard.js +94 -0
  40. package/dist/esm/base/repositories/common/request-filter-guard.js.map +1 -0
  41. package/dist/esm/base/repositories/core/abstract.d.ts +16 -0
  42. package/dist/esm/base/repositories/core/abstract.js +26 -0
  43. package/dist/esm/base/repositories/core/abstract.js.map +1 -1
  44. package/dist/esm/base/repositories/query-schemas/index.d.ts +6 -6
  45. package/package.json +3 -3
@@ -0,0 +1,29 @@
1
+ import type { Context, MiddlewareHandler } from 'hono';
2
+ /**
3
+ * The request body limit: the default every route gets, and the limit one route sets for itself.
4
+ *
5
+ * The application installs the default (`DEFAULT_MAX_SIZE`) ahead of every other middleware, so no route reads
6
+ * a body over it. A route that takes larger bodies (an upload, an import) puts `BodyLimits.route({ maxSize })`
7
+ * in its `middleware`: the default steps aside for that route and this limit answers instead. The limit counts
8
+ * the bytes that arrive, so a chunked body with no `Content-Length` is held to it too.
9
+ */
10
+ export declare class BodyLimits {
11
+ /** The default of every route: 5 MiB. */
12
+ static readonly DEFAULT_MAX_SIZE: number;
13
+ /** The limiter itself: a body over `maxSize` bytes is the framework's 413, or the `onError` answer. */
14
+ static limiter(opts: {
15
+ maxSize: number;
16
+ onError?: (context: Context) => Response | Promise<Response>;
17
+ }): MiddlewareHandler;
18
+ /**
19
+ * The limit of one route, to put in the route's `middleware`. It replaces the default for this route, larger or smaller.
20
+ * A body larger than the host accepts at all (`configs.server.maxRequestBodySize`, Bun's own cap) is still refused there.
21
+ */
22
+ static route(opts: {
23
+ maxSize: number;
24
+ onError?: (context: Context) => Response | Promise<Response>;
25
+ }): MiddlewareHandler;
26
+ /** Whether the route this request matched carries its own limit, so the default stands aside. */
27
+ static hasRouteLimit(context: Context): boolean;
28
+ }
29
+ //# sourceMappingURL=body-limit.d.ts.map
@@ -0,0 +1,49 @@
1
+ import { getError } from '@venizia/ignis-helpers/core';
2
+ import { bodyLimit } from 'hono/body-limit';
3
+ import { RequestErrors } from '../middlewares/common/errors.js';
4
+ /** Marks a middleware as the body limit of ONE route. A registry symbol, so two installed copies of this package still read each other's marks. */
5
+ const ROUTE_BODY_LIMIT = Symbol.for('@venizia/ignis-kernel/route-body-limit');
6
+ /**
7
+ * The request body limit: the default every route gets, and the limit one route sets for itself.
8
+ *
9
+ * The application installs the default (`DEFAULT_MAX_SIZE`) ahead of every other middleware, so no route reads
10
+ * a body over it. A route that takes larger bodies (an upload, an import) puts `BodyLimits.route({ maxSize })`
11
+ * in its `middleware`: the default steps aside for that route and this limit answers instead. The limit counts
12
+ * the bytes that arrive, so a chunked body with no `Content-Length` is held to it too.
13
+ */
14
+ export class BodyLimits {
15
+ /** The default of every route: 5 MiB. */
16
+ static { this.DEFAULT_MAX_SIZE = 5 * 1024 * 1024; }
17
+ /** The limiter itself: a body over `maxSize` bytes is the framework's 413, or the `onError` answer. */
18
+ static limiter(opts) {
19
+ const { maxSize, onError } = opts;
20
+ return bodyLimit({
21
+ maxSize,
22
+ onError: onError ??
23
+ (() => {
24
+ throw getError({
25
+ error: RequestErrors.BODY_TOO_LARGE,
26
+ message: `Request body exceeds the maximum of ${maxSize} bytes`,
27
+ });
28
+ }),
29
+ });
30
+ }
31
+ /**
32
+ * The limit of one route, to put in the route's `middleware`. It replaces the default for this route, larger or smaller.
33
+ * A body larger than the host accepts at all (`configs.server.maxRequestBodySize`, Bun's own cap) is still refused there.
34
+ */
35
+ static route(opts) {
36
+ const { maxSize } = opts;
37
+ if (typeof maxSize !== 'number' || !Number.isFinite(maxSize) || maxSize < 0) {
38
+ throw getError({
39
+ message: `[BodyLimits.route] maxSize must be a non-negative number of bytes | value: ${String(maxSize)}`,
40
+ });
41
+ }
42
+ return Object.assign(BodyLimits.limiter(opts), { [ROUTE_BODY_LIMIT]: maxSize });
43
+ }
44
+ /** Whether the route this request matched carries its own limit, so the default stands aside. */
45
+ static hasRouteLimit(context) {
46
+ return context.req.matchedRoutes.some((matched) => matched.handler[ROUTE_BODY_LIMIT] !== undefined);
47
+ }
48
+ }
49
+ //# sourceMappingURL=body-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"body-limit.js","sourceRoot":"","sources":["../../../../src/base/applications/body-limit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAE7D,mJAAmJ;AACnJ,MAAM,gBAAgB,GAAkB,MAAM,CAAC,GAAG,CAChD,wCAAwC,CAChC,CAAC;AAEX;;;;;;;GAOG;AACH,MAAM,OAAO,UAAU;IACrB,yCAAyC;aACzB,qBAAgB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;IAEnD,uGAAuG;IACvG,MAAM,CAAC,OAAO,CAAC,IAGd;QACC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAElC,OAAO,SAAS,CAAC;YACf,OAAO;YACP,OAAO,EACL,OAAO;gBACP,CAAC,GAAG,EAAE;oBACJ,MAAM,QAAQ,CAAC;wBACb,KAAK,EAAE,aAAa,CAAC,cAAc;wBACnC,OAAO,EAAE,uCAAuC,OAAO,QAAQ;qBAChE,CAAC,CAAC;gBACL,CAAC,CAAC;SACL,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,KAAK,CAAC,IAGZ;QACC,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;YAC5E,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,8EAA8E,MAAM,CAAC,OAAO,CAAC,EAAE;aACzG,CAAC,CAAC;QACL,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;IAClF,CAAC;IAED,iGAAiG;IACjG,MAAM,CAAC,aAAa,CAAC,OAAgB;QACnC,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CACnC,CAAC,OAAO,EAAE,EAAE,CACT,OAAO,CAAC,OAA8C,CAAC,gBAAgB,CAAC,KAAK,SAAS,CAC1F,CAAC;IACJ,CAAC","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { RequestErrors } from '../middlewares/common/errors';\n\n/** Marks a middleware as the body limit of ONE route. A registry symbol, so two installed copies of this package still read each other's marks. */\nconst ROUTE_BODY_LIMIT: unique symbol = Symbol.for(\n '@venizia/ignis-kernel/route-body-limit',\n) as never;\n\n/**\n * The request body limit: the default every route gets, and the limit one route sets for itself.\n *\n * The application installs the default (`DEFAULT_MAX_SIZE`) ahead of every other middleware, so no route reads\n * a body over it. A route that takes larger bodies (an upload, an import) puts `BodyLimits.route({ maxSize })`\n * in its `middleware`: the default steps aside for that route and this limit answers instead. The limit counts\n * the bytes that arrive, so a chunked body with no `Content-Length` is held to it too.\n */\nexport class BodyLimits {\n /** The default of every route: 5 MiB. */\n static readonly DEFAULT_MAX_SIZE = 5 * 1024 * 1024;\n\n /** The limiter itself: a body over `maxSize` bytes is the framework's 413, or the `onError` answer. */\n static limiter(opts: {\n maxSize: number;\n onError?: (context: Context) => Response | Promise<Response>;\n }): MiddlewareHandler {\n const { maxSize, onError } = opts;\n\n return bodyLimit({\n maxSize,\n onError:\n onError ??\n (() => {\n throw getError({\n error: RequestErrors.BODY_TOO_LARGE,\n message: `Request body exceeds the maximum of ${maxSize} bytes`,\n });\n }),\n });\n }\n\n /**\n * The limit of one route, to put in the route's `middleware`. It replaces the default for this route, larger or smaller.\n * A body larger than the host accepts at all (`configs.server.maxRequestBodySize`, Bun's own cap) is still refused there.\n */\n static route(opts: {\n maxSize: number;\n onError?: (context: Context) => Response | Promise<Response>;\n }): MiddlewareHandler {\n const { maxSize } = opts;\n\n if (typeof maxSize !== 'number' || !Number.isFinite(maxSize) || maxSize < 0) {\n throw getError({\n message: `[BodyLimits.route] maxSize must be a non-negative number of bytes | value: ${String(maxSize)}`,\n });\n }\n\n return Object.assign(BodyLimits.limiter(opts), { [ROUTE_BODY_LIMIT]: maxSize });\n }\n\n /** Whether the route this request matched carries its own limit, so the default stands aside. */\n static hasRouteLimit(context: Context): boolean {\n return context.req.matchedRoutes.some(\n (matched) =>\n (matched.handler as unknown as Record<symbol, unknown>)[ROUTE_BODY_LIMIT] !== undefined,\n );\n }\n}\n"]}
@@ -17,7 +17,7 @@ export interface ICompressOptions extends IBaseMiddlewareOptions {
17
17
  encoding: TCompressEncoding;
18
18
  threshold?: number;
19
19
  }
20
- /** Allowed origin for CORS: one origin, a list of origins, or a function that returns the origin to echo (or nothing to reject). A string or a list entry may be a subdomain wildcard such as `https://*.example.com`: the scheme and the port are matched exactly, the apex domain is not included, and the bare `'*'` still means any origin. */
20
+ /** Allowed origin for CORS: one origin, a list of origins, or a function that returns the origin to echo (or nothing to reject). A string or a list entry may be a subdomain wildcard such as `https://*.example.com`, or a pattern with `:*` for any port such as `http://localhost:*` or `https://*.example.com:*`: the scheme is matched exactly, so is the port unless it is `*`, the apex domain is not included by a subdomain wildcard, and the bare `'*'` still means any origin. */
21
21
  export type TOrigin = string | string[] | ((origin: string, c: Context) => Promise<string | undefined | null> | string | undefined | null);
22
22
  /** Options of the CORS middleware the framework installs first. `origin` is required. */
23
23
  export interface ICORSOptions extends IBaseMiddlewareOptions {
@@ -39,7 +39,13 @@ export interface ICSRFOptions extends IBaseMiddlewareOptions {
39
39
  origin?: string | string[] | TIsAllowedOriginHandler;
40
40
  secFetchSite?: TSecFetchSite | TSecFetchSite[] | TIsAllowedSecFetchSiteHandler;
41
41
  }
42
- /** Options of the body limit middleware the framework installs right after the request id. `maxSize` is in bytes. */
42
+ /**
43
+ * Options of the body limit middleware the framework installs right after the request id. `maxSize` is in bytes.
44
+ *
45
+ * Unset (no `bodyLimit` key), every route gets `BodyLimits.DEFAULT_MAX_SIZE`, 5 MiB. Configured, it replaces
46
+ * the default (with a `path`, only the routes under it are limited). `enable: false` removes the limit. A route
47
+ * that takes larger bodies puts `BodyLimits.route({ maxSize })` in its `middleware`.
48
+ */
43
49
  export interface IBodyLimitOptions extends IBaseMiddlewareOptions {
44
50
  maxSize: number;
45
51
  onError?: (c: Context) => Response | Promise<Response>;
@@ -1 +1 @@
1
- {"version":3,"file":"middlewares.js","sourceRoot":"","sources":["../../../../../../src/base/applications/common/types/middlewares.ts"],"names":[],"mappings":"","sourcesContent":["import type { Context } from 'hono';\nimport type { IPRestrictionRules as IIPRestrictionRules } from 'hono/ip-restriction';\nimport { type SecFetchSiteValues, type TCompressEncoding } from '../constants';\n\n/** Options shared by every configurable middleware. Extra keys are allowed. */\nexport interface IBaseMiddlewareOptions {\n /**\n * Only `false` switches the middleware off.\n *\n * @default true\n */\n enable?: boolean;\n path?: string;\n [extra: string | symbol]: any;\n}\n\n/** Options of the compress middleware. Typed only: the framework does not install it. */\nexport interface ICompressOptions extends IBaseMiddlewareOptions {\n encoding: TCompressEncoding;\n threshold?: number;\n}\n\n/** Allowed origin for CORS: one origin, a list of origins, or a function that returns the origin to echo (or nothing to reject). A string or a list entry may be a subdomain wildcard such as `https://*.example.com`: the scheme and the port are matched exactly, the apex domain is not included, and the bare `'*'` still means any origin. */\nexport type TOrigin =\n | string\n | string[]\n | ((\n origin: string,\n c: Context,\n ) => Promise<string | undefined | null> | string | undefined | null);\n/** Options of the CORS middleware the framework installs first. `origin` is required. */\nexport interface ICORSOptions extends IBaseMiddlewareOptions {\n origin: TOrigin;\n allowMethods?: string[] | ((origin: string, c: Context) => Promise<string[]> | string[]);\n allowHeaders?: string[];\n maxAge?: number;\n credentials?: boolean;\n exposeHeaders?: string[];\n}\n\n/** Decides whether the request `Origin` is allowed for the CSRF check. */\nexport type TIsAllowedOriginHandler = (origin: string, context: Context) => boolean;\n/** One value of the `Sec-Fetch-Site` header, taken from `SecFetchSiteValues`. */\nexport type TSecFetchSite = (typeof SecFetchSiteValues)[number];\n/** Decides whether the request `Sec-Fetch-Site` value is allowed for the CSRF check. */\nexport type TIsAllowedSecFetchSiteHandler = (\n secFetchSite: TSecFetchSite,\n context: Context,\n) => boolean;\n\n/** Options of the CSRF middleware. Typed only: the framework does not install it. */\nexport interface ICSRFOptions extends IBaseMiddlewareOptions {\n origin?: string | string[] | TIsAllowedOriginHandler;\n secFetchSite?: TSecFetchSite | TSecFetchSite[] | TIsAllowedSecFetchSiteHandler;\n}\n\n/** Options of the body limit middleware the framework installs right after the request id. `maxSize` is in bytes. */\nexport interface IBodyLimitOptions extends IBaseMiddlewareOptions {\n maxSize: number;\n onError?: (c: Context) => Response | Promise<Response>;\n}\n\n/** Options of the request id middleware. Only the shared options apply. */\nexport interface IRequestIdOptions extends IBaseMiddlewareOptions {}\n\n/** The `configs.middlewares` shape: which framework middleware to switch off or configure. Extra keys are allowed. */\nexport interface IMiddlewareConfigs {\n requestId?: IRequestIdOptions;\n /** Typed only: the framework installs no compress middleware. Wire it in `setupMiddlewares()`. */\n compress?: ICompressOptions;\n /** Installed first, before the request id and the body limit, so early framework responses carry its headers. */\n cors?: ICORSOptions;\n /** Typed only: the framework installs no csrf middleware. Wire it in `setupMiddlewares()`. */\n csrf?: ICSRFOptions;\n /** Installed right after the request id, ahead of every other middleware, so none of them reads a body over it. */\n bodyLimit?: IBodyLimitOptions;\n /** Typed only: the framework installs no ip restriction. Wire it in `setupMiddlewares()`. */\n ipRestriction?: IBaseMiddlewareOptions & IIPRestrictionRules;\n [extra: string | symbol]: any;\n}\n"]}
1
+ {"version":3,"file":"middlewares.js","sourceRoot":"","sources":["../../../../../../src/base/applications/common/types/middlewares.ts"],"names":[],"mappings":"","sourcesContent":["import type { Context } from 'hono';\nimport type { IPRestrictionRules as IIPRestrictionRules } from 'hono/ip-restriction';\nimport { type SecFetchSiteValues, type TCompressEncoding } from '../constants';\n\n/** Options shared by every configurable middleware. Extra keys are allowed. */\nexport interface IBaseMiddlewareOptions {\n /**\n * Only `false` switches the middleware off.\n *\n * @default true\n */\n enable?: boolean;\n path?: string;\n [extra: string | symbol]: any;\n}\n\n/** Options of the compress middleware. Typed only: the framework does not install it. */\nexport interface ICompressOptions extends IBaseMiddlewareOptions {\n encoding: TCompressEncoding;\n threshold?: number;\n}\n\n/** Allowed origin for CORS: one origin, a list of origins, or a function that returns the origin to echo (or nothing to reject). A string or a list entry may be a subdomain wildcard such as `https://*.example.com`, or a pattern with `:*` for any port such as `http://localhost:*` or `https://*.example.com:*`: the scheme is matched exactly, so is the port unless it is `*`, the apex domain is not included by a subdomain wildcard, and the bare `'*'` still means any origin. */\nexport type TOrigin =\n | string\n | string[]\n | ((\n origin: string,\n c: Context,\n ) => Promise<string | undefined | null> | string | undefined | null);\n/** Options of the CORS middleware the framework installs first. `origin` is required. */\nexport interface ICORSOptions extends IBaseMiddlewareOptions {\n origin: TOrigin;\n allowMethods?: string[] | ((origin: string, c: Context) => Promise<string[]> | string[]);\n allowHeaders?: string[];\n maxAge?: number;\n credentials?: boolean;\n exposeHeaders?: string[];\n}\n\n/** Decides whether the request `Origin` is allowed for the CSRF check. */\nexport type TIsAllowedOriginHandler = (origin: string, context: Context) => boolean;\n/** One value of the `Sec-Fetch-Site` header, taken from `SecFetchSiteValues`. */\nexport type TSecFetchSite = (typeof SecFetchSiteValues)[number];\n/** Decides whether the request `Sec-Fetch-Site` value is allowed for the CSRF check. */\nexport type TIsAllowedSecFetchSiteHandler = (\n secFetchSite: TSecFetchSite,\n context: Context,\n) => boolean;\n\n/** Options of the CSRF middleware. Typed only: the framework does not install it. */\nexport interface ICSRFOptions extends IBaseMiddlewareOptions {\n origin?: string | string[] | TIsAllowedOriginHandler;\n secFetchSite?: TSecFetchSite | TSecFetchSite[] | TIsAllowedSecFetchSiteHandler;\n}\n\n/**\n * Options of the body limit middleware the framework installs right after the request id. `maxSize` is in bytes.\n *\n * Unset (no `bodyLimit` key), every route gets `BodyLimits.DEFAULT_MAX_SIZE`, 5 MiB. Configured, it replaces\n * the default (with a `path`, only the routes under it are limited). `enable: false` removes the limit. A route\n * that takes larger bodies puts `BodyLimits.route({ maxSize })` in its `middleware`.\n */\nexport interface IBodyLimitOptions extends IBaseMiddlewareOptions {\n maxSize: number;\n onError?: (c: Context) => Response | Promise<Response>;\n}\n\n/** Options of the request id middleware. Only the shared options apply. */\nexport interface IRequestIdOptions extends IBaseMiddlewareOptions {}\n\n/** The `configs.middlewares` shape: which framework middleware to switch off or configure. Extra keys are allowed. */\nexport interface IMiddlewareConfigs {\n requestId?: IRequestIdOptions;\n /** Typed only: the framework installs no compress middleware. Wire it in `setupMiddlewares()`. */\n compress?: ICompressOptions;\n /** Installed first, before the request id and the body limit, so early framework responses carry its headers. */\n cors?: ICORSOptions;\n /** Typed only: the framework installs no csrf middleware. Wire it in `setupMiddlewares()`. */\n csrf?: ICSRFOptions;\n /** Installed right after the request id, ahead of every other middleware, so none of them reads a body over it. */\n bodyLimit?: IBodyLimitOptions;\n /** Typed only: the framework installs no ip restriction. Wire it in `setupMiddlewares()`. */\n ipRestriction?: IBaseMiddlewareOptions & IIPRestrictionRules;\n [extra: string | symbol]: any;\n}\n"]}
@@ -1,9 +1,14 @@
1
1
  import type { Hono } from 'hono';
2
2
  import type { ICORSOptions, TOrigin } from './common/index.js';
3
- /** A parsed `scheme://*.suffix[:port]` origin pattern. `port` is `null` when the pattern names none. */
3
+ /**
4
+ * A parsed origin pattern: `scheme://*.suffix[:port]` (`subdomain` true) or `scheme://host:*` (an exact
5
+ * `host`, held in `suffix`). `port` is `null` when the pattern names none, a number as text for one port,
6
+ * and `'*'` for any port.
7
+ */
4
8
  interface IOriginPattern {
5
9
  scheme: string;
6
10
  suffix: string;
11
+ subdomain: boolean;
7
12
  port: string | null;
8
13
  }
9
14
  export declare class CorsUtility {
@@ -15,21 +20,25 @@ export declare class CorsUtility {
15
20
  value: string;
16
21
  }): boolean;
17
22
  /**
18
- * Reads `https://*.example.com` into its parts. The only wildcard allowed is the whole leftmost host
19
- * label, so the host has at least two labels after it (`https://*.com` is refused). The scheme is
20
- * required and the port is optional; both are kept for an exact comparison. Anything else with a
21
- * `*` throws, because such a pattern would never match and a hole in it is easy to miss.
23
+ * Reads an origin pattern into its parts. Two shapes are allowed, and nothing else with a `*`:
24
+ * `https://*.example.com[:port]`, where the `*` is the whole leftmost host label and at least two
25
+ * labels follow it (`https://*.com` is refused); and `http://localhost:*`, an exact host whose port
26
+ * is `*` for any port. The port of either shape may be `*`, as in `https://*.example.com:*`. The
27
+ * scheme is required and kept for an exact comparison. An IPv6 host is not supported. Anything else
28
+ * with a `*` throws, because such a pattern would never match and a hole in it is easy to miss.
22
29
  */
23
30
  static parseOriginPattern(opts: {
24
31
  pattern: string;
25
32
  }): IOriginPattern;
26
33
  /**
27
34
  * True when the request `origin` (the `Origin` header, a serialised origin) belongs to `pattern`: the
28
- * scheme and the port are equal, and what stands for the `*` is one or more host labels of letters,
29
- * digits and hyphens. The apex (`https://example.com`), a longer host that merely ends the same
30
- * (`evilexample.com`), a host that merely contains it (`example.com.evil.net`) and a userinfo or path
31
- * trick (`https://evil.com@a.example.com`) all fail. A pattern without a port matches an origin
32
- * without one, so `https://a.example.com:8443` does not match `https://*.example.com`.
35
+ * scheme is equal, the port is equal (or any number when the pattern says `*`), and the host is the
36
+ * exact host, or ends the pattern's suffix after one or more labels of letters, digits and hyphens.
37
+ * The apex (`https://example.com`), a longer host that merely ends the same (`evilexample.com`), a
38
+ * host that merely contains it (`example.com.evil.net`, `localhost.evil.com:3000`) and a userinfo or
39
+ * path trick (`https://evil.com@a.example.com`) all fail. A pattern without a port matches an origin
40
+ * without one only, so `https://a.example.com:8443` does not match `https://*.example.com`; a `*`
41
+ * port matches an origin with a port or without one.
33
42
  */
34
43
  static matchOriginPattern(opts: {
35
44
  pattern: IOriginPattern;
@@ -1,7 +1,9 @@
1
1
  import { getError } from '@venizia/ignis-helpers/core';
2
2
  import { cors } from 'hono/cors';
3
- const WILDCARD_PATTERN = /^([a-z][a-z0-9+.-]*):\/\/\*\.([a-z0-9.-]+)(?::(\d{1,5}))?$/;
3
+ const ANY_PORT = '*';
4
+ const WILDCARD_PATTERN = /^([a-z][a-z0-9+.-]*):\/\/(\*\.)?([a-z0-9.-]+)(?::(\d{1,5}|\*))?$/;
4
5
  const HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
6
+ const PORT_NUMBER = /^[1-9]\d{0,4}$/;
5
7
  export class CorsUtility {
6
8
  /**
7
9
  * True when `value` is a wildcard origin pattern and not a plain origin: it contains a `*` and is not
@@ -12,46 +14,74 @@ export class CorsUtility {
12
14
  return value !== '*' && value.includes('*');
13
15
  }
14
16
  /**
15
- * Reads `https://*.example.com` into its parts. The only wildcard allowed is the whole leftmost host
16
- * label, so the host has at least two labels after it (`https://*.com` is refused). The scheme is
17
- * required and the port is optional; both are kept for an exact comparison. Anything else with a
18
- * `*` throws, because such a pattern would never match and a hole in it is easy to miss.
17
+ * Reads an origin pattern into its parts. Two shapes are allowed, and nothing else with a `*`:
18
+ * `https://*.example.com[:port]`, where the `*` is the whole leftmost host label and at least two
19
+ * labels follow it (`https://*.com` is refused); and `http://localhost:*`, an exact host whose port
20
+ * is `*` for any port. The port of either shape may be `*`, as in `https://*.example.com:*`. The
21
+ * scheme is required and kept for an exact comparison. An IPv6 host is not supported. Anything else
22
+ * with a `*` throws, because such a pattern would never match and a hole in it is easy to miss.
19
23
  */
20
24
  static parseOriginPattern(opts) {
21
25
  const { pattern } = opts;
22
26
  const parts = WILDCARD_PATTERN.exec(pattern);
23
- const [, scheme, suffix, port] = parts ?? [];
27
+ const [, scheme, subdomain, suffix, port] = parts ?? [];
24
28
  const labels = suffix?.split('.') ?? [];
25
29
  if (!scheme ||
26
30
  !suffix ||
27
- labels.length < 2 ||
31
+ (subdomain ? labels.length < 2 : port !== ANY_PORT) ||
28
32
  !labels.every((label) => HOST_LABEL.test(label)) ||
29
- (port !== undefined && (Number(port) < 1 || Number(port) > 65535))) {
33
+ (port !== undefined && port !== ANY_PORT && (Number(port) < 1 || Number(port) > 65535))) {
30
34
  throw getError({
31
- message: `[registerCors] configs.middlewares.cors.origin has an invalid wildcard '${pattern}' | only a subdomain wildcard in lower case is allowed, as in 'https://*.example.com' or 'https://*.example.com:8443', with at least two labels after the '*.'`,
35
+ message: `[registerCors] configs.middlewares.cors.origin has an invalid wildcard '${pattern}' | only a subdomain wildcard in lower case ('https://*.example.com', 'https://*.example.com:8443') or an any-port wildcard ('http://localhost:*', 'https://*.example.com:*') is allowed, with at least two labels after a '*.'`,
32
36
  });
33
37
  }
34
- return { scheme, suffix, port: port ?? null };
38
+ return { scheme, suffix, subdomain: !!subdomain, port: port ?? null };
35
39
  }
36
40
  /**
37
41
  * True when the request `origin` (the `Origin` header, a serialised origin) belongs to `pattern`: the
38
- * scheme and the port are equal, and what stands for the `*` is one or more host labels of letters,
39
- * digits and hyphens. The apex (`https://example.com`), a longer host that merely ends the same
40
- * (`evilexample.com`), a host that merely contains it (`example.com.evil.net`) and a userinfo or path
41
- * trick (`https://evil.com@a.example.com`) all fail. A pattern without a port matches an origin
42
- * without one, so `https://a.example.com:8443` does not match `https://*.example.com`.
42
+ * scheme is equal, the port is equal (or any number when the pattern says `*`), and the host is the
43
+ * exact host, or ends the pattern's suffix after one or more labels of letters, digits and hyphens.
44
+ * The apex (`https://example.com`), a longer host that merely ends the same (`evilexample.com`), a
45
+ * host that merely contains it (`example.com.evil.net`, `localhost.evil.com:3000`) and a userinfo or
46
+ * path trick (`https://evil.com@a.example.com`) all fail. A pattern without a port matches an origin
47
+ * without one only, so `https://a.example.com:8443` does not match `https://*.example.com`; a `*`
48
+ * port matches an origin with a port or without one.
43
49
  */
44
50
  static matchOriginPattern(opts) {
45
51
  const { pattern, origin } = opts;
46
52
  const head = `${pattern.scheme}://`;
47
- const tail = `.${pattern.suffix}${pattern.port === null ? '' : `:${pattern.port}`}`;
48
- if (!origin.startsWith(head) ||
49
- !origin.endsWith(tail) ||
50
- origin.length <= head.length + tail.length) {
53
+ if (!origin.startsWith(head)) {
51
54
  return false;
52
55
  }
53
- const labels = origin.slice(head.length, origin.length - tail.length).split('.');
54
- return labels.every((label) => HOST_LABEL.test(label));
56
+ let host = origin.slice(head.length);
57
+ if (pattern.port === ANY_PORT) {
58
+ const separator = host.lastIndexOf(':');
59
+ if (separator !== -1) {
60
+ const port = host.slice(separator + 1);
61
+ if (!PORT_NUMBER.test(port) || Number(port) > 65535) {
62
+ return false;
63
+ }
64
+ host = host.slice(0, separator);
65
+ }
66
+ }
67
+ else if (pattern.port !== null) {
68
+ const tail = `:${pattern.port}`;
69
+ if (!host.endsWith(tail)) {
70
+ return false;
71
+ }
72
+ host = host.slice(0, host.length - tail.length);
73
+ }
74
+ if (!pattern.subdomain) {
75
+ return host === pattern.suffix;
76
+ }
77
+ const tail = `.${pattern.suffix}`;
78
+ if (!host.endsWith(tail) || host.length <= tail.length) {
79
+ return false;
80
+ }
81
+ return host
82
+ .slice(0, host.length - tail.length)
83
+ .split('.')
84
+ .every((label) => HOST_LABEL.test(label));
55
85
  }
56
86
  /**
57
87
  * Turns an origin that holds a wildcard pattern into the function form Hono takes: it returns the
@@ -1 +1 @@
1
- {"version":3,"file":"cors.js","sourceRoot":"","sources":["../../../../src/base/applications/cors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAUjC,MAAM,gBAAgB,GAAG,4DAA4D,CAAC;AACtF,MAAM,UAAU,GAAG,wCAAwC,CAAC;AAE5D,MAAM,OAAO,WAAW;IACtB;;;OAGG;IACH,MAAM,CAAC,eAAe,CAAC,IAAuB;QAC5C,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEvB,OAAO,KAAK,KAAK,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,kBAAkB,CAAC,IAAyB;QACjD,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACzB,MAAM,KAAK,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC7C,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,KAAK,IAAI,EAAE,CAAC;QAC7C,MAAM,MAAM,GAAG,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QAExC,IACE,CAAC,MAAM;YACP,CAAC,MAAM;YACP,MAAM,CAAC,MAAM,GAAG,CAAC;YACjB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAChD,CAAC,IAAI,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC,EAClE,CAAC;YACD,MAAM,QAAQ,CAAC;gBACb,OAAO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M,EAAE,IAAI,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,GACpF,OAAO,CAAC;QAEV,MAAM,SAAS,GACb,OAAO,MAAM,KAAK,UAAU,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAEzF,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC;gBACb,OAAO,EACL,wGAAwG;aAC3G,CAAC,CAAC;QACL,CAAC;QAED,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAE1D,IAAI,WAAW,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YACzC,MAAM,QAAQ,CAAC;gBACb,OAAO,EACL,mLAAmL;aACtL,CAAC,CAAC;QACL,CAAC;QAED,gGAAgG;QAChG,oFAAoF;QACpF,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC;YACb,MAAM,EAAE,WAAW,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;YAC7C,YAAY;YACZ,YAAY;YACZ,MAAM;YACN,WAAW;YACX,aAAa;SACd,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAC9C,CAAC;QAEF,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,EAAE,IAAI,CAAC,QAAsC,CAAC,CAAC,CAAC;IACxE,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport type { Hono } from 'hono';\nimport { cors } from 'hono/cors';\nimport type { ICORSOptions, TOrigin } from './common';\n\n/** A parsed `scheme://*.suffix[:port]` origin pattern. `port` is `null` when the pattern names none. */\ninterface IOriginPattern {\n scheme: string;\n suffix: string;\n port: string | null;\n}\n\nconst WILDCARD_PATTERN = /^([a-z][a-z0-9+.-]*):\\/\\/\\*\\.([a-z0-9.-]+)(?::(\\d{1,5}))?$/;\nconst HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nexport class CorsUtility {\n /**\n * True when `value` is a wildcard origin pattern and not a plain origin: it contains a `*` and is not\n * the bare `'*'`, which keeps its own meaning (\"any origin\").\n */\n static isOriginPattern(opts: { value: string }): boolean {\n const { value } = opts;\n\n return value !== '*' && value.includes('*');\n }\n\n /**\n * Reads `https://*.example.com` into its parts. The only wildcard allowed is the whole leftmost host\n * label, so the host has at least two labels after it (`https://*.com` is refused). The scheme is\n * required and the port is optional; both are kept for an exact comparison. Anything else with a\n * `*` throws, because such a pattern would never match and a hole in it is easy to miss.\n */\n static parseOriginPattern(opts: { pattern: string }): IOriginPattern {\n const { pattern } = opts;\n const parts = WILDCARD_PATTERN.exec(pattern);\n const [, scheme, suffix, port] = parts ?? [];\n const labels = suffix?.split('.') ?? [];\n\n if (\n !scheme ||\n !suffix ||\n labels.length < 2 ||\n !labels.every((label) => HOST_LABEL.test(label)) ||\n (port !== undefined && (Number(port) < 1 || Number(port) > 65535))\n ) {\n throw getError({\n message: `[registerCors] configs.middlewares.cors.origin has an invalid wildcard '${pattern}' | only a subdomain wildcard in lower case is allowed, as in 'https://*.example.com' or 'https://*.example.com:8443', with at least two labels after the '*.'`,\n });\n }\n\n return { scheme, suffix, port: port ?? null };\n }\n\n /**\n * True when the request `origin` (the `Origin` header, a serialised origin) belongs to `pattern`: the\n * scheme and the port are equal, and what stands for the `*` is one or more host labels of letters,\n * digits and hyphens. The apex (`https://example.com`), a longer host that merely ends the same\n * (`evilexample.com`), a host that merely contains it (`example.com.evil.net`) and a userinfo or path\n * trick (`https://evil.com@a.example.com`) all fail. A pattern without a port matches an origin\n * without one, so `https://a.example.com:8443` does not match `https://*.example.com`.\n */\n static matchOriginPattern(opts: { pattern: IOriginPattern; origin: string }): boolean {\n const { pattern, origin } = opts;\n const head = `${pattern.scheme}://`;\n const tail = `.${pattern.suffix}${pattern.port === null ? '' : `:${pattern.port}`}`;\n\n if (\n !origin.startsWith(head) ||\n !origin.endsWith(tail) ||\n origin.length <= head.length + tail.length\n ) {\n return false;\n }\n\n const labels = origin.slice(head.length, origin.length - tail.length).split('.');\n\n return labels.every((label) => HOST_LABEL.test(label));\n }\n\n /**\n * Turns an origin that holds a wildcard pattern into the function form Hono takes: it returns the\n * request origin when an entry matches (a plain entry by equality, a pattern by\n * {@link CorsUtility.matchOriginPattern}) and `null` otherwise. An origin with no wildcard pattern is\n * returned as it is, so the string, list and function forms behave as before.\n */\n static resolveOrigin(opts: { origin: TOrigin }): TOrigin {\n const { origin } = opts;\n\n if (typeof origin === 'function') {\n return origin;\n }\n\n const entries = Array.isArray(origin) ? origin : [origin];\n\n if (!entries.some((value) => CorsUtility.isOriginPattern({ value }))) {\n return origin;\n }\n\n const exact = new Set<string>();\n const patterns: IOriginPattern[] = [];\n\n for (const value of entries) {\n if (CorsUtility.isOriginPattern({ value })) {\n patterns.push(CorsUtility.parseOriginPattern({ pattern: value }));\n } else {\n exact.add(value);\n }\n }\n\n return (requestOrigin: string) => {\n if (\n exact.has(requestOrigin) ||\n patterns.some((pattern) =>\n CorsUtility.matchOriginPattern({ pattern, origin: requestOrigin }),\n )\n ) {\n return requestOrigin;\n }\n\n return null;\n };\n }\n\n /**\n * Installs `configs.middlewares.cors` on the server when it is set and not disabled; with no config\n * nothing is installed. Called first in the default stack, so every response the framework produces\n * on its own - a bodyLimit 413, a body the request spy cannot parse, the error envelope - leaves\n * with the headers a browser needs to read it.\n *\n * `origin` may hold a subdomain wildcard such as `https://*.example.com` (see\n * {@link CorsUtility.matchOriginPattern}); an invalid pattern, or the bare `'*'` together with\n * `credentials: true`, throws here and not on the first request.\n */\n static registerCors(opts: { server: Hono<any, any, any>; options?: ICORSOptions }): void {\n const { server, options } = opts;\n\n if (!options || options.enable === false) {\n return;\n }\n\n const { origin, path, allowMethods, allowHeaders, maxAge, credentials, exposeHeaders } =\n options;\n\n const hasOrigin =\n typeof origin === 'function' || (Array.isArray(origin) ? origin.length > 0 : !!origin);\n\n if (!hasOrigin) {\n throw getError({\n message:\n '[registerCors] configs.middlewares.cors.origin is required | a string, a list of strings or a function',\n });\n }\n\n const origins = Array.isArray(origin) ? origin : [origin];\n\n if (credentials && origins.includes('*')) {\n throw getError({\n message:\n \"[registerCors] configs.middlewares.cors.credentials cannot be combined with origin '*' | a browser refuses a wildcard origin on a credentialed request | list the origins instead\",\n });\n }\n\n // Only the keys that are set: hono spreads over its defaults, so an `undefined` would erase one\n // (a missing `allowMethods` would then answer a preflight with no allowed methods).\n const settings = Object.fromEntries(\n Object.entries({\n origin: CorsUtility.resolveOrigin({ origin }),\n allowMethods,\n allowHeaders,\n maxAge,\n credentials,\n exposeHeaders,\n }).filter(([, value]) => value !== undefined),\n );\n\n server.use(path ?? '*', cors(settings as Parameters<typeof cors>[0]));\n }\n}\n"]}
1
+ {"version":3,"file":"cors.js","sourceRoot":"","sources":["../../../../src/base/applications/cors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAejC,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,gBAAgB,GAAG,kEAAkE,CAAC;AAC5F,MAAM,UAAU,GAAG,wCAAwC,CAAC;AAC5D,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC,MAAM,OAAO,WAAW;IACtB;;;OAGG;IACH,MAAM,CAAC,eAAe,CAAC,IAAuB;QAC5C,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEvB,OAAO,KAAK,KAAK,GAAG,IAAI,KAAK,C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QACL,CAAC;QAED,gGAAgG;QAChG,oFAAoF;QACpF,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC;YACb,MAAM,EAAE,WAAW,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;YAC7C,YAAY;YACZ,YAAY;YACZ,MAAM;YACN,WAAW;YACX,aAAa;SACd,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAC9C,CAAC;QAEF,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,EAAE,IAAI,CAAC,QAAsC,CAAC,CAAC,CAAC;IACxE,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport type { Hono } from 'hono';\nimport { cors } from 'hono/cors';\nimport type { ICORSOptions, TOrigin } from './common';\n\n/**\n * A parsed origin pattern: `scheme://*.suffix[:port]` (`subdomain` true) or `scheme://host:*` (an exact\n * `host`, held in `suffix`). `port` is `null` when the pattern names none, a number as text for one port,\n * and `'*'` for any port.\n */\ninterface IOriginPattern {\n scheme: string;\n suffix: string;\n subdomain: boolean;\n port: string | null;\n}\n\nconst ANY_PORT = '*';\nconst WILDCARD_PATTERN = /^([a-z][a-z0-9+.-]*):\\/\\/(\\*\\.)?([a-z0-9.-]+)(?::(\\d{1,5}|\\*))?$/;\nconst HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst PORT_NUMBER = /^[1-9]\\d{0,4}$/;\n\nexport class CorsUtility {\n /**\n * True when `value` is a wildcard origin pattern and not a plain origin: it contains a `*` and is not\n * the bare `'*'`, which keeps its own meaning (\"any origin\").\n */\n static isOriginPattern(opts: { value: string }): boolean {\n const { value } = opts;\n\n return value !== '*' && value.includes('*');\n }\n\n /**\n * Reads an origin pattern into its parts. Two shapes are allowed, and nothing else with a `*`:\n * `https://*.example.com[:port]`, where the `*` is the whole leftmost host label and at least two\n * labels follow it (`https://*.com` is refused); and `http://localhost:*`, an exact host whose port\n * is `*` for any port. The port of either shape may be `*`, as in `https://*.example.com:*`. The\n * scheme is required and kept for an exact comparison. An IPv6 host is not supported. Anything else\n * with a `*` throws, because such a pattern would never match and a hole in it is easy to miss.\n */\n static parseOriginPattern(opts: { pattern: string }): IOriginPattern {\n const { pattern } = opts;\n const parts = WILDCARD_PATTERN.exec(pattern);\n const [, scheme, subdomain, suffix, port] = parts ?? [];\n const labels = suffix?.split('.') ?? [];\n\n if (\n !scheme ||\n !suffix ||\n (subdomain ? labels.length < 2 : port !== ANY_PORT) ||\n !labels.every((label) => HOST_LABEL.test(label)) ||\n (port !== undefined && port !== ANY_PORT && (Number(port) < 1 || Number(port) > 65535))\n ) {\n throw getError({\n message: `[registerCors] configs.middlewares.cors.origin has an invalid wildcard '${pattern}' | only a subdomain wildcard in lower case ('https://*.example.com', 'https://*.example.com:8443') or an any-port wildcard ('http://localhost:*', 'https://*.example.com:*') is allowed, with at least two labels after a '*.'`,\n });\n }\n\n return { scheme, suffix, subdomain: !!subdomain, port: port ?? null };\n }\n\n /**\n * True when the request `origin` (the `Origin` header, a serialised origin) belongs to `pattern`: the\n * scheme is equal, the port is equal (or any number when the pattern says `*`), and the host is the\n * exact host, or ends the pattern's suffix after one or more labels of letters, digits and hyphens.\n * The apex (`https://example.com`), a longer host that merely ends the same (`evilexample.com`), a\n * host that merely contains it (`example.com.evil.net`, `localhost.evil.com:3000`) and a userinfo or\n * path trick (`https://evil.com@a.example.com`) all fail. A pattern without a port matches an origin\n * without one only, so `https://a.example.com:8443` does not match `https://*.example.com`; a `*`\n * port matches an origin with a port or without one.\n */\n static matchOriginPattern(opts: { pattern: IOriginPattern; origin: string }): boolean {\n const { pattern, origin } = opts;\n const head = `${pattern.scheme}://`;\n\n if (!origin.startsWith(head)) {\n return false;\n }\n\n let host = origin.slice(head.length);\n\n if (pattern.port === ANY_PORT) {\n const separator = host.lastIndexOf(':');\n\n if (separator !== -1) {\n const port = host.slice(separator + 1);\n\n if (!PORT_NUMBER.test(port) || Number(port) > 65535) {\n return false;\n }\n\n host = host.slice(0, separator);\n }\n } else if (pattern.port !== null) {\n const tail = `:${pattern.port}`;\n\n if (!host.endsWith(tail)) {\n return false;\n }\n\n host = host.slice(0, host.length - tail.length);\n }\n\n if (!pattern.subdomain) {\n return host === pattern.suffix;\n }\n\n const tail = `.${pattern.suffix}`;\n\n if (!host.endsWith(tail) || host.length <= tail.length) {\n return false;\n }\n\n return host\n .slice(0, host.length - tail.length)\n .split('.')\n .every((label) => HOST_LABEL.test(label));\n }\n\n /**\n * Turns an origin that holds a wildcard pattern into the function form Hono takes: it returns the\n * request origin when an entry matches (a plain entry by equality, a pattern by\n * {@link CorsUtility.matchOriginPattern}) and `null` otherwise. An origin with no wildcard pattern is\n * returned as it is, so the string, list and function forms behave as before.\n */\n static resolveOrigin(opts: { origin: TOrigin }): TOrigin {\n const { origin } = opts;\n\n if (typeof origin === 'function') {\n return origin;\n }\n\n const entries = Array.isArray(origin) ? origin : [origin];\n\n if (!entries.some((value) => CorsUtility.isOriginPattern({ value }))) {\n return origin;\n }\n\n const exact = new Set<string>();\n const patterns: IOriginPattern[] = [];\n\n for (const value of entries) {\n if (CorsUtility.isOriginPattern({ value })) {\n patterns.push(CorsUtility.parseOriginPattern({ pattern: value }));\n } else {\n exact.add(value);\n }\n }\n\n return (requestOrigin: string) => {\n if (\n exact.has(requestOrigin) ||\n patterns.some((pattern) =>\n CorsUtility.matchOriginPattern({ pattern, origin: requestOrigin }),\n )\n ) {\n return requestOrigin;\n }\n\n return null;\n };\n }\n\n /**\n * Installs `configs.middlewares.cors` on the server when it is set and not disabled; with no config\n * nothing is installed. Called first in the default stack, so every response the framework produces\n * on its own - a bodyLimit 413, a body the request spy cannot parse, the error envelope - leaves\n * with the headers a browser needs to read it.\n *\n * `origin` may hold a subdomain wildcard such as `https://*.example.com` (see\n * {@link CorsUtility.matchOriginPattern}); an invalid pattern, or the bare `'*'` together with\n * `credentials: true`, throws here and not on the first request.\n */\n static registerCors(opts: { server: Hono<any, any, any>; options?: ICORSOptions }): void {\n const { server, options } = opts;\n\n if (!options || options.enable === false) {\n return;\n }\n\n const { origin, path, allowMethods, allowHeaders, maxAge, credentials, exposeHeaders } =\n options;\n\n const hasOrigin =\n typeof origin === 'function' || (Array.isArray(origin) ? origin.length > 0 : !!origin);\n\n if (!hasOrigin) {\n throw getError({\n message:\n '[registerCors] configs.middlewares.cors.origin is required | a string, a list of strings or a function',\n });\n }\n\n const origins = Array.isArray(origin) ? origin : [origin];\n\n if (credentials && origins.includes('*')) {\n throw getError({\n message:\n \"[registerCors] configs.middlewares.cors.credentials cannot be combined with origin '*' | a browser refuses a wildcard origin on a credentialed request | list the origins instead\",\n });\n }\n\n // Only the keys that are set: hono spreads over its defaults, so an `undefined` would erase one\n // (a missing `allowMethods` would then answer a preflight with no allowed methods).\n const settings = Object.fromEntries(\n Object.entries({\n origin: CorsUtility.resolveOrigin({ origin }),\n allowMethods,\n allowHeaders,\n maxAge,\n credentials,\n exposeHeaders,\n }).filter(([, value]) => value !== undefined),\n );\n\n server.use(path ?? '*', cors(settings as Parameters<typeof cors>[0]));\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  export * from './abstract.js';
2
2
  export * from './artifact-group.js';
3
+ export * from './body-limit.js';
3
4
  export * from './boot-sequence.js';
4
5
  export * from './common/index.js';
5
6
  export * from './rest.js';
@@ -1,5 +1,6 @@
1
1
  export * from './abstract.js';
2
2
  export * from './artifact-group.js';
3
+ export * from './body-limit.js';
3
4
  export * from './boot-sequence.js';
4
5
  export * from './common/index.js';
5
6
  export * from './rest.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/base/applications/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC","sourcesContent":["export * from './abstract';\nexport * from './artifact-group';\nexport * from './boot-sequence';\nexport * from './common';\nexport * from './rest';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/base/applications/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC","sourcesContent":["export * from './abstract';\nexport * from './artifact-group';\nexport * from './body-limit';\nexport * from './boot-sequence';\nexport * from './common';\nexport * from './rest';\n"]}
@@ -53,6 +53,8 @@ export declare abstract class RestApplication<AppEnv extends Env = Env, AppSchem
53
53
  * Registered before `initialize()`, so an application's own handlers still win.
54
54
  */
55
55
  protected registerDefaultMiddlewares(): ValueOrPromise<void>;
56
+ /** The configured `bodyLimit`, or the default one when none is configured. */
57
+ private resolveBodyLimit;
56
58
  /** What a `bodyLimit` config installs: nothing when absent or disabled, else a copy, so a later in-place edit shows. */
57
59
  private toInstalledBodyLimit;
58
60
  private isSameBodyLimit;
@@ -4,15 +4,14 @@ import { BindingVerifier } from '@venizia/ignis-inversion';
4
4
  import { OpenAPIHono } from '@hono/zod-openapi';
5
5
  import { PerformanceUtility, getError, RequestIdGenerator, RetryHelper, } from '@venizia/ignis-helpers/core';
6
6
  import { showRoutes as showApplicationRoutes } from 'hono/dev';
7
- import { bodyLimit } from 'hono/body-limit';
8
7
  import { requestId } from 'hono/request-id';
9
8
  import { ArtifactBindingKeys } from '../metadata/artifact-keys.js';
10
9
  import { RestComponent } from '../components/controller/rest/rest.component.js';
11
10
  import { ControllerTransports } from '../controllers/common/constants.js';
12
11
  import { BaseAppErrorMiddleware } from '../middlewares/app-error/app-error.middleware.js';
13
- import { RequestErrors } from '../middlewares/common/errors.js';
14
12
  import { notFoundHandler } from '../middlewares/not-found/not-found.middleware.js';
15
13
  import { AbstractApplication } from './abstract.js';
14
+ import { BodyLimits } from './body-limit.js';
16
15
  import { CorsUtility } from './cors.js';
17
16
  import { ArtifactIndexHelper } from './artifact-index.js';
18
17
  import { BootSteps } from './boot-sequence.js';
@@ -82,7 +81,10 @@ export class RestApplication extends AbstractApplication {
82
81
  CorsUtility.registerCors({ server, options: this.configs.middlewares?.cors });
83
82
  server.use(requestId({ generator: () => this.generateRequestId() }));
84
83
  // Ahead of every middleware a host adds after this one, so none of them buffers a body over it.
85
- const bodyLimitOptions = this.configs.middlewares?.bodyLimit;
84
+ // Unset, every route gets BodyLimits.DEFAULT_MAX_SIZE; a configured bodyLimit replaces it, and `enable: false` removes it.
85
+ const bodyLimitOptions = this.resolveBodyLimit({
86
+ options: this.configs.middlewares?.bodyLimit,
87
+ });
86
88
  this.installedBodyLimit = { options: this.toInstalledBodyLimit({ options: bodyLimitOptions }) };
87
89
  if (bodyLimitOptions && bodyLimitOptions.enable !== false) {
88
90
  const { maxSize, path, onError } = bodyLimitOptions;
@@ -91,16 +93,9 @@ export class RestApplication extends AbstractApplication {
91
93
  message: `[registerDefaultMiddlewares] configs.middlewares.bodyLimit.maxSize must be a non-negative number of bytes | value: ${String(maxSize)}`,
92
94
  });
93
95
  }
94
- const limiter = bodyLimit({
95
- maxSize,
96
- onError: onError ??
97
- (() => {
98
- throw getError({
99
- error: RequestErrors.BODY_TOO_LARGE,
100
- message: `Request body exceeds the maximum of ${maxSize} bytes`,
101
- });
102
- }),
103
- });
96
+ const defaultLimiter = BodyLimits.limiter({ maxSize, onError });
97
+ // A route with its own limit (BodyLimits.route) is held to that one, not to this.
98
+ const limiter = (context, next) => BodyLimits.hasRouteLimit(context) ? next() : defaultLimiter(context, next);
104
99
  if (path) {
105
100
  server.use(path, limiter);
106
101
  }
@@ -111,6 +106,10 @@ export class RestApplication extends AbstractApplication {
111
106
  server.onError(this.buildErrorMiddleware().value());
112
107
  server.notFound(notFoundHandler({ logger: this.logger }));
113
108
  }
109
+ /** The configured `bodyLimit`, or the default one when none is configured. */
110
+ resolveBodyLimit(opts) {
111
+ return opts.options ?? { maxSize: BodyLimits.DEFAULT_MAX_SIZE };
112
+ }
114
113
  /** What a `bodyLimit` config installs: nothing when absent or disabled, else a copy, so a later in-place edit shows. */
115
114
  toInstalledBodyLimit(opts) {
116
115
  const { options } = opts;
@@ -141,7 +140,9 @@ export class RestApplication extends AbstractApplication {
141
140
  return;
142
141
  }
143
142
  const installed = this.installedBodyLimit.options;
144
- const current = this.toInstalledBodyLimit({ options: this.configs.middlewares?.bodyLimit });
143
+ const current = this.toInstalledBodyLimit({
144
+ options: this.resolveBodyLimit({ options: this.configs.middlewares?.bodyLimit }),
145
+ });
145
146
  if (this.isSameBodyLimit({ left: installed, right: current })) {
146
147
  return;
147
148
  }