@rexezuge/http 1.9.4 → 1.11.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 +159 -8
- package/dist/ErrorMapper.d.ts +65 -10
- package/dist/ErrorMapper.d.ts.map +1 -1
- package/dist/ErrorMapper.js +1 -1
- package/dist/ErrorMapper.js.map +3 -3
- package/dist/errorClassification.d.ts +44 -0
- package/dist/errorClassification.d.ts.map +1 -0
- package/dist/errorClassification.js +1 -0
- package/dist/errorClassification.js.map +7 -0
- package/dist/hono/FamilyRoute.d.ts +56 -0
- package/dist/hono/FamilyRoute.d.ts.map +1 -0
- package/dist/hono/FamilyRoute.js +1 -0
- package/dist/hono/FamilyRoute.js.map +7 -0
- package/dist/hono/auth.d.ts +91 -0
- package/dist/hono/auth.d.ts.map +1 -0
- package/dist/hono/auth.js +1 -0
- package/dist/hono/auth.js.map +7 -0
- package/dist/hono/bookmarks.d.ts +63 -0
- package/dist/hono/bookmarks.d.ts.map +1 -0
- package/dist/hono/bookmarks.js +1 -0
- package/dist/hono/bookmarks.js.map +7 -0
- package/dist/hono/createApiApp.d.ts +93 -0
- package/dist/hono/createApiApp.d.ts.map +1 -0
- package/dist/hono/createApiApp.js +1 -0
- package/dist/hono/createApiApp.js.map +7 -0
- package/dist/hono/errorHandler.d.ts +25 -0
- package/dist/hono/errorHandler.d.ts.map +1 -0
- package/dist/hono/errorHandler.js +1 -0
- package/dist/hono/errorHandler.js.map +7 -0
- package/dist/hono/hardening.d.ts +51 -0
- package/dist/hono/hardening.d.ts.map +1 -0
- package/dist/hono/hardening.js +1 -0
- package/dist/hono/hardening.js.map +7 -0
- package/dist/hono/index.d.ts +33 -0
- package/dist/hono/index.d.ts.map +1 -0
- package/dist/hono/index.js +1 -0
- package/dist/hono/index.js.map +7 -0
- package/dist/hono/rateLimits.d.ts +63 -0
- package/dist/hono/rateLimits.d.ts.map +1 -0
- package/dist/hono/rateLimits.js +1 -0
- package/dist/hono/rateLimits.js.map +7 -0
- package/dist/hono/requestContext.d.ts +28 -0
- package/dist/hono/requestContext.d.ts.map +1 -0
- package/dist/hono/requestContext.js +1 -0
- package/dist/hono/requestContext.js.map +7 -0
- package/dist/hono/types.d.ts +69 -0
- package/dist/hono/types.d.ts.map +1 -0
- package/dist/hono/types.js +1 -0
- package/dist/hono/types.js.map +7 -0
- package/dist/index.d.ts +30 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/openApiErrors.d.ts +63 -0
- package/dist/openApiErrors.d.ts.map +1 -0
- package/dist/openApiErrors.js +1 -0
- package/dist/openApiErrors.js.map +7 -0
- package/dist/requestGuards.d.ts +52 -0
- package/dist/requestGuards.d.ts.map +1 -0
- package/dist/requestGuards.js +1 -0
- package/dist/requestGuards.js.map +7 -0
- package/dist/routeBase.d.ts.map +1 -1
- package/dist/routeBase.js +1 -1
- package/dist/routeBase.js.map +3 -3
- package/dist/testing.d.ts +8 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +1 -0
- package/dist/testing.js.map +7 -0
- package/package.json +30 -8
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The typed Hono context every family API shares.
|
|
3
|
+
*
|
|
4
|
+
* Converged from the `Variables` blocks the workers redeclare — 40-odd
|
|
5
|
+
* `Hono<{ Bindings: Env; Variables: { AuthenticatedUserEmailAddress: string } }>`
|
|
6
|
+
* aliases across Edge-Git, Durable-DAV, Mail-Bee, Mail-Meow, Mail-Otter,
|
|
7
|
+
* AWS-AccessBridge and Image-Host, half of which also carry `AuthenticatedUserId`
|
|
8
|
+
* (some as `?:`, which made every read a narrowing).
|
|
9
|
+
*/
|
|
10
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
11
|
+
/**
|
|
12
|
+
* The logger port. `@rexezuge/runtime`'s `Logger` (from `createLogger`)
|
|
13
|
+
* satisfies it structurally; `http` does not import `runtime`.
|
|
14
|
+
*
|
|
15
|
+
* Kit middleware only ever passes it **static** messages and plain fields
|
|
16
|
+
* (`type`, `status`, `requestId`), never a caught value — log redaction is an
|
|
17
|
+
* invariant, not an option.
|
|
18
|
+
*/
|
|
19
|
+
interface HttpLogger {
|
|
20
|
+
debug(...args: unknown[]): void;
|
|
21
|
+
info(...args: unknown[]): void;
|
|
22
|
+
warn(...args: unknown[]): void;
|
|
23
|
+
error(...args: unknown[]): void;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* What the kit's middleware publishes on the context.
|
|
27
|
+
*
|
|
28
|
+
* `AuthenticatedUserEmailAddress` and `AuthenticatedUserId` are set by
|
|
29
|
+
* `accessAuth` / `apiKeyAuth` on the surfaces they guard and are **only
|
|
30
|
+
* meaningful there**: declared non-optional so an authenticated handler reads
|
|
31
|
+
* them without narrowing, exactly as every consumer declared them. A public
|
|
32
|
+
* route never reads them.
|
|
33
|
+
*/
|
|
34
|
+
interface FamilyVariables {
|
|
35
|
+
/**
|
|
36
|
+
The sign-in address, lowercased. Display, logging and the rate-limit key.
|
|
37
|
+
*/
|
|
38
|
+
AuthenticatedUserEmailAddress: string;
|
|
39
|
+
/**
|
|
40
|
+
The stable account key — the only value that should identify a user.
|
|
41
|
+
*/
|
|
42
|
+
AuthenticatedUserId: string;
|
|
43
|
+
/**
|
|
44
|
+
This request's correlation id, also sent back as `X-Request-Id`.
|
|
45
|
+
*/
|
|
46
|
+
requestId: string;
|
|
47
|
+
/**
|
|
48
|
+
The request-scoped logger.
|
|
49
|
+
*/
|
|
50
|
+
logger: HttpLogger;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The Hono `Env` of a family app: your bindings, the kit's variables, and any
|
|
54
|
+
* variables your own middleware adds.
|
|
55
|
+
*/
|
|
56
|
+
type FamilyEnv<E extends object = object, V extends object = object> = {
|
|
57
|
+
Bindings: E;
|
|
58
|
+
Variables: FamilyVariables & V;
|
|
59
|
+
};
|
|
60
|
+
type FamilyContext<E extends object = object, V extends object = object> = Context<FamilyEnv<E, V>>;
|
|
61
|
+
type FamilyMiddleware<E extends object = object, V extends object = object> = MiddlewareHandler<FamilyEnv<E, V>>;
|
|
62
|
+
/**
|
|
63
|
+
A value fixed at construction, or resolved from the request's bindings.
|
|
64
|
+
*/
|
|
65
|
+
type FromEnv<E, T> = T | ((env: E) => T);
|
|
66
|
+
declare function resolveFromEnv<E, T>(value: FromEnv<E, T>, env: E): T;
|
|
67
|
+
export { resolveFromEnv };
|
|
68
|
+
export type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger };
|
|
69
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/hono/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAEvD;;;;;;;GAOG;AACH,UAAU,UAAU;IAClB,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAChC,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC/B,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC/B,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;CACjC;AAED;;;;;;;;GAQG;AACH,UAAU,eAAe;IACvB;;MAEE;IACF,6BAA6B,EAAE,MAAM,CAAC;IACtC;;MAEE;IACF,mBAAmB,EAAE,MAAM,CAAC;IAC5B;;MAEE;IACF,SAAS,EAAE,MAAM,CAAC;IAClB;;MAEE;IACF,MAAM,EAAE,UAAU,CAAC;CACpB;AAED;;;GAGG;AACH,KAAK,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;IACrE,QAAQ,EAAE,CAAC,CAAC;IACZ,SAAS,EAAE,eAAe,GAAG,CAAC,CAAC;CAChC,CAAC;AAEF,KAAK,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAEpG,KAAK,gBAAgB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAEjH;;EAEE;AACF,KAAK,OAAO,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AAEzC,iBAAS,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAE7D;AAED,OAAO,EAAE,cAAc,EAAE,CAAC;AAC1B,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=Object.defineProperty;var r=(n,o)=>t(n,"name",{value:o,configurable:!0});function e(n,o){return typeof n=="function"?n(o):n}r(e,"resolveFromEnv");export{e as resolveFromEnv};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hono/types.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The typed Hono context every family API shares.\n *\n * Converged from the `Variables` blocks the workers redeclare — 40-odd\n * `Hono<{ Bindings: Env; Variables: { AuthenticatedUserEmailAddress: string } }>`\n * aliases across Edge-Git, Durable-DAV, Mail-Bee, Mail-Meow, Mail-Otter,\n * AWS-AccessBridge and Image-Host, half of which also carry `AuthenticatedUserId`\n * (some as `?:`, which made every read a narrowing).\n */\nimport type { Context, MiddlewareHandler } from 'hono';\n\n/**\n * The logger port. `@rexezuge/runtime`'s `Logger` (from `createLogger`)\n * satisfies it structurally; `http` does not import `runtime`.\n *\n * Kit middleware only ever passes it **static** messages and plain fields\n * (`type`, `status`, `requestId`), never a caught value — log redaction is an\n * invariant, not an option.\n */\ninterface HttpLogger {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\n/**\n * What the kit's middleware publishes on the context.\n *\n * `AuthenticatedUserEmailAddress` and `AuthenticatedUserId` are set by\n * `accessAuth` / `apiKeyAuth` on the surfaces they guard and are **only\n * meaningful there**: declared non-optional so an authenticated handler reads\n * them without narrowing, exactly as every consumer declared them. A public\n * route never reads them.\n */\ninterface FamilyVariables {\n /**\n The sign-in address, lowercased. Display, logging and the rate-limit key.\n */\n AuthenticatedUserEmailAddress: string;\n /**\n The stable account key — the only value that should identify a user.\n */\n AuthenticatedUserId: string;\n /**\n This request's correlation id, also sent back as `X-Request-Id`.\n */\n requestId: string;\n /**\n The request-scoped logger.\n */\n logger: HttpLogger;\n}\n\n/**\n * The Hono `Env` of a family app: your bindings, the kit's variables, and any\n * variables your own middleware adds.\n */\ntype FamilyEnv<E extends object = object, V extends object = object> = {\n Bindings: E;\n Variables: FamilyVariables & V;\n};\n\ntype FamilyContext<E extends object = object, V extends object = object> = Context<FamilyEnv<E, V>>;\n\ntype FamilyMiddleware<E extends object = object, V extends object = object> = MiddlewareHandler<FamilyEnv<E, V>>;\n\n/**\nA value fixed at construction, or resolved from the request's bindings.\n*/\ntype FromEnv<E, T> = T | ((env: E) => T);\n\nfunction resolveFromEnv<E, T>(value: FromEnv<E, T>, env: E): T {\n return typeof value === 'function' ? (value as (env: E) => T)(env) : value;\n}\n\nexport { resolveFromEnv };\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger };\n"],
|
|
5
|
+
"mappings": "+EAwEA,SAASA,EAAqBC,EAAsBC,EAAM,CACxD,OAAO,OAAOD,GAAU,WAAcA,EAAwBC,CAAG,EAAID,CACvE,CAFSE,EAAAH,EAAA",
|
|
6
|
+
"names": ["resolveFromEnv", "value", "env", "__name"]
|
|
7
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
* chanfana-shaped, and four repos shipped four copies of each while the kit's
|
|
11
11
|
* zero-dependency rule silently prevented the fix.
|
|
12
12
|
*
|
|
13
|
-
* So this is the one package that breaks the rule, deliberately
|
|
14
|
-
* only one a repo can choose to skip
|
|
13
|
+
* So this is the one package that breaks the rule, deliberately — and only in its
|
|
14
|
+
* `/hono` subpath. It is also the only one a repo can choose to skip: nothing in
|
|
15
|
+
* the other eight imports it.
|
|
15
16
|
*
|
|
16
17
|
* ## What converged here
|
|
17
18
|
*
|
|
@@ -22,6 +23,17 @@
|
|
|
22
23
|
* | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |
|
|
23
24
|
* | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |
|
|
24
25
|
* | `routeBase` | All three incompatible shapes, with their shared parts converged |
|
|
26
|
+
* | `requestGuards` | HttpHardening ×4, AWS `RequestGuards`, Image-Host's CSRF guard, Pigeongram's origin check |
|
|
27
|
+
* | `openApiErrors` | AWS-AccessBridge's `exceptionResponses` |
|
|
28
|
+
*
|
|
29
|
+
* ## Two entry points
|
|
30
|
+
*
|
|
31
|
+
* This root barrel is **framework-free**: structural context types only, no
|
|
32
|
+
* `hono` or `chanfana` import, so a bare-`Request` dispatcher (a Durable Object,
|
|
33
|
+
* Pigeongram's route table) can take it. Everything that imports `hono` or
|
|
34
|
+
* `chanfana` — `createApiApp`, `FamilyRoute`, the auth and hardening middleware —
|
|
35
|
+
* lives at `@rexezuge/http/hono`, and those two optional peers are required only
|
|
36
|
+
* by a repo that imports that subpath.
|
|
25
37
|
*
|
|
26
38
|
* ## The null rule
|
|
27
39
|
*
|
|
@@ -30,14 +42,27 @@
|
|
|
30
42
|
* Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test
|
|
31
43
|
* double usable without a framework import.
|
|
32
44
|
*/
|
|
33
|
-
|
|
45
|
+
import { getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam, resetRateLimitForTests as resetRateLimitForTestsSeam } from './testing.ts';
|
|
46
|
+
export { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';
|
|
34
47
|
export type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';
|
|
35
48
|
export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
|
|
36
49
|
export type { HeaderContext } from './securityHeaders.ts';
|
|
37
50
|
export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';
|
|
38
51
|
export type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';
|
|
39
|
-
export { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';
|
|
40
|
-
export type { ErrorMapperOptions } from './ErrorMapper.ts';
|
|
52
|
+
export { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';
|
|
53
|
+
export type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';
|
|
54
|
+
export { errorResponses, exceptionResponse } from './openApiErrors.ts';
|
|
55
|
+
export type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';
|
|
56
|
+
export { checkContentLength, checkContentType, checkMethod, checkOrigin, isMutatingMethod, requestOrigin, DEFAULT_ALLOWED_METHODS, DEFAULT_MAX_BODY_BYTES, } from './requestGuards.ts';
|
|
57
|
+
export type { OriginGuardOptions } from './requestGuards.ts';
|
|
41
58
|
export { BaseRoute, createRouteHandler } from './routeBase.ts';
|
|
42
59
|
export type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';
|
|
60
|
+
/**
|
|
61
|
+
* @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.
|
|
62
|
+
*/
|
|
63
|
+
export declare const resetRateLimitForTests: typeof resetRateLimitForTestsSeam;
|
|
64
|
+
/**
|
|
65
|
+
* @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.
|
|
66
|
+
*/
|
|
67
|
+
export declare const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam;
|
|
43
68
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EACL,+BAA+B,IAAI,mCAAmC,EACtE,sBAAsB,IAAI,0BAA0B,EACrD,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAClE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC5G,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE3G,OAAO,EAAE,SAAS,EAAE,wBAAwB,EAAE,QAAQ,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3I,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE5F,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAErG,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAKtF;;GAEG;AACH,eAAO,MAAM,sBAAsB,EAAE,OAAO,0BAAuD,CAAC;AACpG;;GAEG;AACH,eAAO,MAAM,+BAA+B,EAAE,OAAO,mCAAyE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{getRateLimitBucketCountForTests as e,resetRateLimitForTests as t}from"./testing.js";import{clientIp as c,MAX_BUCKETS as a,rateLimit as R}from"./rateLimit.js";import{applySecurityHeaders as m,securityHeaders as E,sensitivePaths as p,CONTENT_SECURITY_POLICY as S,SECURITY_HEADERS as u,STRICT_TRANSPORT_SECURITY as L}from"./securityHeaders.js";import{AccessAuthError as _,authenticateAccess as C,identityFromBinding as h,verifyAccessJwt as x}from"./accessAuth.js";import{errorBody as f,errorResponseFromUnknown as B,mapError as d,toErrorResponse as g,toServiceError as k,INTERNAL_SERVER_MESSAGE as O}from"./ErrorMapper.js";import{errorResponses as I,exceptionResponse as M}from"./openApiErrors.js";import{checkContentLength as D,checkContentType as Y,checkMethod as H,checkOrigin as N,isMutatingMethod as l,requestOrigin as v,DEFAULT_ALLOWED_METHODS as P,DEFAULT_MAX_BODY_BYTES as w}from"./requestGuards.js";import{BaseRoute as q,createRouteHandler as G}from"./routeBase.js";const o=t,s=e;export{_ as AccessAuthError,q as BaseRoute,S as CONTENT_SECURITY_POLICY,P as DEFAULT_ALLOWED_METHODS,w as DEFAULT_MAX_BODY_BYTES,O as INTERNAL_SERVER_MESSAGE,a as MAX_BUCKETS,u as SECURITY_HEADERS,L as STRICT_TRANSPORT_SECURITY,m as applySecurityHeaders,C as authenticateAccess,D as checkContentLength,Y as checkContentType,H as checkMethod,N as checkOrigin,c as clientIp,G as createRouteHandler,f as errorBody,B as errorResponseFromUnknown,I as errorResponses,M as exceptionResponse,s as getRateLimitBucketCountForTests,h as identityFromBinding,l as isMutatingMethod,d as mapError,R as rateLimit,v as requestOrigin,o as resetRateLimitForTests,E as securityHeaders,p as sensitivePaths,g as toErrorResponse,k as toServiceError,x 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. It is also the
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately — and only in its\n * `/hono` subpath. It is also the only one a repo can choose to skip: nothing in\n * the other eight imports it.\n *\n * ## What converged here\n *\n * | Module | From |\n * | ----------------- | --------------------------------------------------------------------- |\n * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |\n * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |\n * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |\n * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |\n * | `routeBase` | All three incompatible shapes, with their shared parts converged |\n * | `requestGuards` | HttpHardening ×4, AWS `RequestGuards`, Image-Host's CSRF guard, Pigeongram's origin check |\n * | `openApiErrors` | AWS-AccessBridge's `exceptionResponses` |\n *\n * ## Two entry points\n *\n * This root barrel is **framework-free**: structural context types only, no\n * `hono` or `chanfana` import, so a bare-`Request` dispatcher (a Durable Object,\n * Pigeongram's route table) can take it. Everything that imports `hono` or\n * `chanfana` — `createApiApp`, `FamilyRoute`, the auth and hardening middleware —\n * lives at `@rexezuge/http/hono`, and those two optional peers are required only\n * by a repo that imports that subpath.\n *\n * ## The null rule\n *\n * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.\n * The middleware in this package takes *structural* context types rather than\n * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test\n * double usable without a framework import.\n */\n\nimport {\n getRateLimitBucketCountForTests as getRateLimitBucketCountForTestsSeam,\n resetRateLimitForTests as resetRateLimitForTestsSeam,\n} from './testing.ts';\n\nexport { clientIp, MAX_BUCKETS, rateLimit } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, errorResponseFromUnknown, mapError, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { DailyLimitDetector, ErrorMapperOptions, MappedError } from './ErrorMapper.ts';\n\nexport { errorResponses, exceptionResponse } from './openApiErrors.ts';\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions } from './openApiErrors.ts';\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n} from './requestGuards.ts';\nexport type { OriginGuardOptions } from './requestGuards.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n\n// Test seams, re-exported from the root barrel only for compatibility. Bound as\n// consts rather than re-export specifiers so the @deprecated tag reaches callers.\n\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const resetRateLimitForTests: typeof resetRateLimitForTestsSeam = resetRateLimitForTestsSeam;\n/**\n * @deprecated Import from '@rexezuge/http/testing'. Removed in 2.0.\n */\nexport const getRateLimitBucketCountForTests: typeof getRateLimitBucketCountForTestsSeam = getRateLimitBucketCountForTestsSeam;\n"],
|
|
5
|
+
"mappings": "AA6CA,OACE,mCAAmCA,EACnC,0BAA0BC,MACrB,eAEP,OAAS,YAAAC,EAAU,eAAAC,EAAa,aAAAC,MAAiB,iBAGjD,OACE,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,6BAAAC,MACK,uBAGP,OAAS,mBAAAC,EAAiB,sBAAAC,EAAoB,uBAAAC,EAAqB,mBAAAC,MAAuB,kBAG1F,OAAS,aAAAC,EAAW,4BAAAC,EAA0B,YAAAC,EAAU,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGxH,OAAS,kBAAAC,EAAgB,qBAAAC,MAAyB,qBAGlD,OACE,sBAAAC,EACA,oBAAAC,EACA,eAAAC,EACA,eAAAC,EACA,oBAAAC,EACA,iBAAAC,EACA,2BAAAC,EACA,0BAAAC,MACK,qBAGP,OAAS,aAAAC,EAAW,sBAAAC,MAA0B,iBASvC,MAAMC,EAA4DhC,EAI5DiC,EAA8ElC",
|
|
6
|
+
"names": ["getRateLimitBucketCountForTestsSeam", "resetRateLimitForTestsSeam", "clientIp", "MAX_BUCKETS", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "errorResponseFromUnknown", "mapError", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "errorResponses", "exceptionResponse", "checkContentLength", "checkContentType", "checkMethod", "checkOrigin", "isMutatingMethod", "requestOrigin", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "BaseRoute", "createRouteHandler", "resetRateLimitForTests", "getRateLimitBucketCountForTests"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
type ExceptionSchema = {
|
|
2
|
+
type: 'object';
|
|
3
|
+
properties: {
|
|
4
|
+
Exception: {
|
|
5
|
+
type: 'object';
|
|
6
|
+
properties: {
|
|
7
|
+
Type: {
|
|
8
|
+
type: 'string';
|
|
9
|
+
description: string;
|
|
10
|
+
example: string;
|
|
11
|
+
};
|
|
12
|
+
Message: {
|
|
13
|
+
type: 'string';
|
|
14
|
+
description: string;
|
|
15
|
+
example: string;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
type ExceptionResponse = {
|
|
22
|
+
description: string;
|
|
23
|
+
content: {
|
|
24
|
+
'application/json': {
|
|
25
|
+
schema: ExceptionSchema;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
interface ExceptionSchemaOptions {
|
|
30
|
+
/**
|
|
31
|
+
The `Type` example. Defaults to the catalog name for the status.
|
|
32
|
+
*/
|
|
33
|
+
type?: string;
|
|
34
|
+
/**
|
|
35
|
+
The `Message` example. Should say what actually goes wrong on this route.
|
|
36
|
+
*/
|
|
37
|
+
message?: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
One `responses` entry for the envelope.
|
|
41
|
+
*/
|
|
42
|
+
declare function exceptionResponse(description: string, options?: ExceptionSchemaOptions): ExceptionResponse;
|
|
43
|
+
/**
|
|
44
|
+
* A `responses` map for several statuses at once:
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* schema = {
|
|
48
|
+
* responses: {
|
|
49
|
+
* '200': { description: 'The volume', ...contentJson(Volume) },
|
|
50
|
+
* ...errorResponses({ 400: 'Invalid name', 404: 'No such volume' }),
|
|
51
|
+
* ...errorResponses([401, 500]),
|
|
52
|
+
* },
|
|
53
|
+
* };
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* A list uses each catalog default as the description; a record names it. An
|
|
57
|
+
* uncatalogued status is described as `InternalServerError`, because that is
|
|
58
|
+
* what the mapper emits for one.
|
|
59
|
+
*/
|
|
60
|
+
declare function errorResponses(statuses: readonly number[] | Readonly<Record<number, string>>): Record<string, ExceptionResponse>;
|
|
61
|
+
export { errorResponses, exceptionResponse };
|
|
62
|
+
export type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions };
|
|
63
|
+
//# sourceMappingURL=openApiErrors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openApiErrors.d.ts","sourceRoot":"","sources":["../src/openApiErrors.ts"],"names":[],"mappings":"AAwBA,KAAK,eAAe,GAAG;IACrB,IAAI,EAAE,QAAQ,CAAC;IACf,UAAU,EAAE;QACV,SAAS,EAAE;YACT,IAAI,EAAE,QAAQ,CAAC;YACf,UAAU,EAAE;gBACV,IAAI,EAAE;oBAAE,IAAI,EAAE,QAAQ,CAAC;oBAAC,WAAW,EAAE,MAAM,CAAC;oBAAC,OAAO,EAAE,MAAM,CAAA;iBAAE,CAAC;gBAC/D,OAAO,EAAE;oBAAE,IAAI,EAAE,QAAQ,CAAC;oBAAC,WAAW,EAAE,MAAM,CAAC;oBAAC,OAAO,EAAE,MAAM,CAAA;iBAAE,CAAC;aACnE,CAAC;SACH,CAAC;KACH,CAAC;CACH,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE;QAAE,kBAAkB,EAAE;YAAE,MAAM,EAAE,eAAe,CAAA;SAAE,CAAA;KAAE,CAAC;CAC9D,CAAC;AAEF,UAAU,sBAAsB;IAC9B;;MAEE;IACF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;MAEE;IACF,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;EAEE;AACF,iBAAS,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,iBAAiB,CAwBvG;AAYD;;;;;;;;;;;;;;;;GAgBG;AACH,iBAAS,cAAc,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAazH;AAED,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,CAAC;AAC7C,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,sBAAsB,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty;var n=(e,t)=>f(e,"name",{value:t,configurable:!0});import{CATALOG as i}from"@rexezuge/errors";import{INTERNAL_SERVER_MESSAGE as c}from"./ErrorMapper.js";function l(e,t={}){return{description:e,content:{"application/json":{schema:{type:"object",properties:{Exception:{type:"object",properties:{Type:{type:"string",description:"Stable machine-readable error type.",example:t.type??"BadRequest"},Message:{type:"string",description:"Human-readable detail about the error.",example:t.message??i.BadRequest.defaultMessage}}}}}}}}}n(l,"exceptionResponse");function m(e){for(const[t,s]of Object.entries(i))if(s.status===e)return{type:t,defaultMessage:s.defaultMessage,expose:s.expose};return null}n(m,"catalogEntry");function d(e){const t=Array.isArray(e)?e.map(r=>[r,null]):Object.entries(e).map(([r,o])=>[Number(r),o]),s={};for(const[r,o]of t){const a=m(r),u=a?.type??"InternalServerError",p=r>=500||a?.expose===!1?c:a?.defaultMessage??c;s[String(r)]=l(o??p,{type:u,message:p})}return s}n(d,"errorResponses");export{d as errorResponses,l as exceptionResponse};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/openApiErrors.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * OpenAPI descriptions of the `{Exception:{Type,Message}}` envelope, for a\n * chanfana route's `responses:`.\n *\n * Converged from AWS-AccessBridge's `packages/shared/src/schema/exceptionResponses.ts`,\n * which replaced 170 hand-copied literals across 46 endpoint files. Plain JSON\n * Schema objects, so this module stays framework-free and the root barrel can\n * carry it.\n *\n * Two changes from the source:\n *\n * - The example `Type` is the **catalog** name the server actually emits\n * (`BadRequest`, not `BadRequestError`). AWS's examples named the class, so\n * `/docs` documented a value no response ever carried.\n * - A 5xx example is always the masked message — the only one a 5xx carries.\n *\n * Both are `type` aliases rather than interfaces, deliberately: chanfana's\n * `SchemaObject` carries an `[x-<string>]` index signature, and only a type\n * alias is assignable to one.\n */\nimport { CATALOG } from '@rexezuge/errors';\nimport type { HttpErrorType } from '@rexezuge/errors';\nimport { INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\n\ntype ExceptionSchema = {\n type: 'object';\n properties: {\n Exception: {\n type: 'object';\n properties: {\n Type: { type: 'string'; description: string; example: string };\n Message: { type: 'string'; description: string; example: string };\n };\n };\n };\n};\n\ntype ExceptionResponse = {\n description: string;\n content: { 'application/json': { schema: ExceptionSchema } };\n};\n\ninterface ExceptionSchemaOptions {\n /**\n The `Type` example. Defaults to the catalog name for the status.\n */\n type?: string;\n /**\n The `Message` example. Should say what actually goes wrong on this route.\n */\n message?: string;\n}\n\n/**\nOne `responses` entry for the envelope.\n*/\nfunction exceptionResponse(description: string, options: ExceptionSchemaOptions = {}): ExceptionResponse {\n return {\n description,\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: {\n Exception: {\n type: 'object',\n properties: {\n Type: { type: 'string', description: 'Stable machine-readable error type.', example: options.type ?? 'BadRequest' },\n Message: {\n type: 'string',\n description: 'Human-readable detail about the error.',\n example: options.message ?? CATALOG.BadRequest.defaultMessage,\n },\n },\n },\n },\n },\n },\n },\n };\n}\n\n/**\nThe catalog entry for a status, so a caller names a number and gets its type.\n*/\nfunction catalogEntry(status: number): { type: HttpErrorType; defaultMessage: string; expose: boolean } | null {\n for (const [type, definition] of Object.entries(CATALOG) as [HttpErrorType, (typeof CATALOG)[HttpErrorType]][]) {\n if (definition.status === status) return { type, defaultMessage: definition.defaultMessage, expose: definition.expose };\n }\n return null;\n}\n\n/**\n * A `responses` map for several statuses at once:\n *\n * ```ts\n * schema = {\n * responses: {\n * '200': { description: 'The volume', ...contentJson(Volume) },\n * ...errorResponses({ 400: 'Invalid name', 404: 'No such volume' }),\n * ...errorResponses([401, 500]),\n * },\n * };\n * ```\n *\n * A list uses each catalog default as the description; a record names it. An\n * uncatalogued status is described as `InternalServerError`, because that is\n * what the mapper emits for one.\n */\nfunction errorResponses(statuses: readonly number[] | Readonly<Record<number, string>>): Record<string, ExceptionResponse> {\n const entries: [number, string | null][] = Array.isArray(statuses)\n ? (statuses as readonly number[]).map((status) => [status, null])\n : Object.entries(statuses as Readonly<Record<number, string>>).map(([status, description]) => [Number(status), description]);\n const responses: Record<string, ExceptionResponse> = {};\n for (const [status, description] of entries) {\n const entry = catalogEntry(status);\n const type = entry?.type ?? 'InternalServerError';\n const masked = status >= 500 || entry?.expose === false;\n const message = masked ? INTERNAL_SERVER_MESSAGE : (entry?.defaultMessage ?? INTERNAL_SERVER_MESSAGE);\n responses[String(status)] = exceptionResponse(description ?? message, { type, message });\n }\n return responses;\n}\n\nexport { errorResponses, exceptionResponse };\nexport type { ExceptionResponse, ExceptionSchema, ExceptionSchemaOptions };\n"],
|
|
5
|
+
"mappings": "+EAoBA,OAAS,WAAAA,MAAe,mBAExB,OAAS,2BAAAC,MAA+B,mBAkCxC,SAASC,EAAkBC,EAAqBC,EAAkC,CAAA,EAAE,CAClF,MAAO,CACL,YAAAD,EACA,QAAS,CACP,mBAAoB,CAClB,OAAQ,CACN,KAAM,SACN,WAAY,CACV,UAAW,CACT,KAAM,SACN,WAAY,CACV,KAAM,CAAE,KAAM,SAAU,YAAa,sCAAuC,QAASC,EAAQ,MAAQ,YAAY,EACjH,QAAS,CACP,KAAM,SACN,YAAa,yCACb,QAASA,EAAQ,SAAWJ,EAAQ,WAAW,sBASjE,CAxBSK,EAAAH,EAAA,qBA6BT,SAASI,EAAaC,EAAc,CAClC,SAAW,CAACC,EAAMC,CAAU,IAAK,OAAO,QAAQT,CAAO,EACrD,GAAIS,EAAW,SAAWF,EAAQ,MAAO,CAAE,KAAAC,EAAM,eAAgBC,EAAW,eAAgB,OAAQA,EAAW,MAAM,EAEvH,OAAO,IACT,CALSJ,EAAAC,EAAA,gBAwBT,SAASI,EAAeC,EAA8D,CACpF,MAAMC,EAAqC,MAAM,QAAQD,CAAQ,EAC5DA,EAA+B,IAAKJ,GAAW,CAACA,EAAQ,IAAI,CAAC,EAC9D,OAAO,QAAQI,CAA4C,EAAE,IAAI,CAAC,CAACJ,EAAQJ,CAAW,IAAM,CAAC,OAAOI,CAAM,EAAGJ,CAAW,CAAC,EACvHU,EAA+C,CAAA,EACrD,SAAW,CAACN,EAAQJ,CAAW,IAAKS,EAAS,CAC3C,MAAME,EAAQR,EAAaC,CAAM,EAC3BC,EAAOM,GAAO,MAAQ,sBAEtBC,EADSR,GAAU,KAAOO,GAAO,SAAW,GACzBb,EAA2Ba,GAAO,gBAAkBb,EAC7EY,EAAU,OAAON,CAAM,CAAC,EAAIL,EAAkBC,GAAeY,EAAS,CAAE,KAAAP,EAAM,QAAAO,CAAO,CAAE,CACzF,CACA,OAAOF,CACT,CAbSR,EAAAK,EAAA",
|
|
6
|
+
"names": ["CATALOG", "INTERNAL_SERVER_MESSAGE", "exceptionResponse", "description", "options", "__name", "catalogEntry", "status", "type", "definition", "errorResponses", "statuses", "entries", "responses", "entry", "message"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { ServiceError } from '@rexezuge/errors';
|
|
2
|
+
/**
|
|
3
|
+
The methods a family API answers; anything else is a 405 before routing.
|
|
4
|
+
*/
|
|
5
|
+
declare const DEFAULT_ALLOWED_METHODS: readonly string[];
|
|
6
|
+
/**
|
|
7
|
+
One MiB — the ceiling every converged route base used for a JSON body.
|
|
8
|
+
*/
|
|
9
|
+
declare const DEFAULT_MAX_BODY_BYTES = 1048576;
|
|
10
|
+
interface OriginGuardOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Origins trusted in addition to the request's own (a Pages origin, a custom
|
|
13
|
+
* domain). Entries are normalised through `URL`; an unparseable one is dropped.
|
|
14
|
+
*/
|
|
15
|
+
allowedOrigins?: readonly string[];
|
|
16
|
+
/**
|
|
17
|
+
* Admit a mutation that carries neither `Origin` nor `Referer`. Off by default:
|
|
18
|
+
* see the file header. Turn it on only for a surface that also serves
|
|
19
|
+
* non-browser callers with a non-cookie credential.
|
|
20
|
+
*/
|
|
21
|
+
allowMissingOrigin?: boolean;
|
|
22
|
+
}
|
|
23
|
+
declare function isMutatingMethod(method: string): boolean;
|
|
24
|
+
/**
|
|
25
|
+
The origin a request claims: `Origin`, else the `Referer`'s origin, else `null`.
|
|
26
|
+
*/
|
|
27
|
+
declare function requestOrigin(request: Request): string | null;
|
|
28
|
+
/**
|
|
29
|
+
* The CSRF guard for a cookie-authenticated surface. Safe methods pass; a
|
|
30
|
+
* mutation passes only when it is not declared cross-site and its origin is
|
|
31
|
+
* allow-listed.
|
|
32
|
+
*/
|
|
33
|
+
declare function checkOrigin(request: Request, options?: OriginGuardOptions): ServiceError | null;
|
|
34
|
+
/**
|
|
35
|
+
A method outside the allow-list is a 405, before any route or auth runs.
|
|
36
|
+
*/
|
|
37
|
+
declare function checkMethod(method: string, allowed?: readonly string[]): ServiceError | null;
|
|
38
|
+
/**
|
|
39
|
+
* A mutating request with a body must declare one of `allowed` (default
|
|
40
|
+
* `application/json`). `text/plain` and form encodings are what a cross-site
|
|
41
|
+
* form can send, so refusing them also closes content-type confusion.
|
|
42
|
+
*/
|
|
43
|
+
declare function checkContentType(request: Request, allowed?: readonly string[]): ServiceError | null;
|
|
44
|
+
/**
|
|
45
|
+
* A declared `Content-Length` over the ceiling is a 413 before the body is read.
|
|
46
|
+
* This is the cheap half; the `/hono` middleware also caps the stream, because a
|
|
47
|
+
* chunked request declares nothing.
|
|
48
|
+
*/
|
|
49
|
+
declare function checkContentLength(request: Request, maxBytes?: number): ServiceError | null;
|
|
50
|
+
export { checkContentLength, checkContentType, checkMethod, checkOrigin, isMutatingMethod, requestOrigin, DEFAULT_ALLOWED_METHODS, DEFAULT_MAX_BODY_BYTES, };
|
|
51
|
+
export type { OriginGuardOptions };
|
|
52
|
+
//# sourceMappingURL=requestGuards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requestGuards.d.ts","sourceRoot":"","sources":["../src/requestGuards.ts"],"names":[],"mappings":"AA6BA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAIrD;;EAEE;AACF,QAAA,MAAM,uBAAuB,EAAE,SAAS,MAAM,EAAiE,CAAC;AAEhH;;EAEE;AACF,QAAA,MAAM,sBAAsB,UAAY,CAAC;AAIzC,UAAU,kBAAkB;IAC1B;;;OAGG;IACH,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,iBAAS,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAEjD;AAYD;;EAEE;AACF,iBAAS,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAEtD;AAED;;;;GAIG;AACH,iBAAS,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,kBAAuB,GAAG,YAAY,GAAG,IAAI,CAqB5F;AAED;;EAEE;AACF,iBAAS,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,SAAS,MAAM,EAA4B,GAAG,YAAY,GAAG,IAAI,CAG9G;AAYD;;;;GAIG;AACH,iBAAS,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,SAAS,MAAM,EAAyB,GAAG,YAAY,GAAG,IAAI,CAIlH;AAED;;;;GAIG;AACH,iBAAS,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,GAAE,MAA+B,GAAG,YAAY,GAAG,IAAI,CAK5G;AAED,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,sBAAsB,GACvB,CAAC;AACF,YAAY,EAAE,kBAAkB,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var p=Object.defineProperty;var o=(n,e)=>p(n,"name",{value:e,configurable:!0});import{ForbiddenError as c,MethodNotAllowedError as m,PayloadTooLargeError as w,UnsupportedMediaTypeError as T}from"@rexezuge/errors";const O=new Set(["GET","HEAD","OPTIONS"]),h=["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"],f=1048576,s="Cross-origin request rejected.";function u(n){return!O.has(n.toUpperCase())}o(u,"isMutatingMethod");function i(n){const e=n?.trim()??"";if(e==="")return null;try{return new URL(e).origin}catch{return null}}o(i,"originOf");function g(n){return i(n.headers.get("origin"))??i(n.headers.get("referer"))}o(g,"requestOrigin");function S(n,e={}){if(!u(n.method))return null;const t=n.headers.get("sec-fetch-site")?.trim().toLowerCase();if(t!==void 0&&t!=="same-origin"&&t!=="none")return new c(s);const r=g(n);if(r===null)return e.allowMissingOrigin?null:new c(s);const l=new Set,a=i(n.url);a!==null&&l.add(a);for(const E of e.allowedOrigins??[]){const d=i(E);d!==null&&l.add(d)}return l.has(r)?null:new c(s)}o(S,"checkOrigin");function C(n,e=h){const t=n.toUpperCase();return e.some(r=>r.toUpperCase()===t)?null:new m}o(C,"checkMethod");function L(n){const e=n.headers.get("content-length");return e===null||e.trim()!=="0"}o(L,"hasBody");function A(n,e=["application/json"]){if(!u(n.method)||n.method.toUpperCase()==="DELETE"||!L(n))return null;const t=(n.headers.get("content-type")??"").split(";",1)[0]?.trim().toLowerCase()??"";return e.some(r=>r.toLowerCase()===t)?null:new T}o(A,"checkContentType");function D(n,e=f){const t=n.headers.get("content-length");if(t===null)return null;const r=Number(t.trim());return Number.isFinite(r)&&r>e?new w:null}o(D,"checkContentLength");export{h as DEFAULT_ALLOWED_METHODS,f as DEFAULT_MAX_BODY_BYTES,D as checkContentLength,A as checkContentType,C as checkMethod,S as checkOrigin,u as isMutatingMethod,g as requestOrigin};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/requestGuards.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Request hardening and the CSRF/origin guard, framework-free.\n *\n * Converged from four shapes of the same idea:\n *\n * - AWS-AccessBridge `apps/api/src/middleware/RequestGuards.ts` — `Sec-Fetch-Site`\n * must be `same-origin`/`none`, and a mutating request with a body must declare\n * `application/json` (the one type a cross-site HTML form cannot send).\n * - Image-Host `apps/api/src/middleware/MiddlewareHandlers.ts` — `Origin`, else\n * `Referer`, must equal the request origin; **both absent is a rejection**.\n * - Pigeongram `packages/backend-services/src/session/origin.ts` — the allow-list\n * is the request origin plus configured origins (`ALLOWED_ORIGINS`,\n * `PAGES_ORIGIN`), and `Sec-Fetch-Site` alone never *admits* a request: a client\n * controls it as much as `Origin`.\n * - The `MAX_JSON_BODY_BYTES` ceilings in the Durable-DAV / Edge-Git route bases.\n *\n * Every check answers a `ServiceError` or `null` rather than a `Response`, so the\n * caller's error boundary renders it in its own dialect — the `/hono` middleware\n * throws it into `app.onError`, a Durable Object maps it itself.\n *\n * ## Why the strict defaults\n *\n * Cloudflare Access cookies are `SameSite=None` by design (they survive the\n * login redirect), so the cookie is not a CSRF defence. A browser always sends\n * `Origin` or `Referer` on a cross-origin mutation, so their joint absence means\n * a non-browser caller — which a cookie-authenticated surface does not serve\n * unless the app opts in with `allowMissingOrigin`.\n */\nimport { ForbiddenError, MethodNotAllowedError, PayloadTooLargeError, UnsupportedMediaTypeError } from '@rexezuge/errors';\nimport type { ServiceError } from '@rexezuge/errors';\n\nconst SAFE_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\nThe methods a family API answers; anything else is a 405 before routing.\n*/\nconst DEFAULT_ALLOWED_METHODS: readonly string[] = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];\n\n/**\nOne MiB — the ceiling every converged route base used for a JSON body.\n*/\nconst DEFAULT_MAX_BODY_BYTES = 1_048_576;\n\nconst CROSS_SITE_MESSAGE = 'Cross-origin request rejected.';\n\ninterface OriginGuardOptions {\n /**\n * Origins trusted in addition to the request's own (a Pages origin, a custom\n * domain). Entries are normalised through `URL`; an unparseable one is dropped.\n */\n allowedOrigins?: readonly string[];\n /**\n * Admit a mutation that carries neither `Origin` nor `Referer`. Off by default:\n * see the file header. Turn it on only for a surface that also serves\n * non-browser callers with a non-cookie credential.\n */\n allowMissingOrigin?: boolean;\n}\n\nfunction isMutatingMethod(method: string): boolean {\n return !SAFE_METHODS.has(method.toUpperCase());\n}\n\nfunction originOf(value: string | null): string | null {\n const trimmed = value?.trim() ?? '';\n if (trimmed === '') return null;\n try {\n return new URL(trimmed).origin;\n } catch {\n return null;\n }\n}\n\n/**\nThe origin a request claims: `Origin`, else the `Referer`'s origin, else `null`.\n*/\nfunction requestOrigin(request: Request): string | null {\n return originOf(request.headers.get('origin')) ?? originOf(request.headers.get('referer'));\n}\n\n/**\n * The CSRF guard for a cookie-authenticated surface. Safe methods pass; a\n * mutation passes only when it is not declared cross-site and its origin is\n * allow-listed.\n */\nfunction checkOrigin(request: Request, options: OriginGuardOptions = {}): ServiceError | null {\n if (!isMutatingMethod(request.method)) return null;\n\n // A rejection signal only, never an admission: `same-site` is a sibling\n // subdomain, which is exactly the attacker a CSRF guard exists to stop.\n const fetchSite = request.headers.get('sec-fetch-site')?.trim().toLowerCase();\n if (fetchSite !== undefined && fetchSite !== 'same-origin' && fetchSite !== 'none') {\n return new ForbiddenError(CROSS_SITE_MESSAGE);\n }\n\n const origin = requestOrigin(request);\n if (origin === null) return options.allowMissingOrigin ? null : new ForbiddenError(CROSS_SITE_MESSAGE);\n\n const allowed = new Set<string>();\n const own = originOf(request.url);\n if (own !== null) allowed.add(own);\n for (const entry of options.allowedOrigins ?? []) {\n const normalized = originOf(entry);\n if (normalized !== null) allowed.add(normalized);\n }\n return allowed.has(origin) ? null : new ForbiddenError(CROSS_SITE_MESSAGE);\n}\n\n/**\nA method outside the allow-list is a 405, before any route or auth runs.\n*/\nfunction checkMethod(method: string, allowed: readonly string[] = DEFAULT_ALLOWED_METHODS): ServiceError | null {\n const upper = method.toUpperCase();\n return allowed.some((entry) => entry.toUpperCase() === upper) ? null : new MethodNotAllowedError();\n}\n\n/**\n * Whether a request carries a body, answered conservatively: only an explicit\n * `Content-Length: 0` is body-less. A request with neither framing header has an\n * *unknown* body, not an empty one (AWS-AccessBridge's rule).\n */\nfunction hasBody(request: Request): boolean {\n const length = request.headers.get('content-length');\n return length === null || length.trim() !== '0';\n}\n\n/**\n * A mutating request with a body must declare one of `allowed` (default\n * `application/json`). `text/plain` and form encodings are what a cross-site\n * form can send, so refusing them also closes content-type confusion.\n */\nfunction checkContentType(request: Request, allowed: readonly string[] = ['application/json']): ServiceError | null {\n if (!isMutatingMethod(request.method) || request.method.toUpperCase() === 'DELETE' || !hasBody(request)) return null;\n const declared = (request.headers.get('content-type') ?? '').split(';', 1)[0]?.trim().toLowerCase() ?? '';\n return allowed.some((type) => type.toLowerCase() === declared) ? null : new UnsupportedMediaTypeError();\n}\n\n/**\n * A declared `Content-Length` over the ceiling is a 413 before the body is read.\n * This is the cheap half; the `/hono` middleware also caps the stream, because a\n * chunked request declares nothing.\n */\nfunction checkContentLength(request: Request, maxBytes: number = DEFAULT_MAX_BODY_BYTES): ServiceError | null {\n const raw = request.headers.get('content-length');\n if (raw === null) return null;\n const length = Number(raw.trim());\n return Number.isFinite(length) && length > maxBytes ? new PayloadTooLargeError() : null;\n}\n\nexport {\n checkContentLength,\n checkContentType,\n checkMethod,\n checkOrigin,\n isMutatingMethod,\n requestOrigin,\n DEFAULT_ALLOWED_METHODS,\n DEFAULT_MAX_BODY_BYTES,\n};\nexport type { OriginGuardOptions };\n"],
|
|
5
|
+
"mappings": "+EA4BA,OAAS,kBAAAA,EAAgB,yBAAAC,EAAuB,wBAAAC,EAAsB,6BAAAC,MAAiC,mBAGvG,MAAMC,EAAoC,IAAI,IAAI,CAAC,MAAO,OAAQ,SAAS,CAAC,EAKtEC,EAA6C,CAAC,MAAO,OAAQ,OAAQ,MAAO,QAAS,SAAU,SAAS,EAKxGC,EAAyB,QAEzBC,EAAqB,iCAgB3B,SAASC,EAAiBC,EAAc,CACtC,MAAO,CAACL,EAAa,IAAIK,EAAO,YAAW,CAAE,CAC/C,CAFSC,EAAAF,EAAA,oBAIT,SAASG,EAASC,EAAoB,CACpC,MAAMC,EAAUD,GAAO,KAAI,GAAM,GACjC,GAAIC,IAAY,GAAI,OAAO,KAC3B,GAAI,CACF,OAAO,IAAI,IAAIA,CAAO,EAAE,MAC1B,MAAQ,CACN,OAAO,IACT,CACF,CARSH,EAAAC,EAAA,YAaT,SAASG,EAAcC,EAAgB,CACrC,OAAOJ,EAASI,EAAQ,QAAQ,IAAI,QAAQ,CAAC,GAAKJ,EAASI,EAAQ,QAAQ,IAAI,SAAS,CAAC,CAC3F,CAFSL,EAAAI,EAAA,iBAST,SAASE,EAAYD,EAAkBE,EAA8B,CAAA,EAAE,CACrE,GAAI,CAACT,EAAiBO,EAAQ,MAAM,EAAG,OAAO,KAI9C,MAAMG,EAAYH,EAAQ,QAAQ,IAAI,gBAAgB,GAAG,KAAI,EAAG,YAAW,EAC3E,GAAIG,IAAc,QAAaA,IAAc,eAAiBA,IAAc,OAC1E,OAAO,IAAIlB,EAAeO,CAAkB,EAG9C,MAAMY,EAASL,EAAcC,CAAO,EACpC,GAAII,IAAW,KAAM,OAAOF,EAAQ,mBAAqB,KAAO,IAAIjB,EAAeO,CAAkB,EAErG,MAAMa,EAAU,IAAI,IACdC,EAAMV,EAASI,EAAQ,GAAG,EAC5BM,IAAQ,MAAMD,EAAQ,IAAIC,CAAG,EACjC,UAAWC,KAASL,EAAQ,gBAAkB,CAAA,EAAI,CAChD,MAAMM,EAAaZ,EAASW,CAAK,EAC7BC,IAAe,MAAMH,EAAQ,IAAIG,CAAU,CACjD,CACA,OAAOH,EAAQ,IAAID,CAAM,EAAI,KAAO,IAAInB,EAAeO,CAAkB,CAC3E,CArBSG,EAAAM,EAAA,eA0BT,SAASQ,EAAYf,EAAgBW,EAA6Bf,EAAuB,CACvF,MAAMoB,EAAQhB,EAAO,YAAW,EAChC,OAAOW,EAAQ,KAAME,GAAUA,EAAM,YAAW,IAAOG,CAAK,EAAI,KAAO,IAAIxB,CAC7E,CAHSS,EAAAc,EAAA,eAUT,SAASE,EAAQX,EAAgB,CAC/B,MAAMY,EAASZ,EAAQ,QAAQ,IAAI,gBAAgB,EACnD,OAAOY,IAAW,MAAQA,EAAO,KAAI,IAAO,GAC9C,CAHSjB,EAAAgB,EAAA,WAUT,SAASE,EAAiBb,EAAkBK,EAA6B,CAAC,kBAAkB,EAAC,CAC3F,GAAI,CAACZ,EAAiBO,EAAQ,MAAM,GAAKA,EAAQ,OAAO,YAAW,IAAO,UAAY,CAACW,EAAQX,CAAO,EAAG,OAAO,KAChH,MAAMc,GAAYd,EAAQ,QAAQ,IAAI,cAAc,GAAK,IAAI,MAAM,IAAK,CAAC,EAAE,CAAC,GAAG,KAAI,EAAG,YAAW,GAAM,GACvG,OAAOK,EAAQ,KAAMU,GAASA,EAAK,YAAW,IAAOD,CAAQ,EAAI,KAAO,IAAI1B,CAC9E,CAJSO,EAAAkB,EAAA,oBAWT,SAASG,EAAmBhB,EAAkBiB,EAAmB1B,EAAsB,CACrF,MAAM2B,EAAMlB,EAAQ,QAAQ,IAAI,gBAAgB,EAChD,GAAIkB,IAAQ,KAAM,OAAO,KACzB,MAAMN,EAAS,OAAOM,EAAI,KAAI,CAAE,EAChC,OAAO,OAAO,SAASN,CAAM,GAAKA,EAASK,EAAW,IAAI9B,EAAyB,IACrF,CALSQ,EAAAqB,EAAA",
|
|
6
|
+
"names": ["ForbiddenError", "MethodNotAllowedError", "PayloadTooLargeError", "UnsupportedMediaTypeError", "SAFE_METHODS", "DEFAULT_ALLOWED_METHODS", "DEFAULT_MAX_BODY_BYTES", "CROSS_SITE_MESSAGE", "isMutatingMethod", "method", "__name", "originOf", "value", "trimmed", "requestOrigin", "request", "checkOrigin", "options", "fetchSite", "origin", "allowed", "own", "entry", "normalized", "checkMethod", "upper", "hasBody", "length", "checkContentType", "declared", "type", "checkContentLength", "maxBytes", "raw"]
|
|
7
|
+
}
|
package/dist/routeBase.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routeBase.d.ts","sourceRoot":"","sources":["../src/routeBase.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"routeBase.d.ts","sourceRoot":"","sources":["../src/routeBase.ts"],"names":[],"mappings":"AAkCA;;EAEE;AACF,UAAU,YAAY;IACpB,GAAG,EAAE;QAAE,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;QAAC,GAAG,EAAE,OAAO,CAAA;KAAE,CAAC;IAChD,GAAG,EAAE,OAAO,CAAC;IACb,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC;IACjF;;MAEE;IACF,GAAG,CAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CAC5B;AAED,KAAK,YAAY,GAAG,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAE3D,UAAU,mBAAmB;IAC3B;;MAEE;IACF,OAAO,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,YAAY,GAAG,QAAQ,CAAC;CACrD;AAMD;;;;;;;GAOG;AACH,QAAA,MAAM,SAAS;IACb;;;;;;OAMG;2BACe,YAAY,KAAG,OAAO,CAAC,OAAO,CAAC;IAQjD;;MAEE;oCACmB,OAAO,SAAS,MAAM,KAAG,MAAM;IAOpD;;MAEE;sCACqB,OAAO,KAAK,YAAY,YAAY,mBAAmB,KAAG,QAAQ;CAGjF,CAAC;AAEX;;;;;;GAMG;AACH,iBAAS,kBAAkB,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,GAAE,mBAAwB,GAAG,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,QAAQ,CAAC,CAQ3H;AAED,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC;AACzC,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,CAAC"}
|
package/dist/routeBase.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var i=Object.defineProperty;var e=(r,
|
|
1
|
+
var i=Object.defineProperty;var e=(r,n)=>i(r,"name",{value:n,configurable:!0});import{BadRequestError as u}from"@rexezuge/errors";import{errorResponseFromUnknown as a}from"./ErrorMapper.js";function o(r,n){return a(r,n.json.bind(n))}e(o,"defaultOnError");const c={async readJson(r){try{return await r.req.json()}catch{return{}}},requireString(r,n){if(typeof r!="string"||r.trim()==="")throw new u(`\`${n}\` is required and must be a non-empty string.`);return r},toErrorResponse(r,n,t){return(t?.onError??o)(r,n)}};function m(r,n={}){return async t=>{try{return await r(t)}catch(s){return(n.onError??o)(s,t)}}}e(m,"createRouteHandler");export{c as BaseRoute,m as createRouteHandler};
|
package/dist/routeBase.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/routeBase.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Shared statics for Hono route handlers.\n *\n * Converged from `endpoints/IBaseRoute.ts` / `endpoints/BaseRoute.ts` in the\n * nine full-framework repos, which hold **two incompatible shapes**: a Hono\n * `Response`-returning base class, and a namespace of statics. Both survive here,\n * because the decision of which to use is genuinely per-repo — but the *parts*\n * they share no longer do.\n *\n * ## Why a namespace and not a base class\n *\n * Durable-DAV's Template Method (`abstract handleRequest` + `handle()` owning the\n * try/catch) had **zero** subclasses — `VolumeScopedRoute` reimplements the same\n * try/catch against the same `toErrorResponse` — so it advertised an inheritance\n * contract nothing was using, while its own doc comment claimed handlers \"stop\n * duplicating\" error mapping.\n *\n * So the shared surface is a namespace of statics. A repo that wants the Template\n * Method takes {@link createRouteHandler}; a repo that does not takes the statics\n * directly. Neither pays for the other's abstraction.\n *\n * ##
|
|
5
|
-
"mappings": "+
|
|
6
|
-
"names": ["BadRequestError", "
|
|
4
|
+
"sourcesContent": ["/**\n * Shared statics for Hono route handlers.\n *\n * Converged from `endpoints/IBaseRoute.ts` / `endpoints/BaseRoute.ts` in the\n * nine full-framework repos, which hold **two incompatible shapes**: a Hono\n * `Response`-returning base class, and a namespace of statics. Both survive here,\n * because the decision of which to use is genuinely per-repo — but the *parts*\n * they share no longer do.\n *\n * ## Why a namespace and not a base class\n *\n * Durable-DAV's Template Method (`abstract handleRequest` + `handle()` owning the\n * try/catch) had **zero** subclasses — `VolumeScopedRoute` reimplements the same\n * try/catch against the same `toErrorResponse` — so it advertised an inheritance\n * contract nothing was using, while its own doc comment claimed handlers \"stop\n * duplicating\" error mapping.\n *\n * So the shared surface is a namespace of statics. A repo that wants the Template\n * Method takes {@link createRouteHandler}; a repo that does not takes the statics\n * directly. Neither pays for the other's abstraction.\n *\n * ## The chanfana half lives in `/hono`\n *\n * Six of the nine repos build routes as chanfana `OpenAPIRoute` subclasses. That\n * shape is converged as `FamilyRoute` in `@rexezuge/http/hono` (from the seven\n * `endpoints/IBaseRoute.ts` copies): the closed `handle()` validates through the\n * route's own chanfana schema, runs `handleRequest`, and maps failures through\n * the same mapper as this module. It lives in the subpath because it imports\n * `chanfana`, and this barrel stays framework-free. The statics here remain for\n * plain-Hono and bare-`Request` handlers.\n */\nimport { BadRequestError } from '@rexezuge/errors';\nimport { errorResponseFromUnknown } from './ErrorMapper.ts';\n\n/**\nThe slice of a Hono context a route handler reads.\n*/\ninterface RouteContext {\n req: { json(): Promise<unknown>; raw: Request };\n env: unknown;\n json(body: unknown, status?: number, headers?: Record<string, string>): Response;\n /**\n Optional request scope, when the repo uses DI.\n */\n get?(key: string): unknown;\n}\n\ntype RouteHandler = (c: RouteContext) => Promise<Response>;\n\ninterface RouteHandlerOptions {\n /**\n A repo-specific mapper. Defaults to the canonical `{Exception:{…}}` dialect.\n */\n onError?(error: unknown, c: RouteContext): Response;\n}\n\nfunction defaultOnError(error: unknown, c: RouteContext): Response {\n return errorResponseFromUnknown(error, c.json.bind(c));\n}\n\n/**\n * The shared statics.\n *\n * `readJson` is deliberately total: a malformed body yields `{}` rather than\n * throwing, because a handler that wants to reject a malformed body validates it\n * and gets a 400 through the normal path. A parse error thrown from here would\n * bypass whatever validation error message the repo has.\n */\nconst BaseRoute = {\n /**\n * Read the JSON body, or `{}`.\n *\n * Bounded by the caller's schema, not here: an unbounded `req.json()` on a\n * worker is a memory ceiling, and each repo's limit is its own\n * `MAX_JSON_BODY_BYTES`.\n */\n async readJson(c: RouteContext): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n return {};\n }\n },\n\n /**\n A required string field, or the error that says which field was missing.\n */\n requireString(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new BadRequestError(`\\`${field}\\` is required and must be a non-empty string.`);\n }\n return value;\n },\n\n /**\n Map a caught value to a response, using the repo's dialect if it declared one.\n */\n toErrorResponse(error: unknown, c: RouteContext, options?: RouteHandlerOptions): Response {\n return (options?.onError ?? defaultOnError)(error, c);\n },\n} as const;\n\n/**\n * Build a Template-Method route handler.\n *\n * The shape Edge-Git and Edge-Sonic converged on: the handler owns only its\n * domain work, and the base owns the try/catch so a private repo's existence and\n * a 5xx's message are decided in exactly one place per app.\n */\nfunction createRouteHandler(handle: RouteHandler, options: RouteHandlerOptions = {}): (c: RouteContext) => Promise<Response> {\n return async (c: RouteContext): Promise<Response> => {\n try {\n return await handle(c);\n } catch (error: unknown) {\n return (options.onError ?? defaultOnError)(error, c);\n }\n };\n}\n\nexport { BaseRoute, createRouteHandler };\nexport type { RouteContext, RouteHandler, RouteHandlerOptions };\n"],
|
|
5
|
+
"mappings": "+EA+BA,OAAS,mBAAAA,MAAuB,mBAChC,OAAS,4BAAAC,MAAgC,mBAwBzC,SAASC,EAAeC,EAAgBC,EAAe,CACrD,OAAOH,EAAyBE,EAAOC,EAAE,KAAK,KAAKA,CAAC,CAAC,CACvD,CAFSC,EAAAH,EAAA,kBAYT,MAAMI,EAAY,CAQhB,MAAM,SAASF,EAAe,CAC5B,GAAI,CACF,OAAO,MAAMA,EAAE,IAAI,KAAI,CACzB,MAAQ,CACN,MAAO,CAAA,CACT,CACF,EAKA,cAAcG,EAAgBC,EAAa,CACzC,GAAI,OAAOD,GAAU,UAAYA,EAAM,KAAI,IAAO,GAChD,MAAM,IAAIP,EAAgB,KAAKQ,CAAK,gDAAgD,EAEtF,OAAOD,CACT,EAKA,gBAAgBJ,EAAgBC,EAAiBK,EAA6B,CAC5E,OAAQA,GAAS,SAAWP,GAAgBC,EAAOC,CAAC,CACtD,GAUF,SAASM,EAAmBC,EAAsBF,EAA+B,CAAA,EAAE,CACjF,MAAO,OAAOL,GAAsC,CAClD,GAAI,CACF,OAAO,MAAMO,EAAOP,CAAC,CACvB,OAASD,EAAgB,CACvB,OAAQM,EAAQ,SAAWP,GAAgBC,EAAOC,CAAC,CACrD,CACF,CACF,CARSC,EAAAK,EAAA",
|
|
6
|
+
"names": ["BadRequestError", "errorResponseFromUnknown", "defaultOnError", "error", "c", "__name", "BaseRoute", "value", "field", "options", "createRouteHandler", "handle"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@rexezuge/http/testing` — test seams, kept off the production barrel.
|
|
3
|
+
*
|
|
4
|
+
* The limiter state these reach is module-global, so a suite that exercises
|
|
5
|
+
* `rateLimit` resets it between cases. Nothing here belongs in a request path.
|
|
6
|
+
*/
|
|
7
|
+
export { getRateLimitBucketCountForTests, resetRateLimitForTests } from './rateLimit.ts';
|
|
8
|
+
//# sourceMappingURL=testing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,+BAA+B,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getRateLimitBucketCountForTests as o,resetRateLimitForTests as r}from"./rateLimit.js";export{o as getRateLimitBucketCountForTests,r as resetRateLimitForTests};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/testing.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * `@rexezuge/http/testing` — test seams, kept off the production barrel.\n *\n * The limiter state these reach is module-global, so a suite that exercises\n * `rateLimit` resets it between cases. Nothing here belongs in a request path.\n */\n\nexport { getRateLimitBucketCountForTests, resetRateLimitForTests } from './rateLimit.ts';\n"],
|
|
5
|
+
"mappings": "AAOA,OAAS,mCAAAA,EAAiC,0BAAAC,MAA8B",
|
|
6
|
+
"names": ["getRateLimitBucketCountForTests", "resetRateLimitForTests"]
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/http",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -16,6 +16,14 @@
|
|
|
16
16
|
"types": "./dist/index.d.ts",
|
|
17
17
|
"default": "./dist/index.js"
|
|
18
18
|
},
|
|
19
|
+
"./testing": {
|
|
20
|
+
"types": "./dist/testing.d.ts",
|
|
21
|
+
"default": "./dist/testing.js"
|
|
22
|
+
},
|
|
23
|
+
"./hono": {
|
|
24
|
+
"types": "./dist/hono/index.d.ts",
|
|
25
|
+
"default": "./dist/hono/index.js"
|
|
26
|
+
},
|
|
19
27
|
"./*": {
|
|
20
28
|
"types": "./dist/*.d.ts",
|
|
21
29
|
"default": "./dist/*.js"
|
|
@@ -25,21 +33,35 @@
|
|
|
25
33
|
"dist"
|
|
26
34
|
],
|
|
27
35
|
"dependencies": {
|
|
28
|
-
"chanfana": "^3.4.0",
|
|
29
|
-
"hono": "^4.13.13",
|
|
30
36
|
"jose": "^6.2.12",
|
|
31
|
-
"@rexezuge/errors": "1.
|
|
32
|
-
"@rexezuge/shared": "1.
|
|
37
|
+
"@rexezuge/errors": "1.11.0",
|
|
38
|
+
"@rexezuge/shared": "1.11.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"chanfana": "^3.4.0",
|
|
42
|
+
"hono": "^4.13.13"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"chanfana": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"hono": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
33
51
|
},
|
|
34
52
|
"devDependencies": {
|
|
35
53
|
"@types/node": "26.6.4",
|
|
54
|
+
"chanfana": "^3.4.0",
|
|
55
|
+
"hono": "^4.13.13",
|
|
36
56
|
"typescript": "6.0.3",
|
|
37
|
-
"vitest": "4.1.11"
|
|
57
|
+
"vitest": "4.1.11",
|
|
58
|
+
"zod": "^4.6.5"
|
|
38
59
|
},
|
|
39
|
-
"description": "
|
|
60
|
+
"description": "Edge HTTP layer for the Rexezuge family: framework-free rate limiter, security headers, request guards, Cloudflare Access auth and error mapper, plus the Hono/chanfana app kernel at @rexezuge/http/hono.",
|
|
40
61
|
"scripts": {
|
|
41
62
|
"build": "tsc -p tsconfig.json && node ../../scripts/minify-dist.mjs",
|
|
42
63
|
"typecheck": "tsc -p tsconfig.test.json --noEmit",
|
|
43
|
-
"test": "vitest run"
|
|
64
|
+
"test": "vitest run",
|
|
65
|
+
"test:coverage": "vitest run --coverage"
|
|
44
66
|
}
|
|
45
67
|
}
|