@rexezuge/http 1.14.0 → 1.16.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 +58 -5
- package/dist/hono/FamilyRoute.d.ts +6 -2
- package/dist/hono/FamilyRoute.d.ts.map +1 -1
- package/dist/hono/FamilyRoute.js.map +2 -2
- package/dist/hono/contracts.d.ts +4 -4
- package/dist/hono/contracts.d.ts.map +1 -1
- package/dist/hono/contracts.js.map +1 -1
- package/dist/hono/createApiApp.d.ts +24 -8
- package/dist/hono/createApiApp.d.ts.map +1 -1
- package/dist/hono/createApiApp.js +1 -1
- package/dist/hono/createApiApp.js.map +3 -3
- package/dist/hono/errorHandler.d.ts +25 -2
- package/dist/hono/errorHandler.d.ts.map +1 -1
- package/dist/hono/errorHandler.js +1 -1
- package/dist/hono/errorHandler.js.map +3 -3
- package/dist/hono/hardening.d.ts +44 -6
- package/dist/hono/hardening.d.ts.map +1 -1
- package/dist/hono/hardening.js +1 -1
- package/dist/hono/hardening.js.map +3 -3
- package/dist/hono/index.d.ts +4 -3
- package/dist/hono/index.d.ts.map +1 -1
- package/dist/hono/index.js.map +2 -2
- package/dist/hono/rateLimits.d.ts +6 -0
- package/dist/hono/rateLimits.d.ts.map +1 -1
- package/dist/hono/rateLimits.js +1 -1
- package/dist/hono/rateLimits.js.map +3 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/securityHeaders.d.ts +21 -2
- package/dist/securityHeaders.d.ts.map +1 -1
- package/dist/securityHeaders.js +1 -1
- package/dist/securityHeaders.js.map +3 -3
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -149,7 +149,7 @@ export default ApiWorker;
|
|
|
149
149
|
| # | Slot | Notes |
|
|
150
150
|
| --- | ----------------------- | ------------------------------------------------------------------------------------- |
|
|
151
151
|
| 1 | request id + logger | `X-Request-Id` on every response; `c.get('logger')` |
|
|
152
|
-
| 2 | security headers | wraps everything, so a 401/404/500 carries them;
|
|
152
|
+
| 2 | security headers | wraps everything, so a 401/404/429/500 carries them; `sensitivePaths` get `no-store` |
|
|
153
153
|
| 3 | CORS | only with `cors`; `X-Request-Id` always exposed |
|
|
154
154
|
| 4 | hardening | method allow-list (405), body ceiling (413), JSON mutations (415), origin guard (403) |
|
|
155
155
|
| 5 | D1 bookmarks | `env[binding]` becomes the session for the rest of the chain |
|
|
@@ -164,7 +164,9 @@ Anything that throws — a route, a guard, a hook — reaches `app.onError`, whi
|
|
|
164
164
|
maps it through the kit mapper to the `{Exception:{Type,Message}}` envelope: 4xx
|
|
165
165
|
messages kept, 5xx masked, zod/chanfana validation → 400, a retryable
|
|
166
166
|
`DatabaseError` → 503, a spent D1 allowance → 503 + `Retry-After`. The log line
|
|
167
|
-
is a static message with `type`, `status
|
|
167
|
+
is a static message with `type`, `status`, `requestId`, `method`, the route pattern (`/user/:id`, not the URL), the error's class name (`errorName`) and,
|
|
168
|
+
for a `ServiceError`, its catalog `errorCode` — never the caught value, its message or its stack. An app that ships to a log sink it controls gets the raw error of
|
|
169
|
+
every 5xx through `errors.reportUnhandled(error, { status, requestId, method, route })` (the open door; a sink that throws is swallowed).
|
|
168
170
|
An unmatched path is the `404 NotFound` envelope. `/docs` and `/openapi.json` are
|
|
169
171
|
served unless `docs: false`. The docs page, and only that path, gets
|
|
170
172
|
`DOCS_CONTENT_SECURITY_POLICY`: the strict HTML policy plus the exact Swagger UI
|
|
@@ -175,6 +177,23 @@ That policy is closed. There is no option to widen the CSP for your own pages.
|
|
|
175
177
|
`AuthenticatedUserId`, `requestId`, `logger`. Add your own with the second type
|
|
176
178
|
parameter: `createApiApp<Env, { RequestScope: Scope }>()`.
|
|
177
179
|
|
|
180
|
+
### `sensitivePaths`
|
|
181
|
+
|
|
182
|
+
`createApiApp({ sensitivePaths })` takes entries of `string | RegExp | ((path: string) => boolean)`; a response whose path matches any of them gets
|
|
183
|
+
`Cache-Control: no-store`. The default is `['/user/', '/api/']`.
|
|
184
|
+
|
|
185
|
+
| Entry | Matches |
|
|
186
|
+
| ---------------------------- | ------------------------------------------------------------------------------- |
|
|
187
|
+
| `'/generate-totp'` | that path **exactly** (and its one trailing-slash form), nothing under it |
|
|
188
|
+
| `'/user/'` | the **prefix**: everything under `/user/` (a string ending in `/` always was) |
|
|
189
|
+
| `'/user/*'` | the prefix, and `/user` itself |
|
|
190
|
+
| `/^\/r-\d+$/`, `(path) => …` | whatever the RegExp or predicate says (a global/sticky RegExp is safe to reuse) |
|
|
191
|
+
|
|
192
|
+
Migration: a bare `'/user'` (no trailing slash) used to mean the prefix `/user/`; it is now the exact path. Write `'/user/'` or `'/user/*'` to keep the prefix.
|
|
193
|
+
`no-store` is applied in the kit's own early middleware, so it also covers the IP limiter's `429`, the error envelope, a `404`, a hardening `405/413/415`
|
|
194
|
+
and a throwing `beforeAuth` hook; no hook can bypass it. The low-level `sensitivePaths(...prefixes)` helper keeps its prefix-only meaning;
|
|
195
|
+
`sensitivePathMatcher(...entries)` is the `createApiApp` semantics for your own `securityHeaders(...)` wiring.
|
|
196
|
+
|
|
178
197
|
### `FamilyRoute`
|
|
179
198
|
|
|
180
199
|
The converged chanfana route base. `handle()` is `@final`: it validates through
|
|
@@ -209,7 +228,8 @@ createApiApp<Env>({
|
|
|
209
228
|
- The handler map must name exactly the contract's endpoints. A missing key is a
|
|
210
229
|
compile error, and a missing or unknown key also throws at startup.
|
|
211
230
|
- The handler gets the validated zod **output** and returns the response's zod
|
|
212
|
-
**input**, `null`, or a `Response` of its own
|
|
231
|
+
**input**, `null`, or a `Response` of its own: the value itself or a promise of it
|
|
232
|
+
(`MaybePromise`), so a handler with nothing to await need not be `async`.
|
|
213
233
|
- **Fail-closed auth:** an `access`/`apiKey` endpoint answers `401` when no auth
|
|
214
234
|
middleware set `AuthenticatedUserId` on its path.
|
|
215
235
|
- `http` depends on `contracts` (framework-free, zod as types only). The adapter
|
|
@@ -221,6 +241,7 @@ createApiApp<Env>({
|
|
|
221
241
|
| You want | Door |
|
|
222
242
|
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
223
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) |
|
|
224
245
|
| Routes from a shared contract | `registerContract(app, contract, handlers)`; `schemaFromEndpoint` for a hand-written `FamilyRoute` |
|
|
225
246
|
| Middleware before / after authentication | `hooks.beforeAuth` / `hooks.afterAuth` (a handler, or `{ path, handler }`) |
|
|
226
247
|
| Another authenticated surface | `auth: { '/partner/*': apiKeyAuth({ verify }) }` |
|
|
@@ -228,12 +249,44 @@ createApiApp<Env>({
|
|
|
228
249
|
| Map a verified address to your account | `accessAuth({ resolveUserId })` |
|
|
229
250
|
| Extra trusted origins (Pages, custom host) | `hardening.origin.allowedOrigins` (a list, or `(env) => list`) |
|
|
230
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` |
|
|
231
255
|
| Your logger / redacting sink | `logger: (env, requestId) => createLogger(…, sink)` |
|
|
232
256
|
| A protocol dialect (Subsonic, WebDAV) | `errors.toResponse` app-wide, or `FamilyRoute.errorMapping()` per route |
|
|
233
257
|
| More context variables | the `V` type parameter |
|
|
258
|
+
| Which paths are `no-store` | `sensitivePaths: ['/generate-totp', '/user/', /^\/export\//, (path) => …]` (see below) |
|
|
259
|
+
| Diagnose a 5xx in your own log sink | `errors.reportUnhandled(error, { status, requestId, method, route })` |
|
|
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`.
|
|
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.
|
|
234
287
|
|
|
235
|
-
Closed, with no flag: the slot order, the error envelope and its masking, the CSP
|
|
236
|
-
(strict everywhere, Swagger UI's directory on the docs page only), log redaction, `email_verified` enforcement, the origin guard on `/user/*`, the
|
|
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
|
|
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
|
|
237
290
|
`@final` route `handle()`.
|
|
238
291
|
|
|
239
292
|
## Renamed: `toErrorResponse` → `errorResponseFromUnknown`
|
|
@@ -32,6 +32,10 @@ import type { FamilyEnv } from './types.ts';
|
|
|
32
32
|
* a non-JSON body); `null` is `204 No Content`; anything else is JSON with 200.
|
|
33
33
|
*/
|
|
34
34
|
type RouteResult<T> = T | Response | null;
|
|
35
|
+
/**
|
|
36
|
+
A value or a promise of it: a handler with nothing to await need not be `async`.
|
|
37
|
+
*/
|
|
38
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
35
39
|
declare abstract class FamilyRoute<S extends OpenAPIRouteSchema = OpenAPIRouteSchema, E extends object = object, V extends object = object, TOutput = unknown> extends OpenAPIRoute<[Context<FamilyEnv<E, V>>]> {
|
|
36
40
|
constructor(params: RouteOptions);
|
|
37
41
|
/**
|
|
@@ -44,7 +48,7 @@ declare abstract class FamilyRoute<S extends OpenAPIRouteSchema = OpenAPIRouteSc
|
|
|
44
48
|
* headers, body }` for this route's `schema`; `c` is the typed family context
|
|
45
49
|
* (bindings, `AuthenticatedUserId`, `logger`, …).
|
|
46
50
|
*/
|
|
47
|
-
protected abstract handleRequest(input: ValidatedData<S>, c: Context<FamilyEnv<E, V>>):
|
|
51
|
+
protected abstract handleRequest(input: ValidatedData<S>, c: Context<FamilyEnv<E, V>>): MaybePromise<RouteResult<TOutput>>;
|
|
48
52
|
/**
|
|
49
53
|
* Open: per-route mapper options, merged over the app's. The hook for a
|
|
50
54
|
* protocol surface with its own dialect (`toResponse`) or extra headers.
|
|
@@ -52,5 +56,5 @@ declare abstract class FamilyRoute<S extends OpenAPIRouteSchema = OpenAPIRouteSc
|
|
|
52
56
|
protected errorMapping(): ErrorMapperOptions;
|
|
53
57
|
}
|
|
54
58
|
export { FamilyRoute };
|
|
55
|
-
export type { RouteResult };
|
|
59
|
+
export type { MaybePromise, RouteResult };
|
|
56
60
|
//# sourceMappingURL=FamilyRoute.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FamilyRoute.d.ts","sourceRoot":"","sources":["../../src/hono/FamilyRoute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAChF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"FamilyRoute.d.ts","sourceRoot":"","sources":["../../src/hono/FamilyRoute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAChF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;;GAGG;AACH,KAAK,WAAW,CAAC,CAAC,IAAI,CAAC,GAAG,QAAQ,GAAG,IAAI,CAAC;AAE1C;;EAEE;AACF,KAAK,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEtC,uBAAe,WAAW,CACxB,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,EACjD,CAAC,SAAS,MAAM,GAAG,MAAM,EACzB,CAAC,SAAS,MAAM,GAAG,MAAM,EACzB,OAAO,GAAG,OAAO,CACjB,SAAQ,YAAY,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC7B,MAAM,EAAE,YAAY;IAKvC;;;OAGG;IACU,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAanE;;;;OAIG;IACH,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAE1H;;;OAGG;IACH,SAAS,CAAC,YAAY,IAAI,kBAAkB;CAG7C;AAED,OAAO,EAAE,WAAW,EAAE,CAAC;AACvB,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/FamilyRoute.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The converged chanfana route base.\n *\n * Converged from the seven `apps/api/src/endpoints/IBaseRoute.ts` copies\n * (ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Bee,\n * Mail-Meow, Mail-Otter), and the answer to the \"unconverged\" note in\n * `../routeBase.ts`. Every copy did the same four things by hand and each got a\n * different one wrong:\n *\n * 1. **Parse and validate.** The Mail-* copies parsed the body themselves and\n * validated against a path-keyed registry (`validateRequestInput`) that failed\n * *open* for a route nobody registered. Here the route's own chanfana `schema`\n * validates — the same object that documents it — so there is no second\n * registry to forget.\n * 2. **Run the handler** — the only open step: {@link FamilyRoute.handleRequest}.\n * 3. **Shape the response.** A `Response` passes through; a value is JSON; `null`\n * is `204`.\n * 4. **Map the failure** through the kit mapper (`respondWithError`), never a\n * hand-built envelope: two copies shipped a 5xx's raw message.\n *\n * Steps 1, 3 and 4 are closed. `handle` and chanfana's `execute` are `@final`\n * and **refused at construction** (`assertFinalMembers`) — chanfana constructs a\n * route once at registration, so an override fails the app at startup.\n */\nimport { OpenAPIRoute } from 'chanfana';\nimport type { OpenAPIRouteSchema, RouteOptions, ValidatedData } from 'chanfana';\nimport type { Context } from 'hono';\nimport { assertFinalMembers } from '@rexezuge/shared';\nimport type { ErrorMapperOptions } from '../ErrorMapper.ts';\nimport { respondWithError } from './errorHandler.ts';\nimport type { FamilyEnv } from './types.ts';\n\n/**\n * Open: what the route returns. A `Response` is sent as-is (redirects, streams,\n * a non-JSON body); `null` is `204 No Content`; anything else is JSON with 200.\n */\ntype RouteResult<T> = T | Response | null;\n\nabstract class FamilyRoute<\n S extends OpenAPIRouteSchema = OpenAPIRouteSchema,\n E extends object = object,\n V extends object = object,\n TOutput = unknown,\n> extends OpenAPIRoute<[Context<FamilyEnv<E, V>>]> {\n public constructor(params: RouteOptions) {\n super(params);\n assertFinalMembers(this, FamilyRoute, ['handle', 'execute']);\n }\n\n /**\n * @final Validate → `handleRequest` → shape, with every failure mapped to the\n * family envelope. Extend through {@link handleRequest} and {@link errorMapping}.\n */\n public async handle(c: Context<FamilyEnv<E, V>>): Promise<Response> {\n try {\n const input = await this.getValidatedData<S>();\n const result = await this.handleRequest(input, c);\n if (result instanceof Response) return result;\n if (result === null) return c.body(null, 204);\n return c.json(result as object);\n } catch (error: unknown) {\n const appOptions = c.get('errorMapperOptions' as never) as
|
|
5
|
-
"mappings": "+EAwBA,OAAS,gBAAAA,MAAoB,WAG7B,OAAS,sBAAAC,MAA0B,mBAEnC,OAAS,oBAAAC,MAAwB,
|
|
4
|
+
"sourcesContent": ["/**\n * The converged chanfana route base.\n *\n * Converged from the seven `apps/api/src/endpoints/IBaseRoute.ts` copies\n * (ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Bee,\n * Mail-Meow, Mail-Otter), and the answer to the \"unconverged\" note in\n * `../routeBase.ts`. Every copy did the same four things by hand and each got a\n * different one wrong:\n *\n * 1. **Parse and validate.** The Mail-* copies parsed the body themselves and\n * validated against a path-keyed registry (`validateRequestInput`) that failed\n * *open* for a route nobody registered. Here the route's own chanfana `schema`\n * validates — the same object that documents it — so there is no second\n * registry to forget.\n * 2. **Run the handler** — the only open step: {@link FamilyRoute.handleRequest}.\n * 3. **Shape the response.** A `Response` passes through; a value is JSON; `null`\n * is `204`.\n * 4. **Map the failure** through the kit mapper (`respondWithError`), never a\n * hand-built envelope: two copies shipped a 5xx's raw message.\n *\n * Steps 1, 3 and 4 are closed. `handle` and chanfana's `execute` are `@final`\n * and **refused at construction** (`assertFinalMembers`) — chanfana constructs a\n * route once at registration, so an override fails the app at startup.\n */\nimport { OpenAPIRoute } from 'chanfana';\nimport type { OpenAPIRouteSchema, RouteOptions, ValidatedData } from 'chanfana';\nimport type { Context } from 'hono';\nimport { assertFinalMembers } from '@rexezuge/shared';\nimport type { ErrorMapperOptions } from '../ErrorMapper.ts';\nimport { respondWithError } from './errorHandler.ts';\nimport type { ErrorBoundaryOptions } from './errorHandler.ts';\nimport type { FamilyEnv } from './types.ts';\n\n/**\n * Open: what the route returns. A `Response` is sent as-is (redirects, streams,\n * a non-JSON body); `null` is `204 No Content`; anything else is JSON with 200.\n */\ntype RouteResult<T> = T | Response | null;\n\n/**\nA value or a promise of it: a handler with nothing to await need not be `async`.\n*/\ntype MaybePromise<T> = T | Promise<T>;\n\nabstract class FamilyRoute<\n S extends OpenAPIRouteSchema = OpenAPIRouteSchema,\n E extends object = object,\n V extends object = object,\n TOutput = unknown,\n> extends OpenAPIRoute<[Context<FamilyEnv<E, V>>]> {\n public constructor(params: RouteOptions) {\n super(params);\n assertFinalMembers(this, FamilyRoute, ['handle', 'execute']);\n }\n\n /**\n * @final Validate → `handleRequest` → shape, with every failure mapped to the\n * family envelope. Extend through {@link handleRequest} and {@link errorMapping}.\n */\n public async handle(c: Context<FamilyEnv<E, V>>): Promise<Response> {\n try {\n const input = await this.getValidatedData<S>();\n const result = await this.handleRequest(input, c);\n if (result instanceof Response) return result;\n if (result === null) return c.body(null, 204);\n return c.json(result as object);\n } catch (error: unknown) {\n const appOptions = c.get('errorMapperOptions' as never) as ErrorBoundaryOptions | undefined;\n return respondWithError(c, error, { ...appOptions, ...this.errorMapping() });\n }\n }\n\n /**\n * The route's domain work. `input` is chanfana's validated `{ params, query,\n * headers, body }` for this route's `schema`; `c` is the typed family context\n * (bindings, `AuthenticatedUserId`, `logger`, …).\n */\n protected abstract handleRequest(input: ValidatedData<S>, c: Context<FamilyEnv<E, V>>): MaybePromise<RouteResult<TOutput>>;\n\n /**\n * Open: per-route mapper options, merged over the app's. The hook for a\n * protocol surface with its own dialect (`toResponse`) or extra headers.\n */\n protected errorMapping(): ErrorMapperOptions {\n return {};\n }\n}\n\nexport { FamilyRoute };\nexport type { MaybePromise, RouteResult };\n"],
|
|
5
|
+
"mappings": "+EAwBA,OAAS,gBAAAA,MAAoB,WAG7B,OAAS,sBAAAC,MAA0B,mBAEnC,OAAS,oBAAAC,MAAwB,oBAejC,MAAeC,UAKLH,CAAwC,CAjDlD,MAiDkD,CAAAI,EAAA,oBAChD,YAAmBC,EAAoB,CACrC,MAAMA,CAAM,EACZJ,EAAmB,KAAME,EAAa,CAAC,SAAU,SAAS,CAAC,CAC7D,CAMO,MAAM,OAAOG,EAA2B,CAC7C,GAAI,CACF,MAAMC,EAAQ,MAAM,KAAK,iBAAgB,EACnCC,EAAS,MAAM,KAAK,cAAcD,EAAOD,CAAC,EAChD,OAAIE,aAAkB,SAAiBA,EACnCA,IAAW,KAAaF,EAAE,KAAK,KAAM,GAAG,EACrCA,EAAE,KAAKE,CAAgB,CAChC,OAASC,EAAgB,CACvB,MAAMC,EAAaJ,EAAE,IAAI,oBAA6B,EACtD,OAAOJ,EAAiBI,EAAGG,EAAO,CAAE,GAAGC,EAAY,GAAG,KAAK,aAAY,CAAE,CAAE,CAC7E,CACF,CAaU,cAAY,CACpB,MAAO,CAAA,CACT",
|
|
6
6
|
"names": ["OpenAPIRoute", "assertFinalMembers", "respondWithError", "FamilyRoute", "__name", "params", "c", "input", "result", "error", "appOptions"]
|
|
7
7
|
}
|
package/dist/hono/contracts.d.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import type { OpenAPIRoute, OpenAPIRouteSchema } from 'chanfana';
|
|
2
2
|
import type { Contract, ContractEndpoints, Endpoint, EndpointResult, EndpointServerInput } from '@rexezuge/contracts';
|
|
3
3
|
import type { ApiApp } from './createApiApp.ts';
|
|
4
|
-
import type { RouteResult } from './FamilyRoute.ts';
|
|
4
|
+
import type { MaybePromise, RouteResult } from './FamilyRoute.ts';
|
|
5
5
|
import type { FamilyContext } from './types.ts';
|
|
6
6
|
/**
|
|
7
7
|
* Your implementation of one endpoint. `input` is the validated request (zod
|
|
8
|
-
* output), and the return value is the response schema's input,
|
|
9
|
-
* `204` endpoint, or a `Response` you built yourself.
|
|
8
|
+
* output), and the return value (or a promise of it: a handler need not be `async`) is the response schema's input,
|
|
9
|
+
* `null` for a `204` endpoint, or a `Response` you built yourself.
|
|
10
10
|
*/
|
|
11
|
-
type EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (input: EndpointServerInput<EP>, c: FamilyContext<E, V>) =>
|
|
11
|
+
type EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (input: EndpointServerInput<EP>, c: FamilyContext<E, V>) => MaybePromise<RouteResult<EndpointResult<EP>>>;
|
|
12
12
|
/**
|
|
13
13
|
One handler per contract endpoint, by name. A missing key is a compile error.
|
|
14
14
|
*/
|
|
@@ -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,WAAW,EAAE,MAAM,kBAAkB,CAAC;
|
|
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,E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 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 { 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 is the response schema's input
|
|
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
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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AAS,OAAO,YAAW,CAAE,GAAG,KAAKkB,EAAKlB,EAAS,KAAMO,EAAkBP,EAAUQ,CAAO,CAAC,CACtG,CACF,CAjBSF,EAAAW,EAAA",
|
|
6
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"]
|
|
7
7
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
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
|
-
import type {
|
|
5
|
+
import type { SensitivePath } from '../securityHeaders.ts';
|
|
5
6
|
import type { D1BookmarkOptions } from './bookmarks.ts';
|
|
7
|
+
import type { ErrorBoundaryOptions } from './errorHandler.ts';
|
|
6
8
|
import type { HardeningOptions } from './hardening.ts';
|
|
7
9
|
import type { RateLimitRule } from './rateLimits.ts';
|
|
8
10
|
import type { RequestContextOptions } from './requestContext.ts';
|
|
@@ -29,10 +31,16 @@ interface DocsOptions {
|
|
|
29
31
|
}
|
|
30
32
|
interface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {
|
|
31
33
|
/**
|
|
32
|
-
* The paths whose responses get `Cache-Control: no-store
|
|
33
|
-
*
|
|
34
|
+
* The paths whose responses get `Cache-Control: no-store`, on **every** response for them: success, the IP
|
|
35
|
+
* rate limiter's 429, the error envelope and a 404. Applied in the kit's own early middleware, which no hook
|
|
36
|
+
* can bypass. Defaults to `['/user/', '/api/']`: both surfaces carry credentials or account data.
|
|
37
|
+
*
|
|
38
|
+
* Entries are `string | RegExp | ((path: string) => boolean)`. A string is an **exact** path (`'/generate-totp'`),
|
|
39
|
+
* unless it ends in `/` or `/*`, which makes it a **prefix** (`'/user/'`, `'/user/*'`). Strings ending in `/`
|
|
40
|
+
* were prefixes before exact matching existed and stay so; a bare `'/user'` is now the exact path, not
|
|
41
|
+
* `/user/*`.
|
|
34
42
|
*/
|
|
35
|
-
sensitivePaths?: readonly
|
|
43
|
+
sensitivePaths?: readonly SensitivePath[];
|
|
36
44
|
/**
|
|
37
45
|
Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.
|
|
38
46
|
*/
|
|
@@ -62,17 +70,25 @@ interface ApiAppOptions<E extends object, V extends object = object> extends Req
|
|
|
62
70
|
afterAuth?: readonly AppHook<E, V>[];
|
|
63
71
|
};
|
|
64
72
|
/**
|
|
65
|
-
Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`).
|
|
73
|
+
Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`) and `reportUnhandled`, the sink that receives the raw error of a 5xx.
|
|
66
74
|
*/
|
|
67
|
-
errors?:
|
|
75
|
+
errors?: ErrorBoundaryOptions;
|
|
68
76
|
/**
|
|
69
77
|
`/docs` and `/openapi.json`. Pass `false` to serve neither.
|
|
70
78
|
*/
|
|
71
79
|
docs?: DocsOptions | false;
|
|
72
80
|
/**
|
|
73
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.
|
|
74
87
|
*/
|
|
75
|
-
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>>;
|
|
76
92
|
}
|
|
77
93
|
type AppHook<E extends object, V extends object> = MiddlewareHandler<FamilyEnv<E, V>> | {
|
|
78
94
|
path: string;
|
|
@@ -89,5 +105,5 @@ declare const ERROR_OPTIONS_KEY = "errorMapperOptions";
|
|
|
89
105
|
*/
|
|
90
106
|
declare function createApiApp<E extends object, V extends object = object>(options?: ApiAppOptions<E, V>): ApiApp<E, V>;
|
|
91
107
|
export { createApiApp, ERROR_OPTIONS_KEY };
|
|
92
|
-
export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };
|
|
108
|
+
export type { ApiApp, ApiAppOptions, AppHook, RawRoutes, CorsOptions, DocsOptions };
|
|
93
109
|
//# sourceMappingURL=createApiApp.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createApiApp.d.ts","sourceRoot":"","sources":["../../src/hono/createApiApp.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,qBAAqB,EAAiB,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"createApiApp.d.ts","sourceRoot":"","sources":["../../src/hono/createApiApp.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,qBAAqB,EAAiB,MAAM,UAAU,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAG3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,KAAK,EAAE,qBAAqB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,WAAW,EAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
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, sensitivePaths } from '../securityHeaders.ts';\nimport type { ErrorMapperOptions } from '../ErrorMapper.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 { 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`. Defaults to\n * `['/user/', '/api/']`: both surfaces carry credentials or account data.\n */\n sensitivePaths?: readonly string[];\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`).\n */\n errors?: ErrorMapperOptions;\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(sensitivePaths(...(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,
|
|
6
|
-
"names": ["fromHono", "Hono", "cors", "securityHeaders", "
|
|
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,W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AAM,OAAQE,GAAUA,EAAM,MAAQ,IAAI,EAChE,UAAWE,KAAQH,EAASrB,EAAK,IAAIwB,EAAK,KAAM/B,EAAiB+B,CAAI,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
|
}
|
|
@@ -11,15 +11,38 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import type { Context, ErrorHandler, NotFoundHandler } from 'hono';
|
|
13
13
|
import type { ErrorMapperOptions } from '../ErrorMapper.ts';
|
|
14
|
+
/**
|
|
15
|
+
What a {@link ErrorBoundaryOptions.reportUnhandled} sink is told about the request, beside the raw error.
|
|
16
|
+
*/
|
|
17
|
+
interface UnhandledContext {
|
|
18
|
+
readonly status: number;
|
|
19
|
+
readonly requestId: string | undefined;
|
|
20
|
+
readonly method: string;
|
|
21
|
+
/**
|
|
22
|
+
The registered route pattern (`/user/:id`), not the concrete URL.
|
|
23
|
+
*/
|
|
24
|
+
readonly route: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The error boundary's options: the mapper's, plus the one open door for diagnosis.
|
|
28
|
+
*
|
|
29
|
+
* Closed: the kit's own log line never carries the caught value, its message or its stack. Open: `reportUnhandled`
|
|
30
|
+
* receives the **raw** error for every 5xx, for an app that ships to a log sink it controls (and has decided what may
|
|
31
|
+
* reach it). A sink that throws is swallowed: reporting must never change the response.
|
|
32
|
+
*/
|
|
33
|
+
interface ErrorBoundaryOptions extends ErrorMapperOptions {
|
|
34
|
+
reportUnhandled?(error: unknown, context: UnhandledContext): void;
|
|
35
|
+
}
|
|
14
36
|
/**
|
|
15
37
|
* Map, log and answer one failure on a Hono context. Shared by `onError` and
|
|
16
38
|
* `FamilyRoute`, so both produce byte-identical envelopes.
|
|
17
39
|
*/
|
|
18
|
-
declare function respondWithError(c: Context, error: unknown, options?:
|
|
19
|
-
declare function createErrorHandler(options?:
|
|
40
|
+
declare function respondWithError(c: Context, error: unknown, options?: ErrorBoundaryOptions): Response;
|
|
41
|
+
declare function createErrorHandler(options?: ErrorBoundaryOptions): ErrorHandler;
|
|
20
42
|
/**
|
|
21
43
|
A miss is a `404 NotFound` envelope, never Hono's `404 Not Found` text.
|
|
22
44
|
*/
|
|
23
45
|
declare function createNotFoundHandler(): NotFoundHandler;
|
|
24
46
|
export { createErrorHandler, createNotFoundHandler, respondWithError };
|
|
47
|
+
export type { ErrorBoundaryOptions, UnhandledContext };
|
|
25
48
|
//# sourceMappingURL=errorHandler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errorHandler.d.ts","sourceRoot":"","sources":["../../src/hono/errorHandler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"errorHandler.d.ts","sourceRoot":"","sources":["../../src/hono/errorHandler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAInE,OAAO,KAAK,EAAE,kBAAkB,EAAe,MAAM,mBAAmB,CAAC;AAGzE;;EAEE;AACF,UAAU,gBAAgB;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;MAEE;IACF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;GAMG;AACH,UAAU,oBAAqB,SAAQ,kBAAkB;IACvD,eAAe,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAAC;CACnE;AA2BD;;;GAGG;AACH,iBAAS,gBAAgB,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,GAAE,oBAAyB,GAAG,QAAQ,CAgBlG;AAED,iBAAS,kBAAkB,CAAC,OAAO,GAAE,oBAAyB,GAAG,YAAY,CAE5E;AAED;;EAEE;AACF,iBAAS,qBAAqB,IAAI,eAAe,CAGhD;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,CAAC;AACvE,YAAY,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var n=(t,e)=>c(t,"name",{value:e,configurable:!0});import{routePath as i}from"hono/route";import{CATALOG as m,NotFoundError as h,ServiceError as p}from"@rexezuge/errors";import{mapError as l}from"../ErrorMapper.js";function y(t){if(typeof t!="object"||t===null)return typeof t;const e=t.constructor?.name;return typeof e=="string"&&e!==""?e:"Object"}n(y,"errorNameOf");function q(t,e,o){if(!t)return;const r={type:e.error.type,status:e.status,...o};e.status>=500?t.error("Request failed with a server error",r):t.warn("Request rejected",r)}n(q,"logMapped");function s(t,e,o={}){const r=l(e,o),f=o.toResponse?.(r.error,r.status),u=t.get("requestId"),a=i(t),d={requestId:u,method:t.req.method,route:a,errorName:y(e)};if(e instanceof p&&(d.errorCode=m[e.type]?.code??e.type),q(t.get("logger"),r,d),r.status>=500&&o.reportUnhandled!==void 0)try{o.reportUnhandled(e,{status:r.status,requestId:u,method:t.req.method,route:a})}catch{}return f??Response.json(r.body,{status:r.status,headers:r.headers})}n(s,"respondWithError");function E(t={}){return(e,o)=>s(o,e,t)}n(E,"createErrorHandler");function N(){return t=>s(t,new h(`No route matches ${t.req.method} ${new URL(t.req.url).pathname}.`))}n(N,"createNotFoundHandler");export{E as createErrorHandler,N as createNotFoundHandler,s as respondWithError};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/errorHandler.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The app-level error boundary: `app.onError` and `app.notFound`.\n *\n * Every family worker ended its chain in one of two broken places: the\n * entrypoint's catch-all (a bare `Internal Error` *text* 500 the SPA cannot\n * parse), or Hono's default `onError` (the same, plus a `console.error` of the\n * caught value). This boundary answers the `{Exception:{Type,Message}}` envelope\n * for anything that escapes a route or a middleware — including a throwing\n * `beforeAuth` hook — through the kit mapper, so a failure answers identically\n * whichever layer caught it.\n */\nimport type { Context, ErrorHandler, NotFoundHandler } from 'hono';\nimport { NotFoundError } from '@rexezuge/errors';\nimport { mapError } from '../ErrorMapper.ts';\nimport type { ErrorMapperOptions, MappedError } from '../ErrorMapper.ts';\nimport type { HttpLogger } from './types.ts';\n\n/**\n * Log one mapped failure. Static message, plain fields: the caught value and its\n * message never reach the sink (a D1 message names tables; an upstream body can\n * carry a token).\n */\nfunction logMapped(logger: HttpLogger | undefined, mapped: MappedError,
|
|
5
|
-
"mappings": "+EAYA,OAAS,
|
|
6
|
-
"names": ["NotFoundError", "mapError", "
|
|
4
|
+
"sourcesContent": ["/**\n * The app-level error boundary: `app.onError` and `app.notFound`.\n *\n * Every family worker ended its chain in one of two broken places: the\n * entrypoint's catch-all (a bare `Internal Error` *text* 500 the SPA cannot\n * parse), or Hono's default `onError` (the same, plus a `console.error` of the\n * caught value). This boundary answers the `{Exception:{Type,Message}}` envelope\n * for anything that escapes a route or a middleware — including a throwing\n * `beforeAuth` hook — through the kit mapper, so a failure answers identically\n * whichever layer caught it.\n */\nimport type { Context, ErrorHandler, NotFoundHandler } from 'hono';\nimport { routePath } from 'hono/route';\nimport { CATALOG, NotFoundError, ServiceError } from '@rexezuge/errors';\nimport { mapError } from '../ErrorMapper.ts';\nimport type { ErrorMapperOptions, MappedError } from '../ErrorMapper.ts';\nimport type { HttpLogger } from './types.ts';\n\n/**\nWhat a {@link ErrorBoundaryOptions.reportUnhandled} sink is told about the request, beside the raw error.\n*/\ninterface UnhandledContext {\n readonly status: number;\n readonly requestId: string | undefined;\n readonly method: string;\n /**\n The registered route pattern (`/user/:id`), not the concrete URL.\n */\n readonly route: string;\n}\n\n/**\n * The error boundary's options: the mapper's, plus the one open door for diagnosis.\n *\n * Closed: the kit's own log line never carries the caught value, its message or its stack. Open: `reportUnhandled`\n * receives the **raw** error for every 5xx, for an app that ships to a log sink it controls (and has decided what may\n * reach it). A sink that throws is swallowed: reporting must never change the response.\n */\ninterface ErrorBoundaryOptions extends ErrorMapperOptions {\n reportUnhandled?(error: unknown, context: UnhandledContext): void;\n}\n\n/**\n * The class name of what was thrown, never its message; the `typeof` of a value that is not an object.\n */\nfunction errorNameOf(error: unknown): string {\n if (typeof error !== 'object' || error === null) return typeof error;\n const name: unknown = (error as { constructor?: { name?: unknown } }).constructor?.name;\n return typeof name === 'string' && name !== '' ? name : 'Object';\n}\n\n/**\n * Log one mapped failure. Static message, plain fields: the caught value and its\n * message never reach the sink (a D1 message names tables; an upstream body can\n * carry a token). What it does carry is enough to find the failure: the class name,\n * the taxonomy code of a `ServiceError`, the request id, the method and the route pattern.\n */\nfunction logMapped(logger: HttpLogger | undefined, mapped: MappedError, fields: Record<string, unknown>): void {\n if (!logger) return;\n const all = { type: mapped.error.type, status: mapped.status, ...fields };\n if (mapped.status >= 500) {\n logger.error('Request failed with a server error', all);\n } else {\n logger.warn('Request rejected', all);\n }\n}\n\n/**\n * Map, log and answer one failure on a Hono context. Shared by `onError` and\n * `FamilyRoute`, so both produce byte-identical envelopes.\n */\nfunction respondWithError(c: Context, error: unknown, options: ErrorBoundaryOptions = {}): Response {\n const mapped = mapError(error, options);\n const custom = options.toResponse?.(mapped.error, mapped.status);\n const requestId = c.get('requestId') as string | undefined;\n const route = routePath(c);\n const fields: Record<string, unknown> = { requestId, method: c.req.method, route, errorName: errorNameOf(error) };\n if (error instanceof ServiceError) fields['errorCode'] = CATALOG[error.type as keyof typeof CATALOG]?.code ?? error.type;\n logMapped(c.get('logger') as HttpLogger | undefined, mapped, fields);\n if (mapped.status >= 500 && options.reportUnhandled !== undefined) {\n try {\n options.reportUnhandled(error, { status: mapped.status, requestId, method: c.req.method, route });\n } catch {\n // A failing sink must not turn a mapped failure into a second one.\n }\n }\n return custom ?? Response.json(mapped.body, { status: mapped.status, headers: mapped.headers });\n}\n\nfunction createErrorHandler(options: ErrorBoundaryOptions = {}): ErrorHandler {\n return (error: unknown, c: Context): Response => respondWithError(c, error, options);\n}\n\n/**\nA miss is a `404 NotFound` envelope, never Hono's `404 Not Found` text.\n*/\nfunction createNotFoundHandler(): NotFoundHandler {\n return (c: Context): Response =>\n respondWithError(c, new NotFoundError(`No route matches ${c.req.method} ${new URL(c.req.url).pathname}.`));\n}\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError };\nexport type { ErrorBoundaryOptions, UnhandledContext };\n"],
|
|
5
|
+
"mappings": "+EAYA,OAAS,aAAAA,MAAiB,aAC1B,OAAS,WAAAC,EAAS,iBAAAC,EAAe,gBAAAC,MAAoB,mBACrD,OAAS,YAAAC,MAAgB,oBA+BzB,SAASC,EAAYC,EAAc,CACjC,GAAI,OAAOA,GAAU,UAAYA,IAAU,KAAM,OAAO,OAAOA,EAC/D,MAAMC,EAAiBD,EAA+C,aAAa,KACnF,OAAO,OAAOC,GAAS,UAAYA,IAAS,GAAKA,EAAO,QAC1D,CAJSC,EAAAH,EAAA,eAYT,SAASI,EAAUC,EAAgCC,EAAqBC,EAA+B,CACrG,GAAI,CAACF,EAAQ,OACb,MAAMG,EAAM,CAAE,KAAMF,EAAO,MAAM,KAAM,OAAQA,EAAO,OAAQ,GAAGC,CAAM,EACnED,EAAO,QAAU,IACnBD,EAAO,MAAM,qCAAsCG,CAAG,EAEtDH,EAAO,KAAK,mBAAoBG,CAAG,CAEvC,CARSL,EAAAC,EAAA,aAcT,SAASK,EAAiBC,EAAYT,EAAgBU,EAAgC,CAAA,EAAE,CACtF,MAAML,EAASP,EAASE,EAAOU,CAAO,EAChCC,EAASD,EAAQ,aAAaL,EAAO,MAAOA,EAAO,MAAM,EACzDO,EAAYH,EAAE,IAAI,WAAW,EAC7BI,EAAQnB,EAAUe,CAAC,EACnBH,EAAkC,CAAE,UAAAM,EAAW,OAAQH,EAAE,IAAI,OAAQ,MAAAI,EAAO,UAAWd,EAAYC,CAAK,CAAC,EAG/G,GAFIA,aAAiBH,IAAcS,EAAO,UAAeX,EAAQK,EAAM,IAA4B,GAAG,MAAQA,EAAM,MACpHG,EAAUM,EAAE,IAAI,QAAQ,EAA6BJ,EAAQC,CAAM,EAC/DD,EAAO,QAAU,KAAOK,EAAQ,kBAAoB,OACtD,GAAI,CACFA,EAAQ,gBAAgBV,EAAO,CAAE,OAAQK,EAAO,OAAQ,UAAAO,EAAW,OAAQH,EAAE,IAAI,OAAQ,MAAAI,CAAK,CAAE,CAClG,MAAQ,CAER,CAEF,OAAOF,GAAU,SAAS,KAAKN,EAAO,KAAM,CAAE,OAAQA,EAAO,OAAQ,QAASA,EAAO,OAAO,CAAE,CAChG,CAhBSH,EAAAM,EAAA,oBAkBT,SAASM,EAAmBJ,EAAgC,CAAA,EAAE,CAC5D,MAAO,CAACV,EAAgBS,IAAyBD,EAAiBC,EAAGT,EAAOU,CAAO,CACrF,CAFSR,EAAAY,EAAA,sBAOT,SAASC,GAAqB,CAC5B,OAAQN,GACND,EAAiBC,EAAG,IAAIb,EAAc,oBAAoBa,EAAE,IAAI,MAAM,IAAI,IAAI,IAAIA,EAAE,IAAI,GAAG,EAAE,QAAQ,GAAG,CAAC,CAC7G,CAHSP,EAAAa,EAAA",
|
|
6
|
+
"names": ["routePath", "CATALOG", "NotFoundError", "ServiceError", "mapError", "errorNameOf", "error", "name", "__name", "logMapped", "logger", "mapped", "fields", "all", "respondWithError", "c", "options", "custom", "requestId", "route", "createErrorHandler", "createNotFoundHandler"]
|
|
7
7
|
}
|
package/dist/hono/hardening.d.ts
CHANGED
|
@@ -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
|
|
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/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ty;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\
|
|
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,
|
|
6
|
-
"names": ["bodyLimit", "PayloadTooLargeError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "resolveFromEnv", "methodGuard", "methods", "c", "next", "rejection", "__name", "
|
|
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,wBAAAC,MAA4B,wBAErC,OAAS,kBAAAC,MAAsB,aAiE/B,SAASC,EAAYC,EAA6BL,EAAuB,CACvE,MAAO,OAAOM,EAAGC,IAAuB,CACtC,MAAMC,EAAYV,EAAYQ,EAAE,IAAI,OAAQD,CAAO,EACnD,GAAIG,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAL,EAAA,eAQT,SAASM,EAAeC,EAAgB,CACtC,GAAI,CAAC,OAAO,cAAcA,CAAQ,GAAKA,GAAY,EACjD,MAAM,IAAI,MAAM,yBAAyB,OAAOA,CAAQ,CAAC,+BAA+B,CAE5F,CAJSF,EAAAC,EAAA,kBAMT,SAASE,EAASD,EAAgB,CAChCD,EAAeC,CAAQ,EACvB,MAAME,EAAWnB,EAAU,CACzB,QAASiB,EACT,QAASF,EAAA,IAAY,CACnB,MAAM,IAAId,CACZ,EAFS,WAGV,EACD,MAAO,OAAOW,EAAGC,IAAkC,CACjD,MAAMC,EAAYZ,EAAmBU,EAAE,IAAI,IAAKK,CAAQ,EACxD,GAAIH,EAAW,MAAMA,EACrB,OAAOK,EAASP,EAAGC,CAAI,CACzB,CACF,CAbSE,EAAAG,EAAA,YAsBT,SAASE,EAAeC,EAAkC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kB,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
|
}
|
package/dist/hono/index.d.ts
CHANGED
|
@@ -16,21 +16,22 @@
|
|
|
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
|
-
export type { RouteResult } from './FamilyRoute.ts';
|
|
22
|
+
export type { MaybePromise, RouteResult } from './FamilyRoute.ts';
|
|
23
23
|
export { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';
|
|
24
24
|
export type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';
|
|
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';
|
|
32
32
|
export type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';
|
|
33
33
|
export { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';
|
|
34
|
+
export type { ErrorBoundaryOptions, UnhandledContext } from './errorHandler.ts';
|
|
34
35
|
export { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';
|
|
35
36
|
export type { RequestContextOptions } from './requestContext.ts';
|
|
36
37
|
export type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';
|
package/dist/hono/index.d.ts.map
CHANGED
|
@@ -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;
|
|
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,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE7G,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E,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/hono/index.js.map
CHANGED
|
@@ -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 { RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
|
|
5
|
-
"mappings": "AAiBA,OAAS,gBAAAA,MAAoB,oBAG7B,OAAS,gCAAAC,MAAoC,YAE7C,OAAS,eAAAC,MAAmB,mBAG5B,OAAS,oBAAAC,EAAkB,qBAAAC,EAAmB,sBAAAC,MAA0B,iBAGxE,OAAS,cAAAC,EAAY,cAAAC,MAAkB,YAGvC,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAG3E,OAAS,eAAAC,MAAmB,iBAG5B,OAAS,iBAAAC,MAAqB,kBAG9B,OAAS,sBAAAC,EAAoB,yBAAAC,EAAuB,oBAAAC,MAAwB,
|
|
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
|
+
"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;
|
|
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;AAG9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD;;EAEE;AACF,UAAU,iBAAiB;IACzB,KAAK,CAAC,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAChE;AAED,UAAU,aAAa,CAAC,CAAC;IACvB;;MAEE;IACF,IAAI,EAAE,MAAM,CAAC;IACb;;;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"}
|
package/dist/hono/rateLimits.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
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,
|
|
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,8 +45,8 @@
|
|
|
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, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
|
|
49
|
-
export type { HeaderContext } 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';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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,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,CAAC;AAE5F,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAErG,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAKtF;;GAEG;AACH,eAAO,MAAM,sBAAsB,EAAE,OAAO,0BAAuD,CAAC;AACpG;;GAEG;AACH,eAAO,MAAM,+BAA+B,EAAE,OAAO,mCAAyE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as
|
|
1
|
+
import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as p,sensitivePaths as E,sensitivePathMatcher as S,pathMatcher as h,CONTENT_SECURITY_POLICY as u,SECURITY_HEADERS as L,STRICT_TRANSPORT_SECURITY as A}from"./securityHeaders.js";import{AccessAuthError as C,authenticateAccess as x,identityFromBinding as F,verifyAccessJwt as f}from"./accessAuth.js";import{errorBody as M,errorResponseFromUnknown as d,mapError as g,toErrorResponse as k,toServiceError as O,INTERNAL_SERVER_MESSAGE as y}from"./ErrorMapper.js";import{errorResponses as U,exceptionResponse as D}from"./openApiErrors.js";import{checkContentLength as H,checkContentType as N,checkMethod as v,checkOrigin as P,isMutatingMethod as l,requestOrigin as w,DEFAULT_ALLOWED_METHODS as X,DEFAULT_MAX_BODY_BYTES as q}from"./requestGuards.js";import{BaseRoute as J,createRouteHandler as K}from"./routeBase.js";const o=t,s=e;export{C as AccessAuthError,J as BaseRoute,u as CONTENT_SECURITY_POLICY,X as DEFAULT_ALLOWED_METHODS,q as DEFAULT_MAX_BODY_BYTES,y as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,L as SECURITY_HEADERS,A as STRICT_TRANSPORT_SECURITY,m as applySecurityHeaders,x as authenticateAccess,H as checkContentLength,N as checkContentType,v as checkMethod,P as checkOrigin,c as clientIp,K as createRouteHandler,M as errorBody,d as errorResponseFromUnknown,U as errorResponses,D as exceptionResponse,s as getRateLimitBucketCountForTests,F as identityFromBinding,l as isMutatingMethod,g as mapError,h as pathMatcher,R as rateLimit,w as requestOrigin,o as resetRateLimitForTests,p as securityHeaders,S as sensitivePathMatcher,E as sensitivePaths,k as toErrorResponse,O as toServiceError,f as verifyAccessJwt};
|
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 CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';\n\nexport { errorResponses, exceptionResponse } from './openApiErrors.ts';\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from './requestGuards.ts';\nexport type { OriginGuardOptions } from './requestGuards.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n\n// Test seams, re-exported from the root barrel only for compatibility. Bound as\n// consts rather than re-export specifiers so the @deprecated tag reaches callers.\n\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const resetRateLimitForTests: typeof resetRateLimitForTestsSeam = resetRateLimitForTestsSeam;\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam = getRateLimitBucketCountForTestsSeam;\n"],
|
|
5
|
-
"mappings": "AA6CA,OACE,mCAAmCA,EACnC,0BAA0BC,MACrB,eAEP,OAAS,YAAAC,EAAU,eAAAC,EAAa,aAAAC,MAAiB,iBAGjD,OACE,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,6BAAAC,MACK,uBAGP,OAAS,mBAAAC,EAAiB,sBAAAC,EAAoB,uBAAAC,EAAqB,mBAAAC,MAAuB,kBAG1F,OAAS,aAAAC,EAAW,4BAAAC,EAA0B,YAAAC,EAAU,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGxH,OAAS,kBAAAC,EAAgB,qBAAAC,MAAyB,qBAGlD,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,oBAAAC,EACA,iBAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,qBAGP,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,
|
|
6
|
-
"names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
|
|
4
|
+
"sourcesContent": ["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately — and only in its\n * `/hono` subpath. It is also the only one a repo can choose to skip: nothing in\n * the other eight imports it.\n *\n * ## What converged here\n *\n * | Module | From |\n * | ----------------- | --------------------------------------------------------------------- |\n * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |\n * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |\n * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |\n * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |\n * | `routeBase` | All three incompatible shapes, with their shared parts converged |\n * | `requestGuards` | HttpHardening ×4, AWS `RequestGuards`, Image-Host's CSRF guard, Pigeongram's origin check |\n * | `openApiErrors` | AWS-AccessBridge's `exceptionResponses` |\n *\n * ## Two entry points\n *\n * This root barrel is **framework-free**: structural context types only, no\n * `hono` or `chanfana` import, so a bare-`Request` dispatcher (a Durable Object,\n * Pigeongram's route table) can take it. Everything that imports `hono` or\n * `chanfana` — `createApiApp`, `FamilyRoute`, the auth and hardening middleware —\n * lives at `@rexezuge/http/hono`, and those two optional peers are required only\n * by a repo that imports that subpath.\n *\n * ## The null rule\n *\n * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.\n * The middleware in this package takes *structural* context types rather than\n * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test\n * double usable without a framework import.\n */\n\nimport {\n getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam,\n resetRateLimitForTests as resetRateLimitForTestsSeam,\n} from './testing.ts';\n\nexport { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n sensitivePathMatcher,\n pathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext, PathMatcher, SensitivePath } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';\n\nexport { errorResponses, exceptionResponse } from './openApiErrors.ts';\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from './requestGuards.ts';\nexport type { OriginGuardOptions } from './requestGuards.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n\n// Test seams, re-exported from the root barrel only for compatibility. Bound as\n// consts rather than re-export specifiers so the @deprecated tag reaches callers.\n\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const resetRateLimitForTests: typeof resetRateLimitForTestsSeam = resetRateLimitForTestsSeam;\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam = getRateLimitBucketCountForTestsSeam;\n"],
|
|
5
|
+
"mappings": "AA6CA,OACE,mCAAmCA,EACnC,0BAA0BC,MACrB,eAEP,OAAS,YAAAC,EAAU,eAAAC,EAAa,aAAAC,MAAiB,iBAGjD,OACE,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,EACA,wBAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,6BAAAC,MACK,uBAGP,OAAS,mBAAAC,EAAiB,sBAAAC,EAAoB,uBAAAC,EAAqB,mBAAAC,MAAuB,kBAG1F,OAAS,aAAAC,EAAW,4BAAAC,EAA0B,YAAAC,EAAU,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGxH,OAAS,kBAAAC,EAAgB,qBAAAC,MAAyB,qBAGlD,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,oBAAAC,EACA,iBAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,qBAGP,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,EAA4DlC,EAI5DmC,EAA8EpC",
|
|
6
|
+
"names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "sensitivePathMatcher", "pathMatcher", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
|
|
7
7
|
}
|
|
@@ -75,6 +75,25 @@ declare function securityHeaders(isSensitive: (pathname: string) => boolean): (c
|
|
|
75
75
|
* test without editing this one.
|
|
76
76
|
*/
|
|
77
77
|
declare function sensitivePaths(...prefixes: readonly string[]): (pathname: string) => boolean;
|
|
78
|
-
|
|
79
|
-
|
|
78
|
+
/**
|
|
79
|
+
* One private-path entry: a string, a `RegExp` tested against the pathname, or a predicate.
|
|
80
|
+
*
|
|
81
|
+
* - `'/generate-totp'` matches that path **exactly** (and its one-trailing-slash form), nothing under it.
|
|
82
|
+
* - `'/user/'` (ends with `/`) and `'/user/*'` match the **prefix**: everything under `/user/`
|
|
83
|
+
* (`'/user/*'` also matches `/user` itself). A string ending in `/` was a prefix before exact
|
|
84
|
+
* matching existed, and stays one.
|
|
85
|
+
* - a `RegExp` or `(path) => boolean` decides for itself.
|
|
86
|
+
*/
|
|
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;
|
|
92
|
+
/**
|
|
93
|
+
* Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).
|
|
94
|
+
* Empty means nothing is private, and says so rather than guessing.
|
|
95
|
+
*/
|
|
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 };
|
|
80
99
|
//# sourceMappingURL=securityHeaders.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"securityHeaders.d.ts","sourceRoot":"","sources":["../src/securityHeaders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;EAEE;AACF,UAAU,aAAa;IACrB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,GAAG,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;IAC1B,GAAG,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,QAAA,MAAM,gBAAgB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAS7C,CAAC;AAEX;;;;;;GAMG;AACH,QAAA,MAAM,uBAAuB,6NAC+L,CAAC;AAE7N;;EAEE;AACF,QAAA,MAAM,yBAAyB,wCAAwC,CAAC;AAExE;;;;;GAKG;AACH,iBAAS,oBAAoB,CAAC,CAAC,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,GAAG,IAAI,CA2Bh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,OAAO,CAAC,IAAI,CAAC,CASnI;AAED;;;;;;;GAOG;AACH,iBAAS,cAAc,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,CAAC,QAAQ,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"}
|
package/dist/securityHeaders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
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\
|
|
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",
|
|
6
|
-
"names": ["SECURITY_HEADERS", "CONTENT_SECURITY_POLICY", "STRICT_TRANSPORT_SECURITY", "applySecurityHeaders", "c", "isSensitive", "key", "value", "pathname", "__name", "securityHeaders", "next", "sensitivePaths", "prefixes", "normalized", "prefix"]
|
|
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,kBAAmB,cACnB,qBAAs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E,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
|
+
"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.
|
|
3
|
+
"version": "1.16.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.
|
|
38
|
-
"@rexezuge/
|
|
39
|
-
"@rexezuge/
|
|
37
|
+
"@rexezuge/contracts": "1.16.0",
|
|
38
|
+
"@rexezuge/errors": "1.16.0",
|
|
39
|
+
"@rexezuge/shared": "1.16.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"chanfana": "^3.4.0",
|