@rexezuge/http 0.0.0-stage → 1.0.8

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rexezuge
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # `@rexezuge/http`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The family's HTTP layer: Hono middleware, route bases, Cloudflare Access auth,
4
+ and error→response mapping.
5
+
6
+ ## Why this package exists
7
+
8
+ Eight other packages in the kit are framework-free on purpose, and that is what
9
+ lets a repo adopt `shared` / `errors` / `runtime` without adopting a web
10
+ framework. The pieces in here cannot be framework-free — they are Hono- and
11
+ chanfana-shaped — and the zero-dependency rule silently prevented the fix while
12
+ four repos each shipped four copies.
13
+
14
+ So this is the one package that breaks the rule, deliberately. Nothing in the
15
+ other eight imports it, so a repo that wants the framework-free core can keep
16
+ taking only that.
17
+
18
+ ## What converged here
19
+
20
+ | Module | From |
21
+ | ----------------- | ---------------------------------------------------------------------------------------------------------- |
22
+ | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |
23
+ | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |
24
+ | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |
25
+ | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |
26
+ | `routeBase` | All three incompatible shapes, with their shared parts converged |
27
+
28
+ ## The three decisions worth knowing
29
+
30
+ **`rateLimit`'s `max` may be a resolver.** The route table is built once in the
31
+ worker constructor, where `env` does not exist. Reading a `*_RATE_LIMIT` var
32
+ there produces a module-level constant wearing a variable's name — which is how
33
+ one repo shipped a declared, validated, templated variable that the limiter never
34
+ read. A resolver is evaluated per request instead. An unusable resolver **fails
35
+ open**, because a broken one would otherwise silently turn the limiter off.
36
+
37
+ **The sweep is time-triggered, the cap is not.** The bucket cap is enforced on
38
+ every request, because memory grows whether or not a sweep runs. The expiry
39
+ sweep runs at most once per 30s, because its cost was previously paid by every
40
+ caller rather than by the one who filled the map — which made a rate limiter a
41
+ denial-of-service vector against itself.
42
+
43
+ **`securityHeaders` requires its `no-store` predicate.** One repo shipped
44
+ `startsWith('/user/')` against a worker that serves no `/user/` route, so the
45
+ predicate could never return `true` and `Cache-Control: no-store` was never
46
+ applied to anything. A predicate copied from another router's route table is not
47
+ a conservative default; it is an unconditional no-op. Passing it is required so
48
+ the compiler asks.
49
+
50
+ ## Usage
51
+
52
+ ```ts
53
+ import { rateLimit, securityHeaders, sensitivePaths, createRouteHandler } from '@rexezuge/http';
54
+
55
+ const app = new Hono();
56
+
57
+ app.use('*', securityHeaders(sensitivePaths('/user', '/internal')));
58
+ app.use('/user/*', userAuthentication());
59
+ // After auth: the limiter prefers the resolved identity over the client address.
60
+ app.use('/user/*', rateLimit({ windowMs: 60_000, max: 60, keyPrefix: 'user' }));
61
+
62
+ const listVolumes = createRouteHandler(async (c) => c.json(await scope.get(Tokens.VolumeDAO).list()));
63
+ ```
64
+
65
+ A surface with its own wire envelope (Subsonic, CalDAV) supplies `onThrottled`
66
+ and `toResponse`; everything else gets the canonical `{Exception:{Type,Message}}`
67
+ dialect every SPA in the family decodes.
68
+
69
+ ## Context types are structural
70
+
71
+ Every entry point takes a context _shape_ (`RateLimitContext`, `HeaderContext`,
72
+ `RouteContext`) rather than Hono's `Context<…>`. That keeps this package from
73
+ pinning the generic parameters, lets a bare-`Request` dispatcher share the same
74
+ middleware, and makes every suite runnable in plain Node — which is what the
75
+ tests here do.
76
+
77
+ ## Null and undefined
78
+
79
+ `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.
80
+ Never compare one of these results against `undefined`: `null` does not equal it,
81
+ so the check silently goes false and reads as "always present".
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Error → response mapping at the HTTP boundary.
3
+ *
4
+ * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and
5
+ * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the
6
+ * only one that states **why** it splits: by surface, not by convenience.
7
+ *
8
+ * ## One surface, one dialect
9
+ *
10
+ * The `{Exception:{Type,Message}}` envelope is the family's established wire
11
+ * format and the one the SPAs decode. A protocol surface with its own envelope —
12
+ * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client
13
+ * parsing that surface has no way to interpret anything else: a 401 carrying an
14
+ * unrecognized body renders as "server error" and the client retries.
15
+ *
16
+ * So the split is by surface, and a caller declares which one it is on rather
17
+ * than each handler deciding for itself. A surface that has its own dialect
18
+ * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the
19
+ * canonical envelope.
20
+ *
21
+ * ## A 5xx never carries its own message
22
+ *
23
+ * `expose` in `@rexezuge/errors` already decides this, and this mapper is where
24
+ * that decision becomes bytes. A D1 error names tables and columns; an upstream
25
+ * body can carry a stack. The substitution lives here once rather than in every
26
+ * boundary mapper.
27
+ *
28
+ * ## A 404 is a 404
29
+ *
30
+ * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code
31
+ * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not
32
+ * second-guess the taxonomy into something a client can misread.
33
+ */
34
+ import { ServiceError } from '@rexezuge/errors';
35
+ interface ErrorMapperOptions {
36
+ /**
37
+ * The HTTP status when the error carries none it should publish. Defaults to
38
+ * 500 — a non-`ServiceError` that reached the boundary is an unknown failure.
39
+ */
40
+ fallbackStatus?: number;
41
+ /** A surface-specific dialect. Returns `undefined` to fall through to the default. */
42
+ toResponse?(error: ServiceError, status: number): Response | undefined;
43
+ /** Adds headers to the response (e.g. `Retry-After` on a 429). */
44
+ headers?(status: number, error: ServiceError): Record<string, string>;
45
+ }
46
+ declare const INTERNAL_SERVER_MESSAGE = "The server encountered an internal error and was unable to complete your request.";
47
+ /**
48
+ * Normalize an unknown catch value into the taxonomy.
49
+ *
50
+ * Re-wrapping a `ServiceError` would bury its context, so it passes through
51
+ * untouched and the caller can rely on `instanceof` downstream.
52
+ */
53
+ declare function toServiceError(error: unknown): ServiceError;
54
+ /**
55
+ * The canonical wire body.
56
+ *
57
+ * A 4xx keeps its message; a 5xx is masked. This is the `{Exception:{…}}`
58
+ * envelope every SPA in the family decodes, and the one a surface with no
59
+ * dialect of its own should answer in.
60
+ */
61
+ declare function errorBody(error: ServiceError): {
62
+ Exception: {
63
+ Type: string;
64
+ Message: string;
65
+ };
66
+ };
67
+ /**
68
+ * Map a caught value to a `Response`.
69
+ *
70
+ * The `json`-shaped callback is injected rather than imported from Hono so this
71
+ * module stays free of the `Context` generic: a caller passes its own `c.json`,
72
+ * which is what makes it usable from a bare-`Request` dispatcher as well.
73
+ */
74
+ declare function toErrorResponse(error: unknown, json: (body: unknown, status: number, headers?: Record<string, string>) => Response, options?: ErrorMapperOptions): Response;
75
+ export { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE };
76
+ export type { ErrorMapperOptions };
77
+ //# sourceMappingURL=ErrorMapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ErrorMapper.d.ts","sourceRoot":"","sources":["../src/ErrorMapper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEhD,UAAU,kBAAkB;IAC1B;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sFAAsF;IACtF,UAAU,CAAC,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;IACvE,kEAAkE;IAClE,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACvE;AAED,QAAA,MAAM,uBAAuB,sFAAsF,CAAC;AAEpH;;;;;GAKG;AACH,iBAAS,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,CAEpD;AAED;;;;;;GAMG;AACH,iBAAS,SAAS,CAAC,KAAK,EAAE,YAAY,GAAG;IAAE,SAAS,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAOxF;AAED;;;;;;GAMG;AACH,iBAAS,eAAe,CACtB,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,QAAQ,EACnF,OAAO,GAAE,kBAAuB,GAC/B,QAAQ,CASV;AAED,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,CAAC;AAC/E,YAAY,EAAE,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Error → response mapping at the HTTP boundary.
3
+ *
4
+ * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and
5
+ * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the
6
+ * only one that states **why** it splits: by surface, not by convenience.
7
+ *
8
+ * ## One surface, one dialect
9
+ *
10
+ * The `{Exception:{Type,Message}}` envelope is the family's established wire
11
+ * format and the one the SPAs decode. A protocol surface with its own envelope —
12
+ * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client
13
+ * parsing that surface has no way to interpret anything else: a 401 carrying an
14
+ * unrecognized body renders as "server error" and the client retries.
15
+ *
16
+ * So the split is by surface, and a caller declares which one it is on rather
17
+ * than each handler deciding for itself. A surface that has its own dialect
18
+ * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the
19
+ * canonical envelope.
20
+ *
21
+ * ## A 5xx never carries its own message
22
+ *
23
+ * `expose` in `@rexezuge/errors` already decides this, and this mapper is where
24
+ * that decision becomes bytes. A D1 error names tables and columns; an upstream
25
+ * body can carry a stack. The substitution lives here once rather than in every
26
+ * boundary mapper.
27
+ *
28
+ * ## A 404 is a 404
29
+ *
30
+ * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code
31
+ * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not
32
+ * second-guess the taxonomy into something a client can misread.
33
+ */
34
+ import { ServiceError } from '@rexezuge/errors';
35
+ const INTERNAL_SERVER_MESSAGE = 'The server encountered an internal error and was unable to complete your request.';
36
+ /**
37
+ * Normalize an unknown catch value into the taxonomy.
38
+ *
39
+ * Re-wrapping a `ServiceError` would bury its context, so it passes through
40
+ * untouched and the caller can rely on `instanceof` downstream.
41
+ */
42
+ function toServiceError(error) {
43
+ return error instanceof ServiceError ? error : ServiceError.from(error);
44
+ }
45
+ /**
46
+ * The canonical wire body.
47
+ *
48
+ * A 4xx keeps its message; a 5xx is masked. This is the `{Exception:{…}}`
49
+ * envelope every SPA in the family decodes, and the one a surface with no
50
+ * dialect of its own should answer in.
51
+ */
52
+ function errorBody(error) {
53
+ return {
54
+ Exception: {
55
+ Type: error.type,
56
+ Message: error.expose ? error.message : INTERNAL_SERVER_MESSAGE,
57
+ },
58
+ };
59
+ }
60
+ /**
61
+ * Map a caught value to a `Response`.
62
+ *
63
+ * The `json`-shaped callback is injected rather than imported from Hono so this
64
+ * module stays free of the `Context` generic: a caller passes its own `c.json`,
65
+ * which is what makes it usable from a bare-`Request` dispatcher as well.
66
+ */
67
+ function toErrorResponse(error, json, options = {}) {
68
+ const serviceError = toServiceError(error);
69
+ const status = serviceError.status || options.fallbackStatus || 500;
70
+ const custom = options.toResponse?.(serviceError, status);
71
+ if (custom)
72
+ return custom;
73
+ const headers = options.headers?.(status, serviceError) ?? {};
74
+ return json(errorBody(serviceError), status, headers);
75
+ }
76
+ export { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE };
77
+ //# sourceMappingURL=ErrorMapper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ErrorMapper.js","sourceRoot":"","sources":["../src/ErrorMapper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAchD,MAAM,uBAAuB,GAAG,mFAAmF,CAAC;AAEpH;;;;;GAKG;AACH,SAAS,cAAc,CAAC,KAAc;IACpC,OAAO,KAAK,YAAY,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC1E,CAAC;AAED;;;;;;GAMG;AACH,SAAS,SAAS,CAAC,KAAmB;IACpC,OAAO;QACL,SAAS,EAAE;YACT,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,uBAAuB;SAChE;KACF,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,eAAe,CACtB,KAAc,EACd,IAAmF,EACnF,UAA8B,EAAE;IAEhC,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;IAC3C,MAAM,MAAM,GAAG,YAAY,CAAC,MAAM,IAAI,OAAO,CAAC,cAAc,IAAI,GAAG,CAAC;IAEpE,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IAC1D,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IAE1B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,YAAY,CAAC,IAAI,EAAE,CAAC;IAC9D,OAAO,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACxD,CAAC;AAED,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,CAAC","sourcesContent":["/**\n * Error → response mapping at the HTTP boundary.\n *\n * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and\n * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the\n * only one that states **why** it splits: by surface, not by convenience.\n *\n * ## One surface, one dialect\n *\n * The `{Exception:{Type,Message}}` envelope is the family's established wire\n * format and the one the SPAs decode. A protocol surface with its own envelope —\n * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client\n * parsing that surface has no way to interpret anything else: a 401 carrying an\n * unrecognized body renders as \"server error\" and the client retries.\n *\n * So the split is by surface, and a caller declares which one it is on rather\n * than each handler deciding for itself. A surface that has its own dialect\n * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the\n * canonical envelope.\n *\n * ## A 5xx never carries its own message\n *\n * `expose` in `@rexezuge/errors` already decides this, and this mapper is where\n * that decision becomes bytes. A D1 error names tables and columns; an upstream\n * body can carry a stack. The substitution lives here once rather than in every\n * boundary mapper.\n *\n * ## A 404 is a 404\n *\n * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code\n * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not\n * second-guess the taxonomy into something a client can misread.\n */\nimport { ServiceError } from '@rexezuge/errors';\n\ninterface ErrorMapperOptions {\n /**\n * The HTTP status when the error carries none it should publish. Defaults to\n * 500 — a non-`ServiceError` that reached the boundary is an unknown failure.\n */\n fallbackStatus?: number;\n /** A surface-specific dialect. Returns `undefined` to fall through to the default. */\n toResponse?(error: ServiceError, status: number): Response | undefined;\n /** Adds headers to the response (e.g. `Retry-After` on a 429). */\n headers?(status: number, error: ServiceError): Record<string, string>;\n}\n\nconst INTERNAL_SERVER_MESSAGE = 'The server encountered an internal error and was unable to complete your request.';\n\n/**\n * Normalize an unknown catch value into the taxonomy.\n *\n * Re-wrapping a `ServiceError` would bury its context, so it passes through\n * untouched and the caller can rely on `instanceof` downstream.\n */\nfunction toServiceError(error: unknown): ServiceError {\n return error instanceof ServiceError ? error : ServiceError.from(error);\n}\n\n/**\n * The canonical wire body.\n *\n * A 4xx keeps its message; a 5xx is masked. This is the `{Exception:{…}}`\n * envelope every SPA in the family decodes, and the one a surface with no\n * dialect of its own should answer in.\n */\nfunction errorBody(error: ServiceError): { Exception: { Type: string; Message: string } } {\n return {\n Exception: {\n Type: error.type,\n Message: error.expose ? error.message : INTERNAL_SERVER_MESSAGE,\n },\n };\n}\n\n/**\n * Map a caught value to a `Response`.\n *\n * The `json`-shaped callback is injected rather than imported from Hono so this\n * module stays free of the `Context` generic: a caller passes its own `c.json`,\n * which is what makes it usable from a bare-`Request` dispatcher as well.\n */\nfunction toErrorResponse(\n error: unknown,\n json: (body: unknown, status: number, headers?: Record<string, string>) => Response,\n options: ErrorMapperOptions = {},\n): Response {\n const serviceError = toServiceError(error);\n const status = serviceError.status || options.fallbackStatus || 500;\n\n const custom = options.toResponse?.(serviceError, status);\n if (custom) return custom;\n\n const headers = options.headers?.(status, serviceError) ?? {};\n return json(errorBody(serviceError), status, headers);\n}\n\nexport { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE };\nexport type { ErrorMapperOptions };\n"]}
@@ -0,0 +1,67 @@
1
+ /** The identity the `ACCESS` binding reports. */
2
+ interface AccessIdentity {
3
+ email?: string | null;
4
+ emailVerified?: boolean | null;
5
+ email_verified?: boolean | null;
6
+ }
7
+ /**
8
+ * The `ACCESS` binding, as the platform provides it.
9
+ *
10
+ * Never a wrangler declaration — see the file header.
11
+ */
12
+ interface AccessBinding {
13
+ getIdentity(): Promise<AccessIdentity | undefined>;
14
+ }
15
+ /** A JWT verifier, so a test can inject one instead of reaching for `jose`. */
16
+ interface AccessJwtVerifier {
17
+ verify(token: string, teamDomain: string, policyAud: string): Promise<string>;
18
+ }
19
+ interface AccessAuthOptions {
20
+ /**
21
+ * Whether this environment may use the dev/demo bypasses.
22
+ *
23
+ * Deliberately an **allow-list** rather than `environment !== 'production'`:
24
+ * a deny-list would enable the bypass for `staging`, `Preview`, and a
25
+ * misspelled `prodcution`.
26
+ */
27
+ bypassAllowed?: boolean;
28
+ /** The demo user, consulted when `bypassAllowed` and demo mode is on. */
29
+ demoUserEmail?: string | null;
30
+ isDemoMode?: boolean;
31
+ /** The dev identity, consulted after demo mode. */
32
+ devAuthEmail?: string | null;
33
+ teamDomain?: string | null;
34
+ policyAud?: string | null;
35
+ verifier?: AccessJwtVerifier;
36
+ }
37
+ /** A rejected address. Local rather than an `Error`, so it cannot be caught as one. */
38
+ declare class AccessAuthError extends Error {
39
+ constructor(message: string);
40
+ }
41
+ /**
42
+ * Resolve the authenticated address, or throw.
43
+ *
44
+ * The order is deliberate: demo → dev → JWT → binding. The first two are gated
45
+ * on {@link AccessAuthOptions.bypassAllowed} rather than on an environment
46
+ * comparison, so a misspelled environment name cannot enable them.
47
+ */
48
+ declare function authenticateAccess(request: Request, binding: AccessBinding | undefined, options: AccessAuthOptions): Promise<string>;
49
+ /**
50
+ * The `ACCESS` binding path.
51
+ *
52
+ * `undefined` is the platform's "no identity" answer and is handled by the same
53
+ * optional chain as a throw: a rejected `getIdentity` resolves to `undefined` and
54
+ * falls through to the single throw site, so a broken binding is a 401 rather
55
+ * than an unhandled rejection in the auth middleware.
56
+ */
57
+ declare function identityFromBinding(binding: AccessBinding | undefined): Promise<string | null>;
58
+ /**
59
+ * Verify the `cf-access-jwt-assertion` header.
60
+ *
61
+ * Throws {@link AccessAuthError} for every failure, with one message: a detailed
62
+ * one tells an unauthenticated caller which part of the token they got right.
63
+ */
64
+ declare function verifyAccessJwt(request: Request, teamDomain: string, policyAud: string, verifier: AccessJwtVerifier): Promise<string>;
65
+ export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt };
66
+ export type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier };
67
+ //# sourceMappingURL=accessAuth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accessAuth.d.ts","sourceRoot":"","sources":["../src/accessAuth.ts"],"names":[],"mappings":"AAsCA,iDAAiD;AACjD,UAAU,cAAc;IACtB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,aAAa,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAC/B,cAAc,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;CACjC;AAED;;;;GAIG;AACH,UAAU,aAAa;IACrB,WAAW,IAAI,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAAC;CACpD;AAED,+EAA+E;AAC/E,UAAU,iBAAiB;IACzB,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC/E;AAED,UAAU,iBAAiB;IACzB;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,yEAAyE;IACzE,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,iBAAiB,CAAC;CAC9B;AAED,uFAAuF;AACvF,cAAM,eAAgB,SAAQ,KAAK;gBACd,OAAO,EAAE,MAAM;CAInC;AAiED;;;;;;GAMG;AACH,iBAAe,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,GAAG,SAAS,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,CAwBnI;AAED;;;;;;;GAOG;AACH,iBAAe,mBAAmB,CAAC,OAAO,EAAE,aAAa,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAK7F;AAED;;;;;GAKG;AACH,iBAAe,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,CAqBpI;AAED,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,CAAC;AACrF,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,CAAC"}
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Cloudflare Access authentication for the **user API**.
3
+ *
4
+ * Converged from `AccessAuthService.ts` in AWS-AccessBridge, Durable-DAV,
5
+ * Durable-DAV-Router, Edge-Git and Edge-Sonic. Edge-Sonic's was the one that had
6
+ * fixed the defect the others carried, so this is that one.
7
+ *
8
+ * ## The defect this converges away
9
+ *
10
+ * AWS-AccessBridge's copy read the identity off a cast `executionCtx.access`.
11
+ * `ExecutionContext` has only `waitUntil` and `passThroughOnException` — there is
12
+ * no `access` member — so **the branch could never execute**. It was documented
13
+ * in two AGENTS.md files and covered by six tests, none of which reflected the
14
+ * deployed path. A deployment with no Access in front of it answered 401 through
15
+ * the JWT path and the fallback was dead code that read as a safety net.
16
+ *
17
+ * `getIdentity` lives on a **binding**, and Cloudflare provisions it for a Worker
18
+ * behind an Access application, so it cannot be declared in a wrangler config
19
+ * and `wrangler types` never emits it. The shape is declared here instead, and
20
+ * **its absence is a supported state**: a deployment with no Access answers 401,
21
+ * not an open door.
22
+ *
23
+ * ## The other two fixes
24
+ *
25
+ * - **`Cf-Access-Authenticated-User-Email` is never trusted.** Cloudflare
26
+ * documents it as a *response* header it sets; read back as a *request* header,
27
+ * any caller can name themselves.
28
+ * - **An unverified identity inside the trusted binding still does not
29
+ * authenticate.** Cloudflare has used both `emailVerified` and
30
+ * `email_verified`; accepting one is a fail-open that only shows in production.
31
+ *
32
+ * Every JWT failure collapses to one message: "signature verification failed"
33
+ * versus "expired" tells an unauthenticated caller which part of the token they
34
+ * got right.
35
+ */
36
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
37
+ import { isValidEmailFormat } from '@rexezuge/shared';
38
+ /** A rejected address. Local rather than an `Error`, so it cannot be caught as one. */
39
+ class AccessAuthError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = 'AccessAuthError';
43
+ }
44
+ }
45
+ /**
46
+ * Bounded LRU of JWKS resolvers, keyed by team domain.
47
+ *
48
+ * Bounded because the map is process-wide and a domain is operator-supplied:
49
+ * without a ceiling, a config that varies the team domain per environment grows
50
+ * one resolver per environment for the isolate's lifetime. Refreshed on read so
51
+ * a rotating domain cannot flush a live one.
52
+ */
53
+ const JWKS_CACHE_LIMIT = 10;
54
+ const jwksCache = new Map();
55
+ function trimTrailingSlashes(value) {
56
+ let end = value.length;
57
+ while (end > 0 && value.codePointAt(end - 1) === 47)
58
+ end -= 1;
59
+ return value.slice(0, end);
60
+ }
61
+ function normalizeTeamDomain(teamDomain) {
62
+ return trimTrailingSlashes(teamDomain.trim().toLowerCase());
63
+ }
64
+ function jwksFor(teamDomain) {
65
+ const normalized = normalizeTeamDomain(teamDomain);
66
+ const cached = jwksCache.get(normalized);
67
+ if (cached) {
68
+ jwksCache.delete(normalized);
69
+ jwksCache.set(normalized, cached);
70
+ return cached;
71
+ }
72
+ const created = createRemoteJWKSet(new URL(`${normalized}/cdn-cgi/access/certs`));
73
+ if (jwksCache.size >= JWKS_CACHE_LIMIT) {
74
+ const oldest = jwksCache.keys().next().value;
75
+ if (oldest !== undefined)
76
+ jwksCache.delete(oldest);
77
+ }
78
+ jwksCache.set(normalized, created);
79
+ return created;
80
+ }
81
+ /**
82
+ * The `jose` verifier, separated so the JWKS cache and the claim handling can be
83
+ * asserted without a network fetch or a signing key.
84
+ */
85
+ const joseVerifier = {
86
+ async verify(token, teamDomain, policyAud) {
87
+ const issuer = normalizeTeamDomain(teamDomain);
88
+ const { payload } = await jwtVerify(token, jwksFor(issuer), { issuer, audience: policyAud });
89
+ return typeof payload.email === 'string' ? payload.email : '';
90
+ },
91
+ };
92
+ /**
93
+ * A plausible address for authentication purposes.
94
+ *
95
+ * Delegates to `@rexezuge/shared`'s canonical validator rather than keeping a
96
+ * fourth regex in the family — the copies that carried their own are how two
97
+ * repos ended up disagreeing about which addresses authenticate at all. The
98
+ * whitespace rejection is separate because an address that reached here with a
99
+ * space in it is a malformed header, not merely an invalid format.
100
+ */
101
+ function isValidAuthEmail(raw) {
102
+ return !/\s/.test(raw) && isValidEmailFormat(raw);
103
+ }
104
+ /**
105
+ * Resolve the authenticated address, or throw.
106
+ *
107
+ * The order is deliberate: demo → dev → JWT → binding. The first two are gated
108
+ * on {@link AccessAuthOptions.bypassAllowed} rather than on an environment
109
+ * comparison, so a misspelled environment name cannot enable them.
110
+ */
111
+ async function authenticateAccess(request, binding, options) {
112
+ if (options.bypassAllowed) {
113
+ if (options.isDemoMode && options.demoUserEmail) {
114
+ return options.demoUserEmail.trim().toLowerCase();
115
+ }
116
+ const dev = options.devAuthEmail?.trim() ?? '';
117
+ if (dev && isValidAuthEmail(dev))
118
+ return dev.toLowerCase();
119
+ }
120
+ const teamDomain = options.teamDomain;
121
+ const policyAud = options.policyAud;
122
+ if (teamDomain && policyAud) {
123
+ try {
124
+ return await verifyAccessJwt(request, teamDomain, policyAud, options.verifier ?? joseVerifier);
125
+ }
126
+ catch {
127
+ // Fall through to the binding. A request can carry either.
128
+ }
129
+ }
130
+ const fromBinding = await identityFromBinding(binding);
131
+ if (fromBinding !== null)
132
+ return fromBinding;
133
+ throw new AccessAuthError('Cloudflare Access authentication failed.');
134
+ }
135
+ /**
136
+ * The `ACCESS` binding path.
137
+ *
138
+ * `undefined` is the platform's "no identity" answer and is handled by the same
139
+ * optional chain as a throw: a rejected `getIdentity` resolves to `undefined` and
140
+ * falls through to the single throw site, so a broken binding is a 401 rather
141
+ * than an unhandled rejection in the auth middleware.
142
+ */
143
+ async function identityFromBinding(binding) {
144
+ const identity = await binding?.getIdentity().catch(() => undefined);
145
+ if (identity?.emailVerified === false || identity?.email_verified === false)
146
+ return null;
147
+ const email = identity?.email?.trim().toLowerCase() ?? '';
148
+ return isValidAuthEmail(email) ? email : null;
149
+ }
150
+ /**
151
+ * Verify the `cf-access-jwt-assertion` header.
152
+ *
153
+ * Throws {@link AccessAuthError} for every failure, with one message: a detailed
154
+ * one tells an unauthenticated caller which part of the token they got right.
155
+ */
156
+ async function verifyAccessJwt(request, teamDomain, policyAud, verifier) {
157
+ const token = request.headers.get('cf-access-jwt-assertion');
158
+ if (!token)
159
+ throw new AccessAuthError('No Cloudflare Access JWT token provided in request headers.');
160
+ const issuer = normalizeTeamDomain(teamDomain);
161
+ const audience = policyAud.trim();
162
+ if (!audience)
163
+ throw new AccessAuthError('Missing required JWT verification configuration.');
164
+ // A comma-joined value would fail inside the verifier with a message that
165
+ // reads like a bad signature, which sends an operator looking at their key.
166
+ if (audience.includes(',')) {
167
+ throw new AccessAuthError('Multiple JWT audiences are not supported. Configure a single POLICY_AUD value.');
168
+ }
169
+ try {
170
+ const email = (await verifier.verify(token, issuer, audience)).trim().toLowerCase();
171
+ if (!isValidAuthEmail(email))
172
+ throw new AccessAuthError('Cloudflare Access authentication failed.');
173
+ return email;
174
+ }
175
+ catch (error) {
176
+ if (error instanceof AccessAuthError)
177
+ throw error;
178
+ throw new AccessAuthError('Cloudflare Access authentication failed.');
179
+ }
180
+ }
181
+ export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt };
182
+ //# sourceMappingURL=accessAuth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accessAuth.js","sourceRoot":"","sources":["../src/accessAuth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AA0CtD,uFAAuF;AACvF,MAAM,eAAgB,SAAQ,KAAK;IACjC,YAAmB,OAAe;QAChC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AAED;;;;;;;GAOG;AACH,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,SAAS,GAAG,IAAI,GAAG,EAAiD,CAAC;AAE3E,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;IACvB,OAAO,GAAG,GAAG,CAAC,IAAI,KAAK,CAAC,WAAW,CAAC,GAAG,GAAG,CAAC,CAAC,KAAK,EAAE;QAAE,GAAG,IAAI,CAAC,CAAC;IAC9D,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,mBAAmB,C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AC,KAAK,CAAC;YAAE,MAAM,IAAI,eAAe,CAAC,0CAA0C,CAAC,CAAC;QACpG,OAAO,KAAK,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,eAAe;YAAE,MAAM,KAAK,CAAC;QAClD,MAAM,IAAI,eAAe,CAAC,0CAA0C,CAAC,CAAC;IACxE,CAAC;AACH,CAAC;AAED,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,CAAC","sourcesContent":["/**\n * Cloudflare Access authentication for the **user API**.\n *\n * Converged from `AccessAuthService.ts` in AWS-AccessBridge, Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic. Edge-Sonic's was the one that had\n * fixed the defect the others carried, so this is that one.\n *\n * ## The defect this converges away\n *\n * AWS-AccessBridge's copy read the identity off a cast `executionCtx.access`.\n * `ExecutionContext` has only `waitUntil` and `passThroughOnException` — there is\n * no `access` member — so **the branch could never execute**. It was documented\n * in two AGENTS.md files and covered by six tests, none of which reflected the\n * deployed path. A deployment with no Access in front of it answered 401 through\n * the JWT path and the fallback was dead code that read as a safety net.\n *\n * `getIdentity` lives on a **binding**, and Cloudflare provisions it for a Worker\n * behind an Access application, so it cannot be declared in a wrangler config\n * and `wrangler types` never emits it. The shape is declared here instead, and\n * **its absence is a supported state**: a deployment with no Access answers 401,\n * not an open door.\n *\n * ## The other two fixes\n *\n * - **`Cf-Access-Authenticated-User-Email` is never trusted.** Cloudflare\n * documents it as a *response* header it sets; read back as a *request* header,\n * any caller can name themselves.\n * - **An unverified identity inside the trusted binding still does not\n * authenticate.** Cloudflare has used both `emailVerified` and\n * `email_verified`; accepting one is a fail-open that only shows in production.\n *\n * Every JWT failure collapses to one message: \"signature verification failed\"\n * versus \"expired\" tells an unauthenticated caller which part of the token they\n * got right.\n */\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { isValidEmailFormat } from '@rexezuge/shared';\n\n/** The identity the `ACCESS` binding reports. */\ninterface AccessIdentity {\n email?: string | null;\n emailVerified?: boolean | null;\n email_verified?: boolean | null;\n}\n\n/**\n * The `ACCESS` binding, as the platform provides it.\n *\n * Never a wrangler declaration — see the file header.\n */\ninterface AccessBinding {\n getIdentity(): Promise<AccessIdentity | undefined>;\n}\n\n/** A JWT verifier, so a test can inject one instead of reaching for `jose`. */\ninterface AccessJwtVerifier {\n verify(token: string, teamDomain: string, policyAud: string): Promise<string>;\n}\n\ninterface AccessAuthOptions {\n /**\n * Whether this environment may use the dev/demo bypasses.\n *\n * Deliberately an **allow-list** rather than `environment !== 'production'`:\n * a deny-list would enable the bypass for `staging`, `Preview`, and a\n * misspelled `prodcution`.\n */\n bypassAllowed?: boolean;\n /** The demo user, consulted when `bypassAllowed` and demo mode is on. */\n demoUserEmail?: string | null;\n isDemoMode?: boolean;\n /** The dev identity, consulted after demo mode. */\n devAuthEmail?: string | null;\n teamDomain?: string | null;\n policyAud?: string | null;\n verifier?: AccessJwtVerifier;\n}\n\n/** A rejected address. Local rather than an `Error`, so it cannot be caught as one. */\nclass AccessAuthError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = 'AccessAuthError';\n }\n}\n\n/**\n * Bounded LRU of JWKS resolvers, keyed by team domain.\n *\n * Bounded because the map is process-wide and a domain is operator-supplied:\n * without a ceiling, a config that varies the team domain per environment grows\n * one resolver per environment for the isolate's lifetime. Refreshed on read so\n * a rotating domain cannot flush a live one.\n */\nconst JWKS_CACHE_LIMIT = 10;\nconst jwksCache = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.codePointAt(end - 1) === 47) end -= 1;\n return value.slice(0, end);\n}\n\nfunction normalizeTeamDomain(teamDomain: string): string {\n return trimTrailingSlashes(teamDomain.trim().toLowerCase());\n}\n\nfunction jwksFor(teamDomain: string): ReturnType<typeof createRemoteJWKSet> {\n const normalized = normalizeTeamDomain(teamDomain);\n const cached = jwksCache.get(normalized);\n if (cached) {\n jwksCache.delete(normalized);\n jwksCache.set(normalized, cached);\n return cached;\n }\n const created = createRemoteJWKSet(new URL(`${normalized}/cdn-cgi/access/certs`));\n if (jwksCache.size >= JWKS_CACHE_LIMIT) {\n const oldest = jwksCache.keys().next().value;\n if (oldest !== undefined) jwksCache.delete(oldest);\n }\n jwksCache.set(normalized, created);\n return created;\n}\n\n/**\n * The `jose` verifier, separated so the JWKS cache and the claim handling can be\n * asserted without a network fetch or a signing key.\n */\nconst joseVerifier: AccessJwtVerifier = {\n async verify(token: string, teamDomain: string, policyAud: string): Promise<string> {\n const issuer = normalizeTeamDomain(teamDomain);\n const { payload } = await jwtVerify(token, jwksFor(issuer), { issuer, audience: policyAud });\n return typeof payload.email === 'string' ? payload.email : '';\n },\n};\n\n/**\n * A plausible address for authentication purposes.\n *\n * Delegates to `@rexezuge/shared`'s canonical validator rather than keeping a\n * fourth regex in the family — the copies that carried their own are how two\n * repos ended up disagreeing about which addresses authenticate at all. The\n * whitespace rejection is separate because an address that reached here with a\n * space in it is a malformed header, not merely an invalid format.\n */\nfunction isValidAuthEmail(raw: string): boolean {\n return !/\\s/.test(raw) && isValidEmailFormat(raw);\n}\n\n/**\n * Resolve the authenticated address, or throw.\n *\n * The order is deliberate: demo → dev → JWT → binding. The first two are gated\n * on {@link AccessAuthOptions.bypassAllowed} rather than on an environment\n * comparison, so a misspelled environment name cannot enable them.\n */\nasync function authenticateAccess(request: Request, binding: AccessBinding | undefined, options: AccessAuthOptions): Promise<string> {\n if (options.bypassAllowed) {\n if (options.isDemoMode && options.demoUserEmail) {\n return options.demoUserEmail.trim().toLowerCase();\n }\n const dev = options.devAuthEmail?.trim() ?? '';\n if (dev && isValidAuthEmail(dev)) return dev.toLowerCase();\n }\n\n const teamDomain = options.teamDomain;\n const policyAud = options.policyAud;\n\n if (teamDomain && policyAud) {\n try {\n return await verifyAccessJwt(request, teamDomain, policyAud, options.verifier ?? joseVerifier);\n } catch {\n // Fall through to the binding. A request can carry either.\n }\n }\n\n const fromBinding = await identityFromBinding(binding);\n if (fromBinding !== null) return fromBinding;\n\n throw new AccessAuthError('Cloudflare Access authentication failed.');\n}\n\n/**\n * The `ACCESS` binding path.\n *\n * `undefined` is the platform's \"no identity\" answer and is handled by the same\n * optional chain as a throw: a rejected `getIdentity` resolves to `undefined` and\n * falls through to the single throw site, so a broken binding is a 401 rather\n * than an unhandled rejection in the auth middleware.\n */\nasync function identityFromBinding(binding: AccessBinding | undefined): Promise<string | null> {\n const identity = await binding?.getIdentity().catch(() => undefined);\n if (identity?.emailVerified === false || identity?.email_verified === false) return null;\n const email = identity?.email?.trim().toLowerCase() ?? '';\n return isValidAuthEmail(email) ? email : null;\n}\n\n/**\n * Verify the `cf-access-jwt-assertion` header.\n *\n * Throws {@link AccessAuthError} for every failure, with one message: a detailed\n * one tells an unauthenticated caller which part of the token they got right.\n */\nasync function verifyAccessJwt(request: Request, teamDomain: string, policyAud: string, verifier: AccessJwtVerifier): Promise<string> {\n const token = request.headers.get('cf-access-jwt-assertion');\n if (!token) throw new AccessAuthError('No Cloudflare Access JWT token provided in request headers.');\n\n const issuer = normalizeTeamDomain(teamDomain);\n const audience = policyAud.trim();\n if (!audience) throw new AccessAuthError('Missing required JWT verification configuration.');\n // A comma-joined value would fail inside the verifier with a message that\n // reads like a bad signature, which sends an operator looking at their key.\n if (audience.includes(',')) {\n throw new AccessAuthError('Multiple JWT audiences are not supported. Configure a single POLICY_AUD value.');\n }\n\n try {\n const email = (await verifier.verify(token, issuer, audience)).trim().toLowerCase();\n if (!isValidAuthEmail(email)) throw new AccessAuthError('Cloudflare Access authentication failed.');\n return email;\n } catch (error) {\n if (error instanceof AccessAuthError) throw error;\n throw new AccessAuthError('Cloudflare Access authentication failed.');\n }\n}\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt };\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier };\n"]}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `@rexezuge/http` — the family's HTTP layer.
3
+ *
4
+ * ## Why this package exists
5
+ *
6
+ * Eight other packages in the kit are framework-free on purpose, and that is
7
+ * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web
8
+ * framework. The rate limiter, the security headers, the route bases and the
9
+ * Access auth service cannot be framework-free: they are Hono- and
10
+ * chanfana-shaped, and four repos shipped four copies of each while the kit's
11
+ * zero-dependency rule silently prevented the fix.
12
+ *
13
+ * So this is the one package that breaks the rule, deliberately. It is also the
14
+ * only one a repo can choose to skip — nothing in the other eight imports it.
15
+ *
16
+ * ## What converged here
17
+ *
18
+ * | Module | From |
19
+ * | ----------------- | --------------------------------------------------------------------- |
20
+ * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |
21
+ * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |
22
+ * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |
23
+ * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |
24
+ * | `routeBase` | All three incompatible shapes, with their shared parts converged |
25
+ *
26
+ * ## The null rule
27
+ *
28
+ * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.
29
+ * The middleware in this package takes *structural* context types rather than
30
+ * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test
31
+ * double usable without a framework import.
32
+ */
33
+ export { clientIp, rateLimit } from './rateLimit';
34
+ export type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface } from './rateLimit';
35
+ export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders';
36
+ export type { HeaderContext } from './securityHeaders';
37
+ export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth';
38
+ export type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth';
39
+ export { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper';
40
+ export type { ErrorMapperOptions } from './ErrorMapper';
41
+ export { BaseRoute, createRouteHandler } from './routeBase';
42
+ export type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase';
43
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAClD,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE1G,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAC3B,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEvD,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACzG,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAExG,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AACpG,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAExD,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAC5D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `@rexezuge/http` — the family's HTTP layer.
3
+ *
4
+ * ## Why this package exists
5
+ *
6
+ * Eight other packages in the kit are framework-free on purpose, and that is
7
+ * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web
8
+ * framework. The rate limiter, the security headers, the route bases and the
9
+ * Access auth service cannot be framework-free: they are Hono- and
10
+ * chanfana-shaped, and four repos shipped four copies of each while the kit's
11
+ * zero-dependency rule silently prevented the fix.
12
+ *
13
+ * So this is the one package that breaks the rule, deliberately. It is also the
14
+ * only one a repo can choose to skip — nothing in the other eight imports it.
15
+ *
16
+ * ## What converged here
17
+ *
18
+ * | Module | From |
19
+ * | ----------------- | --------------------------------------------------------------------- |
20
+ * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |
21
+ * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |
22
+ * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |
23
+ * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |
24
+ * | `routeBase` | All three incompatible shapes, with their shared parts converged |
25
+ *
26
+ * ## The null rule
27
+ *
28
+ * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.
29
+ * The middleware in this package takes *structural* context types rather than
30
+ * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test
31
+ * double usable without a framework import.
32
+ */
33
+ export { clientIp, rateLimit } from './rateLimit';
34
+ export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders';
35
+ export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth';
36
+ export { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper';
37
+ export { BaseRoute, createRouteHandler } from './routeBase';
38
+ //# sourceMappingURL=index.js.map