@rexezuge/http 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +182 -12
  2. package/dist/ErrorMapper.d.ts +65 -10
  3. package/dist/ErrorMapper.d.ts.map +1 -1
  4. package/dist/ErrorMapper.js +1 -1
  5. package/dist/ErrorMapper.js.map +3 -3
  6. package/dist/errorClassification.d.ts +44 -0
  7. package/dist/errorClassification.d.ts.map +1 -0
  8. package/dist/errorClassification.js +1 -0
  9. package/dist/errorClassification.js.map +7 -0
  10. package/dist/hono/FamilyRoute.d.ts +56 -0
  11. package/dist/hono/FamilyRoute.d.ts.map +1 -0
  12. package/dist/hono/FamilyRoute.js +1 -0
  13. package/dist/hono/FamilyRoute.js.map +7 -0
  14. package/dist/hono/auth.d.ts +91 -0
  15. package/dist/hono/auth.d.ts.map +1 -0
  16. package/dist/hono/auth.js +1 -0
  17. package/dist/hono/auth.js.map +7 -0
  18. package/dist/hono/bookmarks.d.ts +63 -0
  19. package/dist/hono/bookmarks.d.ts.map +1 -0
  20. package/dist/hono/bookmarks.js +1 -0
  21. package/dist/hono/bookmarks.js.map +7 -0
  22. package/dist/hono/contracts.d.ts +44 -0
  23. package/dist/hono/contracts.d.ts.map +1 -0
  24. package/dist/hono/contracts.js +1 -0
  25. package/dist/hono/contracts.js.map +7 -0
  26. package/dist/hono/createApiApp.d.ts +93 -0
  27. package/dist/hono/createApiApp.d.ts.map +1 -0
  28. package/dist/hono/createApiApp.js +1 -0
  29. package/dist/hono/createApiApp.js.map +7 -0
  30. package/dist/hono/docs.d.ts +41 -0
  31. package/dist/hono/docs.d.ts.map +1 -0
  32. package/dist/hono/docs.js +1 -0
  33. package/dist/hono/docs.js.map +7 -0
  34. package/dist/hono/errorHandler.d.ts +25 -0
  35. package/dist/hono/errorHandler.d.ts.map +1 -0
  36. package/dist/hono/errorHandler.js +1 -0
  37. package/dist/hono/errorHandler.js.map +7 -0
  38. package/dist/hono/hardening.d.ts +51 -0
  39. package/dist/hono/hardening.d.ts.map +1 -0
  40. package/dist/hono/hardening.js +1 -0
  41. package/dist/hono/hardening.js.map +7 -0
  42. package/dist/hono/index.d.ts +37 -0
  43. package/dist/hono/index.d.ts.map +1 -0
  44. package/dist/hono/index.js +1 -0
  45. package/dist/hono/index.js.map +7 -0
  46. package/dist/hono/rateLimits.d.ts +63 -0
  47. package/dist/hono/rateLimits.d.ts.map +1 -0
  48. package/dist/hono/rateLimits.js +1 -0
  49. package/dist/hono/rateLimits.js.map +7 -0
  50. package/dist/hono/requestContext.d.ts +28 -0
  51. package/dist/hono/requestContext.d.ts.map +1 -0
  52. package/dist/hono/requestContext.js +1 -0
  53. package/dist/hono/requestContext.js.map +7 -0
  54. package/dist/hono/types.d.ts +69 -0
  55. package/dist/hono/types.d.ts.map +1 -0
  56. package/dist/hono/types.js +1 -0
  57. package/dist/hono/types.js.map +7 -0
  58. package/dist/index.d.ts +20 -4
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +1 -1
  61. package/dist/index.js.map +3 -3
  62. package/dist/openApiErrors.d.ts +63 -0
  63. package/dist/openApiErrors.d.ts.map +1 -0
  64. package/dist/openApiErrors.js +1 -0
  65. package/dist/openApiErrors.js.map +7 -0
  66. package/dist/requestGuards.d.ts +52 -0
  67. package/dist/requestGuards.d.ts.map +1 -0
  68. package/dist/requestGuards.js +1 -0
  69. package/dist/requestGuards.js.map +7 -0
  70. package/dist/routeBase.d.ts.map +1 -1
  71. package/dist/routeBase.js +1 -1
  72. package/dist/routeBase.js.map +3 -3
  73. package/package.json +13 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hardening.d.ts","sourceRoot":"","sources":["../../src/hono/hardening.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAW9C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,UAAU,YAAY,CAAC,CAAC;IACtB;;MAEE;IACF,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B;;MAEE;IACF,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IAC/C;;MAEE;IACF,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,UAAU,iBAAiB;IACzB;;MAEE;IACF,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B;;MAEE;IACF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B;AAED,UAAU,gBAAgB,CAAC,CAAC;IAC1B;;MAEE;IACF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B;;MAEE;IACF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,MAAM,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;CAC1B;AAED,iBAAS,WAAW,CAAC,OAAO,GAAE,SAAS,MAAM,EAA4B,GAAG,iBAAiB,CAM5F;AAED;;;GAGG;AACH,iBAAS,cAAc,CAAC,QAAQ,GAAE,MAA+B,GAAG,iBAAiB,CAepF;AAED,iBAAS,gBAAgB,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,iBAAiB,CAMxE;AAED,iBAAS,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,GAAE,YAAY,CAAC,CAAC,CAAM,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAOvG;AAED,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC;AACtE,YAAY,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var i=(r,n)=>a(r,"name",{value:n,configurable:!0});import{bodyLimit as c}from"hono/body-limit";import{PayloadTooLargeError as s}from"@rexezuge/errors";import{checkContentLength as w,checkContentType as d,checkMethod as u,checkOrigin as f,DEFAULT_ALLOWED_METHODS as g,DEFAULT_MAX_BODY_BYTES as h}from"../requestGuards.js";import{resolveFromEnv as m}from"./types.js";function l(r=g){return async(n,e)=>{const o=u(n.req.method,r);if(o)throw o;await e()}}i(l,"methodGuard");function E(r=h){if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Invalid maxBodyBytes: ${String(r)} (must be a positive integer)`);const n=c({maxSize:r,onError:i(()=>{throw new s},"onError")});return async(e,o)=>{const t=w(e.req.raw,r);if(t)throw t;return n(e,o)}}i(E,"bodyLimitGuard");function O(r){return async(n,e)=>{const o=d(n.req.raw,r);if(o)throw o;await e()}}i(O,"contentTypeGuard");function L(r={}){return async(n,e)=>{const o=r.allowedOrigins===void 0?[]:m(r.allowedOrigins,n.env),t=f(n.req.raw,{allowedOrigins:o,allowMissingOrigin:r.allowMissingOrigin});if(t)throw t;await e()}}i(L,"originGuard");export{E as bodyLimitGuard,O as contentTypeGuard,l as methodGuard,L as originGuard};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/hardening.ts"],
4
+ "sourcesContent": ["/**\n * The request-hardening middleware: the Hono form of `../requestGuards.ts`.\n *\n * Converged from `apps/api/src/middleware/HttpHardening.ts` (Mail-Bee, Mail-Meow,\n * Mail-Otter, Pigeongram), AWS-AccessBridge's `RequestGuards.ts`, Image-Host's\n * `csrfProtectionHandler` and Pigeongram's `session/origin.ts`. Each guard\n * **throws** its `ServiceError` rather than answering, so the rejection reaches\n * `app.onError` and leaves in the same envelope (and with the same security\n * headers and request id) as every other failure.\n */\nimport { bodyLimit } from 'hono/body-limit';\nimport type { MiddlewareHandler } from 'hono';\nimport { PayloadTooLargeError } from '@rexezuge/errors';\nimport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from '../requestGuards.ts';\nimport { resolveFromEnv } from './types.ts';\nimport type { FromEnv } from './types.ts';\n\ninterface OriginPolicy<E> {\n /**\n The cookie-authenticated surfaces to guard. Defaults to `['/user/*']`.\n */\n paths?: readonly string[];\n /**\n Origins trusted besides the request's own (a Pages origin, a custom domain).\n */\n allowedOrigins?: FromEnv<E, readonly string[]>;\n /**\n Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.\n */\n allowMissingOrigin?: boolean;\n}\n\ninterface ContentTypePolicy {\n /**\n Where JSON mutations are enforced. Defaults to `['/user/*', '/api/*']`.\n */\n paths?: readonly string[];\n /**\n The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.\n */\n allowed?: readonly string[];\n}\n\ninterface HardeningOptions<E> {\n /**\n The methods the app answers. Defaults to {@link DEFAULT_ALLOWED_METHODS}.\n */\n methods?: readonly string[];\n /**\n The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB.\n */\n maxBodyBytes?: number;\n contentType?: ContentTypePolicy;\n origin?: OriginPolicy<E>;\n}\n\nfunction methodGuard(methods: readonly string[] = DEFAULT_ALLOWED_METHODS): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkMethod(c.req.method, methods);\n if (rejection) throw rejection;\n await next();\n };\n}\n\n/**\n * The declared-length check first (cheap, no read), then Hono's streaming cap\n * for a chunked body that declares nothing.\n */\nfunction bodyLimitGuard(maxBytes: number = DEFAULT_MAX_BODY_BYTES): MiddlewareHandler {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new Error(`Invalid maxBodyBytes: ${String(maxBytes)} (must be a positive integer)`);\n }\n const streamed = bodyLimit({\n maxSize: maxBytes,\n onError: (): never => {\n throw new PayloadTooLargeError();\n },\n });\n return async (c, next): Promise<Response | void> => {\n const rejection = checkContentLength(c.req.raw, maxBytes);\n if (rejection) throw rejection;\n return streamed(c, next);\n };\n}\n\nfunction contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkContentType(c.req.raw, allowed);\n if (rejection) throw rejection;\n await next();\n };\n}\n\nfunction originGuard<E extends object>(policy: OriginPolicy<E> = {}): MiddlewareHandler<{ Bindings: E }> {\n return async (c, next): Promise<void> => {\n const allowedOrigins = policy.allowedOrigins === undefined ? [] : resolveFromEnv(policy.allowedOrigins, c.env);\n const rejection = checkOrigin(c.req.raw, { allowedOrigins, allowMissingOrigin: policy.allowMissingOrigin });\n if (rejection) throw rejection;\n await next();\n };\n}\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard };\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy };\n"],
5
+ "mappings": "+EAUA,OAAS,aAAAA,MAAiB,kBAE1B,OAAS,wBAAAC,MAA4B,mBACrC,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,sBACP,OAAS,kBAAAC,MAAsB,aA0C/B,SAASC,EAAYC,EAA6BJ,EAAuB,CACvE,MAAO,OAAOK,EAAGC,IAAuB,CACtC,MAAMC,EAAYT,EAAYO,EAAE,IAAI,OAAQD,CAAO,EACnD,GAAIG,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAL,EAAA,eAYT,SAASM,EAAeC,EAAmBT,EAAsB,CAC/D,GAAI,CAAC,OAAO,cAAcS,CAAQ,GAAKA,GAAY,EACjD,MAAM,IAAI,MAAM,yBAAyB,OAAOA,CAAQ,CAAC,+BAA+B,EAE1F,MAAMC,EAAWjB,EAAU,CACzB,QAASgB,EACT,QAASF,EAAA,IAAY,CACnB,MAAM,IAAIb,CACZ,EAFS,WAGV,EACD,MAAO,OAAOU,EAAGC,IAAkC,CACjD,MAAMC,EAAYX,EAAmBS,EAAE,IAAI,IAAKK,CAAQ,EACxD,GAAIH,EAAW,MAAMA,EACrB,OAAOI,EAASN,EAAGC,CAAI,CACzB,CACF,CAfSE,EAAAC,EAAA,kBAiBT,SAASG,EAAiBC,EAA2B,CACnD,MAAO,OAAOR,EAAGC,IAAuB,CACtC,MAAMC,EAAYV,EAAiBQ,EAAE,IAAI,IAAKQ,CAAO,EACrD,GAAIN,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAI,EAAA,oBAQT,SAASE,EAA8BC,EAA0B,CAAA,EAAE,CACjE,MAAO,OAAOV,EAAGC,IAAuB,CACtC,MAAMU,EAAiBD,EAAO,iBAAmB,OAAY,CAAA,EAAKb,EAAea,EAAO,eAAgBV,EAAE,GAAG,EACvGE,EAAYR,EAAYM,EAAE,IAAI,IAAK,CAAE,eAAAW,EAAgB,mBAAoBD,EAAO,kBAAkB,CAAE,EAC1G,GAAIR,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CAPSE,EAAAM,EAAA",
6
+ "names": ["bodyLimit", "PayloadTooLargeError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "resolveFromEnv", "methodGuard", "methods", "c", "next", "rejection", "__name", "bodyLimitGuard", "maxBytes", "streamed", "contentTypeGuard", "allowed", "originGuard", "policy", "allowedOrigins"]
7
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `@rexezuge/http/hono` — the Hono + chanfana app kernel.
3
+ *
4
+ * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,
5
+ * so the root barrel stays framework-free. `hono` and `chanfana` are optional
6
+ * peers of the package and **required** by a repo that imports this subpath.
7
+ *
8
+ * | Export | Replaces |
9
+ * | ------------------------------- | ------------------------------------------------------------------------ |
10
+ * | `createApiApp` | each API worker's hand-assembled constructor stack |
11
+ * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |
12
+ * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |
13
+ * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |
14
+ * | `d1Bookmarks` | the `onRequest` D1-session blocks |
15
+ * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |
16
+ * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |
17
+ */
18
+ export { createApiApp } from './createApiApp.ts';
19
+ export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';
20
+ export { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';
21
+ export { FamilyRoute } from './FamilyRoute.ts';
22
+ export type { RouteResult } from './FamilyRoute.ts';
23
+ export { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';
24
+ export type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';
25
+ export { accessAuth, apiKeyAuth } from './auth.ts';
26
+ export type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';
27
+ export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';
28
+ export type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';
29
+ export { d1Bookmarks } from './bookmarks.ts';
30
+ export type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';
31
+ export { rateLimitRule } from './rateLimits.ts';
32
+ export type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';
33
+ export { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';
34
+ export { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';
35
+ export type { RequestContextOptions } from './requestContext.ts';
36
+ export type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElG,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzF,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEvF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACnD,YAAY,EAAE,2BAA2B,EAAE,iBAAiB,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5G,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC5F,YAAY,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAExF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEvG,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEhG,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACvF,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1 @@
1
+ import{createApiApp as e}from"./createApiApp.js";import{DOCS_CONTENT_SECURITY_POLICY as m}from"./docs.js";import{FamilyRoute as a}from"./FamilyRoute.js";import{registerContract as d,routeFromEndpoint as i,schemaFromEndpoint as u}from"./contracts.js";import{accessAuth as f,apiKeyAuth as E}from"./auth.js";import{bodyLimitGuard as s,contentTypeGuard as C,methodGuard as h,originGuard as l}from"./hardening.js";import{d1Bookmarks as R}from"./bookmarks.js";import{rateLimitRule as _}from"./rateLimits.js";import{createErrorHandler as y,createNotFoundHandler as F,respondWithError as G}from"./errorHandler.js";import{consoleLogger as D,requestContext as H,REQUEST_ID_HEADER as I}from"./requestContext.js";export{m as DOCS_CONTENT_SECURITY_POLICY,a as FamilyRoute,I as REQUEST_ID_HEADER,f as accessAuth,E as apiKeyAuth,s as bodyLimitGuard,D as consoleLogger,C as contentTypeGuard,e as createApiApp,y as createErrorHandler,F as createNotFoundHandler,R as d1Bookmarks,h as methodGuard,l as originGuard,_ as rateLimitRule,d as registerContract,H as requestContext,G as respondWithError,i as routeFromEndpoint,u as schemaFromEndpoint};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/index.ts"],
4
+ "sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';\n\nexport { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
5
+ "mappings": "AAiBA,OAAS,gBAAAA,MAAoB,oBAG7B,OAAS,gCAAAC,MAAoC,YAE7C,OAAS,eAAAC,MAAmB,mBAG5B,OAAS,oBAAAC,EAAkB,qBAAAC,EAAmB,sBAAAC,MAA0B,iBAGxE,OAAS,cAAAC,EAAY,cAAAC,MAAkB,YAGvC,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAG3E,OAAS,eAAAC,MAAmB,iBAG5B,OAAS,iBAAAC,MAAqB,kBAG9B,OAAS,sBAAAC,EAAoB,yBAAAC,EAAuB,oBAAAC,MAAwB,oBAE5E,OAAS,iBAAAC,EAAe,kBAAAC,EAAgB,qBAAAC,MAAyB",
6
+ "names": ["createApiApp", "DOCS_CONTENT_SECURITY_POLICY", "FamilyRoute", "registerContract", "routeFromEndpoint", "schemaFromEndpoint", "accessAuth", "apiKeyAuth", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "d1Bookmarks", "rateLimitRule", "createErrorHandler", "createNotFoundHandler", "respondWithError", "consoleLogger", "requestContext", "REQUEST_ID_HEADER"]
7
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Rate-limit rules: the native `ratelimits` binding where configured, the kit's
3
+ * in-isolate limiter as the fallback (RFC 0001, backend conventions).
4
+ *
5
+ * Converged from the per-surface limiters in the four `HttpHardening.ts` copies
6
+ * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before
7
+ * auth). The two disagreed about *when* a limiter runs, and both were right for
8
+ * their surface — so a rule declares its key and the key decides the slot:
9
+ *
10
+ * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT
11
+ * lookup per request is a D1 spend an anonymous caller controls).
12
+ * - `key: 'identity'` (the default) runs **after** auth, keyed on
13
+ * `AuthenticatedUserEmailAddress`. Installed before auth it would see no
14
+ * identity and put every operator behind one NAT in a shared bucket.
15
+ */
16
+ import type { MiddlewareHandler } from 'hono';
17
+ import type { RateLimitContext } from '../rateLimit.ts';
18
+ /**
19
+ The native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).
20
+ */
21
+ interface NativeRateLimiter {
22
+ limit(options: {
23
+ key: string;
24
+ }): Promise<{
25
+ success: boolean;
26
+ }>;
27
+ }
28
+ interface RateLimitRule<E> {
29
+ /**
30
+ The Hono path pattern the rule guards (`'/user/*'`).
31
+ */
32
+ path: string;
33
+ /**
34
+ The bucket namespace; two rules never share one.
35
+ */
36
+ keyPrefix: string;
37
+ /**
38
+ The in-isolate window. Mirror the binding's `period` when one is configured.
39
+ */
40
+ windowMs: number;
41
+ /**
42
+ The in-isolate budget, or a per-request resolver (`env` is not known at construction).
43
+ */
44
+ max: number | ((c: RateLimitContext) => number);
45
+ /**
46
+ What the bucket is keyed on, and therefore which slot the rule runs in.
47
+ */
48
+ key?: 'identity' | 'ip';
49
+ /**
50
+ The native binding, when configured. Absent → the in-isolate limiter answers.
51
+ */
52
+ binding?: (env: E) => NativeRateLimiter | undefined;
53
+ }
54
+ /**
55
+ * One rule's middleware. A native limiter that throws **fails open**, like the
56
+ * in-isolate limiter: a broken limiter must not become an outage.
57
+ */
58
+ declare function rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{
59
+ Bindings: E;
60
+ }>;
61
+ export { rateLimitRule };
62
+ export type { NativeRateLimiter, RateLimitRule };
63
+ //# sourceMappingURL=rateLimits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rateLimits.d.ts","sourceRoot":"","sources":["../../src/hono/rateLimits.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD;;EAEE;AACF,UAAU,iBAAiB;IACzB,KAAK,CAAC,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAChE;AAED,UAAU,aAAa,CAAC,CAAC;IACvB;;MAEE;IACF,IAAI,EAAE,MAAM,CAAC;IACb;;MAEE;IACF,SAAS,EAAE,MAAM,CAAC;IAClB;;MAEE;IACF,QAAQ,EAAE,MAAM,CAAC;IACjB;;MAEE;IACF,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,gBAAgB,KAAK,MAAM,CAAC,CAAC;IAChD;;MAEE;IACF,GAAG,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IACxB;;MAEE;IACF,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,GAAG,SAAS,CAAC;CACrD;AAMD;;;GAGG;AACH,iBAAS,aAAa,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAkBnG;AAED,OAAO,EAAE,aAAa,EAAE,CAAC;AACzB,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var f=Object.defineProperty;var r=(t,i)=>f(t,"name",{value:i,configurable:!0});import{clientIp as m,rateLimit as w}from"../rateLimit.js";function p(t){return{Exception:{Type:"RateLimited",Message:`Too many requests. Retry after ${t}s.`}}}r(p,"throttledBody");function u(t){const i=w({windowMs:t.windowMs,max:t.max,keyPrefix:t.keyPrefix}),a=Math.max(1,Math.ceil(t.windowMs/1e3));return async(e,s)=>{const o=t.binding?.(e.env);if(!o)return i(e,s);const d=t.key==="ip"?void 0:e.get("AuthenticatedUserEmailAddress"),y=`${t.keyPrefix}:${d??`ip:${m(c=>e.req.header(c))}`}`;let n=!0;try{n=(await o.limit({key:y})).success}catch{n=!0}if(!n)return e.json(p(a),429,{"Retry-After":String(a)});await s()}}r(u,"rateLimitRule");export{u as rateLimitRule};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/rateLimits.ts"],
4
+ "sourcesContent": ["/**\n * Rate-limit rules: the native `ratelimits` binding where configured, the kit's\n * in-isolate limiter as the fallback (RFC 0001, backend conventions).\n *\n * Converged from the per-surface limiters in the four `HttpHardening.ts` copies\n * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before\n * auth). The two disagreed about *when* a limiter runs, and both were right for\n * their surface — so a rule declares its key and the key decides the slot:\n *\n * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT\n * lookup per request is a D1 spend an anonymous caller controls).\n * - `key: 'identity'` (the default) runs **after** auth, keyed on\n * `AuthenticatedUserEmailAddress`. Installed before auth it would see no\n * identity and put every operator behind one NAT in a shared bucket.\n */\nimport type { MiddlewareHandler } from 'hono';\nimport { clientIp, rateLimit } from '../rateLimit.ts';\nimport type { RateLimitContext } from '../rateLimit.ts';\n\n/**\nThe native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).\n*/\ninterface NativeRateLimiter {\n limit(options: { key: string }): Promise<{ success: boolean }>;\n}\n\ninterface RateLimitRule<E> {\n /**\n The Hono path pattern the rule guards (`'/user/*'`).\n */\n path: string;\n /**\n The bucket namespace; two rules never share one.\n */\n keyPrefix: string;\n /**\n The in-isolate window. Mirror the binding's `period` when one is configured.\n */\n windowMs: number;\n /**\n The in-isolate budget, or a per-request resolver (`env` is not known at construction).\n */\n max: number | ((c: RateLimitContext) => number);\n /**\n What the bucket is keyed on, and therefore which slot the rule runs in.\n */\n key?: 'identity' | 'ip';\n /**\n The native binding, when configured. Absent → the in-isolate limiter answers.\n */\n binding?: (env: E) => NativeRateLimiter | undefined;\n}\n\nfunction throttledBody(retryAfter: number): { Exception: { Type: string; Message: string } } {\n return { Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } };\n}\n\n/**\n * One rule's middleware. A native limiter that throws **fails open**, like the\n * in-isolate limiter: a broken limiter must not become an outage.\n */\nfunction rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{ Bindings: E }> {\n const fallback = rateLimit({ windowMs: rule.windowMs, max: rule.max, keyPrefix: rule.keyPrefix });\n const retryAfter = Math.max(1, Math.ceil(rule.windowMs / 1000));\n return async (c, next): Promise<Response | void> => {\n const native = rule.binding?.(c.env);\n if (!native) return fallback(c, next);\n\n const identity = rule.key === 'ip' ? undefined : (c.get('AuthenticatedUserEmailAddress' as never) as string | undefined);\n const key = `${rule.keyPrefix}:${identity ?? `ip:${clientIp((name) => c.req.header(name))}`}`;\n let allowed = true;\n try {\n allowed = (await native.limit({ key })).success;\n } catch {\n allowed = true;\n }\n if (!allowed) return c.json(throttledBody(retryAfter), 429, { 'Retry-After': String(retryAfter) });\n await next();\n };\n}\n\nexport { rateLimitRule };\nexport type { NativeRateLimiter, RateLimitRule };\n"],
5
+ "mappings": "+EAgBA,OAAS,YAAAA,EAAU,aAAAC,MAAiB,kBAqCpC,SAASC,EAAcC,EAAkB,CACvC,MAAO,CAAE,UAAW,CAAE,KAAM,cAAe,QAAS,kCAAkCA,CAAU,IAAI,CAAE,CACxG,CAFSC,EAAAF,EAAA,iBAQT,SAASG,EAAgCC,EAAsB,CAC7D,MAAMC,EAAWN,EAAU,CAAE,SAAUK,EAAK,SAAU,IAAKA,EAAK,IAAK,UAAWA,EAAK,SAAS,CAAE,EAC1FH,EAAa,KAAK,IAAI,EAAG,KAAK,KAAKG,EAAK,SAAW,GAAI,CAAC,EAC9D,MAAO,OAAOE,EAAGC,IAAkC,CACjD,MAAMC,EAASJ,EAAK,UAAUE,EAAE,GAAG,EACnC,GAAI,CAACE,EAAQ,OAAOH,EAASC,EAAGC,CAAI,EAEpC,MAAME,EAAWL,EAAK,MAAQ,KAAO,OAAaE,EAAE,IAAI,+BAAwC,EAC1FI,EAAM,GAAGN,EAAK,SAAS,IAAIK,GAAY,MAAMX,EAAUa,GAASL,EAAE,IAAI,OAAOK,CAAI,CAAC,CAAC,EAAE,GAC3F,IAAIC,EAAU,GACd,GAAI,CACFA,GAAW,MAAMJ,EAAO,MAAM,CAAE,IAAAE,CAAG,CAAE,GAAG,OAC1C,MAAQ,CACNE,EAAU,EACZ,CACA,GAAI,CAACA,EAAS,OAAON,EAAE,KAAKN,EAAcC,CAAU,EAAG,IAAK,CAAE,cAAe,OAAOA,CAAU,CAAC,CAAE,EACjG,MAAMM,EAAI,CACZ,CACF,CAlBSL,EAAAC,EAAA",
6
+ "names": ["clientIp", "rateLimit", "throttledBody", "retryAfter", "__name", "rateLimitRule", "rule", "fallback", "c", "next", "native", "identity", "key", "name", "allowed"]
7
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The first middleware: a correlation id and a request-scoped logger.
3
+ *
4
+ * The id is minted here rather than read from the client: an incoming
5
+ * `X-Request-Id` is caller-controlled, and a log line keyed on it lets a caller
6
+ * splice their requests into someone else's trace. A repo that sits behind a
7
+ * proxy it trusts supplies `requestId` and reads the header itself.
8
+ */
9
+ import type { MiddlewareHandler } from 'hono';
10
+ import type { FamilyEnv, HttpLogger } from './types.ts';
11
+ declare const REQUEST_ID_HEADER = "X-Request-Id";
12
+ interface RequestContextOptions<E extends object> {
13
+ /**
14
+ Mint this request's id. Defaults to `crypto.randomUUID()`.
15
+ */
16
+ requestId?: (request: Request) => string;
17
+ /**
18
+ * Build the request-scoped logger. Pass `@rexezuge/runtime`'s `createLogger`:
19
+ * `logger: (env) => createLogger('api', 'Owner/Repo', env)`. Defaults to a
20
+ * console logger prefixed with the request id.
21
+ */
22
+ logger?: (env: E, requestId: string) => HttpLogger;
23
+ }
24
+ declare function consoleLogger(requestId: string): HttpLogger;
25
+ declare function requestContext<E extends object, V extends object>(options?: RequestContextOptions<E>): MiddlewareHandler<FamilyEnv<E, V>>;
26
+ export { consoleLogger, requestContext, REQUEST_ID_HEADER };
27
+ export type { RequestContextOptions };
28
+ //# sourceMappingURL=requestContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestContext.d.ts","sourceRoot":"","sources":["../../src/hono/requestContext.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExD,QAAA,MAAM,iBAAiB,iBAAiB,CAAC;AAEzC,UAAU,qBAAqB,CAAC,CAAC,SAAS,MAAM;IAC9C;;MAEE;IACF,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,CAAC;IACzC;;;;OAIG;IACH,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,SAAS,EAAE,MAAM,KAAK,UAAU,CAAC;CACpD;AAED,iBAAS,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,UAAU,CAQpD;AAED,iBAAS,cAAc,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,EAAE,OAAO,GAAE,qBAAqB,CAAC,CAAC,CAAM,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CActI;AAED,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,CAAC;AAC5D,YAAY,EAAE,qBAAqB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var o=(n,r)=>a(n,"name",{value:r,configurable:!0});const c="X-Request-Id";function u(n){const r=`[${n}]`;return{debug:o((...e)=>console.debug(r,...e),"debug"),info:o((...e)=>console.info(r,...e),"info"),warn:o((...e)=>console.warn(r,...e),"warn"),error:o((...e)=>console.error(r,...e),"error")}}o(u,"consoleLogger");function d(n={}){return async(r,e)=>{const t=r,s=n.requestId?.(t.req.raw)??crypto.randomUUID();t.set("requestId",s),t.set("logger",n.logger?.(t.env,s)??u(s)),await e();try{t.res.headers.set(c,s)}catch{}}}o(d,"requestContext");export{c as REQUEST_ID_HEADER,u as consoleLogger,d as requestContext};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/requestContext.ts"],
4
+ "sourcesContent": ["/**\n * The first middleware: a correlation id and a request-scoped logger.\n *\n * The id is minted here rather than read from the client: an incoming\n * `X-Request-Id` is caller-controlled, and a log line keyed on it lets a caller\n * splice their requests into someone else's trace. A repo that sits behind a\n * proxy it trusts supplies `requestId` and reads the header itself.\n */\nimport type { Context, MiddlewareHandler } from 'hono';\nimport type { FamilyEnv, HttpLogger } from './types.ts';\n\nconst REQUEST_ID_HEADER = 'X-Request-Id';\n\ninterface RequestContextOptions<E extends object> {\n /**\n Mint this request's id. Defaults to `crypto.randomUUID()`.\n */\n requestId?: (request: Request) => string;\n /**\n * Build the request-scoped logger. Pass `@rexezuge/runtime`'s `createLogger`:\n * `logger: (env) => createLogger('api', 'Owner/Repo', env)`. Defaults to a\n * console logger prefixed with the request id.\n */\n logger?: (env: E, requestId: string) => HttpLogger;\n}\n\nfunction consoleLogger(requestId: string): HttpLogger {\n const prefix = `[${requestId}]`;\n return {\n debug: (...args: unknown[]): void => console.debug(prefix, ...args),\n info: (...args: unknown[]): void => console.info(prefix, ...args),\n warn: (...args: unknown[]): void => console.warn(prefix, ...args),\n error: (...args: unknown[]): void => console.error(prefix, ...args),\n };\n}\n\nfunction requestContext<E extends object, V extends object>(options: RequestContextOptions<E> = {}): MiddlewareHandler<FamilyEnv<E, V>> {\n return async (context, next): Promise<void> => {\n // Narrowed to the kit's own variables: the caller's `V` cannot redeclare them.\n const c = context as unknown as Context<FamilyEnv<E>>;\n const id = options.requestId?.(c.req.raw) ?? crypto.randomUUID();\n c.set('requestId', id);\n c.set('logger', options.logger?.(c.env, id) ?? consoleLogger(id));\n await next();\n try {\n c.res.headers.set(REQUEST_ID_HEADER, id);\n } catch {\n // An immutable response (a pass-through `fetch`) keeps its own headers.\n }\n };\n}\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER };\nexport type { RequestContextOptions };\n"],
5
+ "mappings": "+EAWA,MAAMA,EAAoB,eAe1B,SAASC,EAAcC,EAAiB,CACtC,MAAMC,EAAS,IAAID,CAAS,IAC5B,MAAO,CACL,MAAOE,EAAA,IAAIC,IAA0B,QAAQ,MAAMF,EAAQ,GAAGE,CAAI,EAA3D,SACP,KAAMD,EAAA,IAAIC,IAA0B,QAAQ,KAAKF,EAAQ,GAAGE,CAAI,EAA1D,QACN,KAAMD,EAAA,IAAIC,IAA0B,QAAQ,KAAKF,EAAQ,GAAGE,CAAI,EAA1D,QACN,MAAOD,EAAA,IAAIC,IAA0B,QAAQ,MAAMF,EAAQ,GAAGE,CAAI,EAA3D,SAEX,CARSD,EAAAH,EAAA,iBAUT,SAASK,EAAmDC,EAAoC,CAAA,EAAE,CAChG,MAAO,OAAOC,EAASC,IAAuB,CAE5C,MAAMC,EAAIF,EACJG,EAAKJ,EAAQ,YAAYG,EAAE,IAAI,GAAG,GAAK,OAAO,WAAU,EAC9DA,EAAE,IAAI,YAAaC,CAAE,EACrBD,EAAE,IAAI,SAAUH,EAAQ,SAASG,EAAE,IAAKC,CAAE,GAAKV,EAAcU,CAAE,CAAC,EAChE,MAAMF,EAAI,EACV,GAAI,CACFC,EAAE,IAAI,QAAQ,IAAIV,EAAmBW,CAAE,CACzC,MAAQ,CAER,CACF,CACF,CAdSP,EAAAE,EAAA",
6
+ "names": ["REQUEST_ID_HEADER", "consoleLogger", "requestId", "prefix", "__name", "args", "requestContext", "options", "context", "next", "c", "id"]
7
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The typed Hono context every family API shares.
3
+ *
4
+ * Converged from the `Variables` blocks the workers redeclare — 40-odd
5
+ * `Hono<{ Bindings: Env; Variables: { AuthenticatedUserEmailAddress: string } }>`
6
+ * aliases across Edge-Git, Durable-DAV, Mail-Bee, Mail-Meow, Mail-Otter,
7
+ * AWS-AccessBridge and Image-Host, half of which also carry `AuthenticatedUserId`
8
+ * (some as `?:`, which made every read a narrowing).
9
+ */
10
+ import type { Context, MiddlewareHandler } from 'hono';
11
+ /**
12
+ * The logger port. `@rexezuge/runtime`'s `Logger` (from `createLogger`)
13
+ * satisfies it structurally; `http` does not import `runtime`.
14
+ *
15
+ * Kit middleware only ever passes it **static** messages and plain fields
16
+ * (`type`, `status`, `requestId`), never a caught value — log redaction is an
17
+ * invariant, not an option.
18
+ */
19
+ interface HttpLogger {
20
+ debug(...args: unknown[]): void;
21
+ info(...args: unknown[]): void;
22
+ warn(...args: unknown[]): void;
23
+ error(...args: unknown[]): void;
24
+ }
25
+ /**
26
+ * What the kit's middleware publishes on the context.
27
+ *
28
+ * `AuthenticatedUserEmailAddress` and `AuthenticatedUserId` are set by
29
+ * `accessAuth` / `apiKeyAuth` on the surfaces they guard and are **only
30
+ * meaningful there**: declared non-optional so an authenticated handler reads
31
+ * them without narrowing, exactly as every consumer declared them. A public
32
+ * route never reads them.
33
+ */
34
+ interface FamilyVariables {
35
+ /**
36
+ The sign-in address, lowercased. Display, logging and the rate-limit key.
37
+ */
38
+ AuthenticatedUserEmailAddress: string;
39
+ /**
40
+ The stable account key — the only value that should identify a user.
41
+ */
42
+ AuthenticatedUserId: string;
43
+ /**
44
+ This request's correlation id, also sent back as `X-Request-Id`.
45
+ */
46
+ requestId: string;
47
+ /**
48
+ The request-scoped logger.
49
+ */
50
+ logger: HttpLogger;
51
+ }
52
+ /**
53
+ * The Hono `Env` of a family app: your bindings, the kit's variables, and any
54
+ * variables your own middleware adds.
55
+ */
56
+ type FamilyEnv<E extends object = object, V extends object = object> = {
57
+ Bindings: E;
58
+ Variables: FamilyVariables & V;
59
+ };
60
+ type FamilyContext<E extends object = object, V extends object = object> = Context<FamilyEnv<E, V>>;
61
+ type FamilyMiddleware<E extends object = object, V extends object = object> = MiddlewareHandler<FamilyEnv<E, V>>;
62
+ /**
63
+ A value fixed at construction, or resolved from the request's bindings.
64
+ */
65
+ type FromEnv<E, T> = T | ((env: E) => T);
66
+ declare function resolveFromEnv<E, T>(value: FromEnv<E, T>, env: E): T;
67
+ export { resolveFromEnv };
68
+ export type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger };
69
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/hono/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAEvD;;;;;;;GAOG;AACH,UAAU,UAAU;IAClB,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAChC,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC/B,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC/B,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;CACjC;AAED;;;;;;;;GAQG;AACH,UAAU,eAAe;IACvB;;MAEE;IACF,6BAA6B,EAAE,MAAM,CAAC;IACtC;;MAEE;IACF,mBAAmB,EAAE,MAAM,CAAC;IAC5B;;MAEE;IACF,SAAS,EAAE,MAAM,CAAC;IAClB;;MAEE;IACF,MAAM,EAAE,UAAU,CAAC;CACpB;AAED;;;GAGG;AACH,KAAK,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;IACrE,QAAQ,EAAE,CAAC,CAAC;IACZ,SAAS,EAAE,eAAe,GAAG,CAAC,CAAC;CAChC,CAAC;AAEF,KAAK,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAEpG,KAAK,gBAAgB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAEjH;;EAEE;AACF,KAAK,OAAO,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AAEzC,iBAAS,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAE7D;AAED,OAAO,EAAE,cAAc,EAAE,CAAC;AAC1B,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty;var r=(n,o)=>t(n,"name",{value:o,configurable:!0});function e(n,o){return typeof n=="function"?n(o):n}r(e,"resolveFromEnv");export{e as resolveFromEnv};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/hono/types.ts"],
4
+ "sourcesContent": ["/**\n * The typed Hono context every family API shares.\n *\n * Converged from the `Variables` blocks the workers redeclare — 40-odd\n * `Hono<{ Bindings: Env; Variables: { AuthenticatedUserEmailAddress: string } }>`\n * aliases across Edge-Git, Durable-DAV, Mail-Bee, Mail-Meow, Mail-Otter,\n * AWS-AccessBridge and Image-Host, half of which also carry `AuthenticatedUserId`\n * (some as `?:`, which made every read a narrowing).\n */\nimport type { Context, MiddlewareHandler } from 'hono';\n\n/**\n * The logger port. `@rexezuge/runtime`'s `Logger` (from `createLogger`)\n * satisfies it structurally; `http` does not import `runtime`.\n *\n * Kit middleware only ever passes it **static** messages and plain fields\n * (`type`, `status`, `requestId`), never a caught value — log redaction is an\n * invariant, not an option.\n */\ninterface HttpLogger {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\n/**\n * What the kit's middleware publishes on the context.\n *\n * `AuthenticatedUserEmailAddress` and `AuthenticatedUserId` are set by\n * `accessAuth` / `apiKeyAuth` on the surfaces they guard and are **only\n * meaningful there**: declared non-optional so an authenticated handler reads\n * them without narrowing, exactly as every consumer declared them. A public\n * route never reads them.\n */\ninterface FamilyVariables {\n /**\n The sign-in address, lowercased. Display, logging and the rate-limit key.\n */\n AuthenticatedUserEmailAddress: string;\n /**\n The stable account key — the only value that should identify a user.\n */\n AuthenticatedUserId: string;\n /**\n This request's correlation id, also sent back as `X-Request-Id`.\n */\n requestId: string;\n /**\n The request-scoped logger.\n */\n logger: HttpLogger;\n}\n\n/**\n * The Hono `Env` of a family app: your bindings, the kit's variables, and any\n * variables your own middleware adds.\n */\ntype FamilyEnv<E extends object = object, V extends object = object> = {\n Bindings: E;\n Variables: FamilyVariables & V;\n};\n\ntype FamilyContext<E extends object = object, V extends object = object> = Context<FamilyEnv<E, V>>;\n\ntype FamilyMiddleware<E extends object = object, V extends object = object> = MiddlewareHandler<FamilyEnv<E, V>>;\n\n/**\nA value fixed at construction, or resolved from the request's bindings.\n*/\ntype FromEnv<E, T> = T | ((env: E) => T);\n\nfunction resolveFromEnv<E, T>(value: FromEnv<E, T>, env: E): T {\n return typeof value === 'function' ? (value as (env: E) => T)(env) : value;\n}\n\nexport { resolveFromEnv };\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger };\n"],
5
+ "mappings": "+EAwEA,SAASA,EAAqBC,EAAsBC,EAAM,CACxD,OAAO,OAAOD,GAAU,WAAcA,EAAwBC,CAAG,EAAID,CACvE,CAFSE,EAAAH,EAAA",
6
+ "names": ["resolveFromEnv", "value", "env", "__name"]
7
+ }
package/dist/index.d.ts CHANGED
@@ -10,8 +10,9 @@
10
10
  * chanfana-shaped, and four repos shipped four copies of each while the kit's
11
11
  * zero-dependency rule silently prevented the fix.
12
12
  *
13
- * So this is the one package that breaks the rule, deliberately. It is also the
14
- * only one a repo can choose to skip — nothing in the other eight imports it.
13
+ * So this is the one package that breaks the rule, deliberately — and only in its
14
+ * `/hono` subpath. It is also the only one a repo can choose to skip: nothing in
15
+ * the other eight imports it.
15
16
  *
16
17
  * ## What converged here
17
18
  *
@@ -22,6 +23,17 @@
22
23
  * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |
23
24
  * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |
24
25
  * | `routeBase` | All three incompatible shapes, with their shared parts converged |
26
+ * | `requestGuards` | HttpHardening ×4, AWS `RequestGuards`, Image-Host's CSRF guard, Pigeongram's origin check |
27
+ * | `openApiErrors` | AWS-AccessBridge's `exceptionResponses` |
28
+ *
29
+ * ## Two entry points
30
+ *
31
+ * This root barrel is **framework-free**: structural context types only, no
32
+ * `hono` or `chanfana` import, so a bare-`Request` dispatcher (a Durable Object,
33
+ * Pigeongram's route table) can take it. Everything that imports `hono` or
34
+ * `chanfana` — `createApiApp`, `FamilyRoute`, the auth and hardening middleware —
35
+ * lives at `@rexezuge/http/hono`, and those two optional peers are required only
36
+ * by a repo that imports that subpath.
25
37
  *
26
38
  * ## The null rule
27
39
  *
@@ -37,8 +49,12 @@ export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY
37
49
  export type { HeaderContext } from './securityHeaders.ts';
38
50
  export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';
39
51
  export type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';
40
- export { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';
41
- export type { ErrorMapperOptions } from './ErrorMapper.ts';
52
+ export { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';
53
+ export type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';
54
+ export { errorResponses, exceptionResponse } from './openApiErrors.ts';
55
+ export type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';
56
+ export { checkContentLength, checkContentType, checkMethod, checkOrigin, isMutatingMethod, requestOrigin, DEFAULT_ALLOWED_METHODS, DEFAULT_MAX_BODY_BYTES, } from './requestGuards.ts';
57
+ export type { OriginGuardOptions } from './requestGuards.ts';
42
58
  export { BaseRoute, createRouteHandler } from './routeBase.ts';
43
59
  export type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';
44
60
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EACL,+BAA+B,IAAI,mCAAmC,EACtE,sBAAsB,IAAI,0BAA0B,EACrD,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAClE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC5G,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE3G,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AACvG,YAAY,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAKtF;;GAEG;AACH,eAAO,MAAM,sBAAsB,EAAE,OAAO,0BAAuD,CAAC;AACpG;;GAEG;AACH,eAAO,MAAM,+BAA+B,EAAE,OAAO,mCAAyE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EACL,+BAA+B,IAAI,mCAAmC,EACtE,sBAAsB,IAAI,0BAA0B,EACrD,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAClE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC5G,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE3G,OAAO,EAAE,SAAS,EAAE,wBAAwB,EAAE,QAAQ,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3I,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE5F,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAErG,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAKtF;;GAEG;AACH,eAAO,MAAM,sBAAsB,EAAE,OAAO,0BAAuD,CAAC;AACpG;;GAEG;AACH,eAAO,MAAM,+BAA+B,EAAE,OAAO,mCAAyE,CAAC"}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as R,MAX_BUCKETS as c,rateLimit as m}from"./rateLimit.js";import{applySecurityHeaders as E,securityHeaders as S,sensitivePaths as n,CONTENT_SECURITY_POLICY as p,SECURITY_HEADERS as u,STRICT_TRANSPORT_SECURITY as C}from"./securityHeaders.js";import{AccessAuthError as L,authenticateAccess as _,identityFromBinding as f,verifyAccessJwt as x}from"./accessAuth.js";import{errorBody as F,toErrorResponse as I,toServiceError as d,INTERNAL_SERVER_MESSAGE as y}from"./ErrorMapper.js";import{BaseRoute as g,createRouteHandler as H}from"./routeBase.js";const o=t,s=e;export{L as AccessAuthError,g as BaseRoute,p as CONTENT_SECURITY_POLICY,y as INTERNAL_SERVER_MESSAGE,c as MAX_BUCKETS,u as SECURITY_HEADERS,C as STRICT_TRANSPORT_SECURITY,E as applySecurityHeaders,_ as authenticateAccess,R as clientIp,H as createRouteHandler,F as errorBody,s as getRateLimitBucketCountForTests,f as identityFromBinding,m as rateLimit,o as resetRateLimitForTests,S as securityHeaders,n as sensitivePaths,I as toErrorResponse,d as toServiceError,x as verifyAccessJwt};
1
+ import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as E,sensitivePaths as p,CONTENT_SECURITY_POLICY as S,SECURITY_HEADERS as u,STRICT_TRANSPORT_SECURITY as L}from"./securityHeaders.js";import{AccessAuthError as _,authenticateAccess as C,identityFromBinding as h,verifyAccessJwt as x}from"./accessAuth.js";import{errorBody as f,errorResponseFromUnknown as B,mapError as d,toErrorResponse as g,toServiceError as k,INTERNAL_SERVER_MESSAGE as O}from"./ErrorMapper.js";import{errorResponses as I,exceptionResponse as M}from"./openApiErrors.js";import{checkContentLength as D,checkContentType as Y,checkMethod as H,checkOrigin as N,isMutatingMethod as l,requestOrigin as v,DEFAULT_ALLOWED_METHODS as P,DEFAULT_MAX_BODY_BYTES as w}from"./requestGuards.js";import{BaseRoute as q,createRouteHandler as G}from"./routeBase.js";const o=t,s=e;export{_ as AccessAuthError,q as BaseRoute,S as CONTENT_SECURITY_POLICY,P as DEFAULT_ALLOWED_METHODS,w as DEFAULT_MAX_BODY_BYTES,O as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,u as SECURITY_HEADERS,L as STRICT_TRANSPORT_SECURITY,m as applySecurityHeaders,C as authenticateAccess,D as checkContentLength,Y as checkContentType,H as checkMethod,N as checkOrigin,c as clientIp,G as createRouteHandler,f as errorBody,B as errorResponseFromUnknown,I as errorResponses,M as exceptionResponse,s as getRateLimitBucketCountForTests,h as identityFromBinding,l as isMutatingMethod,d as mapError,R as rateLimit,v as requestOrigin,o as resetRateLimitForTests,E as securityHeaders,p as sensitivePaths,g as toErrorResponse,k as toServiceError,x as verifyAccessJwt};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately. It is also the\n * only one a repo can choose to skip — nothing in the other eight imports it.\n *\n * ## What converged here\n *\n * | Module | From |\n * | ----------------- | --------------------------------------------------------------------- |\n * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |\n * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |\n * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |\n * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |\n * | `routeBase` | All three incompatible shapes, with their shared parts converged |\n *\n * ## The null rule\n *\n * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.\n * The middleware in this package takes *structural* context types rather than\n * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test\n * double usable without a framework import.\n */\n\nimport {\n getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam,\n resetRateLimitForTests as resetRateLimitForTestsSeam,\n} from './testing.ts';\n\nexport { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { ErrorMapperOptions } from './ErrorMapper.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n\n// Test seams, re-exported from the root barrel only for compatibility. Bound as\n// consts rather than re-export specifiers so the @deprecated tag reaches callers.\n\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const resetRateLimitForTests: typeof resetRateLimitForTestsSeam = resetRateLimitForTestsSeam;\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam = getRateLimitBucketCountForTestsSeam;\n"],
5
- "mappings": "AAiCA,OACE,mCAAmCA,EACnC,0BAA0BC,MACrB,eAEP,OAAS,YAAAC,EAAU,eAAAC,EAAa,aAAAC,MAAiB,iBAGjD,OACE,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,6BAAAC,MACK,uBAGP,OAAS,mBAAAC,EAAiB,sBAAAC,EAAoB,uBAAAC,EAAqB,mBAAAC,MAAuB,kBAG1F,OAAS,aAAAC,EAAW,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGpF,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,EAA4DpB,EAI5DqB,EAA8EtB",
6
- "names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
4
+ "sourcesContent": ["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately — and only in its\n * `/hono` subpath. It is also the only one a repo can choose to skip: nothing in\n * the other eight imports it.\n *\n * ## What converged here\n *\n * | Module | From |\n * | ----------------- | --------------------------------------------------------------------- |\n * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |\n * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |\n * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |\n * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |\n * | `routeBase` | All three incompatible shapes, with their shared parts converged |\n * | `requestGuards` | HttpHardening ×4, AWS `RequestGuards`, Image-Host's CSRF guard, Pigeongram's origin check |\n * | `openApiErrors` | AWS-AccessBridge's `exceptionResponses` |\n *\n * ## Two entry points\n *\n * This root barrel is **framework-free**: structural context types only, no\n * `hono` or `chanfana` import, so a bare-`Request` dispatcher (a Durable Object,\n * Pigeongram's route table) can take it. Everything that imports `hono` or\n * `chanfana` — `createApiApp`, `FamilyRoute`, the auth and hardening middleware —\n * lives at `@rexezuge/http/hono`, and those two optional peers are required only\n * by a repo that imports that subpath.\n *\n * ## The null rule\n *\n * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.\n * The middleware in this package takes *structural* context types rather than\n * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test\n * double usable without a framework import.\n */\n\nimport {\n getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam,\n resetRateLimitForTests as resetRateLimitForTestsSeam,\n} from './testing.ts';\n\nexport { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';\n\nexport { errorResponses, exceptionResponse } from './openApiErrors.ts';\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from './requestGuards.ts';\nexport type { OriginGuardOptions } from './requestGuards.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n\n// Test seams, re-exported from the root barrel only for compatibility. Bound as\n// consts rather than re-export specifiers so the @deprecated tag reaches callers.\n\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const resetRateLimitForTests: typeof resetRateLimitForTestsSeam = resetRateLimitForTestsSeam;\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam = getRateLimitBucketCountForTestsSeam;\n"],
5
+ "mappings": "AA6CA,OACE,mCAAmCA,EACnC,0BAA0BC,MACrB,eAEP,OAAS,YAAAC,EAAU,eAAAC,EAAa,aAAAC,MAAiB,iBAGjD,OACE,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,6BAAAC,MACK,uBAGP,OAAS,mBAAAC,EAAiB,sBAAAC,EAAoB,uBAAAC,EAAqB,mBAAAC,MAAuB,kBAG1F,OAAS,aAAAC,EAAW,4BAAAC,EAA0B,YAAAC,EAAU,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGxH,OAAS,kBAAAC,EAAgB,qBAAAC,MAAyB,qBAGlD,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,oBAAAC,EACA,iBAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,qBAGP,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,EAA4DhC,EAI5DiC,EAA8ElC",
6
+ "names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
7
7
  }
@@ -0,0 +1,63 @@
1
+ type ExceptionSchema = {
2
+ type: 'object';
3
+ properties: {
4
+ Exception: {
5
+ type: 'object';
6
+ properties: {
7
+ Type: {
8
+ type: 'string';
9
+ description: string;
10
+ example: string;
11
+ };
12
+ Message: {
13
+ type: 'string';
14
+ description: string;
15
+ example: string;
16
+ };
17
+ };
18
+ };
19
+ };
20
+ };
21
+ type ExceptionResponse = {
22
+ description: string;
23
+ content: {
24
+ 'application/json': {
25
+ schema: ExceptionSchema;
26
+ };
27
+ };
28
+ };
29
+ interface ExceptionSchemaOptions {
30
+ /**
31
+ The `Type` example. Defaults to the catalog name for the status.
32
+ */
33
+ type?: string;
34
+ /**
35
+ The `Message` example. Should say what actually goes wrong on this route.
36
+ */
37
+ message?: string;
38
+ }
39
+ /**
40
+ One `responses` entry for the envelope.
41
+ */
42
+ declare function exceptionResponse(description: string, options?: ExceptionSchemaOptions): ExceptionResponse;
43
+ /**
44
+ * A `responses` map for several statuses at once:
45
+ *
46
+ * ```ts
47
+ * schema = {
48
+ * responses: {
49
+ * '200': { description: 'The volume', ...contentJson(Volume) },
50
+ * ...errorResponses({ 400: 'Invalid name', 404: 'No such volume' }),
51
+ * ...errorResponses([401, 500]),
52
+ * },
53
+ * };
54
+ * ```
55
+ *
56
+ * A list uses each catalog default as the description; a record names it. An
57
+ * uncatalogued status is described as `InternalServerError`, because that is
58
+ * what the mapper emits for one.
59
+ */
60
+ declare function errorResponses(statuses: readonly number[] | Readonly<Record<number, string>>): Record<string, ExceptionResponse>;
61
+ export { errorResponses, exceptionResponse };
62
+ export type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions };
63
+ //# sourceMappingURL=openApiErrors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openApiErrors.d.ts","sourceRoot":"","sources":["../src/openApiErrors.ts"],"names":[],"mappings":"AAwBA,KAAK,eAAe,GAAG;IACrB,IAAI,EAAE,QAAQ,CAAC;IACf,UAAU,EAAE;QACV,SAAS,EAAE;YACT,IAAI,EAAE,QAAQ,CAAC;YACf,UAAU,EAAE;gBACV,IAAI,EAAE;oBAAE,IAAI,EAAE,QAAQ,CAAC;oBAAC,WAAW,EAAE,MAAM,CAAC;oBAAC,OAAO,EAAE,MAAM,CAAA;iBAAE,CAAC;gBAC/D,OAAO,EAAE;oBAAE,IAAI,EAAE,QAAQ,CAAC;oBAAC,WAAW,EAAE,MAAM,CAAC;oBAAC,OAAO,EAAE,MAAM,CAAA;iBAAE,CAAC;aACnE,CAAC;SACH,CAAC;KACH,CAAC;CACH,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE;QAAE,kBAAkB,EAAE;YAAE,MAAM,EAAE,eAAe,CAAA;SAAE,CAAA;KAAE,CAAC;CAC9D,CAAC;AAEF,UAAU,sBAAsB;IAC9B;;MAEE;IACF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;MAEE;IACF,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;EAEE;AACF,iBAAS,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,iBAAiB,CAwBvG;AAYD;;;;;;;;;;;;;;;;GAgBG;AACH,iBAAS,cAAc,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAazH;AAED,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,CAAC;AAC7C,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,sBAAsB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var f=Object.defineProperty;var n=(e,t)=>f(e,"name",{value:t,configurable:!0});import{CATALOG as i}from"@rexezuge/errors";import{INTERNAL_SERVER_MESSAGE as c}from"./ErrorMapper.js";function l(e,t={}){return{description:e,content:{"application/json":{schema:{type:"object",properties:{Exception:{type:"object",properties:{Type:{type:"string",description:"Stable machine-readable error type.",example:t.type??"BadRequest"},Message:{type:"string",description:"Human-readable detail about the error.",example:t.message??i.BadRequest.defaultMessage}}}}}}}}}n(l,"exceptionResponse");function m(e){for(const[t,s]of Object.entries(i))if(s.status===e)return{type:t,defaultMessage:s.defaultMessage,expose:s.expose};return null}n(m,"catalogEntry");function d(e){const t=Array.isArray(e)?e.map(r=>[r,null]):Object.entries(e).map(([r,o])=>[Number(r),o]),s={};for(const[r,o]of t){const a=m(r),u=a?.type??"InternalServerError",p=r>=500||a?.expose===!1?c:a?.defaultMessage??c;s[String(r)]=l(o??p,{type:u,message:p})}return s}n(d,"errorResponses");export{d as errorResponses,l as exceptionResponse};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/openApiErrors.ts"],
4
+ "sourcesContent": ["/**\n * OpenAPI descriptions of the `{Exception:{Type,Message}}` envelope, for a\n * chanfana route's `responses:`.\n *\n * Converged from AWS-AccessBridge's `packages/shared/src/schema/exceptionResponses.ts`,\n * which replaced 170 hand-copied literals across 46 endpoint files. Plain JSON\n * Schema objects, so this module stays framework-free and the root barrel can\n * carry it.\n *\n * Two changes from the source:\n *\n * - The example `Type` is the **catalog** name the server actually emits\n * (`BadRequest`, not `BadRequestError`). AWS's examples named the class, so\n * `/docs` documented a value no response ever carried.\n * - A 5xx example is always the masked message — the only one a 5xx carries.\n *\n * Both are `type` aliases rather than interfaces, deliberately: chanfana's\n * `SchemaObject` carries an `[x-<string>]` index signature, and only a type\n * alias is assignable to one.\n */\nimport { CATALOG } from '@rexezuge/errors';\nimport type { HttpErrorType } from '@rexezuge/errors';\nimport { INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\n\ntype ExceptionSchema = {\n type: 'object';\n properties: {\n Exception: {\n type: 'object';\n properties: {\n Type: { type: 'string'; description: string; example: string };\n Message: { type: 'string'; description: string; example: string };\n };\n };\n };\n};\n\ntype ExceptionResponse = {\n description: string;\n content: { 'application/json': { schema: ExceptionSchema } };\n};\n\ninterface ExceptionSchemaOptions {\n /**\n The `Type` example. Defaults to the catalog name for the status.\n */\n type?: string;\n /**\n The `Message` example. Should say what actually goes wrong on this route.\n */\n message?: string;\n}\n\n/**\nOne `responses` entry for the envelope.\n*/\nfunction exceptionResponse(description: string, options: ExceptionSchemaOptions = {}): ExceptionResponse {\n return {\n description,\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: {\n Exception: {\n type: 'object',\n properties: {\n Type: { type: 'string', description: 'Stable machine-readable error type.', example: options.type ?? 'BadRequest' },\n Message: {\n type: 'string',\n description: 'Human-readable detail about the error.',\n example: options.message ?? CATALOG.BadRequest.defaultMessage,\n },\n },\n },\n },\n },\n },\n },\n };\n}\n\n/**\nThe catalog entry for a status, so a caller names a number and gets its type.\n*/\nfunction catalogEntry(status: number): { type: HttpErrorType; defaultMessage: string; expose: boolean } | null {\n for (const [type, definition] of Object.entries(CATALOG) as [HttpErrorType, (typeof CATALOG)[HttpErrorType]][]) {\n if (definition.status === status) return { type, defaultMessage: definition.defaultMessage, expose: definition.expose };\n }\n return null;\n}\n\n/**\n * A `responses` map for several statuses at once:\n *\n * ```ts\n * schema = {\n * responses: {\n * '200': { description: 'The volume', ...contentJson(Volume) },\n * ...errorResponses({ 400: 'Invalid name', 404: 'No such volume' }),\n * ...errorResponses([401, 500]),\n * },\n * };\n * ```\n *\n * A list uses each catalog default as the description; a record names it. An\n * uncatalogued status is described as `InternalServerError`, because that is\n * what the mapper emits for one.\n */\nfunction errorResponses(statuses: readonly number[] | Readonly<Record<number, string>>): Record<string, ExceptionResponse> {\n const entries: [number, string | null][] = Array.isArray(statuses)\n ? (statuses as readonly number[]).map((status) => [status, null])\n : Object.entries(statuses as Readonly<Record<number, string>>).map(([status, description]) => [Number(status), description]);\n const responses: Record<string, ExceptionResponse> = {};\n for (const [status, description] of entries) {\n const entry = catalogEntry(status);\n const type = entry?.type ?? 'InternalServerError';\n const masked = status >= 500 || entry?.expose === false;\n const message = masked ? INTERNAL_SERVER_MESSAGE : (entry?.defaultMessage ?? INTERNAL_SERVER_MESSAGE);\n responses[String(status)] = exceptionResponse(description ?? message, { type, message });\n }\n return responses;\n}\n\nexport { errorResponses, exceptionResponse };\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions };\n"],
5
+ "mappings": "+EAoBA,OAAS,WAAAA,MAAe,mBAExB,OAAS,2BAAAC,MAA+B,mBAkCxC,SAASC,EAAkBC,EAAqBC,EAAkC,CAAA,EAAE,CAClF,MAAO,CACL,YAAAD,EACA,QAAS,CACP,mBAAoB,CAClB,OAAQ,CACN,KAAM,SACN,WAAY,CACV,UAAW,CACT,KAAM,SACN,WAAY,CACV,KAAM,CAAE,KAAM,SAAU,YAAa,sCAAuC,QAASC,EAAQ,MAAQ,YAAY,EACjH,QAAS,CACP,KAAM,SACN,YAAa,yCACb,QAASA,EAAQ,SAAWJ,EAAQ,WAAW,sBASjE,CAxBSK,EAAAH,EAAA,qBA6BT,SAASI,EAAaC,EAAc,CAClC,SAAW,CAACC,EAAMC,CAAU,IAAK,OAAO,QAAQT,CAAO,EACrD,GAAIS,EAAW,SAAWF,EAAQ,MAAO,CAAE,KAAAC,EAAM,eAAgBC,EAAW,eAAgB,OAAQA,EAAW,MAAM,EAEvH,OAAO,IACT,CALSJ,EAAAC,EAAA,gBAwBT,SAASI,EAAeC,EAA8D,CACpF,MAAMC,EAAqC,MAAM,QAAQD,CAAQ,EAC5DA,EAA+B,IAAKJ,GAAW,CAACA,EAAQ,IAAI,CAAC,EAC9D,OAAO,QAAQI,CAA4C,EAAE,IAAI,CAAC,CAACJ,EAAQJ,CAAW,IAAM,CAAC,OAAOI,CAAM,EAAGJ,CAAW,CAAC,EACvHU,EAA+C,CAAA,EACrD,SAAW,CAACN,EAAQJ,CAAW,IAAKS,EAAS,CAC3C,MAAME,EAAQR,EAAaC,CAAM,EAC3BC,EAAOM,GAAO,MAAQ,sBAEtBC,EADSR,GAAU,KAAOO,GAAO,SAAW,GACzBb,EAA2Ba,GAAO,gBAAkBb,EAC7EY,EAAU,OAAON,CAAM,CAAC,EAAIL,EAAkBC,GAAeY,EAAS,CAAE,KAAAP,EAAM,QAAAO,CAAO,CAAE,CACzF,CACA,OAAOF,CACT,CAbSR,EAAAK,EAAA",
6
+ "names": ["CATALOG", "INTERNAL_SERVER_MESSAGE", "exceptionResponse", "description", "options", "__name", "catalogEntry", "status", "type", "definition", "errorResponses", "statuses", "entries", "responses", "entry", "message"]
7
+ }
@@ -0,0 +1,52 @@
1
+ import type { ServiceError } from '@rexezuge/errors';
2
+ /**
3
+ The methods a family API answers; anything else is a 405 before routing.
4
+ */
5
+ declare const DEFAULT_ALLOWED_METHODS: readonly string[];
6
+ /**
7
+ One MiB — the ceiling every converged route base used for a JSON body.
8
+ */
9
+ declare const DEFAULT_MAX_BODY_BYTES = 1048576;
10
+ interface OriginGuardOptions {
11
+ /**
12
+ * Origins trusted in addition to the request's own (a Pages origin, a custom
13
+ * domain). Entries are normalised through `URL`; an unparseable one is dropped.
14
+ */
15
+ allowedOrigins?: readonly string[];
16
+ /**
17
+ * Admit a mutation that carries neither `Origin` nor `Referer`. Off by default:
18
+ * see the file header. Turn it on only for a surface that also serves
19
+ * non-browser callers with a non-cookie credential.
20
+ */
21
+ allowMissingOrigin?: boolean;
22
+ }
23
+ declare function isMutatingMethod(method: string): boolean;
24
+ /**
25
+ The origin a request claims: `Origin`, else the `Referer`'s origin, else `null`.
26
+ */
27
+ declare function requestOrigin(request: Request): string | null;
28
+ /**
29
+ * The CSRF guard for a cookie-authenticated surface. Safe methods pass; a
30
+ * mutation passes only when it is not declared cross-site and its origin is
31
+ * allow-listed.
32
+ */
33
+ declare function checkOrigin(request: Request, options?: OriginGuardOptions): ServiceError | null;
34
+ /**
35
+ A method outside the allow-list is a 405, before any route or auth runs.
36
+ */
37
+ declare function checkMethod(method: string, allowed?: readonly string[]): ServiceError | null;
38
+ /**
39
+ * A mutating request with a body must declare one of `allowed` (default
40
+ * `application/json`). `text/plain` and form encodings are what a cross-site
41
+ * form can send, so refusing them also closes content-type confusion.
42
+ */
43
+ declare function checkContentType(request: Request, allowed?: readonly string[]): ServiceError | null;
44
+ /**
45
+ * A declared `Content-Length` over the ceiling is a 413 before the body is read.
46
+ * This is the cheap half; the `/hono` middleware also caps the stream, because a
47
+ * chunked request declares nothing.
48
+ */
49
+ declare function checkContentLength(request: Request, maxBytes?: number): ServiceError | null;
50
+ export { checkContentLength, checkContentType, checkMethod, checkOrigin, isMutatingMethod, requestOrigin, DEFAULT_ALLOWED_METHODS, DEFAULT_MAX_BODY_BYTES, };
51
+ export type { OriginGuardOptions };
52
+ //# sourceMappingURL=requestGuards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestGuards.d.ts","sourceRoot":"","sources":["../src/requestGuards.ts"],"names":[],"mappings":"AA6BA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAIrD;;EAEE;AACF,QAAA,MAAM,uBAAuB,EAAE,SAAS,MAAM,EAAiE,CAAC;AAEhH;;EAEE;AACF,QAAA,MAAM,sBAAsB,UAAY,CAAC;AAIzC,UAAU,kBAAkB;IAC1B;;;OAGG;IACH,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,iBAAS,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAEjD;AAYD;;EAEE;AACF,iBAAS,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAEtD;AAED;;;;GAIG;AACH,iBAAS,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,kBAAuB,GAAG,YAAY,GAAG,IAAI,CAqB5F;AAED;;EAEE;AACF,iBAAS,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,SAAS,MAAM,EAA4B,GAAG,YAAY,GAAG,IAAI,CAG9G;AAYD;;;;GAIG;AACH,iBAAS,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,SAAS,MAAM,EAAyB,GAAG,YAAY,GAAG,IAAI,CAIlH;AAED;;;;GAIG;AACH,iBAAS,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,GAAE,MAA+B,GAAG,YAAY,GAAG,IAAI,CAK5G;AAED,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,CAAC;AACF,YAAY,EAAE,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var p=Object.defineProperty;var o=(n,e)=>p(n,"name",{value:e,configurable:!0});import{ForbiddenError as c,MethodNotAllowedError as m,PayloadTooLargeError as w,UnsupportedMediaTypeError as T}from"@rexezuge/errors";const O=new Set(["GET","HEAD","OPTIONS"]),h=["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"],f=1048576,s="Cross-origin request rejected.";function u(n){return!O.has(n.toUpperCase())}o(u,"isMutatingMethod");function i(n){const e=n?.trim()??"";if(e==="")return null;try{return new URL(e).origin}catch{return null}}o(i,"originOf");function g(n){return i(n.headers.get("origin"))??i(n.headers.get("referer"))}o(g,"requestOrigin");function S(n,e={}){if(!u(n.method))return null;const t=n.headers.get("sec-fetch-site")?.trim().toLowerCase();if(t!==void 0&&t!=="same-origin"&&t!=="none")return new c(s);const r=g(n);if(r===null)return e.allowMissingOrigin?null:new c(s);const l=new Set,a=i(n.url);a!==null&&l.add(a);for(const E of e.allowedOrigins??[]){const d=i(E);d!==null&&l.add(d)}return l.has(r)?null:new c(s)}o(S,"checkOrigin");function C(n,e=h){const t=n.toUpperCase();return e.some(r=>r.toUpperCase()===t)?null:new m}o(C,"checkMethod");function L(n){const e=n.headers.get("content-length");return e===null||e.trim()!=="0"}o(L,"hasBody");function A(n,e=["application/json"]){if(!u(n.method)||n.method.toUpperCase()==="DELETE"||!L(n))return null;const t=(n.headers.get("content-type")??"").split(";",1)[0]?.trim().toLowerCase()??"";return e.some(r=>r.toLowerCase()===t)?null:new T}o(A,"checkContentType");function D(n,e=f){const t=n.headers.get("content-length");if(t===null)return null;const r=Number(t.trim());return Number.isFinite(r)&&r>e?new w:null}o(D,"checkContentLength");export{h as DEFAULT_ALLOWED_METHODS,f as DEFAULT_MAX_BODY_BYTES,D as checkContentLength,A as checkContentType,C as checkMethod,S as checkOrigin,u as isMutatingMethod,g as requestOrigin};