@rexezuge/http 1.2.0 → 1.4.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/dist/ErrorMapper.d.ts +6 -2
- package/dist/ErrorMapper.d.ts.map +1 -1
- package/dist/ErrorMapper.js +1 -77
- package/dist/ErrorMapper.js.map +7 -1
- package/dist/accessAuth.d.ts +15 -5
- package/dist/accessAuth.d.ts.map +1 -1
- package/dist/accessAuth.js +1 -182
- package/dist/accessAuth.js.map +7 -1
- package/dist/index.d.ts +10 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -38
- package/dist/index.js.map +7 -1
- package/dist/rateLimit.d.ts.map +1 -1
- package/dist/rateLimit.js +1 -225
- package/dist/rateLimit.js.map +7 -1
- package/dist/routeBase.d.ts +15 -5
- package/dist/routeBase.d.ts.map +1 -1
- package/dist/routeBase.js +1 -92
- package/dist/routeBase.js.map +7 -1
- package/dist/securityHeaders.d.ts +6 -2
- package/dist/securityHeaders.d.ts.map +1 -1
- package/dist/securityHeaders.js +1 -119
- package/dist/securityHeaders.js.map +7 -1
- package/package.json +4 -4
package/dist/ErrorMapper.d.ts
CHANGED
|
@@ -38,9 +38,13 @@ interface ErrorMapperOptions {
|
|
|
38
38
|
* 500 — a non-`ServiceError` that reached the boundary is an unknown failure.
|
|
39
39
|
*/
|
|
40
40
|
fallbackStatus?: number;
|
|
41
|
-
/**
|
|
41
|
+
/**
|
|
42
|
+
A surface-specific dialect. Returns `undefined` to fall through to the default.
|
|
43
|
+
*/
|
|
42
44
|
toResponse?(error: ServiceError, status: number): Response | undefined;
|
|
43
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
Adds headers to the response (e.g. `Retry-After` on a 429).
|
|
47
|
+
*/
|
|
44
48
|
headers?(status: number, error: ServiceError): Record<string, string>;
|
|
45
49
|
}
|
|
46
50
|
declare const INTERNAL_SERVER_MESSAGE = "The server encountered an internal error and was unable to complete your request.";
|
|
@@ -1 +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
|
|
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;;MAEE;IACF,UAAU,CAAC,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;IACvE;;MAEE;IACF,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"}
|
package/dist/ErrorMapper.js
CHANGED
|
@@ -1,77 +1 @@
|
|
|
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
|
|
1
|
+
import{ServiceError as o}from"@rexezuge/errors";const c="The server encountered an internal error and was unable to complete your request.";function a(e){return e instanceof o?e:o.from(e)}function u(e){return{Exception:{Type:e.type,Message:e.expose?e.message:c}}}function f(e,E,r={}){const t=a(e),n=t.status||r.fallbackStatus||500,s=r.toResponse?.(t,n);if(s)return s;const i=r.headers?.(n,t)??{};return E(u(t),n,i)}export{c as INTERNAL_SERVER_MESSAGE,u as errorBody,f as toErrorResponse,a as toServiceError};
|
package/dist/ErrorMapper.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/ErrorMapper.ts"],
|
|
4
|
+
"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 /**\n A surface-specific dialect. Returns `undefined` to fall through to the default.\n */\n toResponse?(error: ServiceError, status: number): Response | undefined;\n /**\n Adds headers to the response (e.g. `Retry-After` on a 429).\n */\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"],
|
|
5
|
+
"mappings": "AAiCA,OAAS,gBAAAA,MAAoB,mBAkB7B,MAAMC,EAA0B,oFAQhC,SAASC,EAAeC,EAAc,CACpC,OAAOA,aAAiBH,EAAeG,EAAQH,EAAa,KAAKG,CAAK,CACxE,CASA,SAASC,EAAUD,EAAmB,CACpC,MAAO,CACL,UAAW,CACT,KAAMA,EAAM,KACZ,QAASA,EAAM,OAASA,EAAM,QAAUF,GAG9C,CASA,SAASI,EACPF,EACAG,EACAC,EAA8B,CAAA,EAAE,CAEhC,MAAMC,EAAeN,EAAeC,CAAK,EACnCM,EAASD,EAAa,QAAUD,EAAQ,gBAAkB,IAE1DG,EAASH,EAAQ,aAAaC,EAAcC,CAAM,EACxD,GAAIC,EAAQ,OAAOA,EAEnB,MAAMC,EAAUJ,EAAQ,UAAUE,EAAQD,CAAY,GAAK,CAAA,EAC3D,OAAOF,EAAKF,EAAUI,CAAY,EAAGC,EAAQE,CAAO,CACtD",
|
|
6
|
+
"names": ["ServiceError", "INTERNAL_SERVER_MESSAGE", "toServiceError", "error", "errorBody", "toErrorResponse", "json", "options", "serviceError", "status", "custom", "headers"]
|
|
7
|
+
}
|
package/dist/accessAuth.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
The identity the `ACCESS` binding reports.
|
|
3
|
+
*/
|
|
2
4
|
interface AccessIdentity {
|
|
3
5
|
email?: string | null;
|
|
4
6
|
emailVerified?: boolean | null;
|
|
@@ -12,7 +14,9 @@ interface AccessIdentity {
|
|
|
12
14
|
interface AccessBinding {
|
|
13
15
|
getIdentity(): Promise<AccessIdentity | undefined>;
|
|
14
16
|
}
|
|
15
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
A JWT verifier, so a test can inject one instead of reaching for `jose`.
|
|
19
|
+
*/
|
|
16
20
|
interface AccessJwtVerifier {
|
|
17
21
|
verify(token: string, teamDomain: string, policyAud: string): Promise<string>;
|
|
18
22
|
}
|
|
@@ -25,16 +29,22 @@ interface AccessAuthOptions {
|
|
|
25
29
|
* misspelled `prodcution`.
|
|
26
30
|
*/
|
|
27
31
|
bypassAllowed?: boolean;
|
|
28
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
The demo user, consulted when `bypassAllowed` and demo mode is on.
|
|
34
|
+
*/
|
|
29
35
|
demoUserEmail?: string | null;
|
|
30
36
|
isDemoMode?: boolean;
|
|
31
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
The dev identity, consulted after demo mode.
|
|
39
|
+
*/
|
|
32
40
|
devAuthEmail?: string | null;
|
|
33
41
|
teamDomain?: string | null;
|
|
34
42
|
policyAud?: string | null;
|
|
35
43
|
verifier?: AccessJwtVerifier;
|
|
36
44
|
}
|
|
37
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
A rejected address. Local rather than an `Error`, so it cannot be caught as one.
|
|
47
|
+
*/
|
|
38
48
|
declare class AccessAuthError extends Error {
|
|
39
49
|
constructor(message: string);
|
|
40
50
|
}
|
package/dist/accessAuth.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessAuth.d.ts","sourceRoot":"","sources":["../src/accessAuth.ts"],"names":[],"mappings":"AAsCA
|
|
1
|
+
{"version":3,"file":"accessAuth.d.ts","sourceRoot":"","sources":["../src/accessAuth.ts"],"names":[],"mappings":"AAsCA;;EAEE;AACF,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;;EA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
CHANGED
|
@@ -1,182 +1 @@
|
|
|
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
|
|
1
|
+
import{createRemoteJWKSet as w,jwtVerify as h}from"jose";import{isValidEmailFormat as y}from"@rexezuge/shared";class s extends Error{constructor(e){super(e),this.name="AccessAuthError"}}const A=10,c=new Map;function C(t){let e=t.length;for(;e>0&&t.codePointAt(e-1)===47;)e-=1;return t.slice(0,e)}function u(t){return C(t.trim().toLowerCase())}function g(t){const e=u(t),i=c.get(e);if(i)return c.delete(e),c.set(e,i),i;const n=w(new URL(`${e}/cdn-cgi/access/certs`));if(c.size>=A){const r=c.keys().next().value;r!==void 0&&c.delete(r)}return c.set(e,n),n}const v={async verify(t,e,i){const n=u(e),{payload:r}=await h(t,g(n),{issuer:n,audience:i});return typeof r.email=="string"?r.email:""}};function f(t){return!/\s/.test(t)&&y(t)}async function E(t,e,i){if(i.bypassAllowed){if(i.isDemoMode&&i.demoUserEmail)return i.demoUserEmail.trim().toLowerCase();const a=i.devAuthEmail?.trim()??"";if(a&&f(a))return a.toLowerCase()}const n=i.teamDomain,r=i.policyAud;if(n&&r)try{return await m(t,n,r,i.verifier??v)}catch{}const l=await d(e);if(l!==null)return l;throw new s("Cloudflare Access authentication failed.")}async function d(t){const e=await t?.getIdentity().catch(()=>{});if(e?.emailVerified===!1||e?.email_verified===!1)return null;const i=e?.email?.trim().toLowerCase()??"";return f(i)?i:null}async function m(t,e,i,n){const r=t.headers.get("cf-access-jwt-assertion");if(!r)throw new s("No Cloudflare Access JWT token provided in request headers.");const l=u(e),a=i.trim();if(!a)throw new s("Missing required JWT verification configuration.");if(a.includes(","))throw new s("Multiple JWT audiences are not supported. Configure a single POLICY_AUD value.");try{const o=(await n.verify(r,l,a)).trim().toLowerCase();if(!f(o))throw new s("Cloudflare Access authentication failed.");return o}catch(o){throw o instanceof s?o:new s("Cloudflare Access authentication failed.")}}export{s as AccessAuthError,E as authenticateAccess,d as identityFromBinding,m as verifyAccessJwt};
|
package/dist/accessAuth.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
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;A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,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,eAAe,CAAC,gFAAgF,CAAC,CAAC;IAC9G,CAAC;IAED,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,CAAC,MAAM,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QACpF,IAAI,CAAC,gBAAgB,CAAC,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"]}
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/accessAuth.ts"],
|
|
4
|
+
"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/**\nThe identity the `ACCESS` binding reports.\n*/\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/**\nA JWT verifier, so a test can inject one instead of reaching for `jose`.\n*/\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 /**\n The demo user, consulted when `bypassAllowed` and demo mode is on.\n */\n demoUserEmail?: string | null;\n isDemoMode?: boolean;\n /**\n The dev identity, consulted after demo mode.\n */\n devAuthEmail?: string | null;\n teamDomain?: string | null;\n policyAud?: string | null;\n verifier?: AccessJwtVerifier;\n}\n\n/**\nA rejected address. Local rather than an `Error`, so it cannot be caught as one.\n*/\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(() => {});\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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AAS,GAAG,EACvB,MAAM,IAAIhC,EAAgB,gFAAgF,EAG5G,GAAI,CACF,MAAM8B,GAAS,MAAMC,EAAS,OAAOhB,EAAOE,EAAQe,CAAQ,GAAG,KAAI,EAAG,YAAW,EACjF,GAAI,CAACb,EAAiBW,CAAK,EAAG,MAAM,IAAI9B,EAAgB,0CAA0C,EAClG,OAAO8B,CACT,OAASG,EAAO,CACd,MAAIA,aAAiBjC,EAAuBiC,EACtC,IAAIjC,EAAgB,0CAA0C,CACtE,CACF",
|
|
6
|
+
"names": ["createRemoteJWKSet", "jwtVerify", "isValidEmailFormat", "AccessAuthError", "message", "JWKS_CACHE_LIMIT", "jwksCache", "trimTrailingSlashes", "value", "end", "normalizeTeamDomain", "teamDomain", "jwksFor", "normalized", "cached", "created", "oldest", "joseVerifier", "token", "policyAud", "issuer", "payload", "isValidAuthEmail", "raw", "authenticateAccess", "request", "binding", "options", "dev", "verifyAccessJwt", "fromBinding", "identityFromBinding", "identity", "email", "verifier", "audience", "error"]
|
|
7
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -30,14 +30,14 @@
|
|
|
30
30
|
* Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test
|
|
31
31
|
* double usable without a framework import.
|
|
32
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';
|
|
33
|
+
export { clientIp, rateLimit } from './rateLimit.ts';
|
|
34
|
+
export type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface } from './rateLimit.ts';
|
|
35
|
+
export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
|
|
36
|
+
export type { HeaderContext } from './securityHeaders.ts';
|
|
37
|
+
export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';
|
|
38
|
+
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';
|
|
41
|
+
export { BaseRoute, createRouteHandler } from './routeBase.ts';
|
|
42
|
+
export type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';
|
|
43
43
|
//# 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,
|
|
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,gBAAgB,CAAC;AACrD,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAE7G,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,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AACvG,YAAY,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,38 +1 @@
|
|
|
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
|
|
1
|
+
import{clientIp as t,rateLimit as o}from"./rateLimit.js";import{applySecurityHeaders as i,securityHeaders as E,sensitivePaths as R,CONTENT_SECURITY_POLICY as c,SECURITY_HEADERS as S,STRICT_TRANSPORT_SECURITY as a}from"./securityHeaders.js";import{AccessAuthError as p,authenticateAccess as n,identityFromBinding as A,verifyAccessJwt as m}from"./accessAuth.js";import{errorBody as _,toErrorResponse as d,toServiceError as f,INTERNAL_SERVER_MESSAGE as u}from"./ErrorMapper.js";import{BaseRoute as C,createRouteHandler as x}from"./routeBase.js";export{p as AccessAuthError,C as BaseRoute,c as CONTENT_SECURITY_POLICY,u as INTERNAL_SERVER_MESSAGE,S as SECURITY_HEADERS,a as STRICT_TRANSPORT_SECURITY,i as applySecurityHeaders,n as authenticateAccess,t as clientIp,x as createRouteHandler,_ as errorBody,A as identityFromBinding,o as rateLimit,E as securityHeaders,R as sensitivePaths,d as toErrorResponse,f as toServiceError,m as verifyAccessJwt};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 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\n * only one a repo can choose to skip — nothing in 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 *\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\nexport { clientIp, rateLimit } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface } 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, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper.ts';\nexport type { ErrorMapperOptions } from './ErrorMapper.ts';\n\nexport { BaseRoute, createRouteHandler } from './routeBase.ts';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase.ts';\n"],
|
|
5
|
+
"mappings": "AAiCA,OAAS,YAAAA,EAAU,aAAAC,MAAiB,iBAGpC,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,mBAAAC,EAAiB,kBAAAC,EAAgB,2BAAAC,MAA+B,mBAGpF,OAAS,aAAAC,EAAW,sBAAAC,MAA0B",
|
|
6
|
+
"names": ["clientIp", "rateLimit", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "BaseRoute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