@rexezuge/http 1.15.0 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -0
- package/dist/hono/createApiApp.d.ts +11 -2
- 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/hardening.d.ts +44 -6
- package/dist/hono/hardening.d.ts.map +1 -1
- package/dist/hono/hardening.js +1 -1
- package/dist/hono/hardening.js.map +3 -3
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.d.ts.map +1 -1
- package/dist/hono/index.js.map +1 -1
- package/dist/hono/rateLimits.d.ts +6 -0
- package/dist/hono/rateLimits.d.ts.map +1 -1
- package/dist/hono/rateLimits.js +1 -1
- package/dist/hono/rateLimits.js.map +3 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/securityHeaders.d.ts +8 -4
- package/dist/securityHeaders.d.ts.map +1 -1
- package/dist/securityHeaders.js +1 -1
- package/dist/securityHeaders.js.map +2 -2
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -241,6 +241,7 @@ createApiApp<Env>({
|
|
|
241
241
|
| You want | Door |
|
|
242
242
|
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
243
243
|
| Your own routes | `routes(app)`, or register on the returned app; `FamilyRoute.handleRequest` |
|
|
244
|
+
| Custom verbs (PROPFIND, MKCOL, LOCK, …) | `routes(app, { hono })`: raw Hono routes at the same slot (see below) |
|
|
244
245
|
| Routes from a shared contract | `registerContract(app, contract, handlers)`; `schemaFromEndpoint` for a hand-written `FamilyRoute` |
|
|
245
246
|
| Middleware before / after authentication | `hooks.beforeAuth` / `hooks.afterAuth` (a handler, or `{ path, handler }`) |
|
|
246
247
|
| Another authenticated surface | `auth: { '/partner/*': apiKeyAuth({ verify }) }` |
|
|
@@ -248,12 +249,42 @@ createApiApp<Env>({
|
|
|
248
249
|
| Map a verified address to your account | `accessAuth({ resolveUserId })` |
|
|
249
250
|
| Extra trusted origins (Pages, custom host) | `hardening.origin.allowedOrigins` (a list, or `(env) => list`) |
|
|
250
251
|
| Uploads | `hardening.contentType.allowed: ['application/json', 'multipart/form-data']`, `hardening.maxBodyBytes` |
|
|
252
|
+
| A bigger body on one path | `hardening.maxBodyBytes: { default, paths: [{ match, maxBytes }] }` |
|
|
253
|
+
| A non-JSON plane under a guarded prefix | `hardening.contentType.exclude` / `hardening.origin.exclude` (logged at startup) |
|
|
254
|
+
| A path a rate-limit rule must not charge | `rateLimits[].exclude` |
|
|
251
255
|
| Your logger / redacting sink | `logger: (env, requestId) => createLogger(…, sink)` |
|
|
252
256
|
| A protocol dialect (Subsonic, WebDAV) | `errors.toResponse` app-wide, or `FamilyRoute.errorMapping()` per route |
|
|
253
257
|
| More context variables | the `V` type parameter |
|
|
254
258
|
| Which paths are `no-store` | `sensitivePaths: ['/generate-totp', '/user/', /^\/export\//, (path) => …]` (see below) |
|
|
255
259
|
| Diagnose a 5xx in your own log sink | `errors.reportUnhandled(error, { status, requestId, method, route })` |
|
|
256
260
|
|
|
261
|
+
### Custom verbs, per-path limits and excludes (a WebDAV worker)
|
|
262
|
+
|
|
263
|
+
`routes(app)` gets chanfana's router, which registers one method per route and rejects `on([…], …)`. The second argument is the raw Hono instance, mounted at the same position, so every guard, limiter, auth step and the error boundary still apply (the routes are just not in the OpenAPI document). The method guard still decides which verbs exist: list the custom ones in `hardening.methods`.
|
|
264
|
+
|
|
265
|
+
Everything that loosens a guard is narrow, explicit and visible: a ceiling per path, or an `exclude` list. A matcher is the same type `sensitivePaths` takes (`string` exact, a trailing `/` or `/*` prefix, `RegExp`, predicate). There is no switch that turns a guard off. Every `hardening.*.exclude` pattern is logged once at startup (a static message listing the patterns) so the loosening shows in the logs.
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
createApiApp<Env>({
|
|
269
|
+
hardening: {
|
|
270
|
+
methods: [...DEFAULT_ALLOWED_METHODS, 'PROPFIND', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK', 'PROPPATCH', 'REPORT'],
|
|
271
|
+
// JSON everywhere is capped at 1 MiB; the DAV plane takes file bodies. The first matching rule wins.
|
|
272
|
+
maxBodyBytes: { default: 1_048_576, paths: [{ match: '/user/volumes/', maxBytes: 5 * 1024 ** 3 }] },
|
|
273
|
+
// The DAV plane carries XML and is called cross-origin; the rest of /user/* keeps both guards.
|
|
274
|
+
contentType: { exclude: [/^\/user\/volumes\/[^/]+\/[^/]+\/files\//] },
|
|
275
|
+
origin: { exclude: [/^\/user\/volumes\/[^/]+\/[^/]+\/files\//] },
|
|
276
|
+
},
|
|
277
|
+
// A rule's `path` is a Hono pattern; `exclude` carves a namespace another rule owns out of it.
|
|
278
|
+
rateLimits: [{ path: '/:owner/:volume/*', keyPrefix: 'webdav', windowMs: 60_000, max: 600, exclude: ['/user/'] }],
|
|
279
|
+
routes: (app, { hono }) => {
|
|
280
|
+
app.get('/health', (c) => c.json({ ok: true }));
|
|
281
|
+
hono.on(['PROPFIND', 'MKCOL', 'COPY', 'MOVE'], '/user/volumes/:owner/:volume/files/*', handleDav);
|
|
282
|
+
},
|
|
283
|
+
});
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
`maxBodyBytes` caps a declared `Content-Length` and a streamed (chunked) body alike, and the streamed cap replaces the request body, so a JSON body chanfana validates is capped before it is parsed.
|
|
287
|
+
|
|
257
288
|
Closed, with no flag: the slot order, the error envelope and its masking, `no-store` on every response of a sensitive path, the CSP
|
|
258
289
|
(strict everywhere, Swagger UI's directory on the docs page only), log redaction (no caught value, message or stack in a log line), `email_verified` enforcement, the origin guard on `/user/*`, the
|
|
259
290
|
`@final` route `handle()`.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { HonoOpenAPIRouterType } from 'chanfana';
|
|
2
|
+
import { Hono } from 'hono';
|
|
2
3
|
import type { MiddlewareHandler } from 'hono';
|
|
3
4
|
import { cors } from 'hono/cors';
|
|
4
5
|
import type { SensitivePath } from '../securityHeaders.ts';
|
|
@@ -78,8 +79,16 @@ interface ApiAppOptions<E extends object, V extends object = object> extends Req
|
|
|
78
79
|
docs?: DocsOptions | false;
|
|
79
80
|
/**
|
|
80
81
|
Register your routes. Runs last, after every kit slot.
|
|
82
|
+
|
|
83
|
+
The second argument carries the raw Hono instance (`{ hono }`) for what chanfana's router cannot
|
|
84
|
+
express: custom verbs (`hono.on(['PROPFIND', 'MKCOL'], '/dav/*', handler)`), `all`, sub-app mounts. A
|
|
85
|
+
route on it sits at the same position, after every guard, limiter and auth step, and inside the
|
|
86
|
+
same error boundary. It is not in the OpenAPI document.
|
|
81
87
|
*/
|
|
82
|
-
routes?: (app: ApiApp<E, V>) => void;
|
|
88
|
+
routes?: (app: ApiApp<E, V>, raw: RawRoutes<E, V>) => void;
|
|
89
|
+
}
|
|
90
|
+
interface RawRoutes<E extends object, V extends object = object> {
|
|
91
|
+
hono: Hono<FamilyEnv<E, V>>;
|
|
83
92
|
}
|
|
84
93
|
type AppHook<E extends object, V extends object> = MiddlewareHandler<FamilyEnv<E, V>> | {
|
|
85
94
|
path: string;
|
|
@@ -96,5 +105,5 @@ declare const ERROR_OPTIONS_KEY = "errorMapperOptions";
|
|
|
96
105
|
*/
|
|
97
106
|
declare function createApiApp<E extends object, V extends object = object>(options?: ApiAppOptions<E, V>): ApiApp<E, V>;
|
|
98
107
|
export { createApiApp, ERROR_OPTIONS_KEY };
|
|
99
|
-
export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };
|
|
108
|
+
export type { ApiApp, ApiAppOptions, AppHook, RawRoutes, CorsOptions, DocsOptions };
|
|
100
109
|
//# sourceMappingURL=createApiApp.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createApiApp.d.ts","sourceRoot":"","sources":["../../src/hono/createApiAp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IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;CAC7B;AAED,KAAK,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,IAC7C,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;CAAE,CAAC;AAErG;;EAEE;AACF,QAAA,MAAM,iBAAiB,uBAAuB,CAAC;AA2E/C;;;;GAIG;AACH,iBAAS,YAAY,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,OAAO,GAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAM,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAmBlH;AAED,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC3C,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var a=(e,r)=>m(e,"name",{value:r,configurable:!0});import{fromHono as h}from"chanfana";import{Hono as g}from"hono";import{cors as y}from"hono/cors";import{securityHeaders as T,sensitivePathMatcher as _}from"../securityHeaders.js";import{d1Bookmarks as x}from"./bookmarks.js";import{DOCS_CONTENT_SECURITY_POLICY as E,isDocsPath as O}from"./docs.js";import{createErrorHandler as P,createNotFoundHandler as k}from"./errorHandler.js";import{bodyLimitGuard as H,contentTypeGuard as R,describeMatchers as c,methodGuard as w,originGuard as A,unlessExcluded as i}from"./hardening.js";import{rateLimitRule as l}from"./rateLimits.js";import{consoleLogger as C,requestContext as L}from"./requestContext.js";const d="errorMapperOptions",N=["/user/*"],S=["/user/*","/api/*"];function f(e,r){for(const n of r??[])typeof n=="function"?e.use("*",n):e.use(n.path,n.handler)}a(f,"mountHooks");function G(e){return e===!1?{docs_url:null,openapi_url:null,redoc_url:null,raiseOnError:!0}:{docs_url:e?.url??"/docs",openapi_url:e?.openapiUrl??"/openapi.json",redoc_url:null,raiseOnError:!0,...e?.info&&{schema:{info:e.info}}}}a(G,"routerOptions");function I(e){const r=C("startup"),n=e.contentType?.exclude??[],u=e.origin?.exclude??[];n.length>0&&r.warn(`hardening.contentType.exclude: the content-type guard skips ${c(n)}`),u.length>0&&r.warn(`hardening.origin.exclude: the origin guard skips ${c(u)}`)}a(I,"logExcludedGuardPaths");function U(e,r){e.use("*",L(r)),e.use("*",async(t,o)=>{t.set(d,r.errors??{}),await o()});const n=T(_(...r.sensitivePaths??["/user/","/api/"])),u=r.docs===!1?null:r.docs?.url??"/docs";if(e.use("*",async(t,o)=>{await n(t,o),u!==null&&O(t.req.path,u)&&(t.res.headers.get("content-type")??"").includes("text/html")&&t.header("Content-Security-Policy",E)}),r.cors){const t=[...new Set([...r.cors.exposeHeaders??[],"X-Request-Id"])];e.use("*",y({...r.cors,exposeHeaders:t}))}const s=r.hardening??{};e.use("*",w(s.methods)),e.use("*",H(s.maxBodyBytes));for(const t of s.contentType?.paths??S)e.use(t,i(R(s.contentType?.allowed),s.contentType?.exclude));for(const t of s.origin?.paths??N)e.use(t,i(A(s.origin),s.origin?.exclude));if(I(s),r.d1)for(const t of r.d1.paths??["*"])e.use(t,x(r.d1))}a(U,"mountPlatform");function b(e={}){const r=new g;r.onError(P(e.errors)),r.notFound(k()),U(r,e);const n=e.rateLimits??[],u=n.filter(o=>o.key==="ip"),s=n.filter(o=>o.key!=="ip");for(const o of u)r.use(o.path,l(o));f(r,e.hooks?.beforeAuth);for(const[o,p]of Object.entries(e.auth??{}))r.use(o,p);for(const o of s)r.use(o.path,l(o));f(r,e.hooks?.afterAuth);const t=h(r,G(e.docs));return e.routes?.(t,{hono:r}),t}a(b,"createApiApp");export{d as ERROR_OPTIONS_KEY,b as createApiApp};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/createApiApp.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `createApiApp` — the family API worker's Hono + chanfana app, pre-wired.\n *\n * Every family worker hand-assembled the same stack in its constructor, and each\n * assembly had its own ordering bug: a limiter installed before auth (per-IP\n * buckets for an office NAT), security headers registered after a middleware\n * that returns early (no headers on the 401), no `onError` (a text 500 the SPA\n * cannot parse), a D1 session opened by mutating the shared `env`. The order is\n * the kit's now, and it is **closed**:\n *\n * | # | Slot | Why here |\n * | -- | ----------------------- | ---------------------------------------------------------------- |\n * | 1 | request id + logger | everything after can log and correlate |\n * | 2 | security headers | wraps the rest, so a 401/404/500 leaves with them |\n * | 3 | CORS (option) | a preflight answers before any guard or auth |\n * | 4 | hardening | method, body size, JSON content type, origin guard: cheap, no I/O |\n * | 5 | D1 bookmarks (option) | auth's account lookup already reads through the session |\n * | 6 | `ip` rate limits | throttle before the auth step spends D1 on an anonymous caller |\n * | 7 | `beforeAuth` hooks | your middleware that must see the request unauthenticated |\n * | 8 | auth surfaces | `accessAuth` on `/user/*`, `apiKeyAuth` on `/api/*`, … |\n * | 9 | `identity` rate limits | keyed on the account, which only exists after 8 |\n * | 10 | `afterAuth` hooks | your middleware that needs the account (request scope, audit) |\n * | 11 | `routes(app)` | your routes |\n *\n * plus `onError` (the kit mapper → `{Exception:{Type,Message}}`), `notFound` (the\n * same envelope) and `/docs` + `/openapi.json` (option).\n */\nimport { fromHono } from 'chanfana';\nimport type { HonoOpenAPIRouterType, RouterOptions } from 'chanfana';\nimport { Hono } from 'hono';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\nimport { securityHeaders, sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { SensitivePath } from '../securityHeaders.ts';\nimport { d1Bookmarks } from './bookmarks.ts';\nimport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath } from './docs.ts';\nimport type { D1BookmarkOptions } from './bookmarks.ts';\nimport { createErrorHandler, createNotFoundHandler } from './errorHandler.ts';\nimport type { ErrorBoundaryOptions } from './errorHandler.ts';\nimport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`, on **every** response for them: success, the IP\n * rate limiter's 429, the error envelope and a 404. Applied in the kit's own early middleware, which no hook\n * can bypass. Defaults to `['/user/', '/api/']`: both surfaces carry credentials or account data.\n *\n * Entries are `string | RegExp | ((path: string) => boolean)`. A string is an **exact** path (`'/generate-totp'`),\n * unless it ends in `/` or `/*`, which makes it a **prefix** (`'/user/'`, `'/user/*'`). Strings ending in `/`\n * were prefixes before exact matching existed and stay so; a bare `'/user'` is now the exact path, not\n * `/user/*`.\n */\n sensitivePaths?: readonly SensitivePath[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`) and `reportUnhandled`, the sink that receives the raw error of a 5xx.\n */\n errors?: ErrorBoundaryOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n */\n routes?: (app: ApiApp<E, V>) => void;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n const headers = securityHeaders(sensitivePathMatcher(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler;\n const docsUrl = options.docs === false ? null : (options.docs?.url ?? '/docs');\n hono.use('*', async (c, next) => {\n await headers(c, next);\n // Closed: the docs page (and only it) gets the policy that admits the\n // Swagger UI assets. Every other HTML response keeps the strict one.\n if (docsUrl !== null && isDocsPath(c.req.path, docsUrl) && (c.res.headers.get('content-type') ?? '').includes('text/html')) {\n c.header('Content-Security-Policy', DOCS_CONTENT_SECURITY_POLICY);\n }\n });\n if (options.cors) {\n const exposeHeaders = [...new Set([...(options.cors.exposeHeaders ?? []), 'X-Request-Id'])];\n hono.use('*', cors({ ...options.cors, exposeHeaders }));\n }\n\n const hardening = options.hardening ?? {};\n hono.use('*', methodGuard(hardening.methods));\n hono.use('*', bodyLimitGuard(hardening.maxBodyBytes));\n for (const path of hardening.contentType?.paths ?? DEFAULT_CONTENT_TYPE_PATHS) {\n hono.use(path, contentTypeGuard(hardening.contentType?.allowed));\n }\n for (const path of hardening.origin?.paths ?? DEFAULT_ORIGIN_PATHS) {\n hono.use(path, originGuard<E>(hardening.origin));\n }\n\n if (options.d1) {\n for (const path of options.d1.paths ?? ['*']) hono.use(path, d1Bookmarks<E>(options.d1));\n }\n}\n\n/**\n * Build the app. The returned value is the chanfana router: register routes on\n * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's\n * `onRequest`.\n */\nfunction createApiApp<E extends object, V extends object = object>(options: ApiAppOptions<E, V> = {}): ApiApp<E, V> {\n const hono = new Hono<FamilyEnv<E, V>>();\n hono.onError(createErrorHandler(options.errors));\n hono.notFound(createNotFoundHandler());\n\n mountPlatform(hono, options);\n\n const rules = options.rateLimits ?? [];\n const ipRules = rules.filter((entry) => entry.key === 'ip');\n const identityRules = rules.filter((entry) => entry.key !== 'ip');\n for (const rule of ipRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.beforeAuth);\n for (const [path, middleware] of Object.entries(options.auth ?? {})) hono.use(path, middleware);\n for (const rule of identityRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.afterAuth);\n\n const app = fromHono(hono, routerOptions(options.docs)) as ApiApp<E, V>;\n options.routes?.(app);\n return app;\n}\n\nexport { createApiApp, ERROR_OPTIONS_KEY };\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions };\n"],
|
|
5
|
-
"mappings": "+EA2BA,OAAS,YAAAA,MAAgB,WAEzB,OAAS,QAAAC,MAAY,OAErB,OAAS,QAAAC,MAAY,YACrB,OAAS,mBAAAC,EAAiB,wBAAAC,MAA4B,wBAEtD,OAAS,eAAAC,MAAmB,iBAC5B,OAAS,gCAAAC,EAA8B,cAAAC,MAAkB,YAEzD,OAAS,sBAAAC,EAAoB,yBAAAC,MAA6B,oBAE1D,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,
|
|
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", "
|
|
4
|
+
"sourcesContent": ["/**\n * `createApiApp` — the family API worker's Hono + chanfana app, pre-wired.\n *\n * Every family worker hand-assembled the same stack in its constructor, and each\n * assembly had its own ordering bug: a limiter installed before auth (per-IP\n * buckets for an office NAT), security headers registered after a middleware\n * that returns early (no headers on the 401), no `onError` (a text 500 the SPA\n * cannot parse), a D1 session opened by mutating the shared `env`. The order is\n * the kit's now, and it is **closed**:\n *\n * | # | Slot | Why here |\n * | -- | ----------------------- | ---------------------------------------------------------------- |\n * | 1 | request id + logger | everything after can log and correlate |\n * | 2 | security headers | wraps the rest, so a 401/404/500 leaves with them |\n * | 3 | CORS (option) | a preflight answers before any guard or auth |\n * | 4 | hardening | method, body size, JSON content type, origin guard: cheap, no I/O |\n * | 5 | D1 bookmarks (option) | auth's account lookup already reads through the session |\n * | 6 | `ip` rate limits | throttle before the auth step spends D1 on an anonymous caller |\n * | 7 | `beforeAuth` hooks | your middleware that must see the request unauthenticated |\n * | 8 | auth surfaces | `accessAuth` on `/user/*`, `apiKeyAuth` on `/api/*`, … |\n * | 9 | `identity` rate limits | keyed on the account, which only exists after 8 |\n * | 10 | `afterAuth` hooks | your middleware that needs the account (request scope, audit) |\n * | 11 | `routes(app)` | your routes |\n *\n * plus `onError` (the kit mapper → `{Exception:{Type,Message}}`), `notFound` (the\n * same envelope) and `/docs` + `/openapi.json` (option).\n */\nimport { fromHono } from 'chanfana';\nimport type { HonoOpenAPIRouterType, RouterOptions } from 'chanfana';\nimport { Hono } from 'hono';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\nimport { securityHeaders, sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { SensitivePath } from '../securityHeaders.ts';\nimport { d1Bookmarks } from './bookmarks.ts';\nimport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath } from './docs.ts';\nimport type { D1BookmarkOptions } from './bookmarks.ts';\nimport { createErrorHandler, createNotFoundHandler } from './errorHandler.ts';\nimport type { ErrorBoundaryOptions } from './errorHandler.ts';\nimport { bodyLimitGuard, contentTypeGuard, describeMatchers, methodGuard, originGuard, unlessExcluded } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { consoleLogger, requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`, on **every** response for them: success, the IP\n * rate limiter's 429, the error envelope and a 404. Applied in the kit's own early middleware, which no hook\n * can bypass. Defaults to `['/user/', '/api/']`: both surfaces carry credentials or account data.\n *\n * Entries are `string | RegExp | ((path: string) => boolean)`. A string is an **exact** path (`'/generate-totp'`),\n * unless it ends in `/` or `/*`, which makes it a **prefix** (`'/user/'`, `'/user/*'`). Strings ending in `/`\n * were prefixes before exact matching existed and stay so; a bare `'/user'` is now the exact path, not\n * `/user/*`.\n */\n sensitivePaths?: readonly SensitivePath[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`) and `reportUnhandled`, the sink that receives the raw error of a 5xx.\n */\n errors?: ErrorBoundaryOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n\n The second argument carries the raw Hono instance (`{ hono }`) for what chanfana's router cannot\n express: custom verbs (`hono.on(['PROPFIND', 'MKCOL'], '/dav/*', handler)`), `all`, sub-app mounts. A\n route on it sits at the same position, after every guard, limiter and auth step, and inside the\n same error boundary. It is not in the OpenAPI document.\n */\n routes?: (app: ApiApp<E, V>, raw: RawRoutes<E, V>) => void;\n}\n\ninterface RawRoutes<E extends object, V extends object = object> {\n hono: Hono<FamilyEnv<E, V>>;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * A guard's `exclude` is a loosening, so it is announced: once per app, as a static message listing the\n * configured patterns (never a request value).\n */\nfunction logExcludedGuardPaths(hardening: HardeningOptions<never>): void {\n const logger = consoleLogger('startup');\n const contentType = hardening.contentType?.exclude ?? [];\n const origin = hardening.origin?.exclude ?? [];\n if (contentType.length > 0) logger.warn(`hardening.contentType.exclude: the content-type guard skips ${describeMatchers(contentType)}`);\n if (origin.length > 0) logger.warn(`hardening.origin.exclude: the origin guard skips ${describeMatchers(origin)}`);\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n const headers = securityHeaders(sensitivePathMatcher(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler;\n const docsUrl = options.docs === false ? null : (options.docs?.url ?? '/docs');\n hono.use('*', async (c, next) => {\n await headers(c, next);\n // Closed: the docs page (and only it) gets the policy that admits the\n // Swagger UI assets. Every other HTML response keeps the strict one.\n if (docsUrl !== null && isDocsPath(c.req.path, docsUrl) && (c.res.headers.get('content-type') ?? '').includes('text/html')) {\n c.header('Content-Security-Policy', DOCS_CONTENT_SECURITY_POLICY);\n }\n });\n if (options.cors) {\n const exposeHeaders = [...new Set([...(options.cors.exposeHeaders ?? []), 'X-Request-Id'])];\n hono.use('*', cors({ ...options.cors, exposeHeaders }));\n }\n\n const hardening = options.hardening ?? {};\n hono.use('*', methodGuard(hardening.methods));\n hono.use('*', bodyLimitGuard(hardening.maxBodyBytes));\n for (const path of hardening.contentType?.paths ?? DEFAULT_CONTENT_TYPE_PATHS) {\n hono.use(path, unlessExcluded(contentTypeGuard(hardening.contentType?.allowed), hardening.contentType?.exclude));\n }\n for (const path of hardening.origin?.paths ?? DEFAULT_ORIGIN_PATHS) {\n hono.use(path, unlessExcluded(originGuard<E>(hardening.origin), hardening.origin?.exclude));\n }\n logExcludedGuardPaths(hardening);\n\n if (options.d1) {\n for (const path of options.d1.paths ?? ['*']) hono.use(path, d1Bookmarks<E>(options.d1));\n }\n}\n\n/**\n * Build the app. The returned value is the chanfana router: register routes on\n * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's\n * `onRequest`.\n */\nfunction createApiApp<E extends object, V extends object = object>(options: ApiAppOptions<E, V> = {}): ApiApp<E, V> {\n const hono = new Hono<FamilyEnv<E, V>>();\n hono.onError(createErrorHandler(options.errors));\n hono.notFound(createNotFoundHandler());\n\n mountPlatform(hono, options);\n\n const rules = options.rateLimits ?? [];\n const ipRules = rules.filter((entry) => entry.key === 'ip');\n const identityRules = rules.filter((entry) => entry.key !== 'ip');\n for (const rule of ipRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.beforeAuth);\n for (const [path, middleware] of Object.entries(options.auth ?? {})) hono.use(path, middleware);\n for (const rule of identityRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.afterAuth);\n\n const app = fromHono(hono, routerOptions(options.docs)) as ApiApp<E, V>;\n options.routes?.(app, { hono });\n return app;\n}\n\nexport { createApiApp, ERROR_OPTIONS_KEY };\nexport type { ApiApp, ApiAppOptions, AppHook, RawRoutes, CorsOptions, DocsOptions };\n"],
|
|
5
|
+
"mappings": "+EA2BA,OAAS,YAAAA,MAAgB,WAEzB,OAAS,QAAAC,MAAY,OAErB,OAAS,QAAAC,MAAY,YACrB,OAAS,mBAAAC,EAAiB,wBAAAC,MAA4B,wBAEtD,OAAS,eAAAC,MAAmB,iBAC5B,OAAS,gCAAAC,EAA8B,cAAAC,MAAkB,YAEzD,OAAS,sBAAAC,EAAoB,yBAAAC,MAA6B,oBAE1D,OAAS,kBAAAC,EAAgB,oBAAAC,EA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,EAAAQ,EAAA,iBA0CT,SAASQ,EAA0DP,EAA+B,CAAA,EAAE,CAClG,MAAMZ,EAAO,IAAItB,EACjBsB,EAAK,QAAQf,EAAmB2B,EAAQ,MAAM,CAAC,EAC/CZ,EAAK,SAASd,EAAqB,CAAE,EAErCyB,EAAcX,EAAMY,CAAO,EAE3B,MAAMQ,EAAQR,EAAQ,YAAc,CAAA,EAC9BS,EAAUD,EAAM,OAAQE,GAAUA,EAAM,MAAQ,IAAI,EACpDC,EAAgBH,EAAM,OAAQE,GAAUA,EAAM,MAAQ,IAAI,EAChE,UAAWE,KAAQH,EAASrB,EAAK,IAAIwB,EAAK,KAAM/B,EAAiB+B,CAAI,CAAC,EACtEzB,EAAWC,EAAMY,EAAQ,OAAO,UAAU,EAC1C,SAAW,CAACM,EAAMO,CAAU,IAAK,OAAO,QAAQb,EAAQ,MAAQ,CAAA,CAAE,EAAGZ,EAAK,IAAIkB,EAAMO,CAAU,EAC9F,UAAWD,KAAQD,EAAevB,EAAK,IAAIwB,EAAK,KAAM/B,EAAiB+B,CAAI,CAAC,EAC5EzB,EAAWC,EAAMY,EAAQ,OAAO,SAAS,EAEzC,MAAMc,EAAMjD,EAASuB,EAAMI,EAAcQ,EAAQ,IAAI,CAAC,EACtD,OAAAA,EAAQ,SAASc,EAAK,CAAE,KAAA1B,CAAI,CAAE,EACvB0B,CACT,CAnBSvB,EAAAgB,EAAA",
|
|
6
|
+
"names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePathMatcher", "d1Bookmarks", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "createErrorHandler", "createNotFoundHandler", "bodyLimitGuard", "contentTypeGuard", "describeMatchers", "methodGuard", "originGuard", "unlessExcluded", "rateLimitRule", "consoleLogger", "requestContext", "ERROR_OPTIONS_KEY", "DEFAULT_ORIGIN_PATHS", "DEFAULT_CONTENT_TYPE_PATHS", "mountHooks", "hono", "hooks", "hook", "__name", "routerOptions", "docs", "logExcludedGuardPaths", "hardening", "logger", "contentType", "origin", "mountPlatform", "options", "c", "next", "headers", "docsUrl", "exposeHeaders", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
|
|
7
7
|
}
|
package/dist/hono/hardening.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
import type { PathMatcher } from '../securityHeaders.ts';
|
|
2
3
|
import type { FromEnv } from './types.ts';
|
|
3
4
|
interface OriginPolicy<E> {
|
|
4
5
|
/**
|
|
@@ -13,6 +14,12 @@ interface OriginPolicy<E> {
|
|
|
13
14
|
Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.
|
|
14
15
|
*/
|
|
15
16
|
allowMissingOrigin?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Paths **inside** `paths` that skip this guard (a session-authenticated surface that cross-origin
|
|
19
|
+
* clients legitimately call). Same matcher semantics as `sensitivePaths`. The patterns are logged
|
|
20
|
+
* once at startup so the loosening is visible. There is deliberately no way to switch the guard off.
|
|
21
|
+
*/
|
|
22
|
+
exclude?: readonly PathMatcher[];
|
|
16
23
|
}
|
|
17
24
|
interface ContentTypePolicy {
|
|
18
25
|
/**
|
|
@@ -23,6 +30,23 @@ interface ContentTypePolicy {
|
|
|
23
30
|
The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.
|
|
24
31
|
*/
|
|
25
32
|
allowed?: readonly string[];
|
|
33
|
+
/**
|
|
34
|
+
* Paths **inside** `paths` that skip this guard (an XML or binary plane under a JSON prefix). Same
|
|
35
|
+
* matcher semantics as `sensitivePaths`. The patterns are logged once at startup so the loosening is
|
|
36
|
+
* visible. There is deliberately no way to switch the guard off.
|
|
37
|
+
*/
|
|
38
|
+
exclude?: readonly PathMatcher[];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Per-path body ceilings. The first rule whose `match` accepts the request path wins; `default`
|
|
42
|
+
* applies to every other path.
|
|
43
|
+
*/
|
|
44
|
+
interface BodyLimitPolicy {
|
|
45
|
+
default: number;
|
|
46
|
+
paths: ReadonlyArray<{
|
|
47
|
+
match: PathMatcher;
|
|
48
|
+
maxBytes: number;
|
|
49
|
+
}>;
|
|
26
50
|
}
|
|
27
51
|
interface HardeningOptions<E> {
|
|
28
52
|
/**
|
|
@@ -30,22 +54,36 @@ interface HardeningOptions<E> {
|
|
|
30
54
|
*/
|
|
31
55
|
methods?: readonly string[];
|
|
32
56
|
/**
|
|
33
|
-
The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB.
|
|
57
|
+
The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB. Pass `{ default, paths }` to
|
|
58
|
+
give some paths (an upload route) a different ceiling; the first matching rule wins. Every ceiling is
|
|
59
|
+
validated at construction, and the cap applies to bodies chanfana parses too.
|
|
34
60
|
*/
|
|
35
|
-
maxBodyBytes?: number;
|
|
61
|
+
maxBodyBytes?: number | BodyLimitPolicy;
|
|
36
62
|
contentType?: ContentTypePolicy;
|
|
37
63
|
origin?: OriginPolicy<E>;
|
|
38
64
|
}
|
|
39
65
|
declare function methodGuard(methods?: readonly string[]): MiddlewareHandler;
|
|
40
66
|
/**
|
|
41
67
|
* The declared-length check first (cheap, no read), then Hono's streaming cap
|
|
42
|
-
* for a chunked body that declares nothing.
|
|
68
|
+
* for a chunked body that declares nothing. The streaming cap replaces the
|
|
69
|
+
* request body, so a body chanfana parses afterwards is capped too.
|
|
70
|
+
*
|
|
71
|
+
* With a `{ default, paths }` policy the ceiling is chosen per request path.
|
|
72
|
+
*/
|
|
73
|
+
declare function bodyLimitGuard(limit?: number | BodyLimitPolicy): MiddlewareHandler;
|
|
74
|
+
/**
|
|
75
|
+
* Skip `guard` on the paths `exclude` matches. Used for the guards' `exclude` option; the guard itself
|
|
76
|
+
* stays unconditional everywhere else.
|
|
43
77
|
*/
|
|
44
|
-
declare function
|
|
78
|
+
declare function unlessExcluded(guard: MiddlewareHandler, exclude: readonly PathMatcher[] | undefined): MiddlewareHandler;
|
|
79
|
+
/**
|
|
80
|
+
A static, loggable form of a matcher: strings and regexes as written, a predicate as a placeholder.
|
|
81
|
+
*/
|
|
82
|
+
declare function describeMatchers(entries: readonly PathMatcher[]): string;
|
|
45
83
|
declare function contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler;
|
|
46
84
|
declare function originGuard<E extends object>(policy?: OriginPolicy<E>): MiddlewareHandler<{
|
|
47
85
|
Bindings: E;
|
|
48
86
|
}>;
|
|
49
|
-
export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard };
|
|
50
|
-
export type { ContentTypePolicy, HardeningOptions, OriginPolicy };
|
|
87
|
+
export { bodyLimitGuard, contentTypeGuard, describeMatchers, methodGuard, originGuard, unlessExcluded };
|
|
88
|
+
export type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy };
|
|
51
89
|
//# sourceMappingURL=hardening.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hardening.d.ts","sourceRoot":"","sources":["../../src/hono/hardening.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAW9C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,UAAU,YAAY,CAAC,CAAC;IACtB;;MAEE;IACF,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B;;MAEE;IACF,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IAC/C;;MAEE;IACF,kBAAkB,CAAC,EAAE,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"hardening.d.ts","sourceRoot":"","sources":["../../src/hono/hardening.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAW9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,KAAK,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SAAS,WAAW,EAAE,GAAG,SAAS,GAAG,iBAAiB,CAIhH;AAED;;EAEE;AACF,iBAAS,gBAAgB,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,GAAG,MAAM,CAEjE;AAED,iBAAS,gBAAgB,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,iBAAiB,CAMxE;AAED,iBAAS,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,GAAE,YAAY,CAAC,CAAC,CAAM,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAOvG;AAED,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,CAAC;AACxG,YAAY,EAAE,eAAe,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,CAAC"}
|
package/dist/hono/hardening.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var u=Object.defineProperty;var i=(r,n)=>u(r,"name",{value:n,configurable:!0});import{bodyLimit as f}from"hono/body-limit";import{PayloadTooLargeError as d}from"@rexezuge/errors";import{checkContentLength as h,checkContentType as m,checkMethod as w,checkOrigin as g,DEFAULT_ALLOWED_METHODS as p,DEFAULT_MAX_BODY_BYTES as l}from"../requestGuards.js";import{sensitivePathMatcher as c}from"../securityHeaders.js";import{resolveFromEnv as y}from"./types.js";function E(r=p){return async(n,t)=>{const e=w(n.req.method,r);if(e)throw e;await t()}}i(E,"methodGuard");function O(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Invalid maxBodyBytes: ${String(r)} (must be a positive integer)`)}i(O,"assertMaxBytes");function a(r){O(r);const n=f({maxSize:r,onError:i(()=>{throw new d},"onError")});return async(t,e)=>{const o=h(t.req.raw,r);if(o)throw o;return n(t,e)}}i(a,"capGuard");function L(r=l){if(typeof r=="number")return a(r);const n=a(r.default),t=r.paths.map(e=>({matches:c(e.match),guard:a(e.maxBytes)}));return async(e,o)=>(t.find(s=>s.matches(e.req.path))?.guard??n)(e,o)}i(L,"bodyLimitGuard");function M(r,n){if(n===void 0||n.length===0)return r;const t=c(...n);return async(e,o)=>t(e.req.path)?o():r(e,o)}i(M,"unlessExcluded");function b(r){return r.map(n=>typeof n=="function"?"[predicate]":String(n)).join(", ")}i(b,"describeMatchers");function T(r){return async(n,t)=>{const e=m(n.req.raw,r);if(e)throw e;await t()}}i(T,"contentTypeGuard");function q(r={}){return async(n,t)=>{const e=r.allowedOrigins===void 0?[]:y(r.allowedOrigins,n.env),o=g(n.req.raw,{allowedOrigins:e,allowMissingOrigin:r.allowMissingOrigin});if(o)throw o;await t()}}i(q,"originGuard");export{L as bodyLimitGuard,T as contentTypeGuard,b as describeMatchers,E as methodGuard,q as originGuard,M as unlessExcluded};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/hardening.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The request-hardening middleware: the Hono form of `../requestGuards.ts`.\n *\n * Converged from `apps/api/src/middleware/HttpHardening.ts` (Mail-Bee, Mail-Meow,\n * Mail-Otter, Pigeongram), AWS-AccessBridge's `RequestGuards.ts`, Image-Host's\n * `csrfProtectionHandler` and Pigeongram's `session/origin.ts`. Each guard\n * **throws** its `ServiceError` rather than answering, so the rejection reaches\n * `app.onError` and leaves in the same envelope (and with the same security\n * headers and request id) as every other failure.\n */\nimport { bodyLimit } from 'hono/body-limit';\nimport type { MiddlewareHandler } from 'hono';\nimport { PayloadTooLargeError } from '@rexezuge/errors';\nimport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from '../requestGuards.ts';\nimport { resolveFromEnv } from './types.ts';\nimport type { FromEnv } from './types.ts';\n\ninterface OriginPolicy<E> {\n /**\n The cookie-authenticated surfaces to guard. Defaults to `['/user/*']`.\n */\n paths?: readonly string[];\n /**\n Origins trusted besides the request's own (a Pages origin, a custom domain).\n */\n allowedOrigins?: FromEnv<E, readonly string[]>;\n /**\n Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.\n */\n allowMissingOrigin?: boolean;\n}\n\ninterface ContentTypePolicy {\n /**\n Where JSON mutations are enforced. Defaults to `['/user/*', '/api/*']`.\n */\n paths?: readonly string[];\n /**\n The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.\n */\n allowed?: readonly string[];\n}\n\ninterface HardeningOptions<E> {\n /**\n The methods the app answers. Defaults to {@link DEFAULT_ALLOWED_METHODS}.\n */\n methods?: readonly string[];\n /**\n The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB.\n */\n maxBodyBytes?: number;\n contentType?: ContentTypePolicy;\n origin?: OriginPolicy<E>;\n}\n\nfunction methodGuard(methods: readonly string[] = DEFAULT_ALLOWED_METHODS): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkMethod(c.req.method, methods);\n if (rejection) throw rejection;\n await next();\n };\n}\n\
|
|
5
|
-
"mappings": "+EAUA,OAAS,aAAAA,MAAiB,kBAE1B,OAAS,wBAAAC,MAA4B,mBACrC,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,sBACP,OAAS,kBAAAC,MAAsB,
|
|
6
|
-
"names": ["bodyLimit", "PayloadTooLargeError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "resolveFromEnv", "methodGuard", "methods", "c", "next", "rejection", "__name", "
|
|
4
|
+
"sourcesContent": ["/**\n * The request-hardening middleware: the Hono form of `../requestGuards.ts`.\n *\n * Converged from `apps/api/src/middleware/HttpHardening.ts` (Mail-Bee, Mail-Meow,\n * Mail-Otter, Pigeongram), AWS-AccessBridge's `RequestGuards.ts`, Image-Host's\n * `csrfProtectionHandler` and Pigeongram's `session/origin.ts`. Each guard\n * **throws** its `ServiceError` rather than answering, so the rejection reaches\n * `app.onError` and leaves in the same envelope (and with the same security\n * headers and request id) as every other failure.\n */\nimport { bodyLimit } from 'hono/body-limit';\nimport type { MiddlewareHandler } from 'hono';\nimport { PayloadTooLargeError } from '@rexezuge/errors';\nimport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from '../requestGuards.ts';\nimport { sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { PathMatcher } from '../securityHeaders.ts';\nimport { resolveFromEnv } from './types.ts';\nimport type { FromEnv } from './types.ts';\n\ninterface OriginPolicy<E> {\n /**\n The cookie-authenticated surfaces to guard. Defaults to `['/user/*']`.\n */\n paths?: readonly string[];\n /**\n Origins trusted besides the request's own (a Pages origin, a custom domain).\n */\n allowedOrigins?: FromEnv<E, readonly string[]>;\n /**\n Admit a mutation carrying neither `Origin` nor `Referer`. Off by default.\n */\n allowMissingOrigin?: boolean;\n /**\n * Paths **inside** `paths` that skip this guard (a session-authenticated surface that cross-origin\n * clients legitimately call). Same matcher semantics as `sensitivePaths`. The patterns are logged\n * once at startup so the loosening is visible. There is deliberately no way to switch the guard off.\n */\n exclude?: readonly PathMatcher[];\n}\n\ninterface ContentTypePolicy {\n /**\n Where JSON mutations are enforced. Defaults to `['/user/*', '/api/*']`.\n */\n paths?: readonly string[];\n /**\n The accepted media types. Defaults to `['application/json']`; add `multipart/form-data` for uploads.\n */\n allowed?: readonly string[];\n /**\n * Paths **inside** `paths` that skip this guard (an XML or binary plane under a JSON prefix). Same\n * matcher semantics as `sensitivePaths`. The patterns are logged once at startup so the loosening is\n * visible. There is deliberately no way to switch the guard off.\n */\n exclude?: readonly PathMatcher[];\n}\n\n/**\n * Per-path body ceilings. The first rule whose `match` accepts the request path wins; `default`\n * applies to every other path.\n */\ninterface BodyLimitPolicy {\n default: number;\n paths: ReadonlyArray<{ match: PathMatcher; maxBytes: number }>;\n}\n\ninterface HardeningOptions<E> {\n /**\n The methods the app answers. Defaults to {@link DEFAULT_ALLOWED_METHODS}.\n */\n methods?: readonly string[];\n /**\n The request body ceiling in bytes, declared or streamed. Defaults to 1 MiB. Pass `{ default, paths }` to\n give some paths (an upload route) a different ceiling; the first matching rule wins. Every ceiling is\n validated at construction, and the cap applies to bodies chanfana parses too.\n */\n maxBodyBytes?: number | BodyLimitPolicy;\n contentType?: ContentTypePolicy;\n origin?: OriginPolicy<E>;\n}\n\nfunction methodGuard(methods: readonly string[] = DEFAULT_ALLOWED_METHODS): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkMethod(c.req.method, methods);\n if (rejection) throw rejection;\n await next();\n };\n}\n\nfunction assertMaxBytes(maxBytes: number): void {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new Error(`Invalid maxBodyBytes: ${String(maxBytes)} (must be a positive integer)`);\n }\n}\n\nfunction capGuard(maxBytes: number): MiddlewareHandler {\n assertMaxBytes(maxBytes);\n const streamed = bodyLimit({\n maxSize: maxBytes,\n onError: (): never => {\n throw new PayloadTooLargeError();\n },\n });\n return async (c, next): Promise<Response | void> => {\n const rejection = checkContentLength(c.req.raw, maxBytes);\n if (rejection) throw rejection;\n return streamed(c, next);\n };\n}\n\n/**\n * The declared-length check first (cheap, no read), then Hono's streaming cap\n * for a chunked body that declares nothing. The streaming cap replaces the\n * request body, so a body chanfana parses afterwards is capped too.\n *\n * With a `{ default, paths }` policy the ceiling is chosen per request path.\n */\nfunction bodyLimitGuard(limit: number | BodyLimitPolicy = DEFAULT_MAX_BODY_BYTES): MiddlewareHandler {\n if (typeof limit === 'number') return capGuard(limit);\n const fallback = capGuard(limit.default);\n const rules = limit.paths.map((rule) => ({ matches: sensitivePathMatcher(rule.match), guard: capGuard(rule.maxBytes) }));\n return async (c, next): Promise<Response | void> => {\n const rule = rules.find((entry) => entry.matches(c.req.path));\n return (rule?.guard ?? fallback)(c, next);\n };\n}\n\n/**\n * Skip `guard` on the paths `exclude` matches. Used for the guards' `exclude` option; the guard itself\n * stays unconditional everywhere else.\n */\nfunction unlessExcluded(guard: MiddlewareHandler, exclude: readonly PathMatcher[] | undefined): MiddlewareHandler {\n if (exclude === undefined || exclude.length === 0) return guard;\n const excluded = sensitivePathMatcher(...exclude);\n return async (c, next): Promise<Response | void> => (excluded(c.req.path) ? next() : guard(c, next));\n}\n\n/**\nA static, loggable form of a matcher: strings and regexes as written, a predicate as a placeholder.\n*/\nfunction describeMatchers(entries: readonly PathMatcher[]): string {\n return entries.map((entry) => (typeof entry === 'function' ? '[predicate]' : String(entry))).join(', ');\n}\n\nfunction contentTypeGuard(allowed?: readonly string[]): MiddlewareHandler {\n return async (c, next): Promise<void> => {\n const rejection = checkContentType(c.req.raw, allowed);\n if (rejection) throw rejection;\n await next();\n };\n}\n\nfunction originGuard<E extends object>(policy: OriginPolicy<E> = {}): MiddlewareHandler<{ Bindings: E }> {\n return async (c, next): Promise<void> => {\n const allowedOrigins = policy.allowedOrigins === undefined ? [] : resolveFromEnv(policy.allowedOrigins, c.env);\n const rejection = checkOrigin(c.req.raw, { allowedOrigins, allowMissingOrigin: policy.allowMissingOrigin });\n if (rejection) throw rejection;\n await next();\n };\n}\n\nexport { bodyLimitGuard, contentTypeGuard, describeMatchers, methodGuard, originGuard, unlessExcluded };\nexport type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy };\n"],
|
|
5
|
+
"mappings": "+EAUA,OAAS,aAAAA,MAAiB,kBAE1B,OAAS,wBAAAC,MAA4B,mBACrC,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,sBACP,OAAS,wBAAAC,MAA4B,wBAErC,OAAS,kBAAAC,MAAsB,aAiE/B,SAASC,EAAYC,EAA6BL,EAAuB,CACvE,MAAO,OAAOM,EAAGC,IAAuB,CACtC,M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Mf,EAAGC,CAAI,CACpG,CAJSE,EAAAW,EAAA,kBAST,SAASI,EAAiBC,EAA+B,CACvD,OAAOA,EAAQ,IAAKN,GAAW,OAAOA,GAAU,WAAa,cAAgB,OAAOA,CAAK,CAAE,EAAE,KAAK,IAAI,CACxG,CAFSV,EAAAe,EAAA,oBAIT,SAASE,EAAiBC,EAA2B,CACnD,MAAO,OAAOrB,EAAGC,IAAuB,CACtC,MAAMC,EAAYX,EAAiBS,EAAE,IAAI,IAAKqB,CAAO,EACrD,GAAInB,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CANSE,EAAAiB,EAAA,oBAQT,SAASE,EAA8BC,EAA0B,CAAA,EAAE,CACjE,MAAO,OAAOvB,EAAGC,IAAuB,CACtC,MAAMuB,EAAiBD,EAAO,iBAAmB,OAAY,CAAA,EAAK1B,EAAe0B,EAAO,eAAgBvB,EAAE,GAAG,EACvGE,EAAYT,EAAYO,EAAE,IAAI,IAAK,CAAE,eAAAwB,EAAgB,mBAAoBD,EAAO,kBAAkB,CAAE,EAC1G,GAAIrB,EAAW,MAAMA,EACrB,MAAMD,EAAI,CACZ,CACF,CAPSE,EAAAmB,EAAA",
|
|
6
|
+
"names": ["bodyLimit", "PayloadTooLargeError", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "sensitivePathMatcher", "resolveFromEnv", "methodGuard", "methods", "c", "next", "rejection", "__name", "assertMaxBytes", "maxBytes", "capGuard", "streamed", "bodyLimitGuard", "limit", "fallback", "rules", "rule", "entry", "unlessExcluded", "guard", "exclude", "excluded", "describeMatchers", "entries", "contentTypeGuard", "allowed", "originGuard", "policy", "allowedOrigins"]
|
|
7
7
|
}
|
package/dist/hono/index.d.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |
|
|
17
17
|
*/
|
|
18
18
|
export { createApiApp } from './createApiApp.ts';
|
|
19
|
-
export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';
|
|
19
|
+
export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions, RawRoutes } from './createApiApp.ts';
|
|
20
20
|
export { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';
|
|
21
21
|
export { FamilyRoute } from './FamilyRoute.ts';
|
|
22
22
|
export type { MaybePromise, RouteResult } from './FamilyRoute.ts';
|
|
@@ -25,7 +25,7 @@ export type { ContractHandlers, EndpointHandler, EndpointRoute } from './contrac
|
|
|
25
25
|
export { accessAuth, apiKeyAuth } from './auth.ts';
|
|
26
26
|
export type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';
|
|
27
27
|
export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';
|
|
28
|
-
export type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';
|
|
28
|
+
export type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';
|
|
29
29
|
export { d1Bookmarks } from './bookmarks.ts';
|
|
30
30
|
export type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';
|
|
31
31
|
export { rateLimitRule } from './rateLimits.ts';
|
package/dist/hono/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"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AE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACvF,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/hono/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';\n\nexport { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { MaybePromise, RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\nexport type { ErrorBoundaryOptions, UnhandledContext } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
|
|
4
|
+
"sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions, RawRoutes } from './createApiApp.ts';\n\nexport { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { MaybePromise, RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { BodyLimitPolicy, ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\nexport type { ErrorBoundaryOptions, UnhandledContext } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
|
|
5
5
|
"mappings": "AAiBA,OAAS,gBAAAA,MAAoB,oBAG7B,OAAS,gCAAAC,MAAoC,YAE7C,OAAS,eAAAC,MAAmB,mBAG5B,OAAS,oBAAAC,EAAkB,qBAAAC,EAAmB,sBAAAC,MAA0B,iBAGxE,OAAS,cAAAC,EAAY,cAAAC,MAAkB,YAGvC,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAG3E,OAAS,eAAAC,MAAmB,iBAG5B,OAAS,iBAAAC,MAAqB,kBAG9B,OAAS,sBAAAC,EAAoB,yBAAAC,EAAuB,oBAAAC,MAAwB,oBAG5E,OAAS,iBAAAC,EAAe,kBAAAC,EAAgB,qBAAAC,MAAyB",
|
|
6
6
|
"names": ["createApiApp", "DOCS_CONTENT_SECURITY_POLICY", "FamilyRoute", "registerContract", "routeFromEndpoint", "schemaFromEndpoint", "accessAuth", "apiKeyAuth", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "d1Bookmarks", "rateLimitRule", "createErrorHandler", "createNotFoundHandler", "respondWithError", "consoleLogger", "requestContext", "REQUEST_ID_HEADER"]
|
|
7
7
|
}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* identity and put every operator behind one NAT in a shared bucket.
|
|
15
15
|
*/
|
|
16
16
|
import type { MiddlewareHandler } from 'hono';
|
|
17
|
+
import type { PathMatcher } from '../securityHeaders.ts';
|
|
17
18
|
import type { RateLimitContext } from '../rateLimit.ts';
|
|
18
19
|
/**
|
|
19
20
|
The native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).
|
|
@@ -30,6 +31,11 @@ interface RateLimitRule<E> {
|
|
|
30
31
|
The Hono path pattern the rule guards (`'/user/*'`).
|
|
31
32
|
*/
|
|
32
33
|
path: string;
|
|
34
|
+
/**
|
|
35
|
+
* Paths inside `path` this rule does not charge (a reserved namespace another rule owns). Same matcher
|
|
36
|
+
* semantics as `sensitivePaths`; the other rules and the guards still apply to them.
|
|
37
|
+
*/
|
|
38
|
+
exclude?: readonly PathMatcher[];
|
|
33
39
|
/**
|
|
34
40
|
The bucket namespace; two rules never share one.
|
|
35
41
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rateLimits.d.ts","sourceRoot":"","sources":["../../src/hono/rateLimits.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"rateLimits.d.ts","sourceRoot":"","sources":["../../src/hono/rateLimits.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAG9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD;;EAEE;AACF,UAAU,iBAAiB;IACzB,KAAK,CAAC,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAChE;AAED,UAAU,aAAa,CAAC,CAAC;IACvB;;MAEE;IACF,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,OAAO,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;IACjC;;MAEE;IACF,SAAS,EAAE,MAAM,CAAC;IAClB;;MAEE;IACF,QAAQ,EAAE,MAAM,CAAC;IACjB;;MAEE;IACF,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,gBAAgB,KAAK,MAAM,CAAC,CAAC;IAChD;;MAEE;IACF,GAAG,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IACxB;;MAEE;IACF,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,GAAG,SAAS,CAAC;CACrD;AAMD;;;GAGG;AACH,iBAAS,aAAa,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,CAAC,CAoBnG;AAED,OAAO,EAAE,aAAa,EAAE,CAAC;AACzB,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/hono/rateLimits.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var a=(e,i)=>m(e,"name",{value:i,configurable:!0});import{clientIp as u,rateLimit as h}from"../rateLimit.js";import{sensitivePathMatcher as x}from"../securityHeaders.js";function l(e){return{Exception:{Type:"RateLimited",Message:`Too many requests. Retry after ${e}s.`}}}a(l,"throttledBody");function p(e){const i=h({windowMs:e.windowMs,max:e.max,keyPrefix:e.keyPrefix}),s=Math.max(1,Math.ceil(e.windowMs/1e3)),d=e.exclude===void 0||e.exclude.length===0?null:x(...e.exclude);return async(t,n)=>{if(d?.(t.req.path))return n();const o=e.binding?.(t.env);if(!o)return i(t,n);const c=e.key==="ip"?void 0:t.get("AuthenticatedUserEmailAddress"),f=`${e.keyPrefix}:${c??`ip:${u(y=>t.req.header(y))}`}`;let r=!0;try{r=(await o.limit({key:f})).success}catch{r=!0}if(!r)return t.json(l(s),429,{"Retry-After":String(s)});await n()}}a(p,"rateLimitRule");export{p as rateLimitRule};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/rateLimits.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Rate-limit rules: the native `ratelimits` binding where configured, the kit's\n * in-isolate limiter as the fallback (RFC 0001, backend conventions).\n *\n * Converged from the per-surface limiters in the four `HttpHardening.ts` copies\n * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before\n * auth). The two disagreed about *when* a limiter runs, and both were right for\n * their surface — so a rule declares its key and the key decides the slot:\n *\n * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT\n * lookup per request is a D1 spend an anonymous caller controls).\n * - `key: 'identity'` (the default) runs **after** auth, keyed on\n * `AuthenticatedUserEmailAddress`. Installed before auth it would see no\n * identity and put every operator behind one NAT in a shared bucket.\n */\nimport type { MiddlewareHandler } from 'hono';\nimport { clientIp, rateLimit } from '../rateLimit.ts';\nimport type { RateLimitContext } from '../rateLimit.ts';\n\n/**\nThe native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).\n*/\ninterface NativeRateLimiter {\n limit(options: { key: string }): Promise<{ success: boolean }>;\n}\n\ninterface RateLimitRule<E> {\n /**\n The Hono path pattern the rule guards (`'/user/*'`).\n */\n path: string;\n /**\n The bucket namespace; two rules never share one.\n */\n keyPrefix: string;\n /**\n The in-isolate window. Mirror the binding's `period` when one is configured.\n */\n windowMs: number;\n /**\n The in-isolate budget, or a per-request resolver (`env` is not known at construction).\n */\n max: number | ((c: RateLimitContext) => number);\n /**\n What the bucket is keyed on, and therefore which slot the rule runs in.\n */\n key?: 'identity' | 'ip';\n /**\n The native binding, when configured. Absent → the in-isolate limiter answers.\n */\n binding?: (env: E) => NativeRateLimiter | undefined;\n}\n\nfunction throttledBody(retryAfter: number): { Exception: { Type: string; Message: string } } {\n return { Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } };\n}\n\n/**\n * One rule's middleware. A native limiter that throws **fails open**, like the\n * in-isolate limiter: a broken limiter must not become an outage.\n */\nfunction rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{ Bindings: E }> {\n const fallback = rateLimit({ windowMs: rule.windowMs, max: rule.max, keyPrefix: rule.keyPrefix });\n const retryAfter = Math.max(1, Math.ceil(rule.windowMs / 1000));\n return async (c, next): Promise<Response | void> => {\n const native = rule.binding?.(c.env);\n if (!native) return fallback(c, next);\n\n const identity = rule.key === 'ip' ? undefined : (c.get('AuthenticatedUserEmailAddress' as never) as string | undefined);\n const key = `${rule.keyPrefix}:${identity ?? `ip:${clientIp((name) => c.req.header(name))}`}`;\n let allowed = true;\n try {\n allowed = (await native.limit({ key })).success;\n } catch {\n allowed = true;\n }\n if (!allowed) return c.json(throttledBody(retryAfter), 429, { 'Retry-After': String(retryAfter) });\n await next();\n };\n}\n\nexport { rateLimitRule };\nexport type { NativeRateLimiter, RateLimitRule };\n"],
|
|
5
|
-
"mappings": "+EAgBA,OAAS,YAAAA,EAAU,aAAAC,MAAiB,
|
|
6
|
-
"names": ["clientIp", "rateLimit", "throttledBody", "retryAfter", "__name", "rateLimitRule", "rule", "fallback", "c", "next", "native", "identity", "key", "name", "allowed"]
|
|
4
|
+
"sourcesContent": ["/**\n * Rate-limit rules: the native `ratelimits` binding where configured, the kit's\n * in-isolate limiter as the fallback (RFC 0001, backend conventions).\n *\n * Converged from the per-surface limiters in the four `HttpHardening.ts` copies\n * and AWS-AccessBridge's `rateLimitHandler` (native binding, IP-keyed, before\n * auth). The two disagreed about *when* a limiter runs, and both were right for\n * their surface — so a rule declares its key and the key decides the slot:\n *\n * - `key: 'ip'` runs **before** auth. It protects the auth step itself (a PAT\n * lookup per request is a D1 spend an anonymous caller controls).\n * - `key: 'identity'` (the default) runs **after** auth, keyed on\n * `AuthenticatedUserEmailAddress`. Installed before auth it would see no\n * identity and put every operator behind one NAT in a shared bucket.\n */\nimport type { MiddlewareHandler } from 'hono';\nimport { clientIp, rateLimit } from '../rateLimit.ts';\nimport { sensitivePathMatcher } from '../securityHeaders.ts';\nimport type { PathMatcher } from '../securityHeaders.ts';\nimport type { RateLimitContext } from '../rateLimit.ts';\n\n/**\nThe native `ratelimits` binding, structurally (Cloudflare's `RateLimit`).\n*/\ninterface NativeRateLimiter {\n limit(options: { key: string }): Promise<{ success: boolean }>;\n}\n\ninterface RateLimitRule<E> {\n /**\n The Hono path pattern the rule guards (`'/user/*'`).\n */\n path: string;\n /**\n * Paths inside `path` this rule does not charge (a reserved namespace another rule owns). Same matcher\n * semantics as `sensitivePaths`; the other rules and the guards still apply to them.\n */\n exclude?: readonly PathMatcher[];\n /**\n The bucket namespace; two rules never share one.\n */\n keyPrefix: string;\n /**\n The in-isolate window. Mirror the binding's `period` when one is configured.\n */\n windowMs: number;\n /**\n The in-isolate budget, or a per-request resolver (`env` is not known at construction).\n */\n max: number | ((c: RateLimitContext) => number);\n /**\n What the bucket is keyed on, and therefore which slot the rule runs in.\n */\n key?: 'identity' | 'ip';\n /**\n The native binding, when configured. Absent → the in-isolate limiter answers.\n */\n binding?: (env: E) => NativeRateLimiter | undefined;\n}\n\nfunction throttledBody(retryAfter: number): { Exception: { Type: string; Message: string } } {\n return { Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } };\n}\n\n/**\n * One rule's middleware. A native limiter that throws **fails open**, like the\n * in-isolate limiter: a broken limiter must not become an outage.\n */\nfunction rateLimitRule<E extends object>(rule: RateLimitRule<E>): MiddlewareHandler<{ Bindings: E }> {\n const fallback = rateLimit({ windowMs: rule.windowMs, max: rule.max, keyPrefix: rule.keyPrefix });\n const retryAfter = Math.max(1, Math.ceil(rule.windowMs / 1000));\n const excluded = rule.exclude === undefined || rule.exclude.length === 0 ? null : sensitivePathMatcher(...rule.exclude);\n return async (c, next): Promise<Response | void> => {\n if (excluded?.(c.req.path)) return next();\n const native = rule.binding?.(c.env);\n if (!native) return fallback(c, next);\n\n const identity = rule.key === 'ip' ? undefined : (c.get('AuthenticatedUserEmailAddress' as never) as string | undefined);\n const key = `${rule.keyPrefix}:${identity ?? `ip:${clientIp((name) => c.req.header(name))}`}`;\n let allowed = true;\n try {\n allowed = (await native.limit({ key })).success;\n } catch {\n allowed = true;\n }\n if (!allowed) return c.json(throttledBody(retryAfter), 429, { 'Retry-After': String(retryAfter) });\n await next();\n };\n}\n\nexport { rateLimitRule };\nexport type { NativeRateLimiter, RateLimitRule };\n"],
|
|
5
|
+
"mappings": "+EAgBA,OAAS,YAAAA,EAAU,aAAAC,MAAiB,kBACpC,OAAS,wBAAAC,MAA4B,wBA2CrC,SAASC,EAAcC,EAAkB,CACvC,MAAO,CAAE,UAAW,CAAE,KAAM,cAAe,QAAS,kCAAkCA,CAAU,IAAI,CAAE,CACxG,CAFSC,EAAAF,EAAA,iBAQT,SAASG,EAAgCC,EAAsB,CAC7D,MAAMC,EAAWP,EAAU,CAAE,SAAUM,EAAK,SAAU,IAAKA,EAAK,IAAK,UAAWA,EAAK,SAAS,CAAE,EAC1FH,EAAa,KAAK,IAAI,EAAG,KAAK,KAAKG,EAAK,SAAW,GAAI,CAAC,EACxDE,EAAWF,EAAK,UAAY,QAAaA,EAAK,QAAQ,SAAW,EAAI,KAAOL,EAAqB,GAAGK,EAAK,OAAO,EACtH,MAAO,OAAOG,EAAGC,IAAkC,CACjD,GAAIF,IAAWC,EAAE,IAAI,IAAI,EAAG,OAAOC,EAAI,EACvC,MAAMC,EAASL,EAAK,UAAUG,EAAE,GAAG,EACnC,GAAI,CAACE,EAAQ,OAAOJ,EAASE,EAAGC,CAAI,EAEpC,MAAME,EAAWN,EAAK,MAAQ,KAAO,OAAaG,EAAE,IAAI,+BAAwC,EAC1FI,EAAM,GAAGP,EAAK,SAAS,IAAIM,GAAY,MAAMb,EAAUe,GAASL,EAAE,IAAI,OAAOK,CAAI,CAAC,CAAC,EAAE,GAC3F,IAAIC,EAAU,GACd,GAAI,CACFA,GAAW,MAAMJ,EAAO,MAAM,CAAE,IAAAE,CAAG,CAAE,GAAG,OAC1C,MAAQ,CACNE,EAAU,EACZ,CACA,GAAI,CAACA,EAAS,OAAON,EAAE,KAAKP,EAAcC,CAAU,EAAG,IAAK,CAAE,cAAe,OAAOA,CAAU,CAAC,CAAE,EACjG,MAAMO,EAAI,CACZ,CACF,CApBSN,EAAAC,EAAA",
|
|
6
|
+
"names": ["clientIp", "rateLimit", "sensitivePathMatcher", "throttledBody", "retryAfter", "__name", "rateLimitRule", "rule", "fallback", "excluded", "c", "next", "native", "identity", "key", "name", "allowed"]
|
|
7
7
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
import { getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam, resetRateLimitForTests as resetRateLimitForTestsSeam } from './testing.ts';
|
|
46
46
|
export { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';
|
|
47
47
|
export type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';
|
|
48
|
-
export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
|
|
49
|
-
export type { HeaderContext, SensitivePath } from './securityHeaders.ts';
|
|
48
|
+
export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, pathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
|
|
49
|
+
export type { HeaderContext, PathMatcher, SensitivePath } from './securityHeaders.ts';
|
|
50
50
|
export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';
|
|
51
51
|
export type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';
|
|
52
52
|
export { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';
|
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,EAC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,iBAAiB,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAErG,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAKtF;;GAEG;AACH,eAAO,MAAM,sBAAsB,EAAE,OAAO,0BAAuD,CAAC;AACpG;;GAEG;AACH,eAAO,MAAM,+BAA+B,EAAE,OAAO,mCAAyE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as
|
|
1
|
+
import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as p,sensitivePaths as E,sensitivePathMatcher as S,pathMatcher as h,CONTENT_SECURITY_POLICY as u,SECURITY_HEADERS as L,STRICT_TRANSPORT_SECURITY as A}from"./securityHeaders.js";import{AccessAuthError as C,authenticateAccess as x,identityFromBinding as F,verifyAccessJwt as f}from"./accessAuth.js";import{errorBody as M,errorResponseFromUnknown as d,mapError as g,toErrorResponse as k,toServiceError as O,INTERNAL_SERVER_MESSAGE as y}from"./ErrorMapper.js";import{errorResponses as U,exceptionResponse as D}from"./openApiErrors.js";import{checkContentLength as H,checkContentType as N,checkMethod as v,checkOrigin as P,isMutatingMethod as l,requestOrigin as w,DEFAULT_ALLOWED_METHODS as X,DEFAULT_MAX_BODY_BYTES as q}from"./requestGuards.js";import{BaseRoute as J,createRouteHandler as K}from"./routeBase.js";const o=t,s=e;export{C as AccessAuthError,J as BaseRoute,u as CONTENT_SECURITY_POLICY,X as DEFAULT_ALLOWED_METHODS,q as DEFAULT_MAX_BODY_BYTES,y as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,L as SECURITY_HEADERS,A as STRICT_TRANSPORT_SECURITY,m as applySecurityHeaders,x as authenticateAccess,H as checkContentLength,N as checkContentType,v as checkMethod,P as checkOrigin,c as clientIp,K as createRouteHandler,M as errorBody,d as errorResponseFromUnknown,U as errorResponses,D as exceptionResponse,s as getRateLimitBucketCountForTests,F as identityFromBinding,l as isMutatingMethod,g as mapError,h as pathMatcher,R as rateLimit,w as requestOrigin,o as resetRateLimitForTests,p as securityHeaders,S as sensitivePathMatcher,E as sensitivePaths,k as toErrorResponse,O as toServiceError,f as verifyAccessJwt};
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately — and only in its\n * `/hono` subpath. It is also the only one a repo can choose to skip: nothing in\n * the other eight imports it.\n *\n * ## What converged here\n *\n * | Module | From |\n * | ----------------- | --------------------------------------------------------------------- |\n * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |\n * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |\n * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |\n * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |\n * | `routeBase` | All three incompatible shapes, with their shared parts converged |\n * | `requestGuards` | HttpHardening ×4, AWS `RequestGuards`, Image-Host's CSRF guard, Pigeongram's origin check |\n * | `openApiErrors` | AWS-AccessBridge's `exceptionResponses` |\n *\n * ## Two entry points\n *\n * This root barrel is **framework-free**: structural context types only, no\n * `hono` or `chanfana` import, so a bare-`Request` dispatcher (a Durable Object,\n * Pigeongram's route table) can take it. Everything that imports `hono` or\n * `chanfana` — `createApiApp`, `FamilyRoute`, the auth and hardening middleware —\n * lives at `@rexezuge/http/hono`, and those two optional peers are required only\n * by a repo that imports that subpath.\n *\n * ## The null rule\n *\n * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.\n * The middleware in this package takes *structural* context types rather than\n * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test\n * double usable without a framework import.\n */\n\nimport {\n getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam,\n resetRateLimitForTests as resetRateLimitForTestsSeam,\n} from './testing.ts';\n\nexport { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n 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,
|
|
6
|
-
"names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "sensitivePathMatcher", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
|
|
4
|
+
"sourcesContent": ["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately — and only in its\n * `/hono` subpath. It is also the only one a repo can choose to skip: nothing in\n * the other eight imports it.\n *\n * ## What converged here\n *\n * | Module | From |\n * | ----------------- | --------------------------------------------------------------------- |\n * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |\n * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |\n * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |\n * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |\n * | `routeBase` | All three incompatible shapes, with their shared parts converged |\n * | `requestGuards` | HttpHardening ×4, AWS `RequestGuards`, Image-Host's CSRF guard, Pigeongram's origin check |\n * | `openApiErrors` | AWS-AccessBridge's `exceptionResponses` |\n *\n * ## Two entry points\n *\n * This root barrel is **framework-free**: structural context types only, no\n * `hono` or `chanfana` import, so a bare-`Request` dispatcher (a Durable Object,\n * Pigeongram's route table) can take it. Everything that imports `hono` or\n * `chanfana` — `createApiApp`, `FamilyRoute`, the auth and hardening middleware —\n * lives at `@rexezuge/http/hono`, and those two optional peers are required only\n * by a repo that imports that subpath.\n *\n * ## The null rule\n *\n * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.\n * The middleware in this package takes *structural* context types rather than\n * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test\n * double usable without a framework import.\n */\n\nimport {\n getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam,\n resetRateLimitForTests as resetRateLimitForTestsSeam,\n} from './testing.ts';\n\nexport { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n sensitivePathMatcher,\n pathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext, PathMatcher, SensitivePath } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';\n\nexport { errorResponses, exceptionResponse } from './openApiErrors.ts';\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from './requestGuards.ts';\nexport type { OriginGuardOptions } from './requestGuards.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n\n// Test seams, re-exported from the root barrel only for compatibility. Bound as\n// consts rather than re-export specifiers so the @deprecated tag reaches callers.\n\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const resetRateLimitForTests: typeof resetRateLimitForTestsSeam = resetRateLimitForTestsSeam;\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam = getRateLimitBucketCountForTestsSeam;\n"],
|
|
5
|
+
"mappings": "AA6CA,OACE,mCAAmCA,EACnC,0BAA0BC,MACrB,eAEP,OAAS,YAAAC,EAAU,eAAAC,EAAa,aAAAC,MAAiB,iBAGjD,OACE,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,EACA,wBAAAC,EACA,eAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,6BAAAC,MACK,uBAGP,OAAS,mBAAAC,EAAiB,sBAAAC,EAAoB,uBAAAC,EAAqB,mBAAAC,MAAuB,kBAG1F,OAAS,aAAAC,EAAW,4BAAAC,EAA0B,YAAAC,EAAU,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGxH,OAAS,kBAAAC,EAAgB,qBAAAC,MAAyB,qBAGlD,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,oBAAAC,EACA,iBAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,qBAGP,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,EAA4DlC,EAI5DmC,EAA8EpC",
|
|
6
|
+
"names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "sensitivePathMatcher", "pathMatcher", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
|
|
7
7
|
}
|
|
@@ -84,12 +84,16 @@ declare function sensitivePaths(...prefixes: readonly string[]): (pathname: stri
|
|
|
84
84
|
* matching existed, and stays one.
|
|
85
85
|
* - a `RegExp` or `(path) => boolean` decides for itself.
|
|
86
86
|
*/
|
|
87
|
-
type
|
|
87
|
+
type PathMatcher = string | RegExp | ((pathname: string) => boolean);
|
|
88
|
+
/**
|
|
89
|
+
The same type under the name `sensitivePaths` has always used.
|
|
90
|
+
*/
|
|
91
|
+
type SensitivePath = PathMatcher;
|
|
88
92
|
/**
|
|
89
93
|
* Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).
|
|
90
94
|
* Empty means nothing is private, and says so rather than guessing.
|
|
91
95
|
*/
|
|
92
|
-
declare function sensitivePathMatcher(...entries: readonly
|
|
93
|
-
export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, };
|
|
94
|
-
export type { HeaderContext, SensitivePath };
|
|
96
|
+
declare function sensitivePathMatcher(...entries: readonly PathMatcher[]): (pathname: string) => boolean;
|
|
97
|
+
export { applySecurityHeaders, securityHeaders, sensitivePaths, sensitivePathMatcher, sensitivePathMatcher as pathMatcher, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, };
|
|
98
|
+
export type { HeaderContext, PathMatcher, SensitivePath };
|
|
95
99
|
//# sourceMappingURL=securityHeaders.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"securityHeaders.d.ts","sourceRoot":"","sources":["../src/securityHeaders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;EAEE;AACF,UAAU,aAAa;IACrB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,GAAG,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;IAC1B,GAAG,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,QAAA,MAAM,gBAAgB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAS7C,CAAC;AAEX;;;;;;GAMG;AACH,QAAA,MAAM,uBAAuB,6NAC+L,CAAC;AAE7N;;EAEE;AACF,QAAA,MAAM,yBAAyB,wCAAwC,CAAC;AAExE;;;;;GAKG;AACH,iBAAS,oBAAoB,CAAC,CAAC,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,GAAG,IAAI,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;;;;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WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAErE;;EAEE;AACF,KAAK,aAAa,GAAG,WAAW,CAAC;AAgBjC;;;GAGG;AACH,iBAAS,oBAAoB,CAAC,GAAG,OAAO,EAAE,SAAS,WAAW,EAAE,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAG/F;AAED,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,oBAAoB,IAAI,WAAW,EACnC,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,CAAC;AACF,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/securityHeaders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var n=(e,t)=>h(e,"name",{value:t,configurable:!0});const i={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"same-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=(), payment=(), usb=()","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Resource-Policy":"same-origin","Cross-Origin-Embedder-Policy":"require-corp","Origin-Agent-Cluster":"?1"},o="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests",c="max-age=31536000; includeSubDomains";function a(e,t){for(const[l,f]of Object.entries(i))e.header(l,f);(e.res.headers.get("content-type")??"").includes("text/html")&&e.header("Content-Security-Policy",o);let r;try{r=new URL(e.req.url).pathname}catch{}r!==void 0&&t(r)&&e.header("Cache-Control","no-store");try{new URL(e.req.url).protocol==="https:"&&e.header("Strict-Transport-Security",c)}catch{}}n(a,"applySecurityHeaders");function p(e){return async(t,s)=>{await s();try{a(t,e)}catch{}}}n(p,"securityHeaders");function m(...e){if(e.length===0)return()=>!1;const t=e.map(s=>s.endsWith("/")?s:`${s}/`);return s=>t.some(r=>s.startsWith(r))}n(m,"sensitivePaths");function d(e){if(typeof e=="function")return e;if(e instanceof RegExp)return t=>new RegExp(e.source,e.flags.replaceAll(/[gy]/g,"")).test(t);if(e.endsWith("/*")){const t=e.slice(0,-1);return s=>s.startsWith(t)||s===t.slice(0,-1)}return e.endsWith("/")?t=>t.startsWith(e):t=>t===e||t===`${e}/`}n(d,"matcherFor");function u(...e){const t=e.map(s=>d(s));return s=>t.some(r=>r(s))}n(u,"sensitivePathMatcher");export{o as CONTENT_SECURITY_POLICY,i as SECURITY_HEADERS,c as STRICT_TRANSPORT_SECURITY,a as applySecurityHeaders,u as pathMatcher,p as securityHeaders,u as sensitivePathMatcher,m as sensitivePaths};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/securityHeaders.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Baseline response security headers.\n *\n * Converged from `apps/api/src/middleware/securityHeaders.ts` in Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic, where the four copies are\n * byte-identical apart from one predicate — which is exactly why it is a\n * parameter here rather than a constant.\n *\n * ## Why `isSensitive` is a required argument\n *\n * The copies each shipped a `startsWith('/user/')` predicate, inherited from a\n * reference project. In one repo that worker serves **no `/user/` route**, so the\n * predicate could never return `true` and `Cache-Control: no-store` was never\n * applied to anything: the operator's own address and every user's address\n * shipped with no `Cache-Control` at all.\n *\n * A predicate copied from another router's route table is not a conservative\n * default; it is an unconditional no-op. So a caller states its own private\n * prefixes, and the compiler asks for them rather than letting them be omitted.\n */\n\n/**\nThe slice of a Hono context this middleware reads.\n*/\ninterface HeaderContext {\n header(name: string, value: string): void;\n res: { headers: Headers };\n req: { url: string };\n}\n\n/**\n * Baseline headers for API JSON responses and the SPA shell.\n *\n * The SPA ships inline scripts and styles from the Vite build, so CSP allows\n * 'unsafe-inline' for both, bounded by `same-origin` and `frame-ancestors`.\n * Without it the shell breaks; hashes or nonces are a future tightening once the\n * build emits stable hashes.\n */\nconst SECURITY_HEADERS: Readonly<Record<string, string>> = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'same-origin',\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'require-corp',\n 'Origin-Agent-Cluster': '?1',\n} as const;\n\n/**\n * CSP for the HTML shell.\n *\n * Separate from {@link SECURITY_HEADERS} because it applies only to an HTML\n * response — sending it on JSON is noise at best and a source of confusing\n * violation reports at worst.\n */\nconst CONTENT_SECURITY_POLICY =\n \"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests\";\n\n/**\nHSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning.\n*/\nconst STRICT_TRANSPORT_SECURITY = 'max-age=31536000; includeSubDomains';\n\n/**\n * Apply the headers to a context.\n *\n * Each step is independently guarded: a header must never fail a request, and\n * one unparseable URL should not cost the other headers.\n */\nfunction applySecurityHeaders(c: HeaderContext, isSensitive: (pathname: string) => boolean): void {\n for (const [key, value] of Object.entries(SECURITY_HEADERS)) {\n c.header(key, value);\n }\n\n const contentType = c.res.headers.get('content-type') ?? '';\n if (contentType.includes('text/html')) {\n c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);\n }\n\n let pathname: string | undefined;\n try {\n pathname = new URL(c.req.url).pathname;\n } catch {\n // URL parsing must never fail the request; the `no-store` step is skipped.\n }\n if (pathname !== undefined && isSensitive(pathname)) {\n c.header('Cache-Control', 'no-store');\n }\n\n try {\n if (new URL(c.req.url).protocol === 'https:') {\n c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);\n }\n } catch {\n // URL parsing must never fail the request.\n }\n}\n\n/**\n * The middleware.\n *\n * `isSensitive` is **required**, and its parameter is required, so a caller\n * cannot accidentally ship a predicate that returns `true` for everything\n * (caching a credential response) or `false` for everything (the no-op above).\n */\nfunction securityHeaders(isSensitive: (pathname: string) => boolean): (c: HeaderContext, next: () => Promise<void>) => Promise<void> {\n return async (c: HeaderContext, next: () => Promise<void>): Promise<void> => {\n await next();\n try {\n applySecurityHeaders(c, isSensitive);\n } catch {\n // Headers must never fail the request.\n }\n };\n}\n\n/**\n * Build a predicate from this app's private path prefixes.\n *\n * A convenience over `securityHeaders`, not a default: it matches **exactly**\n * these prefixes, so a caller still has to name its own paths. The returned\n * function composes, so a repo with a second private surface can add its own\n * test without editing this one.\n */\nfunction sensitivePaths(...prefixes: readonly string[]): (pathname: string) => boolean {\n if (prefixes.length === 0) {\n // Not a throw: a repo with nothing private is a legitimate state, and the\n // failure mode to avoid is silently caching a credential, which an empty\n // list cannot do. What it must not do is *look* like it protected something.\n return () => false;\n }\n const normalized = prefixes.map((prefix) => (prefix.endsWith('/') ? prefix : `${prefix}/`));\n return (pathname: string): boolean => normalized.some((prefix) => pathname.startsWith(prefix));\n}\n\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
|
|
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,
|
|
4
|
+
"sourcesContent": ["/**\n * Baseline response security headers.\n *\n * Converged from `apps/api/src/middleware/securityHeaders.ts` in Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic, where the four copies are\n * byte-identical apart from one predicate — which is exactly why it is a\n * parameter here rather than a constant.\n *\n * ## Why `isSensitive` is a required argument\n *\n * The copies each shipped a `startsWith('/user/')` predicate, inherited from a\n * reference project. In one repo that worker serves **no `/user/` route**, so the\n * predicate could never return `true` and `Cache-Control: no-store` was never\n * applied to anything: the operator's own address and every user's address\n * shipped with no `Cache-Control` at all.\n *\n * A predicate copied from another router's route table is not a conservative\n * default; it is an unconditional no-op. So a caller states its own private\n * prefixes, and the compiler asks for them rather than letting them be omitted.\n */\n\n/**\nThe slice of a Hono context this middleware reads.\n*/\ninterface HeaderContext {\n header(name: string, value: string): void;\n res: { headers: Headers };\n req: { url: string };\n}\n\n/**\n * Baseline headers for API JSON responses and the SPA shell.\n *\n * The SPA ships inline scripts and styles from the Vite build, so CSP allows\n * 'unsafe-inline' for both, bounded by `same-origin` and `frame-ancestors`.\n * Without it the shell breaks; hashes or nonces are a future tightening once the\n * build emits stable hashes.\n */\nconst SECURITY_HEADERS: Readonly<Record<string, string>> = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'same-origin',\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'require-corp',\n 'Origin-Agent-Cluster': '?1',\n} as const;\n\n/**\n * CSP for the HTML shell.\n *\n * Separate from {@link SECURITY_HEADERS} because it applies only to an HTML\n * response — sending it on JSON is noise at best and a source of confusing\n * violation reports at worst.\n */\nconst CONTENT_SECURITY_POLICY =\n \"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests\";\n\n/**\nHSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning.\n*/\nconst STRICT_TRANSPORT_SECURITY = 'max-age=31536000; includeSubDomains';\n\n/**\n * Apply the headers to a context.\n *\n * Each step is independently guarded: a header must never fail a request, and\n * one unparseable URL should not cost the other headers.\n */\nfunction applySecurityHeaders(c: HeaderContext, isSensitive: (pathname: string) => boolean): void {\n for (const [key, value] of Object.entries(SECURITY_HEADERS)) {\n c.header(key, value);\n }\n\n const contentType = c.res.headers.get('content-type') ?? '';\n if (contentType.includes('text/html')) {\n c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);\n }\n\n let pathname: string | undefined;\n try {\n pathname = new URL(c.req.url).pathname;\n } catch {\n // URL parsing must never fail the request; the `no-store` step is skipped.\n }\n if (pathname !== undefined && isSensitive(pathname)) {\n c.header('Cache-Control', 'no-store');\n }\n\n try {\n if (new URL(c.req.url).protocol === 'https:') {\n c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);\n }\n } catch {\n // URL parsing must never fail the request.\n }\n}\n\n/**\n * The middleware.\n *\n * `isSensitive` is **required**, and its parameter is required, so a caller\n * cannot accidentally ship a predicate that returns `true` for everything\n * (caching a credential response) or `false` for everything (the no-op above).\n */\nfunction securityHeaders(isSensitive: (pathname: string) => boolean): (c: HeaderContext, next: () => Promise<void>) => Promise<void> {\n return async (c: HeaderContext, next: () => Promise<void>): Promise<void> => {\n await next();\n try {\n applySecurityHeaders(c, isSensitive);\n } catch {\n // Headers must never fail the request.\n }\n };\n}\n\n/**\n * Build a predicate from this app's private path prefixes.\n *\n * A convenience over `securityHeaders`, not a default: it matches **exactly**\n * these prefixes, so a caller still has to name its own paths. The returned\n * function composes, so a repo with a second private surface can add its own\n * test without editing this one.\n */\nfunction sensitivePaths(...prefixes: readonly string[]): (pathname: string) => boolean {\n if (prefixes.length === 0) {\n // Not a throw: a repo with nothing private is a legitimate state, and the\n // failure mode to avoid is silently caching a credential, which an empty\n // list cannot do. What it must not do is *look* like it protected something.\n return () => false;\n }\n const normalized = prefixes.map((prefix) => (prefix.endsWith('/') ? prefix : `${prefix}/`));\n return (pathname: string): boolean => normalized.some((prefix) => pathname.startsWith(prefix));\n}\n\n/**\n * One private-path entry: a string, a `RegExp` tested against the pathname, or a predicate.\n *\n * - `'/generate-totp'` matches that path **exactly** (and its one-trailing-slash form), nothing under it.\n * - `'/user/'` (ends with `/`) and `'/user/*'` match the **prefix**: everything under `/user/`\n * (`'/user/*'` also matches `/user` itself). A string ending in `/` was a prefix before exact\n * matching existed, and stays one.\n * - a `RegExp` or `(path) => boolean` decides for itself.\n */\ntype PathMatcher = string | RegExp | ((pathname: string) => boolean);\n\n/**\nThe same type under the name `sensitivePaths` has always used.\n*/\ntype SensitivePath = PathMatcher;\n\nfunction matcherFor(entry: PathMatcher): (pathname: string) => boolean {\n if (typeof entry === 'function') return entry;\n if (entry instanceof RegExp) {\n // `test` on a global/sticky regex is stateful (`lastIndex`); a fresh clone per call keeps it pure.\n return (pathname) => new RegExp(entry.source, entry.flags.replaceAll(/[gy]/g, '')).test(pathname);\n }\n if (entry.endsWith('/*')) {\n const prefix = entry.slice(0, -1);\n return (pathname) => pathname.startsWith(prefix) || pathname === prefix.slice(0, -1);\n }\n if (entry.endsWith('/')) return (pathname) => pathname.startsWith(entry);\n return (pathname) => pathname === entry || pathname === `${entry}/`;\n}\n\n/**\n * Build the no-store predicate from {@link SensitivePath} entries (what `createApiApp({ sensitivePaths })` takes).\n * Empty means nothing is private, and says so rather than guessing.\n */\nfunction sensitivePathMatcher(...entries: readonly PathMatcher[]): (pathname: string) => boolean {\n const matchers = entries.map((entry) => matcherFor(entry));\n return (pathname) => matchers.some((matches) => matches(pathname));\n}\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n sensitivePathMatcher,\n sensitivePathMatcher as pathMatcher,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n};\nexport type { HeaderContext, PathMatcher, SensitivePath };\n"],
|
|
5
|
+
"mappings": "+EAsCA,MAAMA,EAAqD,CACzD,yBAA0B,UAC1B,kBAAmB,OACnB,kBAAmB,cACnB,qBAAsB,+DACtB,6BAA8B,cAC9B,+BAAgC,cAChC,+BAAgC,eAChC,uBAAwB,MAUpBC,EACJ,2NAKIC,EAA4B,sCAQlC,SA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OAAQT,GAAaA,EAAS,WAAWO,CAAM,GAAKP,IAAaO,EAAO,MAAM,EAAG,EAAE,CACrF,CACA,OAAIE,EAAM,SAAS,GAAG,EAAWT,GAAaA,EAAS,WAAWS,CAAK,EAC/DT,GAAaA,IAAaS,GAAST,IAAa,GAAGS,CAAK,GAClE,CAZSR,EAAAO,EAAA,cAkBT,SAASE,KAAwBC,EAA+B,CAC9D,MAAMC,EAAWD,EAAQ,IAAKF,GAAUD,EAAWC,CAAK,CAAC,EACzD,OAAQT,GAAaY,EAAS,KAAMC,GAAYA,EAAQb,CAAQ,CAAC,CACnE,CAHSC,EAAAS,EAAA",
|
|
6
6
|
"names": ["SECURITY_HEADERS", "CONTENT_SECURITY_POLICY", "STRICT_TRANSPORT_SECURITY", "applySecurityHeaders", "c", "isSensitive", "key", "value", "pathname", "__name", "securityHeaders", "next", "sensitivePaths", "prefixes", "normalized", "prefix", "matcherFor", "entry", "sensitivePathMatcher", "entries", "matchers", "matches"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/http",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -34,9 +34,9 @@
|
|
|
34
34
|
],
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"jose": "^6.2.12",
|
|
37
|
-
"@rexezuge/contracts": "1.
|
|
38
|
-
"@rexezuge/errors": "1.
|
|
39
|
-
"@rexezuge/shared": "1.
|
|
37
|
+
"@rexezuge/contracts": "1.16.0",
|
|
38
|
+
"@rexezuge/errors": "1.16.0",
|
|
39
|
+
"@rexezuge/shared": "1.16.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"chanfana": "^3.4.0",
|