@rexezuge/http 1.13.0 → 1.15.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 +27 -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 +13 -6
- 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/index.d.ts +2 -1
- package/dist/hono/index.d.ts.map +1 -1
- package/dist/hono/index.js.map +2 -2
- 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 +17 -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
|
|
@@ -231,9 +251,11 @@ createApiApp<Env>({
|
|
|
231
251
|
| Your logger / redacting sink | `logger: (env, requestId) => createLogger(…, sink)` |
|
|
232
252
|
| A protocol dialect (Subsonic, WebDAV) | `errors.toResponse` app-wide, or `FamilyRoute.errorMapping()` per route |
|
|
233
253
|
| More context variables | the `V` type parameter |
|
|
254
|
+
| Which paths are `no-store` | `sensitivePaths: ['/generate-totp', '/user/', /^\/export\//, (path) => …]` (see below) |
|
|
255
|
+
| Diagnose a 5xx in your own log sink | `errors.reportUnhandled(error, { status, requestId, method, route })` |
|
|
234
256
|
|
|
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
|
|
257
|
+
Closed, with no flag: the slot order, the error envelope and its masking, `no-store` on every response of a sensitive path, the CSP
|
|
258
|
+
(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
259
|
`@final` route `handle()`.
|
|
238
260
|
|
|
239
261
|
## 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,EAAE,CAAC,CAAC,KACnB,YAAY,CAAC,WAAW,CAAC,cAAc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
-
"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,EAAkC,CAElC,MAAMC,EAASV,EAAmBC,CAAQ,EACpCU,E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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,9 @@
|
|
|
1
1
|
import type { HonoOpenAPIRouterType } from 'chanfana';
|
|
2
2
|
import type { MiddlewareHandler } from 'hono';
|
|
3
3
|
import { cors } from 'hono/cors';
|
|
4
|
-
import type {
|
|
4
|
+
import type { SensitivePath } from '../securityHeaders.ts';
|
|
5
5
|
import type { D1BookmarkOptions } from './bookmarks.ts';
|
|
6
|
+
import type { ErrorBoundaryOptions } from './errorHandler.ts';
|
|
6
7
|
import type { HardeningOptions } from './hardening.ts';
|
|
7
8
|
import type { RateLimitRule } from './rateLimits.ts';
|
|
8
9
|
import type { RequestContextOptions } from './requestContext.ts';
|
|
@@ -29,10 +30,16 @@ interface DocsOptions {
|
|
|
29
30
|
}
|
|
30
31
|
interface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {
|
|
31
32
|
/**
|
|
32
|
-
* The paths whose responses get `Cache-Control: no-store
|
|
33
|
-
*
|
|
33
|
+
* The paths whose responses get `Cache-Control: no-store`, on **every** response for them: success, the IP
|
|
34
|
+
* rate limiter's 429, the error envelope and a 404. Applied in the kit's own early middleware, which no hook
|
|
35
|
+
* can bypass. Defaults to `['/user/', '/api/']`: both surfaces carry credentials or account data.
|
|
36
|
+
*
|
|
37
|
+
* Entries are `string | RegExp | ((path: string) => boolean)`. A string is an **exact** path (`'/generate-totp'`),
|
|
38
|
+
* unless it ends in `/` or `/*`, which makes it a **prefix** (`'/user/'`, `'/user/*'`). Strings ending in `/`
|
|
39
|
+
* were prefixes before exact matching existed and stay so; a bare `'/user'` is now the exact path, not
|
|
40
|
+
* `/user/*`.
|
|
34
41
|
*/
|
|
35
|
-
sensitivePaths?: readonly
|
|
42
|
+
sensitivePaths?: readonly SensitivePath[];
|
|
36
43
|
/**
|
|
37
44
|
Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.
|
|
38
45
|
*/
|
|
@@ -62,9 +69,9 @@ interface ApiAppOptions<E extends object, V extends object = object> extends Req
|
|
|
62
69
|
afterAuth?: readonly AppHook<E, V>[];
|
|
63
70
|
};
|
|
64
71
|
/**
|
|
65
|
-
Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`).
|
|
72
|
+
Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`) and `reportUnhandled`, the sink that receives the raw error of a 5xx.
|
|
66
73
|
*/
|
|
67
|
-
errors?:
|
|
74
|
+
errors?: ErrorBoundaryOptions;
|
|
68
75
|
/**
|
|
69
76
|
`/docs` and `/openapi.json`. Pass `false` to serve neither.
|
|
70
77
|
*/
|
|
@@ -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;AAErE,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"createApiApp.d.ts","sourceRoot":"","sources":["../../src/hono/createApiApp.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,qBAAqB,EAAiB,MAAM,UAAU,CAAC;AAErE,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;A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,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var d=Object.defineProperty;var n=(e,r)=>d(e,"name",{value:r,configurable:!0});import{fromHono as m}from"chanfana";import{Hono as p}from"hono";import{cors as h}from"hono/cors";import{securityHeaders as y,
|
|
1
|
+
var d=Object.defineProperty;var n=(e,r)=>d(e,"name",{value:r,configurable:!0});import{fromHono as m}from"chanfana";import{Hono as p}from"hono";import{cors as h}from"hono/cors";import{securityHeaders as y,sensitivePathMatcher as _}from"../securityHeaders.js";import{d1Bookmarks as T}from"./bookmarks.js";import{DOCS_CONTENT_SECURITY_POLICY as O,isDocsPath as E}from"./docs.js";import{createErrorHandler as H,createNotFoundHandler as P}from"./errorHandler.js";import{bodyLimitGuard as R,contentTypeGuard as k,methodGuard as A,originGuard as C}from"./hardening.js";import{rateLimitRule as i}from"./rateLimits.js";import{requestContext as N}from"./requestContext.js";const c="errorMapperOptions",S=["/user/*"],g=["/user/*","/api/*"];function f(e,r){for(const s of r??[])typeof s=="function"?e.use("*",s):e.use(s.path,s.handler)}n(f,"mountHooks");function w(e){return e===!1?{docs_url:null,openapi_url:null,redoc_url:null,raiseOnError:!0}:{docs_url:e?.url??"/docs",openapi_url:e?.openapiUrl??"/openapi.json",redoc_url:null,raiseOnError:!0,...e?.info&&{schema:{info:e.info}}}}n(w,"routerOptions");function x(e,r){e.use("*",N(r)),e.use("*",async(t,o)=>{t.set(c,r.errors??{}),await o()});const s=y(_(...r.sensitivePaths??["/user/","/api/"])),a=r.docs===!1?null:r.docs?.url??"/docs";if(e.use("*",async(t,o)=>{await s(t,o),a!==null&&E(t.req.path,a)&&(t.res.headers.get("content-type")??"").includes("text/html")&&t.header("Content-Security-Policy",O)}),r.cors){const t=[...new Set([...r.cors.exposeHeaders??[],"X-Request-Id"])];e.use("*",h({...r.cors,exposeHeaders:t}))}const u=r.hardening??{};e.use("*",A(u.methods)),e.use("*",R(u.maxBodyBytes));for(const t of u.contentType?.paths??g)e.use(t,k(u.contentType?.allowed));for(const t of u.origin?.paths??S)e.use(t,C(u.origin));if(r.d1)for(const t of r.d1.paths??["*"])e.use(t,T(r.d1))}n(x,"mountPlatform");function I(e={}){const r=new p;r.onError(H(e.errors)),r.notFound(P()),x(r,e);const s=e.rateLimits??[],a=s.filter(o=>o.key==="ip"),u=s.filter(o=>o.key!=="ip");for(const o of a)r.use(o.path,i(o));f(r,e.hooks?.beforeAuth);for(const[o,l]of Object.entries(e.auth??{}))r.use(o,l);for(const o of u)r.use(o.path,i(o));f(r,e.hooks?.afterAuth);const t=m(r,w(e.docs));return e.routes?.(t),t}n(I,"createApiApp");export{c as ERROR_OPTIONS_KEY,I as createApiApp};
|
|
@@ -1,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, methodGuard, originGuard } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`, on **every** response for them: success, the IP\n * rate limiter's 429, the error envelope and a 404. Applied in the kit's own early middleware, which no hook\n * can bypass. Defaults to `['/user/', '/api/']`: both surfaces carry credentials or account data.\n *\n * Entries are `string | RegExp | ((path: string) => boolean)`. A string is an **exact** path (`'/generate-totp'`),\n * unless it ends in `/` or `/*`, which makes it a **prefix** (`'/user/'`, `'/user/*'`). Strings ending in `/`\n * were prefixes before exact matching existed and stay so; a bare `'/user'` is now the exact path, not\n * `/user/*`.\n */\n sensitivePaths?: readonly SensitivePath[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`) and `reportUnhandled`, the sink that receives the raw error of a 5xx.\n */\n errors?: ErrorBoundaryOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n */\n routes?: (app: ApiApp<E, V>) => void;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n const headers = securityHeaders(sensitivePathMatcher(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler;\n const docsUrl = options.docs === false ? null : (options.docs?.url ?? '/docs');\n hono.use('*', async (c, next) => {\n await headers(c, next);\n // Closed: the docs page (and only it) gets the policy that admits the\n // Swagger UI assets. Every other HTML response keeps the strict one.\n if (docsUrl !== null && isDocsPath(c.req.path, docsUrl) && (c.res.headers.get('content-type') ?? '').includes('text/html')) {\n c.header('Content-Security-Policy', DOCS_CONTENT_SECURITY_POLICY);\n }\n });\n if (options.cors) {\n const exposeHeaders = [...new Set([...(options.cors.exposeHeaders ?? []), 'X-Request-Id'])];\n hono.use('*', cors({ ...options.cors, exposeHeaders }));\n }\n\n const hardening = options.hardening ?? {};\n hono.use('*', methodGuard(hardening.methods));\n hono.use('*', bodyLimitGuard(hardening.maxBodyBytes));\n for (const path of hardening.contentType?.paths ?? DEFAULT_CONTENT_TYPE_PATHS) {\n hono.use(path, contentTypeGuard(hardening.contentType?.allowed));\n }\n for (const path of hardening.origin?.paths ?? DEFAULT_ORIGIN_PATHS) {\n hono.use(path, originGuard<E>(hardening.origin));\n }\n\n if (options.d1) {\n for (const path of options.d1.paths ?? ['*']) hono.use(path, d1Bookmarks<E>(options.d1));\n }\n}\n\n/**\n * Build the app. The returned value is the chanfana router: register routes on\n * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's\n * `onRequest`.\n */\nfunction createApiApp<E extends object, V extends object = object>(options: ApiAppOptions<E, V> = {}): ApiApp<E, V> {\n const hono = new Hono<FamilyEnv<E, V>>();\n hono.onError(createErrorHandler(options.errors));\n hono.notFound(createNotFoundHandler());\n\n mountPlatform(hono, options);\n\n const rules = options.rateLimits ?? [];\n const ipRules = rules.filter((entry) => entry.key === 'ip');\n const identityRules = rules.filter((entry) => entry.key !== 'ip');\n for (const rule of ipRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.beforeAuth);\n for (const [path, middleware] of Object.entries(options.auth ?? {})) hono.use(path, middleware);\n for (const rule of identityRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.afterAuth);\n\n const app = fromHono(hono, routerOptions(options.docs)) as ApiApp<E, V>;\n options.routes?.(app);\n return app;\n}\n\nexport { createApiApp, ERROR_OPTIONS_KEY };\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };\n"],
|
|
5
|
+
"mappings": "+EA2BA,OAAS,YAAAA,MAAgB,WAEzB,OAAS,QAAAC,MAAY,OAErB,OAAS,QAAAC,MAAY,YACrB,OAAS,mBAAAC,EAAiB,wBAAAC,MAA4B,wBAEtD,OAAS,eAAAC,MAAmB,iBAC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M,MAAQ,IAAI,EAChE,UAAWE,KAAQH,EAASjB,EAAK,IAAIoB,EAAK,KAAM1B,EAAiB0B,CAAI,CAAC,EACtErB,EAAWC,EAAMO,EAAQ,OAAO,UAAU,EAC1C,SAAW,CAACO,EAAMO,CAAU,IAAK,OAAO,QAAQd,EAAQ,MAAQ,CAAA,CAAE,EAAGP,EAAK,IAAIc,EAAMO,CAAU,EAC9F,UAAWD,KAAQD,EAAenB,EAAK,IAAIoB,EAAK,KAAM1B,EAAiB0B,CAAI,CAAC,EAC5ErB,EAAWC,EAAMO,EAAQ,OAAO,SAAS,EAEzC,MAAMe,EAAM1C,EAASoB,EAAMI,EAAcG,EAAQ,IAAI,CAAC,EACtD,OAAAA,EAAQ,SAASe,CAAG,EACbA,CACT,CAnBSnB,EAAAY,EAAA",
|
|
6
|
+
"names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePathMatcher", "d1Bookmarks", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "createErrorHandler", "createNotFoundHandler", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "rateLimitRule", "requestContext", "ERROR_OPTIONS_KEY", "DEFAULT_ORIGIN_PATHS", "DEFAULT_CONTENT_TYPE_PATHS", "mountHooks", "hono", "hooks", "hook", "__name", "routerOptions", "docs", "mountPlatform", "options", "c", "next", "headers", "docsUrl", "exposeHeaders", "hardening", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
|
|
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": "+EAY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AAS,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/index.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export { createApiApp } from './createApiApp.ts';
|
|
|
19
19
|
export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } 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';
|
|
@@ -31,6 +31,7 @@ export type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions }
|
|
|
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;AAElG,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElG,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAElE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,E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": ["/**\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 } from './createApiApp.ts';\n\nexport { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { MaybePromise, RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\nexport type { ErrorBoundaryOptions, UnhandledContext } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
|
|
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
|
}
|
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, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
|
|
49
|
+
export type { HeaderContext, 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,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EACL,+BAA+B,IAAI,mCAAmC,EACtE,sBAAsB,IAAI,0BAA0B,EACrD,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAClE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAEzE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC5G,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE3G,OAAO,EAAE,SAAS,EAAE,wBAAwB,EAAE,QAAQ,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3I,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE5F,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAErG,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAKtF;;GAEG;AACH,eAAO,MAAM,sBAAsB,EAAE,OAAO,0BAAuD,CAAC;AACpG;;GAEG;AACH,eAAO,MAAM,+BAA+B,EAAE,OAAO,mCAAyE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as E,sensitivePaths as p,
|
|
1
|
+
import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as E,sensitivePaths as p,sensitivePathMatcher as S,CONTENT_SECURITY_POLICY as u,SECURITY_HEADERS as L,STRICT_TRANSPORT_SECURITY as A}from"./securityHeaders.js";import{AccessAuthError as h,authenticateAccess as C,identityFromBinding as x,verifyAccessJwt as F}from"./accessAuth.js";import{errorBody as B,errorResponseFromUnknown as d,mapError as g,toErrorResponse as k,toServiceError as M,INTERNAL_SERVER_MESSAGE as O}from"./ErrorMapper.js";import{errorResponses as I,exceptionResponse as U}from"./openApiErrors.js";import{checkContentLength as Y,checkContentType as H,checkMethod as N,checkOrigin as v,isMutatingMethod as P,requestOrigin as l,DEFAULT_ALLOWED_METHODS as w,DEFAULT_MAX_BODY_BYTES as X}from"./requestGuards.js";import{BaseRoute as G,createRouteHandler as J}from"./routeBase.js";const o=t,s=e;export{h as AccessAuthError,G as BaseRoute,u as CONTENT_SECURITY_POLICY,w as DEFAULT_ALLOWED_METHODS,X as DEFAULT_MAX_BODY_BYTES,O as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,L as SECURITY_HEADERS,A as STRICT_TRANSPORT_SECURITY,m as applySecurityHeaders,C as authenticateAccess,Y as checkContentLength,H as checkContentType,N as checkMethod,v as checkOrigin,c as clientIp,J as createRouteHandler,B as errorBody,d as errorResponseFromUnknown,I as errorResponses,U as exceptionResponse,s as getRateLimitBucketCountForTests,x as identityFromBinding,P as isMutatingMethod,g as mapError,R as rateLimit,l as requestOrigin,o as resetRateLimitForTests,E as securityHeaders,S as sensitivePathMatcher,p as sensitivePaths,k as toErrorResponse,M as toServiceError,F as verifyAccessJwt};
|
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 CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext, SensitivePath } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';\n\nexport { errorResponses, exceptionResponse } from './openApiErrors.ts';\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from './requestGuards.ts';\nexport type { OriginGuardOptions } from './requestGuards.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n\n// Test seams, re-exported from the root barrel only for compatibility. Bound as\n// consts rather than re-export specifiers so the @deprecated tag reaches callers.\n\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const resetRateLimitForTests: typeof resetRateLimitForTestsSeam = resetRateLimitForTestsSeam;\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam = getRateLimitBucketCountForTestsSeam;\n"],
|
|
5
|
+
"mappings": "AA6CA,OACE,mCAAmCA,EACnC,0BAA0BC,MACrB,eAEP,OAAS,YAAAC,EAAU,eAAAC,EAAa,aAAAC,MAAiB,iBAGjD,OACE,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,EACA,wBAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,6BAAAC,MACK,uBAGP,OAAS,mBAAAC,EAAiB,sBAAAC,EAAoB,uBAAAC,EAAqB,mBAAAC,MAAuB,kBAG1F,OAAS,aAAAC,EAAW,4BAAAC,EAA0B,YAAAC,EAAU,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGxH,OAAS,kBAAAC,EAAgB,qBAAAC,MAAyB,qBAGlD,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,oBAAAC,EACA,iBAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,qBAGP,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,EAA4DjC,EAI5DkC,EAA8EnC",
|
|
6
|
+
"names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "sensitivePathMatcher", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
|
|
7
7
|
}
|
|
@@ -75,6 +75,21 @@ 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 SensitivePath = string | RegExp | ((pathname: string) => boolean);
|
|
88
|
+
/**
|
|
89
|
+
* Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).
|
|
90
|
+
* Empty means nothing is private, and says so rather than guessing.
|
|
91
|
+
*/
|
|
92
|
+
declare function sensitivePathMatcher(...entries: readonly SensitivePath[]): (pathname: string) => boolean;
|
|
93
|
+
export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, };
|
|
94
|
+
export type { HeaderContext, SensitivePath };
|
|
80
95
|
//# 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,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Aa,EAAE,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,GAAG,IAAI,CA2BhG;AAED;;;;;;GAMG;AACH,iBAAS,eAAe,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,GAAG,CAAC,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,KAAK,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,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAgBvE;;;GAGG;AACH,iBAAS,oBAAoB,CAAC,GAAG,OAAO,EAAE,SAAS,aAAa,EAAE,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAGjG;AAED,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,CAAC;AACF,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/securityHeaders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var f=Object.defineProperty;var
|
|
1
|
+
var f=Object.defineProperty;var r=(e,t)=>f(e,"name",{value:t,configurable:!0});const i={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"same-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=(), payment=(), usb=()","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Resource-Policy":"same-origin","Cross-Origin-Embedder-Policy":"require-corp","Origin-Agent-Cluster":"?1"},o="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests",c="max-age=31536000; includeSubDomains";function a(e,t){for(const[u,l]of Object.entries(i))e.header(u,l);(e.res.headers.get("content-type")??"").includes("text/html")&&e.header("Content-Security-Policy",o);let n;try{n=new URL(e.req.url).pathname}catch{}n!==void 0&&t(n)&&e.header("Cache-Control","no-store");try{new URL(e.req.url).protocol==="https:"&&e.header("Strict-Transport-Security",c)}catch{}}r(a,"applySecurityHeaders");function h(e){return async(t,s)=>{await s();try{a(t,e)}catch{}}}r(h,"securityHeaders");function m(...e){if(e.length===0)return()=>!1;const t=e.map(s=>s.endsWith("/")?s:`${s}/`);return s=>t.some(n=>s.startsWith(n))}r(m,"sensitivePaths");function p(e){if(typeof e=="function")return e;if(e instanceof RegExp)return t=>new RegExp(e.source,e.flags.replaceAll(/[gy]/g,"")).test(t);if(e.endsWith("/*")){const t=e.slice(0,-1);return s=>s.startsWith(t)||s===t.slice(0,-1)}return e.endsWith("/")?t=>t.startsWith(e):t=>t===e||t===`${e}/`}r(p,"matcherFor");function d(...e){const t=e.map(s=>p(s));return s=>t.some(n=>n(s))}r(d,"sensitivePathMatcher");export{o as CONTENT_SECURITY_POLICY,i as SECURITY_HEADERS,c as STRICT_TRANSPORT_SECURITY,a as applySecurityHeaders,h as securityHeaders,d as sensitivePathMatcher,m as sensitivePaths};
|
|
@@ -1,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 SensitivePath = string | RegExp | ((pathname: string) => boolean);\n\nfunction matcherFor(entry: SensitivePath): (pathname: string) => boolean {\n if (typeof entry === 'function') return entry;\n if (entry instanceof RegExp) {\n // `test` on a global/sticky regex is stateful (`lastIndex`); a fresh clone per call keeps it pure.\n return (pathname) => new RegExp(entry.source, entry.flags.replaceAll(/[gy]/g, '')).test(pathname);\n }\n if (entry.endsWith('/*')) {\n const prefix = entry.slice(0, -1);\n return (pathname) => pathname.startsWith(prefix) || pathname === prefix.slice(0, -1);\n }\n if (entry.endsWith('/')) return (pathname) => pathname.startsWith(entry);\n return (pathname) => pathname === entry || pathname === `${entry}/`;\n}\n\n/**\n * Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).\n * Empty means nothing is private, and says so rather than guessing.\n */\nfunction sensitivePathMatcher(...entries: readonly SensitivePath[]): (pathname: string) => boolean {\n const matchers = entries.map((entry) => matcherFor(entry));\n return (pathname) => matchers.some((matches) => matches(pathname));\n}\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n sensitivePathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n};\nexport type { HeaderContext, SensitivePath };\n"],
|
|
5
|
+
"mappings": "+E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AQT,GAAa,IAAI,OAAOS,EAAM,OAAQA,EAAM,MAAM,WAAW,QAAS,EAAE,CAAC,EAAE,KAAKT,CAAQ,EAElG,GAAIS,EAAM,SAAS,IAAI,EAAG,CACxB,MAAMF,EAASE,EAAM,MAAM,EAAG,EAAE,EAChC,OAAQT,GAAaA,EAAS,WAAWO,CAAM,GAAKP,IAAaO,EAAO,MAAM,EAAG,EAAE,CACrF,CACA,OAAIE,EAAM,SAAS,GAAG,EAAWT,GAAaA,EAAS,WAAWS,CAAK,EAC/DT,GAAaA,IAAaS,GAAST,IAAa,GAAGS,CAAK,GAClE,CAZSR,EAAAO,EAAA,cAkBT,SAASE,KAAwBC,EAAiC,CAChE,MAAMC,EAAWD,EAAQ,IAAKF,GAAUD,EAAWC,CAAK,CAAC,EACzD,OAAQT,GAAaY,EAAS,KAAMC,GAAYA,EAAQb,CAAQ,CAAC,CACnE,CAHSC,EAAAS,EAAA",
|
|
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.15.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/errors": "1.
|
|
39
|
-
"@rexezuge/shared": "1.
|
|
37
|
+
"@rexezuge/contracts": "1.15.0",
|
|
38
|
+
"@rexezuge/errors": "1.15.0",
|
|
39
|
+
"@rexezuge/shared": "1.15.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"chanfana": "^3.4.0",
|