@rexezuge/http 1.15.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
@@ -241,6 +241,7 @@ createApiApp<Env>({
241
241
  | You want | Door |
242
242
  | ------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
243
243
  | Your own routes | `routes(app)`, or register on the returned app; `FamilyRoute.handleRequest` |
244
+ | Custom verbs (PROPFIND, MKCOL, LOCK, …) | `routes(app, { hono })`: raw Hono routes at the same slot (see below) |
244
245
  | Routes from a shared contract | `registerContract(app, contract, handlers)`; `schemaFromEndpoint` for a hand-written `FamilyRoute` |
245
246
  | Middleware before / after authentication | `hooks.beforeAuth` / `hooks.afterAuth` (a handler, or `{ path, handler }`) |
246
247
  | Another authenticated surface | `auth: { '/partner/*': apiKeyAuth({ verify }) }` |
@@ -248,12 +249,42 @@ createApiApp<Env>({
248
249
  | Map a verified address to your account | `accessAuth({ resolveUserId })` |
249
250
  | Extra trusted origins (Pages, custom host) | `hardening.origin.allowedOrigins` (a list, or `(env) => list`) |
250
251
  | Uploads | `hardening.contentType.allowed: ['application/json', 'multipart/form-data']`, `hardening.maxBodyBytes` |
252
+ | A bigger body on one path | `hardening.maxBodyBytes: { default, paths: [{ match, maxBytes }] }` |
253
+ | A non-JSON plane under a guarded prefix | `hardening.contentType.exclude` / `hardening.origin.exclude` (logged at startup) |
254
+ | A path a rate-limit rule must not charge | `rateLimits[].exclude` |
251
255
  | Your logger / redacting sink | `logger: (env, requestId) => createLogger(…, sink)` |
252
256
  | A protocol dialect (Subsonic, WebDAV) | `errors.toResponse` app-wide, or `FamilyRoute.errorMapping()` per route |
253
257
  | More context variables | the `V` type parameter |
254
258
  | Which paths are `no-store` | `sensitivePaths: ['/generate-totp', '/user/', /^\/export\//, (path) => …]` (see below) |
255
259
  | Diagnose a 5xx in your own log sink | `errors.reportUnhandled(error, { status, requestId, method, route })` |
256
260
 
261
+ ### Custom verbs, per-path limits and excludes (a WebDAV worker)
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`. 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
+
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
+
267
+ ```ts
268
+ createApiApp<Env>({
269
+ hardening: {
270
+ methods: [...DEFAULT_ALLOWED_METHODS, 'PROPFIND', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK', 'PROPPATCH', 'REPORT'],
271
+ // JSON everywhere is capped at 1 MiB; the DAV plane takes file bodies. The first matching rule wins.
272
+ maxBodyBytes: { default: 1_048_576, paths: [{ match: '/user/volumes/', maxBytes: 5 * 1024 ** 3 }] },
273
+ // The DAV plane carries XML and is called cross-origin; the rest of /user/* keeps both guards.
274
+ contentType: { exclude: [/^\/user\/volumes\/[^/]+\/[^/]+\/files\//] },
275
+ origin: { exclude: [/^\/user\/volumes\/[^/]+\/[^/]+\/files\//] },
276
+ },
277
+ // A rule's `path` is a Hono pattern; `exclude` carves a namespace another rule owns out of it.
278
+ rateLimits: [{ path: '/:owner/:volume/*', keyPrefix: 'webdav', windowMs: 60_000, max: 600, exclude: ['/user/'] }],
279
+ routes: (app, { hono }) => {
280
+ app.get('/health', (c) => c.json({ ok: true }));
281
+ hono.on(['PROPFIND', 'MKCOL', 'COPY', 'MOVE'], '/user/volumes/:owner/:volume/files/*', handleDav);
282
+ },
283
+ });
284
+ ```
285
+
286
+ `maxBodyBytes` caps a declared `Content-Length` and a streamed (chunked) body alike, and the streamed cap replaces the request body, so a JSON body chanfana validates is capped before it is parsed.
287
+
257
288
  Closed, with no flag: the slot order, the error envelope and its masking, `no-store` on every response of a sensitive path, the CSP
258
289
  (strict everywhere, Swagger UI's directory on the docs page only), log redaction (no caught value, message or stack in a log line), `email_verified` enforcement, the origin guard on `/user/*`, the
259
290
  `@final` route `handle()`.
@@ -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,QAAQ,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC;AAEnF,UAAU,kBAAkB;IAC1B;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;MAEE;IACF,UAAU,CAAC,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;IACvE;;MAEE;IACF,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtE;;;;OAIG;IACH,UAAU,CAAC,EAAE,kBAAkB,CAAC;IAChC;;MAEE;IACF,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAED;;EAEE;AACF,UAAU,WAAW;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE;QAAE,SAAS,EAAE;YAAE,IA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S,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,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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, MappedError };\n"],
5
+ "mappings": "+EAyCA,OAAS,iBAAAA,MAAmC,mBAC5C,OAAS,gBAAAC,MAAoB,mBAE7B,OAAS,qBAAAC,EAAmB,sBAAAC,EAAoB,kBAAAC,MAAsB,2BACtE,OAAS,oBAAAC,MAAwB,qBAgDjC,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,OAASX,GAAc,IAAG,EAK/C,MAAO,CAAE,MAJW,IAAIE,EAAmB,IAAK,qBAAsBD,EAAkB,oBAAoB,EAAG,CAC7G,MAAOM,EACP,OAAQ,GACT,EAC4B,WAAY,KAAK,IAAI,EAAG,KAAK,MAAMK,EAAM,SAAWC,GAAO,GAAI,CAAC,CAAC,CAChG,CACA,OAAIH,aAAwBX,GAAiBW,EAAa,UACjD,CAAE,MAAO,IAAIR,EAAmB,IAAK,qBAAsBQ,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,EAAOJ,EAAeI,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,GAC/EL,aAAwBN,IAAkBa,EAAQ,MAAWP,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,mBAAmB,CAAC,EAAE,CAAC,EAC9B,CAAC,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,KACnB,YAAY,CAAC,WAAW,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAEnD;;EAEE;AACF,KAAK,gBAAgB,CAAC,CAAC,SAAS,iBAAiB,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;KACxG,CAAC,IAAI,MAAM,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AAEH,KAAK,aAAa,GAAG,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC;AAE9C;;GAEG;AACH,iBAAS,kBAAkB,CAAC,QAAQ,EAAE,QAAQ,GAAG,kBAAkB,CAwBlE;AA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AAgB,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,EAAS,OAAO,OACpB,CAAA,EACA,GAAGH,EAAS,eAAe,IAAI,CAAC,CAAE,OAAAI,EAAQ,YAAAC,CAAW,IACnDR,EAAeQ,IAAgB,KAAO,CAACD,CAAM,EAAI,CAAE,CAACA,CAAM,EAAGC,CAAW,CAAE,CAAC,CAC5E,EAGH,MAAO,CACL,GAAIL,EAAS,UAAY,QAAa,CAAE,QAASA,EAAS,OAAO,EACjE,GAAIA,EAAS,cAAgB,QAAa,CAAE,YAAaA,EAAS,WAAW,EAC7E,GAAIA,EAAS,OAAS,QAAa,CAAE,KAAM,CAAC,GAAGA,EAAS,IAAI,CAAC,EAC7D,QAAAC,EACA,UAAW,CAAE,GAAGC,EAAS,GAAGC,CAAM,EAEtC,CAxBSG,EAAAP,EAAA,sBA8BT,SAASQ,EACPP,EACAQ,EAAkC,CAElC,MAAMC,EAASV,EAAmBC,CAAQ,EACpCU,EAAgBV,E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AAkBP,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,G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", "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
  }
@@ -1,4 +1,5 @@
1
1
  import type { HonoOpenAPIRouterType } from 'chanfana';
2
+ import { Hono } from 'hono';
2
3
  import type { MiddlewareHandler } from 'hono';
3
4
  import { cors } from 'hono/cors';
4
5
  import type { SensitivePath } from '../securityHeaders.ts';
@@ -78,8 +79,16 @@ interface ApiAppOptions<E extends object, V extends object = object> extends Req
78
79
  docs?: DocsOptions | false;
79
80
  /**
80
81
  Register your routes. Runs last, after every kit slot.
82
+
83
+ The second argument carries the raw Hono instance (`{ hono }`) for what chanfana's router cannot
84
+ express: custom verbs (`hono.on(['PROPFIND', 'MKCOL'], '/dav/*', handler)`), `all`, sub-app mounts. A
85
+ route on it sits at the same position, after every guard, limiter and auth step, and inside the
86
+ same error boundary. It is not in the OpenAPI document.
81
87
  */
82
- routes?: (app: ApiApp<E, V>) => void;
88
+ routes?: (app: ApiApp<E, V>, raw: RawRoutes<E, V>) => void;
89
+ }
90
+ interface RawRoutes<E extends object, V extends object = object> {
91
+ hono: Hono<FamilyEnv<E, V>>;
83
92
  }
84
93
  type AppHook<E extends object, V extends object> = MiddlewareHandler<FamilyEnv<E, V>> | {
85
94
  path: string;
@@ -96,5 +105,5 @@ declare const ERROR_OPTIONS_KEY = "errorMapperOptions";
96
105
  */
97
106
  declare function createApiApp<E extends object, V extends object = object>(options?: ApiAppOptions<E, V>): ApiApp<E, V>;
98
107
  export { createApiApp, ERROR_OPTIONS_KEY };
99
- export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };
108
+ export type { ApiApp, ApiAppOptions, AppHook, RawRoutes, CorsOptions, DocsOptions };
100
109
  //# sourceMappingURL=createApiApp.d.ts.map
@@ -1 +1 @@
1
- {"version":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OE;IACF,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC;CAC5D;AAED,UAAU,SAAS,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM;IAC7D,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;CAC7B;AAED,KAAK,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,IAC7C,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;CAAE,CAAC;AAErG;;EAEE;AACF,QAAA,MAAM,iBAAiB,uBAAuB,CAAC;AA2E/C;;;;GAIG;AACH,iBAAS,YAAY,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,OAAO,GAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAM,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAmBlH;AAED,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC3C,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC"}
@@ -1 +1 @@
1
- var d=Object.defineProperty;var n=(e,r)=>d(e,"name",{value:r,configurable:!0});import{fromHono as m}from"chanfana";import{Hono as p}from"hono";import{cors as h}from"hono/cors";import{securityHeaders as y,sensitivePathMatcher as _}from"../securityHeaders.js";import{d1Bookmarks as T}from"./bookmarks.js";import{DOCS_CONTENT_SECURITY_POLICY as O,isDocsPath as E}from"./docs.js";import{createErrorHandler as H,createNotFoundHandler as P}from"./errorHandler.js";import{bodyLimitGuard as R,contentTypeGuard as k,methodGuard as A,originGuard as C}from"./hardening.js";import{rateLimitRule as i}from"./rateLimits.js";import{requestContext as N}from"./requestContext.js";const c="errorMapperOptions",S=["/user/*"],g=["/user/*","/api/*"];function f(e,r){for(const s of r??[])typeof s=="function"?e.use("*",s):e.use(s.path,s.handler)}n(f,"mountHooks");function w(e){return e===!1?{docs_url:null,openapi_url:null,redoc_url:null,raiseOnError:!0}:{docs_url:e?.url??"/docs",openapi_url:e?.openapiUrl??"/openapi.json",redoc_url:null,raiseOnError:!0,...e?.info&&{schema:{info:e.info}}}}n(w,"routerOptions");function x(e,r){e.use("*",N(r)),e.use("*",async(t,o)=>{t.set(c,r.errors??{}),await o()});const s=y(_(...r.sensitivePaths??["/user/","/api/"])),a=r.docs===!1?null:r.docs?.url??"/docs";if(e.use("*",async(t,o)=>{await s(t,o),a!==null&&E(t.req.path,a)&&(t.res.headers.get("content-type")??"").includes("text/html")&&t.header("Content-Security-Policy",O)}),r.cors){const t=[...new Set([...r.cors.exposeHeaders??[],"X-Request-Id"])];e.use("*",h({...r.cors,exposeHeaders:t}))}const u=r.hardening??{};e.use("*",A(u.methods)),e.use("*",R(u.maxBodyBytes));for(const t of u.contentType?.paths??g)e.use(t,k(u.contentType?.allowed));for(const t of u.origin?.paths??S)e.use(t,C(u.origin));if(r.d1)for(const t of r.d1.paths??["*"])e.use(t,T(r.d1))}n(x,"mountPlatform");function I(e={}){const r=new p;r.onError(H(e.errors)),r.notFound(P()),x(r,e);const s=e.rateLimits??[],a=s.filter(o=>o.key==="ip"),u=s.filter(o=>o.key!=="ip");for(const o of a)r.use(o.path,i(o));f(r,e.hooks?.beforeAuth);for(const[o,l]of Object.entries(e.auth??{}))r.use(o,l);for(const o of u)r.use(o.path,i(o));f(r,e.hooks?.afterAuth);const t=m(r,w(e.docs));return e.routes?.(t),t}n(I,"createApiApp");export{c as ERROR_OPTIONS_KEY,I as createApiApp};
1
+ var m=Object.defineProperty;var a=(e,r)=>m(e,"name",{value:r,configurable:!0});import{fromHono as h}from"chanfana";import{Hono as g}from"hono";import{cors as y}from"hono/cors";import{securityHeaders as T,sensitivePathMatcher as _}from"../securityHeaders.js";import{d1Bookmarks as x}from"./bookmarks.js";import{DOCS_CONTENT_SECURITY_POLICY as E,isDocsPath as O}from"./docs.js";import{createErrorHandler as P,createNotFoundHandler as k}from"./errorHandler.js";import{bodyLimitGuard as H,contentTypeGuard as R,describeMatchers as c,methodGuard as w,originGuard as A,unlessExcluded as i}from"./hardening.js";import{rateLimitRule as l}from"./rateLimits.js";import{consoleLogger as C,requestContext as L}from"./requestContext.js";const d="errorMapperOptions",N=["/user/*"],S=["/user/*","/api/*"];function f(e,r){for(const n of r??[])typeof n=="function"?e.use("*",n):e.use(n.path,n.handler)}a(f,"mountHooks");function G(e){return e===!1?{docs_url:null,openapi_url:null,redoc_url:null,raiseOnError:!0}:{docs_url:e?.url??"/docs",openapi_url:e?.openapiUrl??"/openapi.json",redoc_url:null,raiseOnError:!0,...e?.info&&{schema:{info:e.info}}}}a(G,"routerOptions");function I(e){const r=C("startup"),n=e.contentType?.exclude??[],u=e.origin?.exclude??[];n.length>0&&r.warn(`hardening.contentType.exclude: the content-type guard skips ${c(n)}`),u.length>0&&r.warn(`hardening.origin.exclude: the origin guard skips ${c(u)}`)}a(I,"logExcludedGuardPaths");function U(e,r){e.use("*",L(r)),e.use("*",async(t,o)=>{t.set(d,r.errors??{}),await o()});const n=T(_(...r.sensitivePaths??["/user/","/api/"])),u=r.docs===!1?null:r.docs?.url??"/docs";if(e.use("*",async(t,o)=>{await n(t,o),u!==null&&O(t.req.path,u)&&(t.res.headers.get("content-type")??"").includes("text/html")&&t.header("Content-Security-Policy",E)}),r.cors){const t=[...new Set([...r.cors.exposeHeaders??[],"X-Request-Id"])];e.use("*",y({...r.cors,exposeHeaders:t}))}const s=r.hardening??{};e.use("*",w(s.methods)),e.use("*",H(s.maxBodyBytes));for(const t of s.contentType?.paths??S)e.use(t,i(R(s.contentType?.allowed),s.contentType?.exclude));for(const t of s.origin?.paths??N)e.use(t,i(A(s.origin),s.origin?.exclude));if(I(s),r.d1)for(const t of r.d1.paths??["*"])e.use(t,x(r.d1))}a(U,"mountPlatform");function b(e={}){const r=new g;r.onError(P(e.errors)),r.notFound(k()),U(r,e);const n=e.rateLimits??[],u=n.filter(o=>o.key==="ip"),s=n.filter(o=>o.key!=="ip");for(const o of u)r.use(o.path,l(o));f(r,e.hooks?.beforeAuth);for(const[o,p]of Object.entries(e.auth??{}))r.use(o,p);for(const o of s)r.use(o.path,l(o));f(r,e.hooks?.afterAuth);const t=h(r,G(e.docs));return e.routes?.(t,{hono:r}),t}a(b,"createApiApp");export{d as ERROR_OPTIONS_KEY,b as createApiApp};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/hono/createApiApp.ts"],
4
- "sourcesContent": ["/**\n * `createApiApp` — the family API worker's Hono + chanfana app, pre-wired.\n *\n * Every family worker hand-assembled the same stack in its constructor, and each\n * assembly had its own ordering bug: a limiter installed before auth (per-IP\n * buckets for an office NAT), security headers registered after a middleware\n * that returns early (no headers on the 401), no `onError` (a text 500 the SPA\n * cannot parse), a D1 session opened by mutating the shared `env`. The order is\n * the kit's now, and it is **closed**:\n *\n * | # | Slot | Why here |\n * | -- | ----------------------- | ---------------------------------------------------------------- |\n * | 1 | request id + logger | everything after can log and correlate |\n * | 2 | security headers | wraps the rest, so a 401/404/500 leaves with them |\n * | 3 | CORS (option) | a preflight answers before any guard or auth |\n * | 4 | hardening | method, body size, JSON content type, origin guard: cheap, no I/O |\n * | 5 | D1 bookmarks (option) | auth's account lookup already reads through the session |\n * | 6 | `ip` rate limits | throttle before the auth step spends D1 on an anonymous caller |\n * | 7 | `beforeAuth` hooks | your middleware that must see the request unauthenticated |\n * | 8 | auth surfaces | `accessAuth` on `/user/*`, `apiKeyAuth` on `/api/*`, … |\n * | 9 | `identity` rate limits | keyed on the account, which only exists after 8 |\n * | 10 | `afterAuth` hooks | your middleware that needs the account (request scope, audit) |\n * | 11 | `routes(app)` | your routes |\n *\n * plus `onError` (the kit mapper → `{Exception:{Type,Message}}`), `notFound` (the\n * same envelope) and `/docs` + `/openapi.json` (option).\n */\nimport { fromHono } from 'chanfana';\nimport type { HonoOpenAPIRouterType, RouterOptions } from 'chanfana';\nimport { Hono } from 'hono';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\nimport { securityHeaders, sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { SensitivePath } from '../securityHeaders.ts';\nimport { d1Bookmarks } from './bookmarks.ts';\nimport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath } from './docs.ts';\nimport type { D1BookmarkOptions } from './bookmarks.ts';\nimport { createErrorHandler, createNotFoundHandler } from './errorHandler.ts';\nimport type { ErrorBoundaryOptions } from './errorHandler.ts';\nimport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`, on **every** response for them: success, the IP\n * rate limiter's 429, the error envelope and a 404. Applied in the kit's own early middleware, which no hook\n * can bypass. Defaults to `['/user/', '/api/']`: both surfaces carry credentials or account data.\n *\n * Entries are `string | RegExp | ((path: string) => boolean)`. A string is an **exact** path (`'/generate-totp'`),\n * unless it ends in `/` or `/*`, which makes it a **prefix** (`'/user/'`, `'/user/*'`). Strings ending in `/`\n * were prefixes before exact matching existed and stay so; a bare `'/user'` is now the exact path, not\n * `/user/*`.\n */\n sensitivePaths?: readonly SensitivePath[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`) and `reportUnhandled`, the sink that receives the raw error of a 5xx.\n */\n errors?: ErrorBoundaryOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n */\n routes?: (app: ApiApp<E, V>) => void;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n const headers = securityHeaders(sensitivePathMatcher(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler;\n const docsUrl = options.docs === false ? null : (options.docs?.url ?? '/docs');\n hono.use('*', async (c, next) => {\n await headers(c, next);\n // Closed: the docs page (and only it) gets the policy that admits the\n // Swagger UI assets. Every other HTML response keeps the strict one.\n if (docsUrl !== null && isDocsPath(c.req.path, docsUrl) && (c.res.headers.get('content-type') ?? '').includes('text/html')) {\n c.header('Content-Security-Policy', DOCS_CONTENT_SECURITY_POLICY);\n }\n });\n if (options.cors) {\n const exposeHeaders = [...new Set([...(options.cors.exposeHeaders ?? []), 'X-Request-Id'])];\n hono.use('*', cors({ ...options.cors, exposeHeaders }));\n }\n\n const hardening = options.hardening ?? {};\n hono.use('*', methodGuard(hardening.methods));\n hono.use('*', bodyLimitGuard(hardening.maxBodyBytes));\n for (const path of hardening.contentType?.paths ?? DEFAULT_CONTENT_TYPE_PATHS) {\n hono.use(path, contentTypeGuard(hardening.contentType?.allowed));\n }\n for (const path of hardening.origin?.paths ?? DEFAULT_ORIGIN_PATHS) {\n hono.use(path, originGuard<E>(hardening.origin));\n }\n\n if (options.d1) {\n for (const path of options.d1.paths ?? ['*']) hono.use(path, d1Bookmarks<E>(options.d1));\n }\n}\n\n/**\n * Build the app. The returned value is the chanfana router: register routes on\n * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's\n * `onRequest`.\n */\nfunction createApiApp<E extends object, V extends object = object>(options: ApiAppOptions<E, V> = {}): ApiApp<E, V> {\n const hono = new Hono<FamilyEnv<E, V>>();\n hono.onError(createErrorHandler(options.errors));\n hono.notFound(createNotFoundHandler());\n\n mountPlatform(hono, options);\n\n const rules = options.rateLimits ?? [];\n const ipRules = rules.filter((entry) => entry.key === 'ip');\n const identityRules = rules.filter((entry) => entry.key !== 'ip');\n for (const rule of ipRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.beforeAuth);\n for (const [path, middleware] of Object.entries(options.auth ?? {})) hono.use(path, middleware);\n for (const rule of identityRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.afterAuth);\n\n const app = fromHono(hono, routerOptions(options.docs)) as ApiApp<E, V>;\n options.routes?.(app);\n return app;\n}\n\nexport { createApiApp, ERROR_OPTIONS_KEY };\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };\n"],
5
- "mappings": "+EA2BA,OAAS,YAAAA,MAAgB,WAEzB,OAAS,QAAAC,MAAY,OAErB,OAAS,QAAAC,MAAY,YACrB,OAAS,mBAAAC,EAAiB,wBAAAC,MAA4B,wBAEtD,OAAS,eAAAC,MAAmB,iBAC5B,OAAS,gCAAAC,EAA8B,cAAAC,MAAkB,YAEzD,OAAS,sBAAAC,EAAoB,yBAAAC,MAA6B,oBAE1D,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAE3E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U,IAAK,OAAO,QAAQd,EAAQ,MAAQ,CAAA,CAAE,EAAGP,EAAK,IAAIc,EAAMO,CAAU,EAC9F,UAAWD,KAAQD,EAAenB,EAAK,IAAIoB,EAAK,KAAM1B,EAAiB0B,CAAI,CAAC,EAC5ErB,EAAWC,EAAMO,EAAQ,OAAO,SAAS,EAEzC,MAAMe,EAAM1C,EAASoB,EAAMI,EAAcG,EAAQ,IAAI,CAAC,EACtD,OAAAA,EAAQ,SAASe,CAAG,EACbA,CACT,CAnBSnB,EAAAY,EAAA",
6
- "names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePathMatcher", "d1Bookmarks", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "createErrorHandler", "createNotFoundHandler", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "rateLimitRule", "requestContext", "ERROR_OPTIONS_KEY", "DEFAULT_ORIGIN_PATHS", "DEFAULT_CONTENT_TYPE_PATHS", "mountHooks", "hono", "hooks", "hook", "__name", "routerOptions", "docs", "mountPlatform", "options", "c", "next", "headers", "docsUrl", "exposeHeaders", "hardening", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
4
+ "sourcesContent": ["/**\n * `createApiApp` — the family API worker's Hono + chanfana app, pre-wired.\n *\n * Every family worker hand-assembled the same stack in its constructor, and each\n * assembly had its own ordering bug: a limiter installed before auth (per-IP\n * buckets for an office NAT), security headers registered after a middleware\n * that returns early (no headers on the 401), no `onError` (a text 500 the SPA\n * cannot parse), a D1 session opened by mutating the shared `env`. The order is\n * the kit's now, and it is **closed**:\n *\n * | # | Slot | Why here |\n * | -- | ----------------------- | ---------------------------------------------------------------- |\n * | 1 | request id + logger | everything after can log and correlate |\n * | 2 | security headers | wraps the rest, so a 401/404/500 leaves with them |\n * | 3 | CORS (option) | a preflight answers before any guard or auth |\n * | 4 | hardening | method, body size, JSON content type, origin guard: cheap, no I/O |\n * | 5 | D1 bookmarks (option) | auth's account lookup already reads through the session |\n * | 6 | `ip` rate limits | throttle before the auth step spends D1 on an anonymous caller |\n * | 7 | `beforeAuth` hooks | your middleware that must see the request unauthenticated |\n * | 8 | auth surfaces | `accessAuth` on `/user/*`, `apiKeyAuth` on `/api/*`, … |\n * | 9 | `identity` rate limits | keyed on the account, which only exists after 8 |\n * | 10 | `afterAuth` hooks | your middleware that needs the account (request scope, audit) |\n * | 11 | `routes(app)` | your routes |\n *\n * plus `onError` (the kit mapper → `{Exception:{Type,Message}}`), `notFound` (the\n * same envelope) and `/docs` + `/openapi.json` (option).\n */\nimport { fromHono } from 'chanfana';\nimport type { HonoOpenAPIRouterType, RouterOptions } from 'chanfana';\nimport { Hono } from 'hono';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\nimport { securityHeaders, sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { SensitivePath } from '../securityHeaders.ts';\nimport { d1Bookmarks } from './bookmarks.ts';\nimport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath } from './docs.ts';\nimport type { D1BookmarkOptions } from './bookmarks.ts';\nimport { createErrorHandler, createNotFoundHandler } from './errorHandler.ts';\nimport type { ErrorBoundaryOptions } from './errorHandler.ts';\nimport { bodyLimitGuard, contentTypeGuard, describeMatchers, methodGuard, originGuard, unlessExcluded } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { consoleLogger, requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`, on **every** response for them: success, the IP\n * rate limiter's 429, the error envelope and a 404. Applied in the kit's own early middleware, which no hook\n * can bypass. Defaults to `['/user/', '/api/']`: both surfaces carry credentials or account data.\n *\n * Entries are `string | RegExp | ((path: string) => boolean)`. A string is an **exact** path (`'/generate-totp'`),\n * unless it ends in `/` or `/*`, which makes it a **prefix** (`'/user/'`, `'/user/*'`). Strings ending in `/`\n * were prefixes before exact matching existed and stay so; a bare `'/user'` is now the exact path, not\n * `/user/*`.\n */\n sensitivePaths?: readonly SensitivePath[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`) and `reportUnhandled`, the sink that receives the raw error of a 5xx.\n */\n errors?: ErrorBoundaryOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n\n The second argument carries the raw Hono instance (`{ hono }`) for what chanfana's router cannot\n express: custom verbs (`hono.on(['PROPFIND', 'MKCOL'], '/dav/*', handler)`), `all`, sub-app mounts. A\n route on it sits at the same position, after every guard, limiter and auth step, and inside the\n same error boundary. It is not in the OpenAPI document.\n */\n routes?: (app: ApiApp<E, V>, raw: RawRoutes<E, V>) => void;\n}\n\ninterface RawRoutes<E extends object, V extends object = object> {\n hono: Hono<FamilyEnv<E, V>>;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * A guard's `exclude` is a loosening, so it is announced: once per app, as a static message listing the\n * configured patterns (never a request value).\n */\nfunction logExcludedGuardPaths(hardening: HardeningOptions<never>): void {\n const logger = consoleLogger('startup');\n const contentType = hardening.contentType?.exclude ?? [];\n const origin = hardening.origin?.exclude ?? [];\n if (contentType.length > 0) logger.warn(`hardening.contentType.exclude: the content-type guard skips ${describeMatchers(contentType)}`);\n if (origin.length > 0) logger.warn(`hardening.origin.exclude: the origin guard skips ${describeMatchers(origin)}`);\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n const headers = securityHeaders(sensitivePathMatcher(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler;\n const docsUrl = options.docs === false ? null : (options.docs?.url ?? '/docs');\n hono.use('*', async (c, next) => {\n await headers(c, next);\n // Closed: the docs page (and only it) gets the policy that admits the\n // Swagger UI assets. Every other HTML response keeps the strict one.\n if (docsUrl !== null && isDocsPath(c.req.path, docsUrl) && (c.res.headers.get('content-type') ?? '').includes('text/html')) {\n c.header('Content-Security-Policy', DOCS_CONTENT_SECURITY_POLICY);\n }\n });\n if (options.cors) {\n const exposeHeaders = [...new Set([...(options.cors.exposeHeaders ?? []), 'X-Request-Id'])];\n hono.use('*', cors({ ...options.cors, exposeHeaders }));\n }\n\n const hardening = options.hardening ?? {};\n hono.use('*', methodGuard(hardening.methods));\n hono.use('*', bodyLimitGuard(hardening.maxBodyBytes));\n for (const path of hardening.contentType?.paths ?? DEFAULT_CONTENT_TYPE_PATHS) {\n hono.use(path, unlessExcluded(contentTypeGuard(hardening.contentType?.allowed), hardening.contentType?.exclude));\n }\n for (const path of hardening.origin?.paths ?? DEFAULT_ORIGIN_PATHS) {\n hono.use(path, unlessExcluded(originGuard<E>(hardening.origin), hardening.origin?.exclude));\n }\n logExcludedGuardPaths(hardening);\n\n if (options.d1) {\n for (const path of options.d1.paths ?? ['*']) hono.use(path, d1Bookmarks<E>(options.d1));\n }\n}\n\n/**\n * Build the app. The returned value is the chanfana router: register routes on\n * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's\n * `onRequest`.\n */\nfunction createApiApp<E extends object, V extends object = object>(options: ApiAppOptions<E, V> = {}): ApiApp<E, V> {\n const hono = new Hono<FamilyEnv<E, V>>();\n hono.onError(createErrorHandler(options.errors));\n hono.notFound(createNotFoundHandler());\n\n mountPlatform(hono, options);\n\n const rules = options.rateLimits ?? [];\n const ipRules = rules.filter((entry) => entry.key === 'ip');\n const identityRules = rules.filter((entry) => entry.key !== 'ip');\n for (const rule of ipRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.beforeAuth);\n for (const [path, middleware] of Object.entries(options.auth ?? {})) hono.use(path, middleware);\n for (const rule of identityRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.afterAuth);\n\n const app = fromHono(hono, routerOptions(options.docs)) as ApiApp<E, V>;\n options.routes?.(app, { hono });\n return app;\n}\n\nexport { createApiApp, ERROR_OPTIONS_KEY };\nexport type { ApiApp, ApiAppOptions, AppHook, RawRoutes, CorsOptions, DocsOptions };\n"],
5
+ "mappings": "+EA2BA,OAAS,YAAAA,MAAgB,WAEzB,OAAS,QAAAC,MAAY,OAErB,OAAS,QAAAC,MAAY,YACrB,OAAS,mBAAAC,EAAiB,wBAAAC,MAA4B,wBAEtD,OAAS,eAAAC,MAAmB,iBAC5B,OAAS,gCAAAC,EAA8B,cAAAC,MAAkB,YAEzD,OAAS,sBAAAC,EAAoB,yBAAAC,MAA6B,oBAE1D,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,EAAa,kBAAAC,MAAsB,iBAE7G,OAAS,iBAAAC,MAAqB,kBAE9B,OAAS,iBAAAC,EAAe,kBAAAC,MAAsB,sBA4F9C,MAAMC,EAAoB,qBAEpBC,EAA0C,CAAC,SAAS,EACpDC,EAAgD,CAAC,UAAW,QAAQ,EAE1E,SAASC,EAA+CC,EAA6BC,EAA2C,CAC9H,UAAWC,KAAQD,GAAS,CAAA,EACtB,OAAOC,GAAS,WAAYF,EAAK,IAAI,IAAKE,CAAI,EAC7CF,EAAK,IAAIE,EAAK,KAAMA,EAAK,OAAO,CAEzC,CALSC,EAAAJ,EAAA,c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AI,CAAC,EACtEzB,EAAWC,EAAMY,EAAQ,OAAO,UAAU,EAC1C,SAAW,CAACM,EAAMO,CAAU,IAAK,OAAO,QAAQb,EAAQ,MAAQ,CAAA,CAAE,EAAGZ,EAAK,IAAIkB,EAAMO,CAAU,EAC9F,UAAWD,KAAQD,EAAevB,EAAK,IAAIwB,EAAK,KAAM/B,EAAiB+B,CAAI,CAAC,EAC5EzB,EAAWC,EAAMY,EAAQ,OAAO,SAAS,EAEzC,MAAMc,EAAMjD,EAASuB,EAAMI,EAAcQ,EAAQ,IAAI,CAAC,EACtD,OAAAA,EAAQ,SAASc,EAAK,CAAE,KAAA1B,CAAI,CAAE,EACvB0B,CACT,CAnBSvB,EAAAgB,EAAA",
6
+ "names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePathMatcher", "d1Bookmarks", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "createErrorHandler", "createNotFoundHandler", "bodyLimitGuard", "contentTypeGuard", "describeMatchers", "methodGuard", "originGuard", "unlessExcluded", "rateLimitRule", "consoleLogger", "requestContext", "ERROR_OPTIONS_KEY", "DEFAULT_ORIGIN_PATHS", "DEFAULT_CONTENT_TYPE_PATHS", "mountHooks", "hono", "hooks", "hook", "__name", "routerOptions", "docs", "logExcludedGuardPaths", "hardening", "logger", "contentType", "origin", "mountPlatform", "options", "c", "next", "headers", "docsUrl", "exposeHeaders", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
7
7
  }
@@ -1,4 +1,5 @@
1
1
  import type { MiddlewareHandler } from 'hono';
2
+ import type { PathMatcher } from '../securityHeaders.ts';
2
3
  import type { FromEnv } from './types.ts';
3
4
  interface OriginPolicy<E> {
4
5
  /**
@@ -13,6 +14,12 @@ interface OriginPolicy<E> {
13
14
  Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.
14
15
  */
15
16
  allowMissingOrigin?: boolean;
17
+ /**
18
+ * Paths **inside** `paths` that skip this guard (a session-authenticated surface that cross-origin
19
+ * clients legitimately call). Same matcher semantics as `sensitivePaths`. The patterns are logged
20
+ * once at startup so the loosening is visible. There is deliberately no way to switch the guard off.
21
+ */
22
+ exclude?: readonly PathMatcher[];
16
23
  }
17
24
  interface ContentTypePolicy {
18
25
  /**
@@ -23,6 +30,23 @@ interface ContentTypePolicy {
23
30
  The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.
24
31
  */
25
32
  allowed?: readonly string[];
33
+ /**
34
+ * Paths **inside** `paths` that skip this guard (an XML or binary plane under a JSON prefix). Same
35
+ * matcher semantics as `sensitivePaths`. The patterns are logged once at startup so the loosening is
36
+ * visible. There is deliberately no way to switch the guard off.
37
+ */
38
+ exclude?: readonly PathMatcher[];
39
+ }
40
+ /**
41
+ * Per-path body ceilings. The first rule whose `match` accepts the request path wins; `default`
42
+ * applies to every other path.
43
+ */
44
+ interface BodyLimitPolicy {
45
+ default: number;
46
+ paths: ReadonlyArray<{
47
+ match: PathMatcher;
48
+ maxBytes: number;
49
+ }>;
26
50
  }
27
51
  interface HardeningOptions<E> {
28
52
  /**
@@ -30,22 +54,36 @@ interface HardeningOptions<E> {
30
54
  */
31
55
  methods?: readonly string[];
32
56
  /**
33
- The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB.
57
+ The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB. Pass `{ default, paths }` to
58
+ give some paths (an upload route) a different ceiling; the first matching rule wins. Every ceiling is
59
+ validated at construction, and the cap applies to bodies chanfana parses too.
34
60
  */
35
- maxBodyBytes?: number;
61
+ maxBodyBytes?: number | BodyLimitPolicy;
36
62
  contentType?: ContentTypePolicy;
37
63
  origin?: OriginPolicy<E>;
38
64
  }
39
65
  declare function methodGuard(methods?: readonly string[]): MiddlewareHandler;
40
66
  /**
41
67
  * The declared-length check first (cheap, no read), then Hono's streaming cap
42
- * for a chunked body that declares nothing.
68
+ * for a chunked body that declares nothing. The streaming cap replaces the
69
+ * request body, so a body chanfana parses afterwards is capped too.
70
+ *
71
+ * With a `{ default, paths }` policy the ceiling is chosen per request path.
72
+ */
73
+ declare function bodyLimitGuard(limit?: number | BodyLimitPolicy): MiddlewareHandler;
74
+ /**
75
+ * Skip `guard` on the paths `exclude` matches. Used for the guards' `exclude` option; the guard itself
76
+ * stays unconditional everywhere else.
43
77
  */
44
- declare function bodyLimitGuard(maxBytes?: number): MiddlewareHandler;
78
+ declare function unlessExcluded(guard: MiddlewareHandler, exclude: readonly PathMatcher[] | undefined): MiddlewareHandler;
79
+ /**
80
+ A static, loggable form of a matcher: strings and regexes as written, a predicate as a placeholder.
81
+ */
82
+ declare function describeMatchers(entries: readonly PathMatcher[]): string;
45
83
  declare function contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler;
46
84
  declare function originGuard<E extends object>(policy?: OriginPolicy<E>): MiddlewareHandler<{
47
85
  Bindings: E;
48
86
  }>;
49
- export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard };
50
- export type { ContentTypePolicy, HardeningOptions, OriginPolicy };
87
+ export { bodyLimitGuard, contentTypeGuard, describeMatchers, methodGuard, originGuard, unlessExcluded };
88
+ export type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy };
51
89
  //# sourceMappingURL=hardening.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hardening.d.ts","sourceRoot":"","sources":["../../src/hono/hardening.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAW9C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,UAAU,YAAY,CAAC,CAAC;IACtB;;MAEE;IACF,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B;;MAEE;IACF,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IAC/C;;MAEE;IACF,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,UAAU,iBAAiB;IACz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AAG,MAAM,CAEjE;AAED,iBAAS,gBAAgB,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,iBAAiB,CAMxE;AAED,iBAAS,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,GAAE,YAAY,CAAC,CAAC,CAAM,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAOvG;AAED,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,CAAC;AACxG,YAAY,EAAE,eAAe,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,CAAC"}
@@ -1 +1 @@
1
- var a=Object.defineProperty;var i=(r,n)=>a(r,"name",{value:n,configurable:!0});import{bodyLimit as c}from"hono/body-limit";import{PayloadTooLargeError as s}from"@rexezuge/errors";import{checkContentLength as w,checkContentType as d,checkMethod as u,checkOrigin as f,DEFAULT_ALLOWED_METHODS as g,DEFAULT_MAX_BODY_BYTES as h}from"../requestGuards.js";import{resolveFromEnv as m}from"./types.js";function l(r=g){return async(n,e)=>{const o=u(n.req.method,r);if(o)throw o;await e()}}i(l,"methodGuard");function E(r=h){if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Invalid maxBodyBytes: ${String(r)} (must be a positive integer)`);const n=c({maxSize:r,onError:i(()=>{throw new s},"onError")});return async(e,o)=>{const t=w(e.req.raw,r);if(t)throw t;return n(e,o)}}i(E,"bodyLimitGuard");function O(r){return async(n,e)=>{const o=d(n.req.raw,r);if(o)throw o;await e()}}i(O,"contentTypeGuard");function L(r={}){return async(n,e)=>{const o=r.allowedOrigins===void 0?[]:m(r.allowedOrigins,n.env),t=f(n.req.raw,{allowedOrigins:o,allowMissingOrigin:r.allowMissingOrigin});if(t)throw t;await e()}}i(L,"originGuard");export{E as bodyLimitGuard,O as contentTypeGuard,l as methodGuard,L as originGuard};
1
+ var u=Object.defineProperty;var i=(r,n)=>u(r,"name",{value:n,configurable:!0});import{bodyLimit as f}from"hono/body-limit";import{PayloadTooLargeError as d}from"@rexezuge/errors";import{checkContentLength as h,checkContentType as m,checkMethod as w,checkOrigin as g,DEFAULT_ALLOWED_METHODS as p,DEFAULT_MAX_BODY_BYTES as l}from"../requestGuards.js";import{sensitivePathMatcher as c}from"../securityHeaders.js";import{resolveFromEnv as y}from"./types.js";function E(r=p){return async(n,t)=>{const e=w(n.req.method,r);if(e)throw e;await t()}}i(E,"methodGuard");function O(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Invalid maxBodyBytes: ${String(r)} (must be a positive integer)`)}i(O,"assertMaxBytes");function a(r){O(r);const n=f({maxSize:r,onError:i(()=>{throw new d},"onError")});return async(t,e)=>{const o=h(t.req.raw,r);if(o)throw o;return n(t,e)}}i(a,"capGuard");function L(r=l){if(typeof r=="number")return a(r);const n=a(r.default),t=r.paths.map(e=>({matches:c(e.match),guard:a(e.maxBytes)}));return async(e,o)=>(t.find(s=>s.matches(e.req.path))?.guard??n)(e,o)}i(L,"bodyLimitGuard");function M(r,n){if(n===void 0||n.length===0)return r;const t=c(...n);return async(e,o)=>t(e.req.path)?o():r(e,o)}i(M,"unlessExcluded");function b(r){return r.map(n=>typeof n=="function"?"[predicate]":String(n)).join(", ")}i(b,"describeMatchers");function T(r){return async(n,t)=>{const e=m(n.req.raw,r);if(e)throw e;await t()}}i(T,"contentTypeGuard");function q(r={}){return async(n,t)=>{const e=r.allowedOrigins===void 0?[]:y(r.allowedOrigins,n.env),o=g(n.req.raw,{allowedOrigins:e,allowMissingOrigin:r.allowMissingOrigin});if(o)throw o;await t()}}i(q,"originGuard");export{L as bodyLimitGuard,T as contentTypeGuard,b as describeMatchers,E as methodGuard,q as originGuard,M as unlessExcluded};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/hono/hardening.ts"],
4
- "sourcesContent": ["/**\n * The request-hardening middleware: the Hono form of `../requestGuards.ts`.\n *\n * Converged from `apps/api/src/middleware/HttpHardening.ts` (Mail-Bee, Mail-Meow,\n * Mail-Otter, Pigeongram), AWS-AccessBridge's `RequestGuards.ts`, Image-Host's\n * `csrfProtectionHandler` and Pigeongram's `session/origin.ts`. Each guard\n * **throws** its `ServiceError` rather than answering, so the rejection reaches\n * `app.onError` and leaves in the same envelope (and with the same security\n * headers and request id) as every other failure.\n */\nimport { bodyLimit } from 'hono/body-limit';\nimport type { MiddlewareHandler } from 'hono';\nimport { PayloadTooLargeError } from '@rexezuge/errors';\nimport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from '../requestGuards.ts';\nimport { resolveFromEnv } from './types.ts';\nimport type { FromEnv } from './types.ts';\n\ninterface OriginPolicy<E> {\n /**\n The cookie-authenticated surfaces to guard. Defaults to `['/user/*']`.\n */\n paths?: readonly string[];\n /**\n Origins trusted besides the request's own (a Pages origin, a custom domain).\n */\n allowedOrigins?: FromEnv<E, readonly string[]>;\n /**\n Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.\n */\n allowMissingOrigin?: boolean;\n}\n\ninterface ContentTypePolicy {\n /**\n Where JSON mutations are enforced. Defaults to `['/user/*', '/api/*']`.\n */\n paths?: readonly string[];\n /**\n The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.\n */\n allowed?: readonly string[];\n}\n\ninterface HardeningOptions<E> {\n /**\n The methods the app answers. Defaults to {@link DEFAULT_ALLOWED_METHODS}.\n */\n methods?: readonly string[];\n /**\n The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB.\n */\n maxBodyBytes?: number;\n contentType?: ContentTypePolicy;\n origin?: OriginPolicy<E>;\n}\n\nfunction methodGuard(methods: readonly string[] = DEFAULT_ALLOWED_METHODS): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkMethod(c.req.method, methods);\n if (rejection) throw rejection;\n await next();\n };\n}\n\n/**\n * The declared-length check first (cheap, no read), then Hono's streaming cap\n * for a chunked body that declares nothing.\n */\nfunction bodyLimitGuard(maxBytes: number = DEFAULT_MAX_BODY_BYTES): MiddlewareHandler {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new Error(`Invalid maxBodyBytes: ${String(maxBytes)} (must be a positive integer)`);\n }\n const streamed = bodyLimit({\n maxSize: maxBytes,\n onError: (): never => {\n throw new PayloadTooLargeError();\n },\n });\n return async (c, next): Promise<Response | void> => {\n const rejection = checkContentLength(c.req.raw, maxBytes);\n if (rejection) throw rejection;\n return streamed(c, next);\n };\n}\n\nfunction contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkContentType(c.req.raw, allowed);\n if (rejection) throw rejection;\n await next();\n };\n}\n\nfunction originGuard<E extends object>(policy: OriginPolicy<E> = {}): MiddlewareHandler<{ Bindings: E }> {\n return async (c, next): Promise<void> => {\n const allowedOrigins = policy.allowedOrigins === undefined ? [] : resolveFromEnv(policy.allowedOrigins, c.env);\n const rejection = checkOrigin(c.req.raw, { allowedOrigins, allowMissingOrigin: policy.allowMissingOrigin });\n if (rejection) throw rejection;\n await next();\n };\n}\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard };\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy };\n"],
5
- "mappings": "+EAUA,OAAS,aAAAA,MAAiB,kBAE1B,OAAS,wBAAAC,MAA4B,mBACrC,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,sBACP,OAAS,kBAAAC,MAAsB,aA0C/B,SAASC,EAAYC,EAA6BJ,EAAuB,CACvE,MAAO,OAAOK,EAAGC,IAAuB,CACtC,MAAMC,EAAYT,EAAYO,EAAE,IAAI,OAAQD,CAAO,EACnD,GAAIG,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAL,EAAA,eAYT,SAASM,EAAeC,EAAmBT,EAAsB,CAC/D,GAAI,CAAC,OAAO,cAAcS,CAAQ,GAAKA,GAAY,EACjD,MAAM,IAAI,MAAM,yBAAyB,OAAOA,CAAQ,CAAC,+BAA+B,EAE1F,MAAMC,EAAWjB,EAAU,CACzB,QAASgB,EACT,QAASF,EAAA,IAAY,CACnB,MAAM,IAAIb,CACZ,EAFS,WAGV,EACD,MAAO,OAAOU,EAAGC,IAAkC,CACjD,MAAMC,EAAYX,EAAmBS,EAAE,IAAI,IAAKK,CAAQ,EACxD,GAAIH,EAAW,MAAMA,EACrB,OAAOI,EAASN,EAAGC,CAAI,CACzB,CACF,CAfSE,EAAAC,EAAA,kBAiBT,SAASG,EAAiBC,EAA2B,CACnD,MAAO,OAAOR,EAAGC,IAAuB,CACtC,MAAMC,EAAYV,EAAiBQ,EAAE,IAAI,IAAKQ,CAAO,EACrD,GAAIN,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAI,EAAA,oBAQT,SAASE,EAA8BC,EAA0B,CAAA,EAAE,CACjE,MAAO,OAAOV,EAAGC,IAAuB,CACtC,MAAMU,EAAiBD,EAAO,iBAAmB,OAAY,CAAA,EAAKb,EAAea,EAAO,eAAgBV,EAAE,GAAG,EACvGE,EAAYR,EAAYM,EAAE,IAAI,IAAK,CAAE,eAAAW,EAAgB,mBAAoBD,EAAO,kBAAkB,CAAE,EAC1G,GAAIR,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CAPSE,EAAAM,EAAA",
6
- "names": ["bodyLimit", "PayloadTooLargeError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "resolveFromEnv", "methodGuard", "methods", "c", "next", "rejection", "__name", "bodyLimitGuard", "maxBytes", "streamed", "contentTypeGuard", "allowed", "originGuard", "policy", "allowedOrigins"]
4
+ "sourcesContent": ["/**\n * The request-hardening middleware: the Hono form of `../requestGuards.ts`.\n *\n * Converged from `apps/api/src/middleware/HttpHardening.ts` (Mail-Bee, Mail-Meow,\n * Mail-Otter, Pigeongram), AWS-AccessBridge's `RequestGuards.ts`, Image-Host's\n * `csrfProtectionHandler` and Pigeongram's `session/origin.ts`. Each guard\n * **throws** its `ServiceError` rather than answering, so the rejection reaches\n * `app.onError` and leaves in the same envelope (and with the same security\n * headers and request id) as every other failure.\n */\nimport { bodyLimit } from 'hono/body-limit';\nimport type { MiddlewareHandler } from 'hono';\nimport { PayloadTooLargeError } from '@rexezuge/errors';\nimport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from '../requestGuards.ts';\nimport { sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { PathMatcher } from '../securityHeaders.ts';\nimport { resolveFromEnv } from './types.ts';\nimport type { FromEnv } from './types.ts';\n\ninterface OriginPolicy<E> {\n /**\n The cookie-authenticated surfaces to guard. Defaults to `['/user/*']`.\n */\n paths?: readonly string[];\n /**\n Origins trusted besides the request's own (a Pages origin, a custom domain).\n */\n allowedOrigins?: FromEnv<E, readonly string[]>;\n /**\n Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.\n */\n allowMissingOrigin?: boolean;\n /**\n * Paths **inside** `paths` that skip this guard (a session-authenticated surface that cross-origin\n * clients legitimately call). Same matcher semantics as `sensitivePaths`. The patterns are logged\n * once at startup so the loosening is visible. There is deliberately no way to switch the guard off.\n */\n exclude?: readonly PathMatcher[];\n}\n\ninterface ContentTypePolicy {\n /**\n Where JSON mutations are enforced. Defaults to `['/user/*', '/api/*']`.\n */\n paths?: readonly string[];\n /**\n The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.\n */\n allowed?: readonly string[];\n /**\n * Paths **inside** `paths` that skip this guard (an XML or binary plane under a JSON prefix). Same\n * matcher semantics as `sensitivePaths`. The patterns are logged once at startup so the loosening is\n * visible. There is deliberately no way to switch the guard off.\n */\n exclude?: readonly PathMatcher[];\n}\n\n/**\n * Per-path body ceilings. The first rule whose `match` accepts the request path wins; `default`\n * applies to every other path.\n */\ninterface BodyLimitPolicy {\n default: number;\n paths: ReadonlyArray<{ match: PathMatcher; maxBytes: number }>;\n}\n\ninterface HardeningOptions<E> {\n /**\n The methods the app answers. Defaults to {@link DEFAULT_ALLOWED_METHODS}.\n */\n methods?: readonly string[];\n /**\n The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB. Pass `{ default, paths }` to\n give some paths (an upload route) a different ceiling; the first matching rule wins. Every ceiling is\n validated at construction, and the cap applies to bodies chanfana parses too.\n */\n maxBodyBytes?: number | BodyLimitPolicy;\n contentType?: ContentTypePolicy;\n origin?: OriginPolicy<E>;\n}\n\nfunction methodGuard(methods: readonly string[] = DEFAULT_ALLOWED_METHODS): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkMethod(c.req.method, methods);\n if (rejection) throw rejection;\n await next();\n };\n}\n\nfunction assertMaxBytes(maxBytes: number): void {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new Error(`Invalid maxBodyBytes: ${String(maxBytes)} (must be a positive integer)`);\n }\n}\n\nfunction capGuard(maxBytes: number): MiddlewareHandler {\n assertMaxBytes(maxBytes);\n const streamed = bodyLimit({\n maxSize: maxBytes,\n onError: (): never => {\n throw new PayloadTooLargeError();\n },\n });\n return async (c, next): Promise<Response | void> => {\n const rejection = checkContentLength(c.req.raw, maxBytes);\n if (rejection) throw rejection;\n return streamed(c, next);\n };\n}\n\n/**\n * The declared-length check first (cheap, no read), then Hono's streaming cap\n * for a chunked body that declares nothing. The streaming cap replaces the\n * request body, so a body chanfana parses afterwards is capped too.\n *\n * With a `{ default, paths }` policy the ceiling is chosen per request path.\n */\nfunction bodyLimitGuard(limit: number | BodyLimitPolicy = DEFAULT_MAX_BODY_BYTES): MiddlewareHandler {\n if (typeof limit === 'number') return capGuard(limit);\n const fallback = capGuard(limit.default);\n const rules = limit.paths.map((rule) => ({ matches: sensitivePathMatcher(rule.match), guard: capGuard(rule.maxBytes) }));\n return async (c, next): Promise<Response | void> => {\n const rule = rules.find((entry) => entry.matches(c.req.path));\n return (rule?.guard ?? fallback)(c, next);\n };\n}\n\n/**\n * Skip `guard` on the paths `exclude` matches. Used for the guards' `exclude` option; the guard itself\n * stays unconditional everywhere else.\n */\nfunction unlessExcluded(guard: MiddlewareHandler, exclude: readonly PathMatcher[] | undefined): MiddlewareHandler {\n if (exclude === undefined || exclude.length === 0) return guard;\n const excluded = sensitivePathMatcher(...exclude);\n return async (c, next): Promise<Response | void> => (excluded(c.req.path) ? next() : guard(c, next));\n}\n\n/**\nA static, loggable form of a matcher: strings and regexes as written, a predicate as a placeholder.\n*/\nfunction describeMatchers(entries: readonly PathMatcher[]): string {\n return entries.map((entry) => (typeof entry === 'function' ? '[predicate]' : String(entry))).join(', ');\n}\n\nfunction contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkContentType(c.req.raw, allowed);\n if (rejection) throw rejection;\n await next();\n };\n}\n\nfunction originGuard<E extends object>(policy: OriginPolicy<E> = {}): MiddlewareHandler<{ Bindings: E }> {\n return async (c, next): Promise<void> => {\n const allowedOrigins = policy.allowedOrigins === undefined ? [] : resolveFromEnv(policy.allowedOrigins, c.env);\n const rejection = checkOrigin(c.req.raw, { allowedOrigins, allowMissingOrigin: policy.allowMissingOrigin });\n if (rejection) throw rejection;\n await next();\n };\n}\n\nexport { bodyLimitGuard, contentTypeGuard, describeMatchers, methodGuard, originGuard, unlessExcluded };\nexport type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy };\n"],
5
+ "mappings": "+EAUA,OAAS,aAAAA,MAAiB,kBAE1B,OAAS,wBAAAC,MAA4B,mBACrC,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,sBACP,OAAS,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MAAME,EAAWrB,EAAqB,GAAGoB,CAAO,EAChD,MAAO,OAAOhB,EAAGC,IAAoCgB,EAASjB,EAAE,IAAI,IAAI,EAAIC,EAAI,EAAKc,EAAMf,EAAGC,CAAI,CACpG,CAJSE,EAAAW,EAAA,kBAST,SAASI,EAAiBC,EAA+B,CACvD,OAAOA,EAAQ,IAAKN,GAAW,OAAOA,GAAU,WAAa,cAAgB,OAAOA,CAAK,CAAE,EAAE,KAAK,IAAI,CACxG,CAFSV,EAAAe,EAAA,oBAIT,SAASE,EAAiBC,EAA2B,CACnD,MAAO,OAAOrB,EAAGC,IAAuB,CACtC,MAAMC,EAAYX,EAAiBS,EAAE,IAAI,IAAKqB,CAAO,EACrD,GAAInB,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAiB,EAAA,oBAQT,SAASE,EAA8BC,EAA0B,CAAA,EAAE,CACjE,MAAO,OAAOvB,EAAGC,IAAuB,CACtC,MAAMuB,EAAiBD,EAAO,iBAAmB,OAAY,CAAA,EAAK1B,EAAe0B,EAAO,eAAgBvB,EAAE,GAAG,EACvGE,EAAYT,EAAYO,EAAE,IAAI,IAAK,CAAE,eAAAwB,EAAgB,mBAAoBD,EAAO,kBAAkB,CAAE,EAC1G,GAAIrB,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CAPSE,EAAAmB,EAAA",
6
+ "names": ["bodyLimit", "PayloadTooLargeError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "sensitivePathMatcher", "resolveFromEnv", "methodGuard", "methods", "c", "next", "rejection", "__name", "assertMaxBytes", "maxBytes", "capGuard", "streamed", "bodyLimitGuard", "limit", "fallback", "rules", "rule", "entry", "unlessExcluded", "guard", "exclude", "excluded", "describeMatchers", "entries", "contentTypeGuard", "allowed", "originGuard", "policy", "allowedOrigins"]
7
7
  }
@@ -16,7 +16,7 @@
16
16
  * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |
17
17
  */
18
18
  export { createApiApp } from './createApiApp.ts';
19
- export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';
19
+ export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions, RawRoutes } from './createApiApp.ts';
20
20
  export { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';
21
21
  export { FamilyRoute } from './FamilyRoute.ts';
22
22
  export type { MaybePromise, RouteResult } from './FamilyRoute.ts';
@@ -25,7 +25,7 @@ export type { ContractHandlers, EndpointHandler, EndpointRoute } from './contrac
25
25
  export { accessAuth, apiKeyAuth } from './auth.ts';
26
26
  export type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';
27
27
  export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';
28
- export type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';
28
+ export type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';
29
29
  export { d1Bookmarks } from './bookmarks.ts';
30
30
  export type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';
31
31
  export { rateLimitRule } from './rateLimits.ts';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElG,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE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AM,mBAAmB,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACvF,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/hono/index.ts"],
4
- "sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';\n\nexport { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { MaybePromise, RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\nexport type { ErrorBoundaryOptions, UnhandledContext } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
4
+ "sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions, RawRoutes } from './createApiApp.ts';\n\nexport { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { MaybePromise, RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\nexport type { ErrorBoundaryOptions, UnhandledContext } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
5
5
  "mappings": "AAiBA,OAAS,gBAAAA,MAAoB,oBAG7B,OAAS,gCAAAC,MAAoC,YAE7C,OAAS,eAAAC,MAAmB,mBAG5B,OAAS,oBAAAC,EAAkB,qBAAAC,EAAmB,sBAAAC,MAA0B,iBAGxE,OAAS,cAAAC,EAAY,cAAAC,MAAkB,YAGvC,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAG3E,OAAS,eAAAC,MAAmB,iBAG5B,OAAS,iBAAAC,MAAqB,kBAG9B,OAAS,sBAAAC,EAAoB,yBAAAC,EAAuB,oBAAAC,MAAwB,oBAG5E,OAAS,iBAAAC,EAAe,kBAAAC,EAAgB,qBAAAC,MAAyB",
6
6
  "names": ["createApiApp", "DOCS_CONTENT_SECURITY_POLICY", "FamilyRoute", "registerContract", "routeFromEndpoint", "schemaFromEndpoint", "accessAuth", "apiKeyAuth", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "d1Bookmarks", "rateLimitRule", "createErrorHandler", "createNotFoundHandler", "respondWithError", "consoleLogger", "requestContext", "REQUEST_ID_HEADER"]
7
7
  }
@@ -14,6 +14,7 @@
14
14
  * identity and put every operator behind one NAT in a shared bucket.
15
15
  */
16
16
  import type { MiddlewareHandler } from 'hono';
17
+ import type { PathMatcher } from '../securityHeaders.ts';
17
18
  import type { RateLimitContext } from '../rateLimit.ts';
18
19
  /**
19
20
  The native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).
@@ -30,6 +31,11 @@ interface RateLimitRule<E> {
30
31
  The Hono path pattern the rule guards (`'/user/*'`).
31
32
  */
32
33
  path: string;
34
+ /**
35
+ * Paths inside `path` this rule does not charge (a reserved namespace another rule owns). Same matcher
36
+ * semantics as `sensitivePaths`; the other rules and the guards still apply to them.
37
+ */
38
+ exclude?: readonly PathMatcher[];
33
39
  /**
34
40
  The bucket namespace; two rules never share one.
35
41
  */
@@ -1 +1 @@
1
- {"version":3,"file":"rateLimits.d.ts","sourceRoot":"","sources":["../../src/hono/rateLimits.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD;;EAEE;AACF,UAAU,iBAAiB;IACzB,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AE,CAAC,CAAC;CAChE;AAED,UAAU,aAAa,CAAC,CAAC;IACvB;;MAEE;IACF,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,OAAO,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;IACjC;;MAEE;IACF,SAAS,EAAE,MAAM,CAAC;IAClB;;MAEE;IACF,QAAQ,EAAE,MAAM,CAAC;IACjB;;MAEE;IACF,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,gBAAgB,KAAK,MAAM,CAAC,CAAC;IAChD;;MAEE;IACF,GAAG,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IACxB;;MAEE;IACF,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,GAAG,SAAS,CAAC;CACrD;AAMD;;;GAGG;AACH,iBAAS,aAAa,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAoBnG;AAED,OAAO,EAAE,aAAa,EAAE,CAAC;AACzB,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,CAAC"}
@@ -1 +1 @@
1
- var f=Object.defineProperty;var r=(t,i)=>f(t,"name",{value:i,configurable:!0});import{clientIp as m,rateLimit as w}from"../rateLimit.js";function p(t){return{Exception:{Type:"RateLimited",Message:`Too many requests. Retry after ${t}s.`}}}r(p,"throttledBody");function u(t){const i=w({windowMs:t.windowMs,max:t.max,keyPrefix:t.keyPrefix}),a=Math.max(1,Math.ceil(t.windowMs/1e3));return async(e,s)=>{const o=t.binding?.(e.env);if(!o)return i(e,s);const d=t.key==="ip"?void 0:e.get("AuthenticatedUserEmailAddress"),y=`${t.keyPrefix}:${d??`ip:${m(c=>e.req.header(c))}`}`;let n=!0;try{n=(await o.limit({key:y})).success}catch{n=!0}if(!n)return e.json(p(a),429,{"Retry-After":String(a)});await s()}}r(u,"rateLimitRule");export{u as rateLimitRule};
1
+ var m=Object.defineProperty;var a=(e,i)=>m(e,"name",{value:i,configurable:!0});import{clientIp as u,rateLimit as h}from"../rateLimit.js";import{sensitivePathMatcher as x}from"../securityHeaders.js";function l(e){return{Exception:{Type:"RateLimited",Message:`Too many requests. Retry after ${e}s.`}}}a(l,"throttledBody");function p(e){const i=h({windowMs:e.windowMs,max:e.max,keyPrefix:e.keyPrefix}),s=Math.max(1,Math.ceil(e.windowMs/1e3)),d=e.exclude===void 0||e.exclude.length===0?null:x(...e.exclude);return async(t,n)=>{if(d?.(t.req.path))return n();const o=e.binding?.(t.env);if(!o)return i(t,n);const c=e.key==="ip"?void 0:t.get("AuthenticatedUserEmailAddress"),f=`${e.keyPrefix}:${c??`ip:${u(y=>t.req.header(y))}`}`;let r=!0;try{r=(await o.limit({key:f})).success}catch{r=!0}if(!r)return t.json(l(s),429,{"Retry-After":String(s)});await n()}}a(p,"rateLimitRule");export{p as rateLimitRule};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/hono/rateLimits.ts"],
4
- "sourcesContent": ["/**\n * Rate-limit rules: the native `ratelimits` binding where configured, the kit's\n * in-isolate limiter as the fallback (RFC 0001, backend conventions).\n *\n * Converged from the per-surface limiters in the four `HttpHardening.ts` copies\n * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before\n * auth). The two disagreed about *when* a limiter runs, and both were right for\n * their surface — so a rule declares its key and the key decides the slot:\n *\n * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT\n * lookup per request is a D1 spend an anonymous caller controls).\n * - `key: 'identity'` (the default) runs **after** auth, keyed on\n * `AuthenticatedUserEmailAddress`. Installed before auth it would see no\n * identity and put every operator behind one NAT in a shared bucket.\n */\nimport type { MiddlewareHandler } from 'hono';\nimport { clientIp, rateLimit } from '../rateLimit.ts';\nimport type { RateLimitContext } from '../rateLimit.ts';\n\n/**\nThe native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).\n*/\ninterface NativeRateLimiter {\n limit(options: { key: string }): Promise<{ success: boolean }>;\n}\n\ninterface RateLimitRule<E> {\n /**\n The Hono path pattern the rule guards (`'/user/*'`).\n */\n path: string;\n /**\n The bucket namespace; two rules never share one.\n */\n keyPrefix: string;\n /**\n The in-isolate window. Mirror the binding's `period` when one is configured.\n */\n windowMs: number;\n /**\n The in-isolate budget, or a per-request resolver (`env` is not known at construction).\n */\n max: number | ((c: RateLimitContext) => number);\n /**\n What the bucket is keyed on, and therefore which slot the rule runs in.\n */\n key?: 'identity' | 'ip';\n /**\n The native binding, when configured. Absent → the in-isolate limiter answers.\n */\n binding?: (env: E) => NativeRateLimiter | undefined;\n}\n\nfunction throttledBody(retryAfter: number): { Exception: { Type: string; Message: string } } {\n return { Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } };\n}\n\n/**\n * One rule's middleware. A native limiter that throws **fails open**, like the\n * in-isolate limiter: a broken limiter must not become an outage.\n */\nfunction rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{ Bindings: E }> {\n const fallback = rateLimit({ windowMs: rule.windowMs, max: rule.max, keyPrefix: rule.keyPrefix });\n const retryAfter = Math.max(1, Math.ceil(rule.windowMs / 1000));\n return async (c, next): Promise<Response | void> => {\n const native = rule.binding?.(c.env);\n if (!native) return fallback(c, next);\n\n const identity = rule.key === 'ip' ? undefined : (c.get('AuthenticatedUserEmailAddress' as never) as string | undefined);\n const key = `${rule.keyPrefix}:${identity ?? `ip:${clientIp((name) => c.req.header(name))}`}`;\n let allowed = true;\n try {\n allowed = (await native.limit({ key })).success;\n } catch {\n allowed = true;\n }\n if (!allowed) return c.json(throttledBody(retryAfter), 429, { 'Retry-After': String(retryAfter) });\n await next();\n };\n}\n\nexport { rateLimitRule };\nexport type { NativeRateLimiter, RateLimitRule };\n"],
5
- "mappings": "+EAgBA,OAAS,YAAAA,EAAU,aAAAC,MAAiB,kBAqCpC,SAASC,EAAcC,EAAkB,CACvC,MAAO,CAAE,UAAW,CAAE,KAAM,cAAe,QAAS,kCAAkCA,CAAU,IAAI,CAAE,CACxG,CAFSC,EAAAF,EAAA,iBAQT,SAASG,EAAgCC,EAAsB,CAC7D,MAAMC,EAAWN,EAAU,CAAE,SAAUK,EAAK,SAAU,IAAKA,EAAK,IAAK,UAAWA,EAAK,SAAS,CAAE,EAC1FH,EAAa,KAAK,IAAI,EAAG,KAAK,KAAKG,EAAK,SAAW,GAAI,CAAC,EAC9D,MAAO,OAAOE,EAAGC,IAAkC,CACjD,MAAMC,EAASJ,EAAK,UAAUE,EAAE,GAAG,EACnC,GAAI,CAACE,EAAQ,OAAOH,EAASC,EAAGC,CAAI,EAEpC,MAAME,EAAWL,EAAK,MAAQ,KAAO,OAAaE,EAAE,IAAI,+BAAwC,EAC1FI,EAAM,GAAGN,EAAK,SAAS,IAAIK,GAAY,MAAMX,EAAUa,GAASL,EAAE,IAAI,OAAOK,CAAI,CAAC,CAAC,EAAE,GAC3F,IAAIC,EAAU,GACd,GAAI,CACFA,GAAW,MAAMJ,EAAO,MAAM,CAAE,IAAAE,CAAG,CAAE,GAAG,OAC1C,MAAQ,CACNE,EAAU,EACZ,CACA,GAAI,CAACA,EAAS,OAAON,EAAE,KAAKN,EAAcC,CAAU,EAAG,IAAK,CAAE,cAAe,OAAOA,CAAU,CAAC,CAAE,EACjG,MAAMM,EAAI,CACZ,CACF,CAlBSL,EAAAC,EAAA",
6
- "names": ["clientIp", "rateLimit", "throttledBody", "retryAfter", "__name", "rateLimitRule", "rule", "fallback", "c", "next", "native", "identity", "key", "name", "allowed"]
4
+ "sourcesContent": ["/**\n * Rate-limit rules: the native `ratelimits` binding where configured, the kit's\n * in-isolate limiter as the fallback (RFC 0001, backend conventions).\n *\n * Converged from the per-surface limiters in the four `HttpHardening.ts` copies\n * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before\n * auth). The two disagreed about *when* a limiter runs, and both were right for\n * their surface — so a rule declares its key and the key decides the slot:\n *\n * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT\n * lookup per request is a D1 spend an anonymous caller controls).\n * - `key: 'identity'` (the default) runs **after** auth, keyed on\n * `AuthenticatedUserEmailAddress`. Installed before auth it would see no\n * identity and put every operator behind one NAT in a shared bucket.\n */\nimport type { MiddlewareHandler } from 'hono';\nimport { clientIp, rateLimit } from '../rateLimit.ts';\nimport { sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { PathMatcher } from '../securityHeaders.ts';\nimport type { RateLimitContext } from '../rateLimit.ts';\n\n/**\nThe native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).\n*/\ninterface NativeRateLimiter {\n limit(options: { key: string }): Promise<{ success: boolean }>;\n}\n\ninterface RateLimitRule<E> {\n /**\n The Hono path pattern the rule guards (`'/user/*'`).\n */\n path: string;\n /**\n * Paths inside `path` this rule does not charge (a reserved namespace another rule owns). Same matcher\n * semantics as `sensitivePaths`; the other rules and the guards still apply to them.\n */\n exclude?: readonly PathMatcher[];\n /**\n The bucket namespace; two rules never share one.\n */\n keyPrefix: string;\n /**\n The in-isolate window. Mirror the binding's `period` when one is configured.\n */\n windowMs: number;\n /**\n The in-isolate budget, or a per-request resolver (`env` is not known at construction).\n */\n max: number | ((c: RateLimitContext) => number);\n /**\n What the bucket is keyed on, and therefore which slot the rule runs in.\n */\n key?: 'identity' | 'ip';\n /**\n The native binding, when configured. Absent → the in-isolate limiter answers.\n */\n binding?: (env: E) => NativeRateLimiter | undefined;\n}\n\nfunction throttledBody(retryAfter: number): { Exception: { Type: string; Message: string } } {\n return { Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } };\n}\n\n/**\n * One rule's middleware. A native limiter that throws **fails open**, like the\n * in-isolate limiter: a broken limiter must not become an outage.\n */\nfunction rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{ Bindings: E }> {\n const fallback = rateLimit({ windowMs: rule.windowMs, max: rule.max, keyPrefix: rule.keyPrefix });\n const retryAfter = Math.max(1, Math.ceil(rule.windowMs / 1000));\n const excluded = rule.exclude === undefined || rule.exclude.length === 0 ? null : sensitivePathMatcher(...rule.exclude);\n return async (c, next): Promise<Response | void> => {\n if (excluded?.(c.req.path)) return next();\n const native = rule.binding?.(c.env);\n if (!native) return fallback(c, next);\n\n const identity = rule.key === 'ip' ? undefined : (c.get('AuthenticatedUserEmailAddress' as never) as string | undefined);\n const key = `${rule.keyPrefix}:${identity ?? `ip:${clientIp((name) => c.req.header(name))}`}`;\n let allowed = true;\n try {\n allowed = (await native.limit({ key })).success;\n } catch {\n allowed = true;\n }\n if (!allowed) return c.json(throttledBody(retryAfter), 429, { 'Retry-After': String(retryAfter) });\n await next();\n };\n}\n\nexport { rateLimitRule };\nexport type { NativeRateLimiter, RateLimitRule };\n"],
5
+ "mappings": "+EAgBA,OAAS,YAAAA,EAAU,aAAAC,MAAiB,kBACpC,OAAS,wBAAAC,MAA4B,wBA2CrC,SAASC,EAAcC,EAAkB,CACvC,MAAO,CAAE,UAAW,CAAE,KAAM,cAAe,QAAS,kCAAkCA,CAAU,IAAI,CAAE,CACxG,CAFSC,EAAAF,EAAA,iBAQT,SAASG,EAAgCC,EAAsB,CAC7D,MAAMC,EAAWP,EAAU,CAAE,SAAUM,EAAK,SAAU,IAAKA,EAAK,IAAK,UAAWA,EAAK,SAAS,CAAE,EAC1FH,EAAa,KAAK,IAAI,EAAG,KAAK,KAAKG,EAAK,SAAW,GAAI,CAAC,EACxDE,EAAWF,EAAK,UAAY,QAAaA,EAAK,QAAQ,SAAW,EAAI,KAAOL,EAAqB,GAAGK,EAAK,OAAO,EACtH,MAAO,OAAOG,EAAGC,IAAkC,CACjD,GAAIF,IAAWC,EAAE,IAAI,IAAI,EAAG,OAAOC,EAAI,EACvC,MAAMC,EAASL,EAAK,UAAUG,EAAE,GAAG,EACnC,GAAI,CAACE,EAAQ,OAAOJ,EAASE,EAAGC,CAAI,EAEpC,MAAME,EAAWN,EAAK,MAAQ,KAAO,OAAaG,EAAE,IAAI,+BAAwC,EAC1FI,EAAM,GAAGP,EAAK,SAAS,IAAIM,GAAY,MAAMb,EAAUe,GAASL,EAAE,IAAI,OAAOK,CAAI,CAAC,CAAC,EAAE,GAC3F,IAAIC,EAAU,GACd,GAAI,CACFA,GAAW,MAAMJ,EAAO,MAAM,CAAE,IAAAE,CAAG,CAAE,GAAG,OAC1C,MAAQ,CACNE,EAAU,EACZ,CACA,GAAI,CAACA,EAAS,OAAON,EAAE,KAAKP,EAAcC,CAAU,EAAG,IAAK,CAAE,cAAe,OAAOA,CAAU,CAAC,CAAE,EACjG,MAAMO,EAAI,CACZ,CACF,CApBSN,EAAAC,EAAA",
6
+ "names": ["clientIp", "rateLimit", "sensitivePathMatcher", "throttledBody", "retryAfter", "__name", "rateLimitRule", "rule", "fallback", "excluded", "c", "next", "native", "identity", "key", "name", "allowed"]
7
7
  }
package/dist/index.d.ts CHANGED
@@ -45,15 +45,15 @@
45
45
  import { getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam, resetRateLimitForTests as resetRateLimitForTestsSeam } from './testing.ts';
46
46
  export { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';
47
47
  export type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';
48
- export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
49
- export type { HeaderContext, SensitivePath } from './securityHeaders.ts';
48
+ export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, pathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
49
+ export type { HeaderContext, PathMatcher, SensitivePath } from './securityHeaders.ts';
50
50
  export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';
51
51
  export type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';
52
52
  export { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';
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,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,aAAa,EAAE,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AY,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 E,sensitivePaths as p,sensitivePathMatcher as S,CONTENT_SECURITY_POLICY as u,SECURITY_HEADERS as L,STRICT_TRANSPORT_SECURITY as A}from"./securityHeaders.js";import{AccessAuthError as h,authenticateAccess as C,identityFromBinding as x,verifyAccessJwt as F}from"./accessAuth.js";import{errorBody as B,errorResponseFromUnknown as d,mapError as g,toErrorResponse as k,toServiceError as M,INTERNAL_SERVER_MESSAGE as O}from"./ErrorMapper.js";import{errorResponses as I,exceptionResponse as U}from"./openApiErrors.js";import{checkContentLength as Y,checkContentType as H,checkMethod as N,checkOrigin as v,isMutatingMethod as P,requestOrigin as l,DEFAULT_ALLOWED_METHODS as w,DEFAULT_MAX_BODY_BYTES as X}from"./requestGuards.js";import{BaseRoute as G,createRouteHandler as J}from"./routeBase.js";const o=t,s=e;export{h as AccessAuthError,G as BaseRoute,u as CONTENT_SECURITY_POLICY,w as DEFAULT_ALLOWED_METHODS,X as DEFAULT_MAX_BODY_BYTES,O as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,L as SECURITY_HEADERS,A as STRICT_TRANSPORT_SECURITY,m as applySecurityHeaders,C as authenticateAccess,Y as checkContentLength,H as checkContentType,N as checkMethod,v as checkOrigin,c as clientIp,J as createRouteHandler,B as errorBody,d as errorResponseFromUnknown,I as errorResponses,U as exceptionResponse,s as getRateLimitBucketCountForTests,x as identityFromBinding,P as isMutatingMethod,g as mapError,R as rateLimit,l as requestOrigin,o as resetRateLimitForTests,E as securityHeaders,S as sensitivePathMatcher,p as sensitivePaths,k as toErrorResponse,M 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 CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext, 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,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,EAA4DjC,EAI5DkC,EAA8EnC",
6
- "names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "sensitivePathMatcher", "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,EAA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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;;;;GAIG;AACH,cAAM,gBAAiB,SAAQ,qBAAqB;IAClD;;MAEE;IACF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;gBAEX,OAAO,EAAE,SAAS,MAAM,EAAE;CAIvC;AAED;;EAEE;AACF,iBAAS,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,SAAS,MAAM,EAA4B,GAAG,YAAY,GAAG,IAAI,CAG9G;AAYD;;;;GAIG;AACH,iBAAS,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,SAAS,MAAM,EAAyB,GAAG,YAAY,GAAG,IAAI,CAIlH;AAED;;;;GAIG;AACH,iBAAS,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,GAAE,MAA+B,GAAG,YAAY,GAAG,IAAI,CAK5G;AAED,OAAO,EACL,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,OA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AiBb,EAAkBK,EAA6B,CAAC,kBAAkB,EAAC,CAC3F,GAAI,CAACZ,EAAiBO,EAAQ,MAAM,GAAKA,EAAQ,OAAO,YAAW,IAAO,UAAY,CAACW,EAAQX,CAAO,EAAG,OAAO,KAChH,MAAMc,GAAYd,EAAQ,QAAQ,IAAI,cAAc,GAAK,IAAI,MAAM,IAAK,CAAC,EAAE,CAAC,GAAG,KAAI,EAAG,YAAW,GAAM,GACvG,OAAOK,EAAQ,KAAMU,GAASA,EAAK,YAAW,IAAOD,CAAQ,EAAI,KAAO,IAAI1B,CAC9E,CAJSO,EAAAkB,EAAA,oBAWT,SAASG,EAAmBhB,EAAkBiB,EAAmB1B,EAAsB,CACrF,MAAM2B,EAAMlB,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,O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W,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
  }
@@ -84,12 +84,16 @@ declare function sensitivePaths(...prefixes: readonly string[]): (pathname: stri
84
84
  * matching existed, and stays one.
85
85
  * - a `RegExp` or `(path) => boolean` decides for itself.
86
86
  */
87
- type SensitivePath = string | RegExp | ((pathname: string) => boolean);
87
+ type PathMatcher = string | RegExp | ((pathname: string) => boolean);
88
+ /**
89
+ The same type under the name `sensitivePaths` has always used.
90
+ */
91
+ type SensitivePath = PathMatcher;
88
92
  /**
89
93
  * Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).
90
94
  * Empty means nothing is private, and says so rather than guessing.
91
95
  */
92
- declare function sensitivePathMatcher(...entries: readonly SensitivePath[]): (pathname: string) => boolean;
93
- export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, };
94
- export type { HeaderContext, SensitivePath };
96
+ declare function sensitivePathMatcher(...entries: readonly PathMatcher[]): (pathname: string) => boolean;
97
+ export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, sensitivePathMatcher as pathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, };
98
+ export type { HeaderContext, PathMatcher, SensitivePath };
95
99
  //# sourceMappingURL=securityHeaders.d.ts.map
@@ -1 +1 @@
1
- {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Q,EAAE,MAAM,KAAK,OAAO,CASrF;AAED;;;;;;;;GAQG;AACH,KAAK,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAErE;;EAEE;AACF,KAAK,aAAa,GAAG,WAAW,CAAC;AAgBjC;;;GAGG;AACH,iBAAS,oBAAoB,CAAC,GAAG,OAAO,EAAE,SAAS,WAAW,EAAE,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAG/F;AAED,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,oBAAoB,IAAI,WAAW,EACnC,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,CAAC;AACF,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,CAAC"}
@@ -1 +1 @@
1
- var f=Object.defineProperty;var r=(e,t)=>f(e,"name",{value:t,configurable:!0});const i={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"same-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=(), payment=(), usb=()","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Resource-Policy":"same-origin","Cross-Origin-Embedder-Policy":"require-corp","Origin-Agent-Cluster":"?1"},o="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests",c="max-age=31536000; includeSubDomains";function a(e,t){for(const[u,l]of Object.entries(i))e.header(u,l);(e.res.headers.get("content-type")??"").includes("text/html")&&e.header("Content-Security-Policy",o);let n;try{n=new URL(e.req.url).pathname}catch{}n!==void 0&&t(n)&&e.header("Cache-Control","no-store");try{new URL(e.req.url).protocol==="https:"&&e.header("Strict-Transport-Security",c)}catch{}}r(a,"applySecurityHeaders");function h(e){return async(t,s)=>{await s();try{a(t,e)}catch{}}}r(h,"securityHeaders");function m(...e){if(e.length===0)return()=>!1;const t=e.map(s=>s.endsWith("/")?s:`${s}/`);return s=>t.some(n=>s.startsWith(n))}r(m,"sensitivePaths");function p(e){if(typeof e=="function")return e;if(e instanceof RegExp)return t=>new RegExp(e.source,e.flags.replaceAll(/[gy]/g,"")).test(t);if(e.endsWith("/*")){const t=e.slice(0,-1);return s=>s.startsWith(t)||s===t.slice(0,-1)}return e.endsWith("/")?t=>t.startsWith(e):t=>t===e||t===`${e}/`}r(p,"matcherFor");function d(...e){const t=e.map(s=>p(s));return s=>t.some(n=>n(s))}r(d,"sensitivePathMatcher");export{o as CONTENT_SECURITY_POLICY,i as SECURITY_HEADERS,c as STRICT_TRANSPORT_SECURITY,a as applySecurityHeaders,h as securityHeaders,d as sensitivePathMatcher,m as sensitivePaths};
1
+ var h=Object.defineProperty;var n=(e,t)=>h(e,"name",{value:t,configurable:!0});const i={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"same-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=(), payment=(), usb=()","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Resource-Policy":"same-origin","Cross-Origin-Embedder-Policy":"require-corp","Origin-Agent-Cluster":"?1"},o="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests",c="max-age=31536000; includeSubDomains";function a(e,t){for(const[l,f]of Object.entries(i))e.header(l,f);(e.res.headers.get("content-type")??"").includes("text/html")&&e.header("Content-Security-Policy",o);let r;try{r=new URL(e.req.url).pathname}catch{}r!==void 0&&t(r)&&e.header("Cache-Control","no-store");try{new URL(e.req.url).protocol==="https:"&&e.header("Strict-Transport-Security",c)}catch{}}n(a,"applySecurityHeaders");function p(e){return async(t,s)=>{await s();try{a(t,e)}catch{}}}n(p,"securityHeaders");function m(...e){if(e.length===0)return()=>!1;const t=e.map(s=>s.endsWith("/")?s:`${s}/`);return s=>t.some(r=>s.startsWith(r))}n(m,"sensitivePaths");function d(e){if(typeof e=="function")return e;if(e instanceof RegExp)return t=>new RegExp(e.source,e.flags.replaceAll(/[gy]/g,"")).test(t);if(e.endsWith("/*")){const t=e.slice(0,-1);return s=>s.startsWith(t)||s===t.slice(0,-1)}return e.endsWith("/")?t=>t.startsWith(e):t=>t===e||t===`${e}/`}n(d,"matcherFor");function u(...e){const t=e.map(s=>d(s));return s=>t.some(r=>r(s))}n(u,"sensitivePathMatcher");export{o as CONTENT_SECURITY_POLICY,i as SECURITY_HEADERS,c as STRICT_TRANSPORT_SECURITY,a as applySecurityHeaders,u as pathMatcher,p as securityHeaders,u as sensitivePathMatcher,m as sensitivePaths};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/securityHeaders.ts"],
4
- "sourcesContent": ["/**\n * Baseline response security headers.\n *\n * Converged from `apps/api/src/middleware/securityHeaders.ts` in Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic, where the four copies are\n * byte-identical apart from one predicate — which is exactly why it is a\n * parameter here rather than a constant.\n *\n * ## Why `isSensitive` is a required argument\n *\n * The copies each shipped a `startsWith('/user/')` predicate, inherited from a\n * reference project. In one repo that worker serves **no `/user/` route**, so the\n * predicate could never return `true` and `Cache-Control: no-store` was never\n * applied to anything: the operator's own address and every user's address\n * shipped with no `Cache-Control` at all.\n *\n * A predicate copied from another router's route table is not a conservative\n * default; it is an unconditional no-op. So a caller states its own private\n * prefixes, and the compiler asks for them rather than letting them be omitted.\n */\n\n/**\nThe slice of a Hono context this middleware reads.\n*/\ninterface HeaderContext {\n header(name: string, value: string): void;\n res: { headers: Headers };\n req: { url: string };\n}\n\n/**\n * Baseline headers for API JSON responses and the SPA shell.\n *\n * The SPA ships inline scripts and styles from the Vite build, so CSP allows\n * 'unsafe-inline' for both, bounded by `same-origin` and `frame-ancestors`.\n * Without it the shell breaks; hashes or nonces are a future tightening once the\n * build emits stable hashes.\n */\nconst SECURITY_HEADERS: Readonly<Record<string, string>> = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'same-origin',\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'require-corp',\n 'Origin-Agent-Cluster': '?1',\n} as const;\n\n/**\n * CSP for the HTML shell.\n *\n * Separate from {@link SECURITY_HEADERS} because it applies only to an HTML\n * response — sending it on JSON is noise at best and a source of confusing\n * violation reports at worst.\n */\nconst CONTENT_SECURITY_POLICY =\n \"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests\";\n\n/**\nHSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning.\n*/\nconst STRICT_TRANSPORT_SECURITY = 'max-age=31536000; includeSubDomains';\n\n/**\n * Apply the headers to a context.\n *\n * Each step is independently guarded: a header must never fail a request, and\n * one unparseable URL should not cost the other headers.\n */\nfunction applySecurityHeaders(c: HeaderContext, isSensitive: (pathname: string) => boolean): void {\n for (const [key, value] of Object.entries(SECURITY_HEADERS)) {\n c.header(key, value);\n }\n\n const contentType = c.res.headers.get('content-type') ?? '';\n if (contentType.includes('text/html')) {\n c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);\n }\n\n let pathname: string | undefined;\n try {\n pathname = new URL(c.req.url).pathname;\n } catch {\n // URL parsing must never fail the request; the `no-store` step is skipped.\n }\n if (pathname !== undefined && isSensitive(pathname)) {\n c.header('Cache-Control', 'no-store');\n }\n\n try {\n if (new URL(c.req.url).protocol === 'https:') {\n c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);\n }\n } catch {\n // URL parsing must never fail the request.\n }\n}\n\n/**\n * The middleware.\n *\n * `isSensitive` is **required**, and its parameter is required, so a caller\n * cannot accidentally ship a predicate that returns `true` for everything\n * (caching a credential response) or `false` for everything (the no-op above).\n */\nfunction securityHeaders(isSensitive: (pathname: string) => boolean): (c: HeaderContext, next: () => Promise<void>) => Promise<void> {\n return async (c: HeaderContext, next: () => Promise<void>): Promise<void> => {\n await next();\n try {\n applySecurityHeaders(c, isSensitive);\n } catch {\n // Headers must never fail the request.\n }\n };\n}\n\n/**\n * Build a predicate from this app's private path prefixes.\n *\n * A convenience over `securityHeaders`, not a default: it matches **exactly**\n * these prefixes, so a caller still has to name its own paths. The returned\n * function composes, so a repo with a second private surface can add its own\n * test without editing this one.\n */\nfunction sensitivePaths(...prefixes: readonly string[]): (pathname: string) => boolean {\n if (prefixes.length === 0) {\n // Not a throw: a repo with nothing private is a legitimate state, and the\n // failure mode to avoid is silently caching a credential, which an empty\n // list cannot do. What it must not do is *look* like it protected something.\n return () => false;\n }\n const normalized = prefixes.map((prefix) => (prefix.endsWith('/') ? prefix : `${prefix}/`));\n return (pathname: string): boolean => normalized.some((prefix) => pathname.startsWith(prefix));\n}\n\n/**\n * One private-path entry: a string, a `RegExp` tested against the pathname, or a predicate.\n *\n * - `'/generate-totp'` matches that path **exactly** (and its one-trailing-slash form), nothing under it.\n * - `'/user/'` (ends with `/`) and `'/user/*'` match the **prefix**: everything under `/user/`\n * (`'/user/*'` also matches `/user` itself). A string ending in `/` was a prefix before exact\n * matching existed, and stays one.\n * - a `RegExp` or `(path) => boolean` decides for itself.\n */\ntype SensitivePath = string | RegExp | ((pathname: string) => boolean);\n\nfunction matcherFor(entry: SensitivePath): (pathname: string) => boolean {\n if (typeof entry === 'function') return entry;\n if (entry instanceof RegExp) {\n // `test` on a global/sticky regex is stateful (`lastIndex`); a fresh clone per call keeps it pure.\n return (pathname) => new RegExp(entry.source, entry.flags.replaceAll(/[gy]/g, '')).test(pathname);\n }\n if (entry.endsWith('/*')) {\n const prefix = entry.slice(0, -1);\n return (pathname) => pathname.startsWith(prefix) || pathname === prefix.slice(0, -1);\n }\n if (entry.endsWith('/')) return (pathname) => pathname.startsWith(entry);\n return (pathname) => pathname === entry || pathname === `${entry}/`;\n}\n\n/**\n * Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).\n * Empty means nothing is private, and says so rather than guessing.\n */\nfunction sensitivePathMatcher(...entries: readonly SensitivePath[]): (pathname: string) => boolean {\n const matchers = entries.map((entry) => matcherFor(entry));\n return (pathname) => matchers.some((matches) => matches(pathname));\n}\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n sensitivePathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n};\nexport type { HeaderContext, SensitivePath };\n"],
5
- "mappings": "+EAsCA,MAAMA,EAAqD,CACzD,yBAA0B,UAC1B,kBAAmB,OACnB,kBAAmB,cACnB,qBAAsB,+DACtB,6BAA8B,cAC9B,+BAAgC,cAChC,+BAAgC,eAChC,uBAAwB,MAUpBC,EACJ,2NAKIC,EAA4B,sCAQlC,SAASC,EAAqBC,EAAkBC,EAA0C,CACxF,SAAW,CAACC,EAAKC,CAAK,IAAK,OAAO,QAAQP,CAAgB,EACxDI,EAAE,OAAOE,EAAKC,CAAK,GAGDH,EAAE,IAAI,QAAQ,IAAI,cAAc,GAAK,IACzC,SAAS,WAAW,GAClCA,EAAE,OAAO,0BAA2BH,CAAuB,EAG7D,IAAIO,EACJ,GAAI,CACFA,EAAW,IAAI,IAAIJ,EAAE,IAAI,GAAG,EAAE,QAChC,MAAQ,CAER,CACII,IAAa,QAAaH,EAAYG,CAAQ,GAChDJ,EAAE,OAAO,gBAAiB,UAAU,EAGtC,GAAI,CACE,IAAI,IAAIA,EAAE,IAAI,GAAG,EAAE,WAAa,UAClCA,EAAE,OAAO,4BAA6BF,CAAyB,CAEnE,MAAQ,CAER,CACF,CA3BSO,EAAAN,EAAA,wBAoCT,SAASO,EAAgBL,EAA0C,CACjE,MAAO,OAAOD,EAAkBO,IAA4C,CAC1E,MAAMA,EAAI,EACV,GAAI,CACFR,EAAqBC,EAAGC,CAAW,CACrC,MAAQ,CAER,CACF,CACF,CATSI,EAAAC,EAAA,mBAmBT,SAASE,KAAkBC,EAA2B,CACpD,GAAIA,EAAS,SAAW,EAItB,MAAO,IAAM,GAEf,MAAMC,EAAaD,EAAS,IAAKE,GAAYA,EAAO,SAAS,GAAG,EAAIA,EAAS,GAAGA,CAAM,GAAI,EAC1F,OAAQP,GAA8BM,EAAW,KAAMC,GAAWP,EAAS,WAAWO,CAAM,CAAC,CAC/F,CATSN,EAAAG,EAAA,kBAsBT,SAASI,EAAWC,EAAoB,CACtC,GAAI,OAAOA,GAAU,WAAY,OAAOA,EACxC,GAAIA,aAAiB,OAEnB,OAAQT,GAAa,IAAI,OAAOS,EAAM,OAAQA,EAAM,MAAM,WAAW,QAAS,EAAE,CAAC,EAAE,KAAKT,CAAQ,EAElG,GAAIS,EAAM,SAAS,IAAI,EAAG,CACxB,MAAMF,EAASE,EAAM,MAAM,EAAG,EAAE,EAChC,OAAQT,GAAaA,EAAS,WAAWO,CAAM,GAAKP,IAAaO,EAAO,MAAM,EAAG,EAAE,CACrF,CACA,OAAIE,EAAM,SAAS,GAAG,EAAWT,GAAaA,EAAS,WAAWS,CAAK,EAC/DT,GAAaA,IAAaS,GAAST,IAAa,GAAGS,CAAK,GAClE,CAZSR,EAAAO,EAAA,cAkBT,SAASE,KAAwBC,EAAiC,CAChE,MAAMC,EAAWD,EAAQ,IAAKF,GAAUD,EAAWC,CAAK,CAAC,EACzD,OAAQT,GAAaY,EAAS,KAAMC,GAAYA,EAAQb,CAAQ,CAAC,CACnE,CAHSC,EAAAS,EAAA",
4
+ "sourcesContent": ["/**\n * Baseline response security headers.\n *\n * Converged from `apps/api/src/middleware/securityHeaders.ts` in Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic, where the four copies are\n * byte-identical apart from one predicate — which is exactly why it is a\n * parameter here rather than a constant.\n *\n * ## Why `isSensitive` is a required argument\n *\n * The copies each shipped a `startsWith('/user/')` predicate, inherited from a\n * reference project. In one repo that worker serves **no `/user/` route**, so the\n * predicate could never return `true` and `Cache-Control: no-store` was never\n * applied to anything: the operator's own address and every user's address\n * shipped with no `Cache-Control` at all.\n *\n * A predicate copied from another router's route table is not a conservative\n * default; it is an unconditional no-op. So a caller states its own private\n * prefixes, and the compiler asks for them rather than letting them be omitted.\n */\n\n/**\nThe slice of a Hono context this middleware reads.\n*/\ninterface HeaderContext {\n header(name: string, value: string): void;\n res: { headers: Headers };\n req: { url: string };\n}\n\n/**\n * Baseline headers for API JSON responses and the SPA shell.\n *\n * The SPA ships inline scripts and styles from the Vite build, so CSP allows\n * 'unsafe-inline' for both, bounded by `same-origin` and `frame-ancestors`.\n * Without it the shell breaks; hashes or nonces are a future tightening once the\n * build emits stable hashes.\n */\nconst SECURITY_HEADERS: Readonly<Record<string, string>> = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'same-origin',\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'require-corp',\n 'Origin-Agent-Cluster': '?1',\n} as const;\n\n/**\n * CSP for the HTML shell.\n *\n * Separate from {@link SECURITY_HEADERS} because it applies only to an HTML\n * response — sending it on JSON is noise at best and a source of confusing\n * violation reports at worst.\n */\nconst CONTENT_SECURITY_POLICY =\n \"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests\";\n\n/**\nHSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning.\n*/\nconst STRICT_TRANSPORT_SECURITY = 'max-age=31536000; includeSubDomains';\n\n/**\n * Apply the headers to a context.\n *\n * Each step is independently guarded: a header must never fail a request, and\n * one unparseable URL should not cost the other headers.\n */\nfunction applySecurityHeaders(c: HeaderContext, isSensitive: (pathname: string) => boolean): void {\n for (const [key, value] of Object.entries(SECURITY_HEADERS)) {\n c.header(key, value);\n }\n\n const contentType = c.res.headers.get('content-type') ?? '';\n if (contentType.includes('text/html')) {\n c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);\n }\n\n let pathname: string | undefined;\n try {\n pathname = new URL(c.req.url).pathname;\n } catch {\n // URL parsing must never fail the request; the `no-store` step is skipped.\n }\n if (pathname !== undefined && isSensitive(pathname)) {\n c.header('Cache-Control', 'no-store');\n }\n\n try {\n if (new URL(c.req.url).protocol === 'https:') {\n c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);\n }\n } catch {\n // URL parsing must never fail the request.\n }\n}\n\n/**\n * The middleware.\n *\n * `isSensitive` is **required**, and its parameter is required, so a caller\n * cannot accidentally ship a predicate that returns `true` for everything\n * (caching a credential response) or `false` for everything (the no-op above).\n */\nfunction securityHeaders(isSensitive: (pathname: string) => boolean): (c: HeaderContext, next: () => Promise<void>) => Promise<void> {\n return async (c: HeaderContext, next: () => Promise<void>): Promise<void> => {\n await next();\n try {\n applySecurityHeaders(c, isSensitive);\n } catch {\n // Headers must never fail the request.\n }\n };\n}\n\n/**\n * Build a predicate from this app's private path prefixes.\n *\n * A convenience over `securityHeaders`, not a default: it matches **exactly**\n * these prefixes, so a caller still has to name its own paths. The returned\n * function composes, so a repo with a second private surface can add its own\n * test without editing this one.\n */\nfunction sensitivePaths(...prefixes: readonly string[]): (pathname: string) => boolean {\n if (prefixes.length === 0) {\n // Not a throw: a repo with nothing private is a legitimate state, and the\n // failure mode to avoid is silently caching a credential, which an empty\n // list cannot do. What it must not do is *look* like it protected something.\n return () => false;\n }\n const normalized = prefixes.map((prefix) => (prefix.endsWith('/') ? prefix : `${prefix}/`));\n return (pathname: string): boolean => normalized.some((prefix) => pathname.startsWith(prefix));\n}\n\n/**\n * One private-path entry: a string, a `RegExp` tested against the pathname, or a predicate.\n *\n * - `'/generate-totp'` matches that path **exactly** (and its one-trailing-slash form), nothing under it.\n * - `'/user/'` (ends with `/`) and `'/user/*'` match the **prefix**: everything under `/user/`\n * (`'/user/*'` also matches `/user` itself). A string ending in `/` was a prefix before exact\n * matching existed, and stays one.\n * - a `RegExp` or `(path) => boolean` decides for itself.\n */\ntype PathMatcher = string | RegExp | ((pathname: string) => boolean);\n\n/**\nThe same type under the name `sensitivePaths` has always used.\n*/\ntype SensitivePath = PathMatcher;\n\nfunction matcherFor(entry: PathMatcher): (pathname: string) => boolean {\n if (typeof entry === 'function') return entry;\n if (entry instanceof RegExp) {\n // `test` on a global/sticky regex is stateful (`lastIndex`); a fresh clone per call keeps it pure.\n return (pathname) => new RegExp(entry.source, entry.flags.replaceAll(/[gy]/g, '')).test(pathname);\n }\n if (entry.endsWith('/*')) {\n const prefix = entry.slice(0, -1);\n return (pathname) => pathname.startsWith(prefix) || pathname === prefix.slice(0, -1);\n }\n if (entry.endsWith('/')) return (pathname) => pathname.startsWith(entry);\n return (pathname) => pathname === entry || pathname === `${entry}/`;\n}\n\n/**\n * Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).\n * Empty means nothing is private, and says so rather than guessing.\n */\nfunction sensitivePathMatcher(...entries: readonly PathMatcher[]): (pathname: string) => boolean {\n const matchers = entries.map((entry) => matcherFor(entry));\n return (pathname) => matchers.some((matches) => matches(pathname));\n}\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n sensitivePathMatcher,\n sensitivePathMatcher as pathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n};\nexport type { HeaderContext, PathMatcher, SensitivePath };\n"],
5
+ "mappings": "+EAsCA,MAAMA,EAAqD,CACzD,yBAA0B,UAC1B,kBAAmB,OACnB,kBAAm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AAE,CAAC,EAAE,KAAKT,CAAQ,EAElG,GAAIS,EAAM,SAAS,IAAI,EAAG,CACxB,MAAMF,EAASE,EAAM,MAAM,EAAG,EAAE,EAChC,OAAQT,GAAaA,EAAS,WAAWO,CAAM,GAAKP,IAAaO,EAAO,MAAM,EAAG,EAAE,CACrF,CACA,OAAIE,EAAM,SAAS,GAAG,EAAWT,GAAaA,EAAS,WAAWS,CAAK,EAC/DT,GAAaA,IAAaS,GAAST,IAAa,GAAGS,CAAK,GAClE,CAZSR,EAAAO,EAAA,cAkBT,SAASE,KAAwBC,EAA+B,CAC9D,MAAMC,EAAWD,EAAQ,IAAKF,GAAUD,EAAWC,CAAK,CAAC,EACzD,OAAQT,GAAaY,EAAS,KAAMC,GAAYA,EAAQb,CAAQ,CAAC,CACnE,CAHSC,EAAAS,EAAA",
6
6
  "names": ["SECURITY_HEADERS", "CONTENT_SECURITY_POLICY", "STRICT_TRANSPORT_SECURITY", "applySecurityHeaders", "c", "isSensitive", "key", "value", "pathname", "__name", "securityHeaders", "next", "sensitivePaths", "prefixes", "normalized", "prefix", "matcherFor", "entry", "sensitivePathMatcher", "entries", "matchers", "matches"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/http",
3
- "version": "1.15.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.15.0",
38
- "@rexezuge/errors": "1.15.0",
39
- "@rexezuge/shared": "1.15.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",