@rexezuge/http 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -260,7 +260,7 @@ createApiApp<Env>({
260
260
 
261
261
  ### Custom verbs, per-path limits and excludes (a WebDAV worker)
262
262
 
263
- `routes(app)` gets chanfana's router, which registers one method per route and rejects `on([…], …)`. The second argument is the raw Hono instance, mounted at the same position, so every guard, limiter, auth step and the error boundary still apply (the routes are just not in the OpenAPI document). The method guard still decides which verbs exist: list the custom ones in `hardening.methods`.
263
+ `routes(app)` gets chanfana's router, which registers one method per route and rejects `on([…], …)`. The second argument is the raw Hono instance, mounted at the same position, so every guard, limiter, auth step and the error boundary still apply (the routes are just not in the OpenAPI document). The method guard still decides which verbs exist: list the custom ones in `hardening.methods`. A request outside the list is a `405` that carries `Allow: <the configured methods>` (RFC 9110); the header comes from `mapError`, so `FamilyRoute` and `errorResponseFromUnknown` answer it too (`MethodGuardError.allow`). An unregistered method on a registered path is a `404` envelope, not a `405`, because Hono does not distinguish them.
264
264
 
265
265
  Everything that loosens a guard is narrow, explicit and visible: a ceiling per path, or an `exclude` list. A matcher is the same type `sensitivePaths` takes (`string` exact, a trailing `/` or `/*` prefix, `RegExp`, predicate). There is no switch that turns a guard off. Every `hardening.*.exclude` pattern is logged once at startup (a static message listing the patterns) so the loosening shows in the logs.
266
266
 
@@ -1 +1 @@
1
- {"version":3,"file":"ErrorMapper.d.ts","sourceRoot":"","sources":["../src/ErrorMapper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,OAAO,EAAiB,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE/D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAG9C;;;;GAIG;AACH,KAAK,kBAAkB,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK;IAAE,QAAQ,CAAC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,EAAE;QAAE,SAAS,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IACvD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC;;MAEE;IACF,KAAK,EAAE,YAAY,CAAC;CACrB;AAED,QAAA,MAAM,uBAAuB,sFAAsF,CAAC;AAEpH;;;;;;GAMG;AACH,iBAAS,SAAS,CAAC,KAAK,EAAE,YAAY,GAAG;IAAE,SAAS,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAOxF;AA2BD;;;;;;GAMG;AACH,iBAAS,QAAQ,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAQ/E;AAED;;;;;;;;;GASG;AACH,iBAAS,wBAAwB,CAC/B,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,QAAQ,EACnF,OAAO,GAAE,kBAAuB,GAC/B,QAAQ,CAKV;AAED;;;;GAIG;AACH,QAAA,MAAM,eAAe,EAAE,OAAO,wBAAmD,CAAC;AAElF,OAAO,EAAE,SAAS,EAAE,wBAAwB,EAAE,QAAQ,EAAE,eAAe,EAAE,uBAAuB,EAAE,CAAC;AACnG,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,CAAC"}
@@ -1 +1 @@
1
- var m=Object.defineProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});import{DatabaseError as p}from"@rexezuge/errors";import{SYSTEM_CLOCK as y}from"@rexezuge/shared";import{catalogMessageFor as S,MappedServiceError as c,toServiceError as d}from"./errorClassification.js";const l="The server encountered an internal error and was unable to complete your request.";function u(e){return{Exception:{Type:e.type,Message:e.expose?e.message:l}}}o(u,"errorBody");function b(e,t,n){const r=n.dailyLimit?.(e)??null;if(r!==null){const a=(n.clock??y).now();return{error:new c(503,"ServiceUnavailable",S("ServiceUnavailable"),{cause:e,expose:!0}),retryAfter:Math.max(1,Math.ceil((r.resetsAt-a)/1e3))}}return t instanceof p&&t.retryable?{error:new c(503,"ServiceUnavailable",t.message,{cause:e}),retryAfter:null}:{error:t,retryAfter:null}}o(b,"refine");function i(e,t={}){const n=b(e,d(e),t),r=n.error,a=r.status||t.fallbackStatus||500,s={...t.headers?.(a,r)};return n.retryAfter!==null&&(s["Retry-After"]=String(n.retryAfter)),{status:a,body:u(r),headers:s,error:r}}o(i,"mapError");function f(e,t,n={}){const r=i(e,n),a=n.toResponse?.(r.error,r.status);return a||t(r.body,r.status,r.headers)}o(f,"errorResponseFromUnknown");const E=f;import{toServiceError as w}from"./errorClassification.js";export{l as INTERNAL_SERVER_MESSAGE,u as errorBody,f as errorResponseFromUnknown,i as mapError,E as toErrorResponse,w as toServiceError};
1
+ var m=Object.defineProperty;var a=(r,t)=>m(r,"name",{value:t,configurable:!0});import{DatabaseError as p}from"@rexezuge/errors";import{SYSTEM_CLOCK as d}from"@rexezuge/shared";import{catalogMessageFor as y,MappedServiceError as l,toServiceError as S}from"./errorClassification.js";import{MethodGuardError as E}from"./requestGuards.js";const c="The server encountered an internal error and was unable to complete your request.";function u(r){return{Exception:{Type:r.type,Message:r.expose?r.message:c}}}a(u,"errorBody");function b(r,t,n){const e=n.dailyLimit?.(r)??null;if(e!==null){const o=(n.clock??d).now();return{error:new l(503,"ServiceUnavailable",y("ServiceUnavailable"),{cause:r,expose:!0}),retryAfter:Math.max(1,Math.ceil((e.resetsAt-o)/1e3))}}return t instanceof p&&t.retryable?{error:new l(503,"ServiceUnavailable",t.message,{cause:r}),retryAfter:null}:{error:t,retryAfter:null}}a(b,"refine");function i(r,t={}){const n=b(r,S(r),t),e=n.error,o=e.status||t.fallbackStatus||500,s={...t.headers?.(o,e)};return n.retryAfter!==null&&(s["Retry-After"]=String(n.retryAfter)),e instanceof E&&(s.Allow=e.allow),{status:o,body:u(e),headers:s,error:e}}a(i,"mapError");function f(r,t,n={}){const e=i(r,n),o=n.toResponse?.(e.error,e.status);return o||t(e.body,e.status,e.headers)}a(f,"errorResponseFromUnknown");const v=f;import{toServiceError as T}from"./errorClassification.js";export{c as INTERNAL_SERVER_MESSAGE,u as errorBody,f as errorResponseFromUnknown,i as mapError,v as toErrorResponse,T as toServiceError};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/ErrorMapper.ts"],
4
- "sourcesContent": ["/**\n * Error → response mapping at the HTTP boundary.\n *\n * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and\n * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the\n * only one that states **why** it splits: by surface, not by convenience.\n *\n * ## One surface, one dialect\n *\n * The `{Exception:{Type,Message}}` envelope is the family's established wire\n * format and the one the SPAs decode. A protocol surface with its own envelope —\n * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client\n * parsing that surface has no way to interpret anything else: a 401 carrying an\n * unrecognized body renders as \"server error\" and the client retries.\n *\n * So the split is by surface, and a caller declares which one it is on rather\n * than each handler deciding for itself. A surface that has its own dialect\n * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the\n * canonical envelope.\n *\n * ## A 5xx never carries its own message\n *\n * `expose` in `@rexezuge/errors` already decides this, and this mapper is where\n * that decision becomes bytes. A D1 error names tables and columns; an upstream\n * body can carry a stack. The substitution lives here once rather than in every\n * boundary mapper.\n *\n * ## A 404 is a 404\n *\n * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code\n * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not\n * second-guess the taxonomy into something a client can misread.\n *\n * ## What else converged here\n *\n * Zod and chanfana validation failures (a 400 naming the first issue), raw `D1_`\n * errors (a masked `DatabaseError`), a retryable `DatabaseError` (503) and a spent\n * D1 daily allowance (503 + `Retry-After`, through the {@link DailyLimitDetector}\n * port) — the union of Edge-Git, Edge-Sonic, Durable-DAV-Router and Mail-Meow's\n * boundary mappers. See `errorClassification.ts`.\n */\nimport { DatabaseError, ServiceError } from '@rexezuge/errors';\nimport { SYSTEM_CLOCK } from '@rexezuge/shared';\nimport type { Clock } from '@rexezuge/shared';\nimport { catalogMessageFor, MappedServiceError, toServiceError } from './errorClassification.ts';\n\n/**\n * A D1 daily-allowance detector, structurally: `@rexezuge/d1`'s\n * `isD1DailyLimitError` satisfies it. A port rather than an import because\n * `http` may only depend on `errors` and `shared`.\n */\ntype DailyLimitDetector = (error: unknown) => { readonly resetsAt: number } | null;\n\ninterface ErrorMapperOptions {\n /**\n * The HTTP status when the error carries none it should publish. Defaults to\n * 500 — a non-`ServiceError` that reached the boundary is an unknown failure.\n */\n fallbackStatus?: number;\n /**\n A surface-specific dialect. Returns `undefined` to fall through to the default.\n */\n toResponse?(error: ServiceError, status: number): Response | undefined;\n /**\n Adds headers to the response (e.g. `Retry-After` on a 429).\n */\n headers?(status: number, error: ServiceError): Record<string, string>;\n /**\n * Recognise a spent D1 daily allowance (pass `isD1DailyLimitError` from\n * `@rexezuge/d1`). Such a failure answers `503 ServiceUnavailable` with a\n * `Retry-After` until the reset, so a client does not retry straight into it.\n */\n dailyLimit?: DailyLimitDetector;\n /**\n The clock `Retry-After` is computed against. Defaults to the system clock.\n */\n clock?: Clock;\n}\n\n/**\nWhat a caught value becomes on the wire, before any framework writes it.\n*/\ninterface MappedError {\n status: number;\n body: { Exception: { Type: string; Message: string } };\n headers: Record<string, string>;\n /**\n The taxonomy error the body was built from — for logging its `type`, never its message.\n */\n error: ServiceError;\n}\n\nconst INTERNAL_SERVER_MESSAGE = 'The server encountered an internal error and was unable to complete your request.';\n\n/**\n * The canonical wire body.\n *\n * A 4xx keeps its message; a 5xx is masked. This is the `{Exception:{…}}`\n * envelope every SPA in the family decodes, and the one a surface with no\n * dialect of its own should answer in.\n */\nfunction errorBody(error: ServiceError): { Exception: { Type: string; Message: string } } {\n return {\n Exception: {\n Type: error.type,\n Message: error.expose ? error.message : INTERNAL_SERVER_MESSAGE,\n },\n };\n}\n\n/**\n * A transient D1 failure is a 503, not a 500: `retryable` already says a retry\n * is meaningful, and a 500 tells a client the opposite. A spent daily allowance\n * is a 503 with a known wait.\n */\nfunction refine(\n error: unknown,\n serviceError: ServiceError,\n options: ErrorMapperOptions,\n): { error: ServiceError; retryAfter: number | null } {\n const limit = options.dailyLimit?.(error) ?? null;\n if (limit !== null) {\n const now = (options.clock ?? SYSTEM_CLOCK).now();\n const unavailable = new MappedServiceError(503, 'ServiceUnavailable', catalogMessageFor('ServiceUnavailable'), {\n cause: error,\n expose: true,\n });\n return { error: unavailable, retryAfter: Math.max(1, Math.ceil((limit.resetsAt - now) / 1000)) };\n }\n if (serviceError instanceof DatabaseError && serviceError.retryable) {\n return { error: new MappedServiceError(503, 'ServiceUnavailable', serviceError.message, { cause: error }), retryAfter: null };\n }\n return { error: serviceError, retryAfter: null };\n}\n\n/**\n * Map a caught value to its status, envelope and headers, framework-free.\n *\n * The one decision table behind `errorResponseFromUnknown`, the `/hono`\n * `onError` handler and `FamilyRoute`, so a failure answers identically\n * whichever layer caught it.\n */\nfunction mapError(error: unknown, options: ErrorMapperOptions = {}): MappedError {\n const refined = refine(error, toServiceError(error), options);\n const serviceError = refined.error;\n const status = serviceError.status || options.fallbackStatus || 500;\n const headers = { ...options.headers?.(status, serviceError) };\n if (refined.retryAfter !== null) headers['Retry-After'] = String(refined.retryAfter);\n return { status, body: errorBody(serviceError), headers, error: serviceError };\n}\n\n/**\n * Map a caught value to a `Response`.\n *\n * The `json`-shaped callback is injected rather than imported from Hono so this\n * module stays free of the `Context` generic: a caller passes its own `c.json`,\n * which is what makes it usable from a bare-`Request` dispatcher as well.\n *\n * Named for what it accepts: `ServiceError#toErrorResponse()` in\n * `@rexezuge/errors` is a different function (a payload, not a `Response`).\n */\nfunction errorResponseFromUnknown(\n error: unknown,\n json: (body: unknown, status: number, headers?: Record<string, string>) => Response,\n options: ErrorMapperOptions = {},\n): Response {\n const mapped = mapError(error, options);\n const custom = options.toResponse?.(mapped.error, mapped.status);\n if (custom) return custom;\n return json(mapped.body, mapped.status, mapped.headers);\n}\n\n/**\n * @deprecated Renamed to {@link errorResponseFromUnknown}: the old name collides\n * with `ServiceError#toErrorResponse` in `@rexezuge/errors`. Removed in 2.0; the\n * kit codemod rewrites imports from `@rexezuge/http`.\n */\nconst toErrorResponse: typeof errorResponseFromUnknown = errorResponseFromUnknown;\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, INTERNAL_SERVER_MESSAGE };\nexport { toServiceError } from './errorClassification.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError };\n"],
5
- "mappings": "+EAyCA,OAAS,iBAAAA,MAAmC,mBAC5C,OAAS,gBAAAC,MAAoB,mBAE7B,OAAS,qBAAAC,EAAmB,sBAAAC,EAAoB,kBAAAC,MAAsB,2BAgDtE,MAAMC,EAA0B,oFAShC,SAASC,EAAUC,EAAmB,CACpC,MAAO,CACL,UAAW,CACT,KAAMA,EAAM,KACZ,QAASA,EAAM,OAASA,EAAM,QAAUF,GAG9C,CAPSG,EAAAF,EAAA,aAcT,SAASG,EACPF,EACAG,EACAC,EAA2B,CAE3B,MAAMC,EAAQD,EAAQ,aAAaJ,CAAK,GAAK,KAC7C,GAAIK,IAAU,KAAM,CAClB,MAAMC,GAAOF,EAAQ,OAASV,GAAc,IAAG,EAK/C,MAAO,CAAE,MAJW,IAAIE,EAAmB,IAAK,qBAAsBD,EAAkB,oBAAoB,EAAG,CAC7G,MAAOK,EACP,OAAQ,GACT,EAC4B,WAAY,KAAK,IAAI,EAAG,KAAK,MAAMK,EAAM,SAAWC,GAAO,GAAI,CAAC,CAAC,CAChG,CACA,OAAIH,aAAwBV,GAAiBU,EAAa,UACjD,CAAE,MAAO,IAAIP,EAAmB,IAAK,qBAAsBO,EAAa,QAAS,CAAE,MAAOH,CAAK,CAAE,EAAG,WAAY,IAAI,EAEtH,CAAE,MAAOG,EAAc,WAAY,IAAI,CAChD,CAlBSF,EAAAC,EAAA,UA2BT,SAASK,EAASP,EAAgBI,EAA8B,CAAA,EAAE,CAChE,MAAMI,EAAUN,EAAOF,EAAOH,EAAeG,CAAK,EAAGI,CAAO,EACtDD,EAAeK,EAAQ,MACvBC,EAASN,EAAa,QAAUC,EAAQ,gBAAkB,IAC1DM,EAAU,CAAE,GAAGN,EAAQ,UAAUK,EAAQN,CAAY,CAAC,EAC5D,OAAIK,EAAQ,aAAe,OAAME,EAAQ,aAAa,EAAI,OAAOF,EAAQ,UAAU,GAC5E,CAAE,OAAAC,EAAQ,KAAMV,EAAUI,CAAY,EAAG,QAAAO,EAAS,MAAOP,CAAY,CAC9E,CAPSF,EAAAM,EAAA,YAmBT,SAASI,EACPX,EACAY,EACAR,EAA8B,CAAA,EAAE,CAEhC,MAAMS,EAASN,EAASP,EAAOI,CAAO,EAChCU,EAASV,EAAQ,aAAaS,EAAO,MAAOA,EAAO,MAAM,EAC/D,OAAIC,GACGF,EAAKC,EAAO,KAAMA,EAAO,OAAQA,EAAO,OAAO,CACxD,CATSZ,EAAAU,EAAA,4BAgBT,MAAMI,EAAmDJ,EAGzD,OAAS,kBAAAd,MAAsB",
6
- "names": ["DatabaseError", "SYSTEM_CLOCK", "catalogMessageFor", "MappedServiceError", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorBody", "error", "__name", "refine", "serviceError", "options", "limit", "now", "mapError", "refined", "status", "headers", "errorResponseFromUnknown", "json", "mapped", "custom", "toErrorResponse"]
4
+ "sourcesContent": ["/**\n * Error → response mapping at the HTTP boundary.\n *\n * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and\n * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the\n * only one that states **why** it splits: by surface, not by convenience.\n *\n * ## One surface, one dialect\n *\n * The `{Exception:{Type,Message}}` envelope is the family's established wire\n * format and the one the SPAs decode. A protocol surface with its own envelope —\n * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client\n * parsing that surface has no way to interpret anything else: a 401 carrying an\n * unrecognized body renders as \"server error\" and the client retries.\n *\n * So the split is by surface, and a caller declares which one it is on rather\n * than each handler deciding for itself. A surface that has its own dialect\n * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the\n * canonical envelope.\n *\n * ## A 5xx never carries its own message\n *\n * `expose` in `@rexezuge/errors` already decides this, and this mapper is where\n * that decision becomes bytes. A D1 error names tables and columns; an upstream\n * body can carry a stack. The substitution lives here once rather than in every\n * boundary mapper.\n *\n * ## A 404 is a 404\n *\n * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code\n * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not\n * second-guess the taxonomy into something a client can misread.\n *\n * ## What else converged here\n *\n * Zod and chanfana validation failures (a 400 naming the first issue), raw `D1_`\n * errors (a masked `DatabaseError`), a retryable `DatabaseError` (503) and a spent\n * D1 daily allowance (503 + `Retry-After`, through the {@link DailyLimitDetector}\n * port) — the union of Edge-Git, Edge-Sonic, Durable-DAV-Router and Mail-Meow's\n * boundary mappers. See `errorClassification.ts`.\n */\nimport { DatabaseError, ServiceError } from '@rexezuge/errors';\nimport { SYSTEM_CLOCK } from '@rexezuge/shared';\nimport type { Clock } from '@rexezuge/shared';\nimport { catalogMessageFor, MappedServiceError, toServiceError } from './errorClassification.ts';\nimport { MethodGuardError } from './requestGuards.ts';\n\n/**\n * A D1 daily-allowance detector, structurally: `@rexezuge/d1`'s\n * `isD1DailyLimitError` satisfies it. A port rather than an import because\n * `http` may only depend on `errors` and `shared`.\n */\ntype DailyLimitDetector = (error: unknown) => { readonly resetsAt: number } | null;\n\ninterface ErrorMapperOptions {\n /**\n * The HTTP status when the error carries none it should publish. Defaults to\n * 500 — a non-`ServiceError` that reached the boundary is an unknown failure.\n */\n fallbackStatus?: number;\n /**\n A surface-specific dialect. Returns `undefined` to fall through to the default.\n */\n toResponse?(error: ServiceError, status: number): Response | undefined;\n /**\n Adds headers to the response (e.g. `Retry-After` on a 429).\n */\n headers?(status: number, error: ServiceError): Record<string, string>;\n /**\n * Recognise a spent D1 daily allowance (pass `isD1DailyLimitError` from\n * `@rexezuge/d1`). Such a failure answers `503 ServiceUnavailable` with a\n * `Retry-After` until the reset, so a client does not retry straight into it.\n */\n dailyLimit?: DailyLimitDetector;\n /**\n The clock `Retry-After` is computed against. Defaults to the system clock.\n */\n clock?: Clock;\n}\n\n/**\nWhat a caught value becomes on the wire, before any framework writes it.\n*/\ninterface MappedError {\n status: number;\n body: { Exception: { Type: string; Message: string } };\n headers: Record<string, string>;\n /**\n The taxonomy error the body was built from — for logging its `type`, never its message.\n */\n error: ServiceError;\n}\n\nconst INTERNAL_SERVER_MESSAGE = 'The server encountered an internal error and was unable to complete your request.';\n\n/**\n * The canonical wire body.\n *\n * A 4xx keeps its message; a 5xx is masked. This is the `{Exception:{…}}`\n * envelope every SPA in the family decodes, and the one a surface with no\n * dialect of its own should answer in.\n */\nfunction errorBody(error: ServiceError): { Exception: { Type: string; Message: string } } {\n return {\n Exception: {\n Type: error.type,\n Message: error.expose ? error.message : INTERNAL_SERVER_MESSAGE,\n },\n };\n}\n\n/**\n * A transient D1 failure is a 503, not a 500: `retryable` already says a retry\n * is meaningful, and a 500 tells a client the opposite. A spent daily allowance\n * is a 503 with a known wait.\n */\nfunction refine(\n error: unknown,\n serviceError: ServiceError,\n options: ErrorMapperOptions,\n): { error: ServiceError; retryAfter: number | null } {\n const limit = options.dailyLimit?.(error) ?? null;\n if (limit !== null) {\n const now = (options.clock ?? SYSTEM_CLOCK).now();\n const unavailable = new MappedServiceError(503, 'ServiceUnavailable', catalogMessageFor('ServiceUnavailable'), {\n cause: error,\n expose: true,\n });\n return { error: unavailable, retryAfter: Math.max(1, Math.ceil((limit.resetsAt - now) / 1000)) };\n }\n if (serviceError instanceof DatabaseError && serviceError.retryable) {\n return { error: new MappedServiceError(503, 'ServiceUnavailable', serviceError.message, { cause: error }), retryAfter: null };\n }\n return { error: serviceError, retryAfter: null };\n}\n\n/**\n * Map a caught value to its status, envelope and headers, framework-free.\n *\n * The one decision table behind `errorResponseFromUnknown`, the `/hono`\n * `onError` handler and `FamilyRoute`, so a failure answers identically\n * whichever layer caught it.\n */\nfunction mapError(error: unknown, options: ErrorMapperOptions = {}): MappedError {\n const refined = refine(error, toServiceError(error), options);\n const serviceError = refined.error;\n const status = serviceError.status || options.fallbackStatus || 500;\n const headers = { ...options.headers?.(status, serviceError) };\n if (refined.retryAfter !== null) headers['Retry-After'] = String(refined.retryAfter);\n if (serviceError instanceof MethodGuardError) headers['Allow'] = serviceError.allow;\n return { status, body: errorBody(serviceError), headers, error: serviceError };\n}\n\n/**\n * Map a caught value to a `Response`.\n *\n * The `json`-shaped callback is injected rather than imported from Hono so this\n * module stays free of the `Context` generic: a caller passes its own `c.json`,\n * which is what makes it usable from a bare-`Request` dispatcher as well.\n *\n * Named for what it accepts: `ServiceError#toErrorResponse()` in\n * `@rexezuge/errors` is a different function (a payload, not a `Response`).\n */\nfunction errorResponseFromUnknown(\n error: unknown,\n json: (body: unknown, status: number, headers?: Record<string, string>) => Response,\n options: ErrorMapperOptions = {},\n): Response {\n const mapped = mapError(error, options);\n const custom = options.toResponse?.(mapped.error, mapped.status);\n if (custom) return custom;\n return json(mapped.body, mapped.status, mapped.headers);\n}\n\n/**\n * @deprecated Renamed to {@link errorResponseFromUnknown}: the old name collides\n * with `ServiceError#toErrorResponse` in `@rexezuge/errors`. Removed in 2.0; the\n * kit codemod rewrites imports from `@rexezuge/http`.\n */\nconst toErrorResponse: typeof errorResponseFromUnknown = errorResponseFromUnknown;\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, INTERNAL_SERVER_MESSAGE };\nexport { toServiceError } from './errorClassification.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, Mapped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AWP,EAAa,OACvE,CAAE,OAAAM,EAAQ,KAAMV,EAAUI,CAAY,EAAG,QAAAO,EAAS,MAAOP,CAAY,CAC9E,CARSF,EAAAM,EAAA,YAoBT,SAASI,EACPX,EACAY,EACAR,EAA8B,CAAA,EAAE,CAEhC,MAAMS,EAASN,EAASP,EAAOI,CAAO,EAChCU,EAASV,EAAQ,aAAaS,EAAO,MAAOA,EAAO,MAAM,EAC/D,OAAIC,GACGF,EAAKC,EAAO,KAAMA,EAAO,OAAQA,EAAO,OAAO,CACxD,CATSZ,EAAAU,EAAA,4BAgBT,MAAMI,EAAmDJ,EAGzD,OAAS,kBAAAf,MAAsB",
6
+ "names": ["DatabaseError", "SYSTEM_CLOCK", "catalogMessageFor", "MappedServiceError", "toServiceError", "MethodGuardError", "INTERNAL_SERVER_MESSAGE", "errorBody", "error", "__name", "refine", "serviceError", "options", "limit", "now", "mapError", "refined", "status", "headers", "errorResponseFromUnknown", "json", "mapped", "custom", "toErrorResponse"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/hono/contracts.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAiC,MAAM,UAAU,CAAC;AAEhG,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,QAAQ,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAEtH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;GAIG;AACH,KAAK,eAAe,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,CAChG,KAAK,EAAE,mB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,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAClG,QAAQ,EAAE,EAAE,EACZ,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,GACjC,aAAa,CA6Bf;AAID;;;;;;;;GAQG;AACH,iBAAS,gBAAgB,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,iBAAiB,EACvF,GAAG,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EACjB,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,EACrB,QAAQ,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAClC,IAAI,CAaN;AAED,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,CAAC;AACnE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC"}
@@ -1 +1 @@
1
- var h=Object.defineProperty;var i=(e,r)=>h(e,"name",{value:r,configurable:!0});import{contentJson as y}from"chanfana";import{UnauthorizedError as b}from"@rexezuge/errors";import{errorResponses as g}from"../openApiErrors.js";import{FamilyRoute as w}from"./FamilyRoute.js";function l(e){const r={};e.params!==void 0&&(r.params=e.params),e.query!==void 0&&(r.query=e.query),e.body!==void 0&&(r.body=y(e.body));const o=e.response===null?{204:{description:"No Content"}}:{200:{description:e.summary??"OK",...y(e.response)}},a=Object.assign({},...e.errorResponses.map(({status:t,description:u})=>g(u===null?[t]:{[t]:u})));return{...e.summary!==void 0&&{summary:e.summary},...e.description!==void 0&&{description:e.description},...e.tags!==void 0&&{tags:[...e.tags]},request:r,responses:{...o,...a}}}i(l,"schemaFromEndpoint");function d(e,r){const o=l(e),a=e.auth!=="public";class t extends w{static{i(this,"ContractRoute")}schema=o;async handleRequest(f,s){if(a&&!s.get("AuthenticatedUserId"))throw new b;const n=f,c={};e.params!==void 0&&(c.params=n.params),e.query!==void 0&&(c.query=n.query),e.body!==void 0&&(c.body=n.body);const m=await r(c,s);return e.response===null&&!(m instanceof Response)?null:m}}return Object.defineProperty(t,"name",{value:`${e.method} ${e.path}`}),t}i(d,"routeFromEndpoint");function p(e,r,o){const a=Object.keys(r),t=a.filter(s=>typeof o[s]!="function");if(t.length>0)throw new TypeError(`registerContract: no handler for ${t.join(", ")}`);const u=Object.keys(o).filter(s=>!Object.hasOwn(r,s));if(u.length>0)throw new TypeError(`registerContract: ${u.join(", ")} is not in the contract`);const f=e;for(const s of a){const n=r[s],c=o[s];f[n.method.toLowerCase()]?.call(e,n.path,d(n,c))}}i(p,"registerContract");export{p as registerContract,d as routeFromEndpoint,l as schemaFromEndpoint};
1
+ var g=Object.defineProperty;var f=(e,r)=>g(e,"name",{value:r,configurable:!0});import{contentJson as y}from"chanfana";import{UnauthorizedError as b}from"@rexezuge/errors";import{honoPath as w,isTextResponse as l,textMediaType as h}from"@rexezuge/contracts";import{errorResponses as q}from"../openApiErrors.js";import{FamilyRoute as R}from"./FamilyRoute.js";function d(e){const r={};e.params!==void 0&&(r.params=e.params),e.query!==void 0&&(r.query=e.query),e.body!==void 0&&(r.body=y(e.body));const o=e.summary??"OK";let s;e.response===null?s={204:{description:"No Content"}}:l(e.response)?s={200:{description:o,content:{[h(e.response)]:{schema:{type:"string"}}}}}:s={200:{description:o,...y(e.response)}};const n=Object.assign({},...e.errorResponses.map(({status:u,description:c})=>q(c===null?[u]:{[u]:c})));return{...e.summary!==void 0&&{summary:e.summary},...e.description!==void 0&&{description:e.description},...e.tags!==void 0&&{tags:[...e.tags]},request:r,responses:{...s,...n}}}f(d,"schemaFromEndpoint");function p(e,r){const o=d(e),s=e.auth!=="public";class n extends R{static{f(this,"ContractRoute")}schema=o;async handleRequest(c,t){if(s&&!t.get("AuthenticatedUserId"))throw new b;const a=c,i={};e.params!==void 0&&(i.params=a.params),e.query!==void 0&&(i.query=a.query),e.body!==void 0&&(i.body=a.body);const m=await r(i,t);return e.response===null&&!(m instanceof Response)?null:l(e.response)&&typeof m=="string"?new Response(m,{headers:{"Content-Type":`${h(e.response)}; charset=UTF-8`}}):m}}return Object.defineProperty(n,"name",{value:`${e.method} ${e.path}`}),n}f(p,"routeFromEndpoint");function j(e,r,o){const s=Object.keys(r),n=s.filter(t=>typeof o[t]!="function");if(n.length>0)throw new TypeError(`registerContract: no handler for ${n.join(", ")}`);const u=Object.keys(o).filter(t=>!Object.hasOwn(r,t));if(u.length>0)throw new TypeError(`registerContract: ${u.join(", ")} is not in the contract`);const c=e;for(const t of s){const a=r[t],i=o[t];c[a.method.toLowerCase()]?.call(e,w(a.path),p(a,i))}}f(j,"registerContract");export{j as registerContract,p as routeFromEndpoint,d as schemaFromEndpoint};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/hono/contracts.ts"],
4
- "sourcesContent": ["/**\n * The backend half of `@rexezuge/contracts`: an endpoint becomes a chanfana\n * route on the family app.\n *\n * ## Why here, and why `http` depends on `contracts`\n *\n * The adapter needs chanfana (`contentJson`, `OpenAPIRoute`), and the kit's rule\n * is that `hono`/`chanfana` are imported under `packages/http/src/hono/` and\n * nowhere else. So the adapter lives in `/hono`, and `http` takes a dependency on\n * `contracts`, a framework-free package that depends on neither `http` nor\n * `web`. The graph stays acyclic: `errors`/`shared` → `contracts` → `http` →\n * `web`. The other direction (a `/hono` subpath inside `contracts`) would have\n * put a second framework package in the kit.\n *\n * ## Closed\n *\n * - The route's chanfana `schema` is **derived** from the endpoint: request\n * `params`/`query`/`body`, the success response (`200` + the response schema,\n * or `204`), and every documented error as the kit's `{Exception}` envelope\n * (`errorResponses`). There is no second hand-written schema to drift.\n * - The route is a `FamilyRoute`, so validation, result shaping and error\n * mapping are the kit's `@final` `handle()`.\n * - **Fail-closed auth.** An `access`/`apiKey` endpoint answers `401` when no\n * auth middleware set `AuthenticatedUserId`, so forgetting to mount\n * `accessAuth` on a path does not publish an authenticated route.\n * - `registerContract` refuses a missing or an unknown handler at startup.\n *\n * ## Open\n *\n * The handler, the app (`E`, `V`), and `schemaFromEndpoint` for a hand-written\n * `FamilyRoute` subclass that needs `errorMapping()` or a raw `Response`.\n */\nimport { contentJson } from 'chanfana';\nimport type { OpenAPIRoute, OpenAPIRouteSchema, ResponseConfig, ValidatedData } from 'chanfana';\nimport { UnauthorizedError } from '@rexezuge/errors';\nimport type { Contract, ContractEndpoints, Endpoint, EndpointResult, EndpointServerInput } from '@rexezuge/contracts';\nimport { errorResponses } from '../openApiErrors.ts';\nimport type { ApiApp } from './createApiApp.ts';\nimport { FamilyRoute } from './FamilyRoute.ts';\nimport type { MaybePromise, RouteResult } from './FamilyRoute.ts';\nimport type { FamilyContext } from './types.ts';\n\n/**\n * Your implementation of one endpoint. `input` is the validated request (zod\n * output), and the return value (or a promise of it: a handler need not be `async`) is the response schema's input,\n * `null` for a `204` endpoint, or a `Response` you built yourself.\n */\ntype EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (\n input: EndpointServerInput<EP>,\n c: FamilyContext<E, V>,\n) => MaybePromise<RouteResult<EndpointResult<EP>>>;\n\n/**\nOne handler per contract endpoint, by name. A missing key is a compile error.\n*/\ntype ContractHandlers<C extends ContractEndpoints, E extends object = object, V extends object = object> = {\n [K in keyof C]: EndpointHandler<C[K], E, V>;\n};\n\n/**\n * A route class, in the type chanfana's `app.get(path, Route)` accepts. It is\n * constructed once, at registration.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- chanfana's own registration parameter type\ntype EndpointRoute = typeof OpenAPIRoute<any>;\n\n/**\n * The chanfana schema for an endpoint: request, success and error responses.\n */\nfunction schemaFromEndpoint(endpoint: Endpoint): OpenAPIRouteSchema {\n const request: NonNullable<OpenAPIRouteSchema['request']> = {};\n if (endpoint.params !== undefined) request.params = endpoint.params;\n if (endpoint.query !== undefined) request.query = endpoint.query;\n if (endpoint.body !== undefined) request.body = contentJson(endpoint.body);\n\n const success: Record<string, ResponseConfig> =\n endpoint.response === null\n ? { '204': { description: 'No Content' } }\n : { '200': { description: endpoint.summary ?? 'OK', ...contentJson(endpoint.response) } };\n const errors = Object.assign(\n {},\n ...endpoint.errorResponses.map(({ status, description }) =>\n errorResponses(description === null ? [status] : { [status]: description }),\n ),\n ) as ReturnType<typeof errorResponses>;\n\n return {\n ...(endpoint.summary !== undefined && { summary: endpoint.summary }),\n ...(endpoint.description !== undefined && { description: endpoint.description }),\n ...(endpoint.tags !== undefined && { tags: [...endpoint.tags] }),\n request,\n responses: { ...success, ...errors },\n };\n}\n\n/**\n * One endpoint as a route class: `app.get(endpoint.path, routeFromEndpoint(endpoint, handler))`.\n * Prefer `registerContract`, which also checks the method and path for you.\n */\nfunction routeFromEndpoint<EP extends Endpoint, E extends object = object, V extends object = object>(\n endpoint: EP,\n handler: EndpointHandler<EP, E, V>,\n): EndpointRoute {\n const schema = schemaFromEndpoint(endpoint);\n const authenticated = endpoint.auth !== 'public';\n\n class ContractRoute extends FamilyRoute<OpenAPIRouteSchema, E, V> {\n public override schema = schema;\n\n protected async handleRequest(input: ValidatedData<OpenAPIRouteSchema>, c: FamilyContext<E, V>): Promise<RouteResult<unknown>> {\n // Read loosely on purpose: the variable is typed as always present, and\n // this is the check that it really is.\n if (authenticated && !(c.get('AuthenticatedUserId') as string | undefined)) throw new UnauthorizedError();\n const validated = input as { params?: unknown; query?: unknown; body?: unknown };\n const slots: Record<string, unknown> = {};\n if (endpoint.params !== undefined) slots.params = validated.params;\n if (endpoint.query !== undefined) slots.query = validated.query;\n if (endpoint.body !== undefined) slots.body = validated.body;\n const result = await handler(slots as EndpointServerInput<EP>, c);\n // A 204 endpoint answers 204 whatever the handler returned, unless it\n // built its own Response.\n if (endpoint.response === null && !(result instanceof Response)) return null;\n return result;\n }\n }\n Object.defineProperty(ContractRoute, 'name', { value: `${endpoint.method} ${endpoint.path}` });\n return ContractRoute;\n}\n\ntype Register = (path: string, route: unknown) => unknown;\n\n/**\n * Register every endpoint of a contract. `handlers` must name exactly the\n * contract's endpoints: the type requires every key, and a missing or an extra\n * key also throws a `TypeError` here, at startup.\n *\n * ```ts\n * createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, { getItem, listItems, renameItem }) });\n * ```\n */\nfunction registerContract<E extends object, V extends object, C extends ContractEndpoints>(\n app: ApiApp<E, V>,\n contract: Contract<C>,\n handlers: ContractHandlers<C, E, V>,\n): void {\n const names = Object.keys(contract);\n const missing = names.filter((name) => typeof (handlers as Record<string, unknown>)[name] !== 'function');\n if (missing.length > 0) throw new TypeError(`registerContract: no handler for ${missing.join(', ')}`);\n const unknown = Object.keys(handlers).filter((name) => !Object.hasOwn(contract, name));\n if (unknown.length > 0) throw new TypeError(`registerContract: ${unknown.join(', ')} is not in the contract`);\n\n const router = app as unknown as Record<string, Register>;\n for (const name of names) {\n const endpoint = contract[name] as Endpoint;\n const handler = (handlers as Record<string, EndpointHandler<Endpoint, E, V>>)[name];\n router[endpoint.method.toLowerCase()]?.call(app, endpoint.path, routeFromEndpoint(endpoint, handler));\n }\n}\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint };\nexport type { ContractHandlers, EndpointHandler, EndpointRoute };\n"],
5
- "mappings": "+EAgCA,OAAS,eAAAA,MAAmB,WAE5B,OAAS,qBAAAC,MAAyB,mBAElC,OAAS,kBAAAC,MAAsB,sBAE/B,OAAS,eAAAC,MAAmB,mBA+B5B,SAASC,EAAmBC,EAAkB,CAC5C,MAAMC,EAAsD,CAAA,EACxDD,EAAS,SAAW,SAAWC,EAAQ,OAASD,EAAS,QACzDA,EAAS,QAAU,SAAWC,EAAQ,MAAQD,EAAS,OACvDA,EAAS,OAAS,SAAWC,EAAQ,KAAON,EAAYK,EAAS,IAAI,GAEzE,MAAME,EACJF,EAAS,WAAa,KAClB,CAAE,IAAO,CAAE,YAAa,YAAY,CAAE,EACtC,CAAE,IAAO,CAAE,YAAaA,EAAS,SAAW,KAAM,GAAGL,EAAYK,EAAS,QAAQ,CAAC,CAAE,EACrFG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,EAAQ,OAAO,KAAKF,CAAQ,EAC5BG,EAAUD,EAAM,OAAQE,GAAS,OAAQH,EAAqCG,CAAI,GAAM,UAAU,EACxG,GAAID,EAAQ,OAAS,EAAG,MAAM,IAAI,UAAU,oCAAoCA,EAAQ,KAAK,IAAI,CAAC,EAAE,EACpG,MAAME,EAAU,OAAO,KAAKJ,CAAQ,EAAE,OAAQG,GAAS,CAAC,OAAO,OAAOJ,EAAUI,CAAI,CAAC,EACrF,GAAIC,EAAQ,OAAS,EAAG,MAAM,IAAI,UAAU,qBAAqBA,EAAQ,KAAK,IAAI,CAAC,yBAAyB,EAE5G,MAAMC,EAASP,EACf,UAAWK,KAAQF,EAAO,CACxB,MAAMrB,EAAWmB,EAASI,CAAI,EACxBf,EAAWY,EAA6DG,CAAI,EAClFE,EAAOzB,EAAS,OAAO,YAAW,CAAE,GAAG,KAAKkB,EAAKlB,EAAS,KAAMO,EAAkBP,EAAUQ,CAAO,CAAC,CACtG,CACF,CAjBSF,EAAAW,EAAA",
6
- "names": ["contentJson", "UnauthorizedError", "errorResponses", "FamilyRoute", "schemaFromEndpoint", "endpoint", "request", "success", "errors", "status", "description", "__name", "routeFromEndpoint", "handler", "schema", "authenticated", "ContractRoute", "input", "c", "validated", "slots", "result", "registerContract", "app", "contract", "handlers", "names", "missing", "name", "unknown", "router"]
4
+ "sourcesContent": ["/**\n * The backend half of `@rexezuge/contracts`: an endpoint becomes a chanfana\n * route on the family app.\n *\n * ## Why here, and why `http` depends on `contracts`\n *\n * The adapter needs chanfana (`contentJson`, `OpenAPIRoute`), and the kit's rule\n * is that `hono`/`chanfana` are imported under `packages/http/src/hono/` and\n * nowhere else. So the adapter lives in `/hono`, and `http` takes a dependency on\n * `contracts`, a framework-free package that depends on neither `http` nor\n * `web`. The graph stays acyclic: `errors`/`shared` → `contracts` → `http` →\n * `web`. The other direction (a `/hono` subpath inside `contracts`) would have\n * put a second framework package in the kit.\n *\n * ## Closed\n *\n * - The route's chanfana `schema` is **derived** from the endpoint: request\n * `params`/`query`/`body`, the success response (`200` + the response schema,\n * or `204`), and every documented error as the kit's `{Exception}` envelope\n * (`errorResponses`). There is no second hand-written schema to drift.\n * - The route is a `FamilyRoute`, so validation, result shaping and error\n * mapping are the kit's `@final` `handle()`.\n * - **Fail-closed auth.** An `access`/`apiKey` endpoint answers `401` when no\n * auth middleware set `AuthenticatedUserId`, so forgetting to mount\n * `accessAuth` on a path does not publish an authenticated route.\n * - A trailing wildcard (`/:path*`, `/*`) registers as Hono's `:path{.+}` and arrives in `params`; a `{ kind: 'text' }`\n * response documents `text/plain` (or its `mediaType`) and sends the handler's string with that content type.\n * - `registerContract` refuses a missing or an unknown handler at startup.\n *\n * ## Open\n *\n * The handler, the app (`E`, `V`), and `schemaFromEndpoint` for a hand-written\n * `FamilyRoute` subclass that needs `errorMapping()` or a raw `Response`.\n */\nimport { contentJson } from 'chanfana';\nimport type { OpenAPIRoute, OpenAPIRouteSchema, ResponseConfig, ValidatedData } from 'chanfana';\nimport { UnauthorizedError } from '@rexezuge/errors';\nimport { honoPath, isTextResponse, textMediaType } from '@rexezuge/contracts';\nimport type { Contract, ContractEndpoints, Endpoint, EndpointResult, EndpointServerInput } from '@rexezuge/contracts';\nimport { errorResponses } from '../openApiErrors.ts';\nimport type { ApiApp } from './createApiApp.ts';\nimport { FamilyRoute } from './FamilyRoute.ts';\nimport type { MaybePromise, RouteResult } from './FamilyRoute.ts';\nimport type { FamilyContext } from './types.ts';\n\n/**\n * Your implementation of one endpoint. `input` is the validated request (zod\n * output), and the return value (or a promise of it: a handler need not be `async`) is the response schema's input,\n * `null` for a `204` endpoint, or a `Response` you built yourself.\n */\ntype EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (\n input: EndpointServerInput<EP>,\n c: FamilyContext<E, V>,\n) => MaybePromise<RouteResult<EndpointResult<EP>>>;\n\n/**\nOne handler per contract endpoint, by name. A missing key is a compile error.\n*/\ntype ContractHandlers<C extends ContractEndpoints, E extends object = object, V extends object = object> = {\n [K in keyof C]: EndpointHandler<C[K], E, V>;\n};\n\n/**\n * A route class, in the type chanfana's `app.get(path, Route)` accepts. It is\n * constructed once, at registration.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- chanfana's own registration parameter type\ntype EndpointRoute = typeof OpenAPIRoute<any>;\n\n/**\n * The chanfana schema for an endpoint: request, success and error responses.\n */\nfunction schemaFromEndpoint(endpoint: Endpoint): OpenAPIRouteSchema {\n const request: NonNullable<OpenAPIRouteSchema['request']> = {};\n if (endpoint.params !== undefined) request.params = endpoint.params;\n if (endpoint.query !== undefined) request.query = endpoint.query;\n if (endpoint.body !== undefined) request.body = contentJson(endpoint.body);\n\n const description = endpoint.summary ?? 'OK';\n let success: Record<string, ResponseConfig>;\n if (endpoint.response === null) success = { '204': { description: 'No Content' } };\n else if (isTextResponse(endpoint.response)) {\n success = { '200': { description, content: { [textMediaType(endpoint.response)]: { schema: { type: 'string' } } } } };\n } else success = { '200': { description, ...contentJson(endpoint.response) } };\n const errors = Object.assign(\n {},\n ...endpoint.errorResponses.map(({ status, description }) =>\n errorResponses(description === null ? [status] : { [status]: description }),\n ),\n ) as ReturnType<typeof errorResponses>;\n\n return {\n ...(endpoint.summary !== undefined && { summary: endpoint.summary }),\n ...(endpoint.description !== undefined && { description: endpoint.description }),\n ...(endpoint.tags !== undefined && { tags: [...endpoint.tags] }),\n request,\n responses: { ...success, ...errors },\n };\n}\n\n/**\n * One endpoint as a route class: `app.get(endpoint.path, routeFromEndpoint(endpoint, handler))`.\n * Prefer `registerContract`, which also checks the method and path for you.\n */\nfunction routeFromEndpoint<EP extends Endpoint, E extends object = object, V extends object = object>(\n endpoint: EP,\n handler: EndpointHandler<EP, E, V>,\n): EndpointRoute {\n const schema = schemaFromEndpoint(endpoint);\n const authenticated = endpoint.auth !== 'public';\n\n class ContractRoute extends FamilyRoute<OpenAPIRouteSchema, E, V> {\n public override schema = schema;\n\n protected async handleRequest(input: ValidatedData<OpenAPIRouteSchema>, c: FamilyContext<E, V>): Promise<RouteResult<unknown>> {\n // Read loosely on purpose: the variable is typed as always present, and\n // this is the check that it really is.\n if (authenticated && !(c.get('AuthenticatedUserId') as string | undefined)) throw new UnauthorizedError();\n const validated = input as { params?: unknown; query?: unknown; body?: unknown };\n const slots: Record<string, unknown> = {};\n if (endpoint.params !== undefined) slots.params = validated.params;\n if (endpoint.query !== undefined) slots.query = validated.query;\n if (endpoint.body !== undefined) slots.body = validated.body;\n const result = await handler(slots as EndpointServerInput<EP>, c);\n // A 204 endpoint answers 204 whatever the handler returned, unless it\n // built its own Response.\n if (endpoint.response === null && !(result instanceof Response)) return null;\n // A text endpoint sends the string as its media type, not as a JSON string.\n if (isTextResponse(endpoint.response) && typeof result === 'string') {\n return new Response(result, { headers: { 'Content-Type': `${textMediaType(endpoint.response)}; charset=UTF-8` } });\n }\n return result;\n }\n }\n Object.defineProperty(ContractRoute, 'name', { value: `${endpoint.method} ${endpoint.path}` });\n return ContractRoute;\n}\n\ntype Register = (path: string, route: unknown) => unknown;\n\n/**\n * Register every endpoint of a contract. `handlers` must name exactly the\n * contract's endpoints: the type requires every key, and a missing or an extra\n * key also throws a `TypeError` here, at startup.\n *\n * ```ts\n * createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, { getItem, listItems, renameItem }) });\n * ```\n */\nfunction registerContract<E extends object, V extends object, C extends ContractEndpoints>(\n app: ApiApp<E, V>,\n contract: Contract<C>,\n handlers: ContractHandlers<C, E, V>,\n): void {\n const names = Object.keys(contract);\n const missing = names.filter((name) => typeof (handlers as Record<string, unknown>)[name] !== 'function');\n if (missing.length > 0) throw new TypeError(`registerContract: no handler for ${missing.join(', ')}`);\n const unknown = Object.keys(handlers).filter((name) => !Object.hasOwn(contract, name));\n if (unknown.length > 0) throw new TypeError(`registerContract: ${unknown.join(', ')} is not in the contract`);\n\n const router = app as unknown as Record<string, Register>;\n for (const name of names) {\n const endpoint = contract[name] as Endpoint;\n const handler = (handlers as Record<string, EndpointHandler<Endpoint, E, V>>)[name];\n router[endpoint.method.toLowerCase()]?.call(app, honoPath(endpoint.path), routeFromEndpoint(endpoint, handler));\n }\n}\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint };\nexport type { ContractHandlers, EndpointHandler, EndpointRoute };\n"],
5
+ "mappings": "+EAkCA,OAAS,eAAAA,MAAmB,WAE5B,OAAS,qBAAAC,MAAyB,mBAClC,OAAS,YAAAC,EAAU,kBAAAC,EAAgB,iBAAAC,MAAqB,sBAExD,OAAS,kBAAAC,MAAsB,sBAE/B,OAAS,eAAAC,MAAmB,mBA+B5B,SAASC,EAAmBC,EAAkB,CAC5C,MAAMC,EAAsD,CAAA,EACxDD,EAAS,SAAW,SAAWC,EAAQ,OAASD,EAAS,QACzDA,EAAS,QAAU,SAAWC,EAAQ,MAAQD,EAAS,OACvDA,EAAS,OAAS,SAAWC,EAAQ,KAAOT,EAAYQ,EAAS,IAAI,GAEzE,MAAME,EAAcF,EAAS,SAAW,KACxC,IAAIG,EACAH,EAAS,WAAa,KAAMG,EAAU,CAAE,IAAO,CAAE,YAAa,YAAY,CAAE,EACvER,EAAeK,EAAS,QAAQ,EACvCG,EAAU,CAAE,IAAO,CAAE,YAAAD,EAAa,QAAS,CAAE,CAACN,EAAcI,EAAS,QAAQ,CAAC,EAAG,CAAE,OAAQ,CAAE,KAAM,QAAQ,CAAE,CAAE,CAAE,CAAE,EAC9GG,EAAU,CAAE,IAAO,CAAE,YAAAD,EAAa,GAAGV,EAAYQ,EAAS,QAAQ,CAAC,CAAE,EAC5E,MAAMI,EAAS,OAAO,OACpB,CAAA,EACA,GAAGJ,EAAS,eAAe,IAAI,CAAC,CAAE,OAAAK,EAAQ,YAAAH,CAAW,IACnDL,EAAeK,IAAgB,KAAO,CAACG,CAAM,EAAI,CAAE,CAACA,CAAM,EAAGH,CAAW,CAAE,CAAC,CAC5E,EAGH,MAAO,CACL,GAAIF,EAAS,UAAY,QAAa,CAAE,QAASA,EAAS,OAAO,EACjE,GAAIA,EAA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AAS,EAAG,MAAM,IAAI,UAAU,oCAAoCA,EAAQ,KAAK,IAAI,CAAC,EAAE,EACpG,MAAME,EAAU,OAAO,KAAKJ,CAAQ,EAAE,OAAQG,GAAS,CAAC,OAAO,OAAOJ,EAAUI,CAAI,CAAC,EACrF,GAAIC,EAAQ,OAAS,EAAG,MAAM,IAAI,UAAU,qBAAqBA,EAAQ,KAAK,IAAI,CAAC,yBAAyB,EAE5G,MAAMC,EAASP,EACf,UAAWK,KAAQF,EAAO,CACxB,MAAMrB,EAAWmB,EAASI,CAAI,EACxBf,EAAWY,EAA6DG,CAAI,EAClFE,EAAOzB,EAAS,OAAO,YAAW,CAAE,GAAG,KAAKkB,EAAKxB,EAASM,EAAS,IAAI,EAAGO,EAAkBP,EAAUQ,CAAO,CAAC,CAChH,CACF,CAjBSF,EAAAW,EAAA",
6
+ "names": ["contentJson", "UnauthorizedError", "honoPath", "isTextResponse", "textMediaType", "errorResponses", "FamilyRoute", "schemaFromEndpoint", "endpoint", "request", "description", "success", "errors", "status", "__name", "routeFromEndpoint", "handler", "schema", "authenticated", "ContractRoute", "input", "c", "validated", "slots", "result", "registerContract", "app", "contract", "handlers", "names", "missing", "name", "unknown", "router"]
7
7
  }
package/dist/index.d.ts CHANGED
@@ -53,7 +53,7 @@ export { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServi
53
53
  export type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';
54
54
  export { errorResponses, exceptionResponse } from './openApiErrors.ts';
55
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';
56
+ export { MethodGuardError, checkContentLength, checkContentType, checkMethod, checkOrigin, isMutatingMethod, requestOrigin, DEFAULT_ALLOWED_METHODS, DEFAULT_MAX_BODY_BYTES, } from './requestGuards.ts';
57
57
  export type { OriginGuardOptions } from './requestGuards.ts';
58
58
  export { BaseRoute, createRouteHandler } from './routeBase.ts';
59
59
  export type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';
@@ -1 +1 @@
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,oBAAoB,EACpB,WAAW,EACX,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAEtF,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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Y,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,gBAAgB,EAChB,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 c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as p,sensitivePaths as E,sensitivePathMatcher as S,pathMatcher as h,CONTENT_SECURITY_POLICY as u,SECURITY_HEADERS as L,STRICT_TRANSPORT_SECURITY as A}from"./securityHeaders.js";import{AccessAuthError as C,authenticateAccess as x,identityFromBinding as F,verifyAccessJwt as f}from"./accessAuth.js";import{errorBody as M,errorResponseFromUnknown as d,mapError as g,toErrorResponse as k,toServiceError as O,INTERNAL_SERVER_MESSAGE as y}from"./ErrorMapper.js";import{errorResponses as U,exceptionResponse as D}from"./openApiErrors.js";import{checkContentLength as H,checkContentType as N,checkMethod as v,checkOrigin as P,isMutatingMethod as l,requestOrigin as w,DEFAULT_ALLOWED_METHODS as X,DEFAULT_MAX_BODY_BYTES as q}from"./requestGuards.js";import{BaseRoute as J,createRouteHandler as K}from"./routeBase.js";const o=t,s=e;export{C as AccessAuthError,J as BaseRoute,u as CONTENT_SECURITY_POLICY,X as DEFAULT_ALLOWED_METHODS,q as DEFAULT_MAX_BODY_BYTES,y as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,L as SECURITY_HEADERS,A as STRICT_TRANSPORT_SECURITY,m as applySecurityHeaders,x as authenticateAccess,H as checkContentLength,N as checkContentType,v as checkMethod,P as checkOrigin,c as clientIp,K as createRouteHandler,M as errorBody,d as errorResponseFromUnknown,U as errorResponses,D as exceptionResponse,s as getRateLimitBucketCountForTests,F as identityFromBinding,l as isMutatingMethod,g as mapError,h as pathMatcher,R as rateLimit,w as requestOrigin,o as resetRateLimitForTests,p as securityHeaders,S as sensitivePathMatcher,E as sensitivePaths,k as toErrorResponse,O as toServiceError,f as verifyAccessJwt};
1
+ import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as E}from"./rateLimit.js";import{applySecurityHeaders as T,securityHeaders as m,sensitivePaths as p,sensitivePathMatcher as S,pathMatcher as h,CONTENT_SECURITY_POLICY as u,SECURITY_HEADERS as L,STRICT_TRANSPORT_SECURITY as A}from"./securityHeaders.js";import{AccessAuthError as C,authenticateAccess as d,identityFromBinding as x,verifyAccessJwt as F}from"./accessAuth.js";import{errorBody as f,errorResponseFromUnknown as B,mapError as g,toErrorResponse as k,toServiceError as O,INTERNAL_SERVER_MESSAGE as y}from"./ErrorMapper.js";import{errorResponses as U,exceptionResponse as D}from"./openApiErrors.js";import{MethodGuardError as H,checkContentLength as N,checkContentType as v,checkMethod as P,checkOrigin as l,isMutatingMethod as w,requestOrigin as G,DEFAULT_ALLOWED_METHODS as X,DEFAULT_MAX_BODY_BYTES as q}from"./requestGuards.js";import{BaseRoute as K,createRouteHandler as V}from"./routeBase.js";const o=t,s=e;export{C as AccessAuthError,K as BaseRoute,u as CONTENT_SECURITY_POLICY,X as DEFAULT_ALLOWED_METHODS,q as DEFAULT_MAX_BODY_BYTES,y as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,H as MethodGuardError,L as SECURITY_HEADERS,A as STRICT_TRANSPORT_SECURITY,T as applySecurityHeaders,d as authenticateAccess,N as checkContentLength,v as checkContentType,P as checkMethod,l as checkOrigin,c as clientIp,V as createRouteHandler,f as errorBody,B as errorResponseFromUnknown,U as errorResponses,D as exceptionResponse,s as getRateLimitBucketCountForTests,x as identityFromBinding,w as isMutatingMethod,g as mapError,h as pathMatcher,E as rateLimit,G as requestOrigin,o as resetRateLimitForTests,m as securityHeaders,S as sensitivePathMatcher,p as sensitivePaths,k as toErrorResponse,O as toServiceError,F 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 — 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 sensitivePathMatcher,\n pathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext, PathMatcher, SensitivePath } 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,wBAAAC,EACA,eAAAC,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,EAA4DlC,EAI5DmC,EAA8EpC",
6
- "names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "sensitivePathMatcher", "pathMatcher", "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"]
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 sensitivePathMatcher,\n pathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext, PathMatcher, SensitivePath } 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 MethodGuardError,\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,wBAAAC,EACA,eAAAC,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,oBAAAC,EACA,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,oBAAAC,EACA,iBAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,qBAGP,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,EAA4DnC,EAI5DoC,EAA8ErC",
6
+ "names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "sensitivePathMatcher", "pathMatcher", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "MethodGuardError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
7
7
  }
@@ -1,3 +1,32 @@
1
+ /**
2
+ * Request hardening and the CSRF/origin guard, framework-free.
3
+ *
4
+ * Converged from four shapes of the same idea:
5
+ *
6
+ * - AWS-AccessBridge `apps/api/src/middleware/RequestGuards.ts` — `Sec-Fetch-Site`
7
+ * must be `same-origin`/`none`, and a mutating request with a body must declare
8
+ * `application/json` (the one type a cross-site HTML form cannot send).
9
+ * - Image-Host `apps/api/src/middleware/MiddlewareHandlers.ts` — `Origin`, else
10
+ * `Referer`, must equal the request origin; **both absent is a rejection**.
11
+ * - Pigeongram `packages/backend-services/src/session/origin.ts` — the allow-list
12
+ * is the request origin plus configured origins (`ALLOWED_ORIGINS`,
13
+ * `PAGES_ORIGIN`), and `Sec-Fetch-Site` alone never *admits* a request: a client
14
+ * controls it as much as `Origin`.
15
+ * - The `MAX_JSON_BODY_BYTES` ceilings in the Durable-DAV / Edge-Git route bases.
16
+ *
17
+ * Every check answers a `ServiceError` or `null` rather than a `Response`, so the
18
+ * caller's error boundary renders it in its own dialect — the `/hono` middleware
19
+ * throws it into `app.onError`, a Durable Object maps it itself.
20
+ *
21
+ * ## Why the strict defaults
22
+ *
23
+ * Cloudflare Access cookies are `SameSite=None` by design (they survive the
24
+ * login redirect), so the cookie is not a CSRF defence. A browser always sends
25
+ * `Origin` or `Referer` on a cross-origin mutation, so their joint absence means
26
+ * a non-browser caller — which a cookie-authenticated surface does not serve
27
+ * unless the app opts in with `allowMissingOrigin`.
28
+ */
29
+ import { MethodNotAllowedError } from '@rexezuge/errors';
1
30
  import type { ServiceError } from '@rexezuge/errors';
2
31
  /**
3
32
  The methods a family API answers; anything else is a 405 before routing.
@@ -32,7 +61,19 @@ declare function requestOrigin(request: Request): string | null;
32
61
  */
33
62
  declare function checkOrigin(request: Request, options?: OriginGuardOptions): ServiceError | null;
34
63
  /**
35
- A method outside the allow-list is a 405, before any route or auth runs.
64
+ * The 405 the method guard throws. It carries the configured allow-list as an `Allow` header value (RFC 9110
65
+ * §15.5.6 requires one), which `mapError` copies onto the response, so every surface that maps it (`onError`,
66
+ * `FamilyRoute`, `errorResponseFromUnknown`) answers with the header.
67
+ */
68
+ declare class MethodGuardError extends MethodNotAllowedError {
69
+ /**
70
+ The `Allow` header value: the configured methods, upper-cased and de-duplicated.
71
+ */
72
+ readonly allow: string;
73
+ constructor(allowed: readonly string[]);
74
+ }
75
+ /**
76
+ A method outside the allow-list is a 405 (with `Allow`), before any route or auth runs.
36
77
  */
37
78
  declare function checkMethod(method: string, allowed?: readonly string[]): ServiceError | null;
38
79
  /**
@@ -47,6 +88,6 @@ declare function checkContentType(request: Request, allowed?: readonly string[])
47
88
  * chunked request declares nothing.
48
89
  */
49
90
  declare function checkContentLength(request: Request, maxBytes?: number): ServiceError | null;
50
- export { checkContentLength, checkContentType, checkMethod, checkOrigin, isMutatingMethod, requestOrigin, DEFAULT_ALLOWED_METHODS, DEFAULT_MAX_BODY_BYTES, };
91
+ export { MethodGuardError, checkContentLength, checkContentType, checkMethod, checkOrigin, isMutatingMethod, requestOrigin, DEFAULT_ALLOWED_METHODS, DEFAULT_MAX_BODY_BYTES, };
51
92
  export type { OriginGuardOptions };
52
93
  //# sourceMappingURL=requestGuards.d.ts.map
@@ -1 +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,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,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,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,CAAC;AACF,YAAY,EAAE,kBAAkB,EAAE,CAAC"}
@@ -1 +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};
1
+ var w=Object.defineProperty;var r=(n,e)=>w(n,"name",{value:e,configurable:!0});import{ForbiddenError as s,MethodNotAllowedError as m,PayloadTooLargeError as T,UnsupportedMediaTypeError as S}from"@rexezuge/errors";const O=new Set(["GET","HEAD","OPTIONS"]),h=["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"],E=1048576,c="Cross-origin request rejected.";function u(n){return!O.has(n.toUpperCase())}r(u,"isMutatingMethod");function i(n){const e=n?.trim()??"";if(e==="")return null;try{return new URL(e).origin}catch{return null}}r(i,"originOf");function f(n){return i(n.headers.get("origin"))??i(n.headers.get("referer"))}r(f,"requestOrigin");function C(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 s(c);const o=f(n);if(o===null)return e.allowMissingOrigin?null:new s(c);const l=new Set,a=i(n.url);a!==null&&l.add(a);for(const p of e.allowedOrigins??[]){const d=i(p);d!==null&&l.add(d)}return l.has(o)?null:new s(c)}r(C,"checkOrigin");class g extends m{static{r(this,"MethodGuardError")}allow;constructor(e){super(),this.allow=[...new Set(e.map(t=>t.toUpperCase()))].join(", ")}}function L(n,e=h){const t=n.toUpperCase();return e.some(o=>o.toUpperCase()===t)?null:new g(e)}r(L,"checkMethod");function M(n){const e=n.headers.get("content-length");return e===null||e.trim()!=="0"}r(M,"hasBody");function A(n,e=["application/json"]){if(!u(n.method)||n.method.toUpperCase()==="DELETE"||!M(n))return null;const t=(n.headers.get("content-type")??"").split(";",1)[0]?.trim().toLowerCase()??"";return e.some(o=>o.toLowerCase()===t)?null:new S}r(A,"checkContentType");function D(n,e=E){const t=n.headers.get("content-length");if(t===null)return null;const o=Number(t.trim());return Number.isFinite(o)&&o>e?new T:null}r(D,"checkContentLength");export{h as DEFAULT_ALLOWED_METHODS,E as DEFAULT_MAX_BODY_BYTES,g as MethodGuardError,D as checkContentLength,A as checkContentType,L as checkMethod,C as checkOrigin,u as isMutatingMethod,f as requestOrigin};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/requestGuards.ts"],
4
- "sourcesContent": ["/**\n * Request hardening and the CSRF/origin guard, framework-free.\n *\n * Converged from four shapes of the same idea:\n *\n * - AWS-AccessBridge `apps/api/src/middleware/RequestGuards.ts` — `Sec-Fetch-Site`\n * must be `same-origin`/`none`, and a mutating request with a body must declare\n * `application/json` (the one type a cross-site HTML form cannot send).\n * - Image-Host `apps/api/src/middleware/MiddlewareHandlers.ts` — `Origin`, else\n * `Referer`, must equal the request origin; **both absent is a rejection**.\n * - Pigeongram `packages/backend-services/src/session/origin.ts` — the allow-list\n * is the request origin plus configured origins (`ALLOWED_ORIGINS`,\n * `PAGES_ORIGIN`), and `Sec-Fetch-Site` alone never *admits* a request: a client\n * controls it as much as `Origin`.\n * - The `MAX_JSON_BODY_BYTES` ceilings in the Durable-DAV / Edge-Git route bases.\n *\n * Every check answers a `ServiceError` or `null` rather than a `Response`, so the\n * caller's error boundary renders it in its own dialect — the `/hono` middleware\n * throws it into `app.onError`, a Durable Object maps it itself.\n *\n * ## Why the strict defaults\n *\n * Cloudflare Access cookies are `SameSite=None` by design (they survive the\n * login redirect), so the cookie is not a CSRF defence. A browser always sends\n * `Origin` or `Referer` on a cross-origin mutation, so their joint absence means\n * a non-browser caller — which a cookie-authenticated surface does not serve\n * unless the app opts in with `allowMissingOrigin`.\n */\nimport { ForbiddenError, MethodNotAllowedError, PayloadTooLargeError, UnsupportedMediaTypeError } from '@rexezuge/errors';\nimport type { ServiceError } from '@rexezuge/errors';\n\nconst SAFE_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\nThe methods a family API answers; anything else is a 405 before routing.\n*/\nconst DEFAULT_ALLOWED_METHODS: readonly string[] = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];\n\n/**\nOne MiB — the ceiling every converged route base used for a JSON body.\n*/\nconst DEFAULT_MAX_BODY_BYTES = 1_048_576;\n\nconst CROSS_SITE_MESSAGE = 'Cross-origin request rejected.';\n\ninterface OriginGuardOptions {\n /**\n * Origins trusted in addition to the request's own (a Pages origin, a custom\n * domain). Entries are normalised through `URL`; an unparseable one is dropped.\n */\n allowedOrigins?: readonly string[];\n /**\n * Admit a mutation that carries neither `Origin` nor `Referer`. Off by default:\n * see the file header. Turn it on only for a surface that also serves\n * non-browser callers with a non-cookie credential.\n */\n allowMissingOrigin?: boolean;\n}\n\nfunction isMutatingMethod(method: string): boolean {\n return !SAFE_METHODS.has(method.toUpperCase());\n}\n\nfunction originOf(value: string | null): string | null {\n const trimmed = value?.trim() ?? '';\n if (trimmed === '') return null;\n try {\n return new URL(trimmed).origin;\n } catch {\n return null;\n }\n}\n\n/**\nThe origin a request claims: `Origin`, else the `Referer`'s origin, else `null`.\n*/\nfunction requestOrigin(request: Request): string | null {\n return originOf(request.headers.get('origin')) ?? originOf(request.headers.get('referer'));\n}\n\n/**\n * The CSRF guard for a cookie-authenticated surface. Safe methods pass; a\n * mutation passes only when it is not declared cross-site and its origin is\n * allow-listed.\n */\nfunction checkOrigin(request: Request, options: OriginGuardOptions = {}): ServiceError | null {\n if (!isMutatingMethod(request.method)) return null;\n\n // A rejection signal only, never an admission: `same-site` is a sibling\n // subdomain, which is exactly the attacker a CSRF guard exists to stop.\n const fetchSite = request.headers.get('sec-fetch-site')?.trim().toLowerCase();\n if (fetchSite !== undefined && fetchSite !== 'same-origin' && fetchSite !== 'none') {\n return new ForbiddenError(CROSS_SITE_MESSAGE);\n }\n\n const origin = requestOrigin(request);\n if (origin === null) return options.allowMissingOrigin ? null : new ForbiddenError(CROSS_SITE_MESSAGE);\n\n const allowed = new Set<string>();\n const own = originOf(request.url);\n if (own !== null) allowed.add(own);\n for (const entry of options.allowedOrigins ?? []) {\n const normalized = originOf(entry);\n if (normalized !== null) allowed.add(normalized);\n }\n return allowed.has(origin) ? null : new ForbiddenError(CROSS_SITE_MESSAGE);\n}\n\n/**\nA method outside the allow-list is a 405, before any route or auth runs.\n*/\nfunction checkMethod(method: string, allowed: readonly string[] = DEFAULT_ALLOWED_METHODS): ServiceError | null {\n const upper = method.toUpperCase();\n return allowed.some((entry) => entry.toUpperCase() === upper) ? null : new MethodNotAllowedError();\n}\n\n/**\n * Whether a request carries a body, answered conservatively: only an explicit\n * `Content-Length: 0` is body-less. A request with neither framing header has an\n * *unknown* body, not an empty one (AWS-AccessBridge's rule).\n */\nfunction hasBody(request: Request): boolean {\n const length = request.headers.get('content-length');\n return length === null || length.trim() !== '0';\n}\n\n/**\n * A mutating request with a body must declare one of `allowed` (default\n * `application/json`). `text/plain` and form encodings are what a cross-site\n * form can send, so refusing them also closes content-type confusion.\n */\nfunction checkContentType(request: Request, allowed: readonly string[] = ['application/json']): ServiceError | null {\n if (!isMutatingMethod(request.method) || request.method.toUpperCase() === 'DELETE' || !hasBody(request)) return null;\n const declared = (request.headers.get('content-type') ?? '').split(';', 1)[0]?.trim().toLowerCase() ?? '';\n return allowed.some((type) => type.toLowerCase() === declared) ? null : new UnsupportedMediaTypeError();\n}\n\n/**\n * A declared `Content-Length` over the ceiling is a 413 before the body is read.\n * This is the cheap half; the `/hono` middleware also caps the stream, because a\n * chunked request declares nothing.\n */\nfunction checkContentLength(request: Request, maxBytes: number = DEFAULT_MAX_BODY_BYTES): ServiceError | null {\n const raw = request.headers.get('content-length');\n if (raw === null) return null;\n const length = Number(raw.trim());\n return Number.isFinite(length) && length > maxBytes ? new PayloadTooLargeError() : null;\n}\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n};\nexport type { OriginGuardOptions };\n"],
5
- "mappings": "+EA4BA,OAAS,kBAAAA,EAAgB,yBAAAC,EAAuB,wBAAAC,EAAsB,6BAAAC,MAAiC,mBAGvG,MAAMC,EAAoC,IAAI,IAAI,CAAC,MAAO,OAAQ,SAAS,CAAC,EAKtEC,EAA6C,CAAC,MAAO,OAAQ,OAAQ,MAAO,QAAS,SAAU,SAAS,EAKxGC,EAAyB,QAEzBC,EAAqB,iCAgB3B,SAASC,EAAiBC,EAAc,CACtC,MAAO,CAACL,EAAa,IAAIK,EAAO,YAAW,CAAE,CAC/C,CAFSC,EAAAF,EAAA,oBAIT,SAASG,EAASC,EAAoB,CACpC,MAAMC,EAAUD,GAAO,KAAI,GAAM,GACjC,GAAIC,IAAY,GAAI,OAAO,KAC3B,GAAI,CACF,OAAO,IAAI,IAAIA,CAAO,EAAE,MAC1B,MAAQ,CACN,OAAO,IACT,CACF,CARSH,EAAAC,EAAA,YAaT,SAASG,EAAcC,EAAgB,CACrC,OAAOJ,EAASI,EAAQ,QAAQ,IAAI,QAAQ,CAAC,GAAKJ,EAASI,EAAQ,QAAQ,IAAI,SAAS,CAAC,CAC3F,CAFSL,EAAAI,EAAA,iBAST,SAASE,EAAYD,EAAkBE,EAA8B,CAAA,EAAE,CACrE,GAAI,CAACT,EAAiBO,EAAQ,MAAM,EAAG,OAAO,KAI9C,MAAMG,EAAYH,EAAQ,QAAQ,IAAI,gBAAgB,GAAG,KAAI,EAAG,YAAW,EAC3E,GAAIG,IAAc,QAAaA,IAAc,eAAiBA,IAAc,OAC1E,OAAO,IAAIlB,EAAeO,CAAkB,EA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AAMlB,EAAQ,QAAQ,IAAI,gBAAgB,EAChD,GAAIkB,IAAQ,KAAM,OAAO,KACzB,MAAMN,EAAS,OAAOM,EAAI,KAAI,CAAE,EAChC,OAAO,OAAO,SAASN,CAAM,GAAKA,EAASK,EAAW,IAAI9B,EAAyB,IACrF,CALSQ,EAAAqB,EAAA",
6
- "names": ["ForbiddenError", "MethodNotAllowedError", "PayloadTooLargeError", "UnsupportedMediaTypeError", "SAFE_METHODS", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "CROSS_SITE_MESSAGE", "isMutatingMethod", "method", "__name", "originOf", "value", "trimmed", "requestOrigin", "request", "checkOrigin", "options", "fetchSite", "origin", "allowed", "own", "entry", "normalized", "checkMethod", "upper", "hasBody", "length", "checkContentType", "declared", "type", "checkContentLength", "maxBytes", "raw"]
4
+ "sourcesContent": ["/**\n * Request hardening and the CSRF/origin guard, framework-free.\n *\n * Converged from four shapes of the same idea:\n *\n * - AWS-AccessBridge `apps/api/src/middleware/RequestGuards.ts` — `Sec-Fetch-Site`\n * must be `same-origin`/`none`, and a mutating request with a body must declare\n * `application/json` (the one type a cross-site HTML form cannot send).\n * - Image-Host `apps/api/src/middleware/MiddlewareHandlers.ts` — `Origin`, else\n * `Referer`, must equal the request origin; **both absent is a rejection**.\n * - Pigeongram `packages/backend-services/src/session/origin.ts` — the allow-list\n * is the request origin plus configured origins (`ALLOWED_ORIGINS`,\n * `PAGES_ORIGIN`), and `Sec-Fetch-Site` alone never *admits* a request: a client\n * controls it as much as `Origin`.\n * - The `MAX_JSON_BODY_BYTES` ceilings in the Durable-DAV / Edge-Git route bases.\n *\n * Every check answers a `ServiceError` or `null` rather than a `Response`, so the\n * caller's error boundary renders it in its own dialect — the `/hono` middleware\n * throws it into `app.onError`, a Durable Object maps it itself.\n *\n * ## Why the strict defaults\n *\n * Cloudflare Access cookies are `SameSite=None` by design (they survive the\n * login redirect), so the cookie is not a CSRF defence. A browser always sends\n * `Origin` or `Referer` on a cross-origin mutation, so their joint absence means\n * a non-browser caller — which a cookie-authenticated surface does not serve\n * unless the app opts in with `allowMissingOrigin`.\n */\nimport { ForbiddenError, MethodNotAllowedError, PayloadTooLargeError, UnsupportedMediaTypeError } from '@rexezuge/errors';\nimport type { ServiceError } from '@rexezuge/errors';\n\nconst SAFE_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\nThe methods a family API answers; anything else is a 405 before routing.\n*/\nconst DEFAULT_ALLOWED_METHODS: readonly string[] = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];\n\n/**\nOne MiB — the ceiling every converged route base used for a JSON body.\n*/\nconst DEFAULT_MAX_BODY_BYTES = 1_048_576;\n\nconst CROSS_SITE_MESSAGE = 'Cross-origin request rejected.';\n\ninterface OriginGuardOptions {\n /**\n * Origins trusted in addition to the request's own (a Pages origin, a custom\n * domain). Entries are normalised through `URL`; an unparseable one is dropped.\n */\n allowedOrigins?: readonly string[];\n /**\n * Admit a mutation that carries neither `Origin` nor `Referer`. Off by default:\n * see the file header. Turn it on only for a surface that also serves\n * non-browser callers with a non-cookie credential.\n */\n allowMissingOrigin?: boolean;\n}\n\nfunction isMutatingMethod(method: string): boolean {\n return !SAFE_METHODS.has(method.toUpperCase());\n}\n\nfunction originOf(value: string | null): string | null {\n const trimmed = value?.trim() ?? '';\n if (trimmed === '') return null;\n try {\n return new URL(trimmed).origin;\n } catch {\n return null;\n }\n}\n\n/**\nThe origin a request claims: `Origin`, else the `Referer`'s origin, else `null`.\n*/\nfunction requestOrigin(request: Request): string | null {\n return originOf(request.headers.get('origin')) ?? originOf(request.headers.get('referer'));\n}\n\n/**\n * The CSRF guard for a cookie-authenticated surface. Safe methods pass; a\n * mutation passes only when it is not declared cross-site and its origin is\n * allow-listed.\n */\nfunction checkOrigin(request: Request, options: OriginGuardOptions = {}): ServiceError | null {\n if (!isMutatingMethod(request.method)) return null;\n\n // A rejection signal only, never an admission: `same-site` is a sibling\n // subdomain, which is exactly the attacker a CSRF guard exists to stop.\n const fetchSite = request.headers.get('sec-fetch-site')?.trim().toLowerCase();\n if (fetchSite !== undefined && fetchSite !== 'same-origin' && fetchSite !== 'none') {\n return new ForbiddenError(CROSS_SITE_MESSAGE);\n }\n\n const origin = requestOrigin(request);\n if (origin === null) return options.allowMissingOrigin ? null : new ForbiddenError(CROSS_SITE_MESSAGE);\n\n const allowed = new Set<string>();\n const own = originOf(request.url);\n if (own !== null) allowed.add(own);\n for (const entry of options.allowedOrigins ?? []) {\n const normalized = originOf(entry);\n if (normalized !== null) allowed.add(normalized);\n }\n return allowed.has(origin) ? null : new ForbiddenError(CROSS_SITE_MESSAGE);\n}\n\n/**\n * The 405 the method guard throws. It carries the configured allow-list as an `Allow` header value (RFC 9110\n * §15.5.6 requires one), which `mapError` copies onto the response, so every surface that maps it (`onError`,\n * `FamilyRoute`, `errorResponseFromUnknown`) answers with the header.\n */\nclass MethodGuardError extends MethodNotAllowedError {\n /**\n The `Allow` header value: the configured methods, upper-cased and de-duplicated.\n */\n readonly allow: string;\n\n constructor(allowed: readonly string[]) {\n super();\n this.allow = [...new Set(allowed.map((entry) => entry.toUpperCase()))].join(', ');\n }\n}\n\n/**\nA method outside the allow-list is a 405 (with `Allow`), before any route or auth runs.\n*/\nfunction checkMethod(method: string, allowed: readonly string[] = DEFAULT_ALLOWED_METHODS): ServiceError | null {\n const upper = method.toUpperCase();\n return allowed.some((entry) => entry.toUpperCase() === upper) ? null : new MethodGuardError(allowed);\n}\n\n/**\n * Whether a request carries a body, answered conservatively: only an explicit\n * `Content-Length: 0` is body-less. A request with neither framing header has an\n * *unknown* body, not an empty one (AWS-AccessBridge's rule).\n */\nfunction hasBody(request: Request): boolean {\n const length = request.headers.get('content-length');\n return length === null || length.trim() !== '0';\n}\n\n/**\n * A mutating request with a body must declare one of `allowed` (default\n * `application/json`). `text/plain` and form encodings are what a cross-site\n * form can send, so refusing them also closes content-type confusion.\n */\nfunction checkContentType(request: Request, allowed: readonly string[] = ['application/json']): ServiceError | null {\n if (!isMutatingMethod(request.method) || request.method.toUpperCase() === 'DELETE' || !hasBody(request)) return null;\n const declared = (request.headers.get('content-type') ?? '').split(';', 1)[0]?.trim().toLowerCase() ?? '';\n return allowed.some((type) => type.toLowerCase() === declared) ? null : new UnsupportedMediaTypeError();\n}\n\n/**\n * A declared `Content-Length` over the ceiling is a 413 before the body is read.\n * This is the cheap half; the `/hono` middleware also caps the stream, because a\n * chunked request declares nothing.\n */\nfunction checkContentLength(request: Request, maxBytes: number = DEFAULT_MAX_BODY_BYTES): ServiceError | null {\n const raw = request.headers.get('content-length');\n if (raw === null) return null;\n const length = Number(raw.trim());\n return Number.isFinite(length) && length > maxBytes ? new PayloadTooLargeError() : null;\n}\n\nexport {\n MethodGuardError,\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n};\nexport type { OriginGuardOptions };\n"],
5
+ "mappings": "+EA4BA,OAAS,kBAAAA,EAAgB,yBAAAC,EAAuB,wBAAAC,EAAsB,6BAAAC,MAAiC,mBAGvG,MAAMC,EAAoC,IAAI,IAAI,CAAC,MAAO,OAAQ,SAAS,CAAC,EAKtEC,EAA6C,CAAC,MAAO,OAAQ,OAAQ,MAAO,QAAS,SAAU,SAAS,EAKxGC,EAAyB,QAEzBC,EAAqB,iCAgB3B,SAASC,EAAiBC,EAAc,CACtC,MAAO,CAACL,EAAa,IAAIK,EAAO,YAAW,CAAE,CAC/C,CAFSC,EAAAF,EAAA,oBAIT,SAASG,EAASC,EAAoB,CACpC,MAAMC,EAAUD,GAAO,KAAI,GAAM,GACjC,GAAIC,IAAY,GAAI,OAAO,KAC3B,GAAI,CACF,OAAO,IAAI,IAAIA,CAAO,EAAE,MAC1B,MAAQ,CACN,OAAO,IACT,CACF,CARSH,EAAAC,EAAA,YAaT,SAASG,EAAcC,EAAgB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Ae,EAAA,eAUT,SAASE,EAAQZ,EAAgB,CAC/B,MAAMa,EAASb,EAAQ,QAAQ,IAAI,gBAAgB,EACnD,OAAOa,IAAW,MAAQA,EAAO,KAAI,IAAO,GAC9C,CAHSlB,EAAAiB,EAAA,WAUT,SAASE,EAAiBd,EAAkBK,EAA6B,CAAC,kBAAkB,EAAC,CAC3F,GAAI,CAACZ,EAAiBO,EAAQ,MAAM,GAAKA,EAAQ,OAAO,YAAW,IAAO,UAAY,CAACY,EAAQZ,CAAO,EAAG,OAAO,KAChH,MAAMe,GAAYf,EAAQ,QAAQ,IAAI,cAAc,GAAK,IAAI,MAAM,IAAK,CAAC,EAAE,CAAC,GAAG,KAAI,EAAG,YAAW,GAAM,GACvG,OAAOK,EAAQ,KAAMW,GAASA,EAAK,YAAW,IAAOD,CAAQ,EAAI,KAAO,IAAI3B,CAC9E,CAJSO,EAAAmB,EAAA,oBAWT,SAASG,EAAmBjB,EAAkBkB,EAAmB3B,EAAsB,CACrF,MAAM4B,EAAMnB,EAAQ,QAAQ,IAAI,gBAAgB,EAChD,GAAImB,IAAQ,KAAM,OAAO,KACzB,MAAMN,EAAS,OAAOM,EAAI,KAAI,CAAE,EAChC,OAAO,OAAO,SAASN,CAAM,GAAKA,EAASK,EAAW,IAAI/B,EAAyB,IACrF,CALSQ,EAAAsB,EAAA",
6
+ "names": ["ForbiddenError", "MethodNotAllowedError", "PayloadTooLargeError", "UnsupportedMediaTypeError", "SAFE_METHODS", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "CROSS_SITE_MESSAGE", "isMutatingMethod", "method", "__name", "originOf", "value", "trimmed", "requestOrigin", "request", "checkOrigin", "options", "fetchSite", "origin", "allowed", "own", "entry", "normalized", "MethodGuardError", "checkMethod", "upper", "hasBody", "length", "checkContentType", "declared", "type", "checkContentLength", "maxBytes", "raw"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/http",
3
- "version": "1.16.0",
3
+ "version": "1.17.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,9 +34,9 @@
34
34
  ],
35
35
  "dependencies": {
36
36
  "jose": "^6.2.12",
37
- "@rexezuge/contracts": "1.16.0",
38
- "@rexezuge/errors": "1.16.0",
39
- "@rexezuge/shared": "1.16.0"
37
+ "@rexezuge/contracts": "1.17.0",
38
+ "@rexezuge/errors": "1.17.0",
39
+ "@rexezuge/shared": "1.17.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "chanfana": "^3.4.0",