@rexezuge/http 1.6.1 → 1.7.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.
@@ -1,3 +1,4 @@
1
+ import { UnauthorizedError } from '@rexezuge/errors';
1
2
  /**
2
3
  The identity the `ACCESS` binding reports.
3
4
  */
@@ -43,9 +44,22 @@ interface AccessAuthOptions {
43
44
  verifier?: AccessJwtVerifier;
44
45
  }
45
46
  /**
46
- A rejected address. Local rather than an `Error`, so it cannot be caught as one.
47
+ A rejected address.
48
+
49
+ A `ServiceError` with `status: 401`, not a bare `Error`. Every error boundary
50
+ in the family asks `error instanceof ServiceError` before deciding what to do,
51
+ so an authentication failure that is *not* one arrives as an unexpected 500: a
52
+ signed-out operator is told the server broke, the boundary logs every ordinary
53
+ sign-out as a bug, and the client's "am I signed in?" probe cannot distinguish
54
+ the two. This class extended `Error` and the comment above it claimed it did
55
+ not, which is how a 401 became a 500 without either statement being wrong about
56
+ itself.
57
+
58
+ `expose` is inherited: a 401 is a status the message is safe to show, and every
59
+ message here is a single fixed sentence that tells an unauthenticated caller
60
+ nothing about how far their token got.
47
61
  */
48
- declare class AccessAuthError extends Error {
62
+ declare class AccessAuthError extends UnauthorizedError {
49
63
  constructor(message: string);
50
64
  }
51
65
  /**
@@ -63,6 +77,12 @@ declare function authenticateAccess(request: Request, binding: AccessBinding | u
63
77
  * optional chain as a throw: a rejected `getIdentity` resolves to `undefined` and
64
78
  * falls through to the single throw site, so a broken binding is a 401 rather
65
79
  * than an unhandled rejection in the auth middleware.
80
+ *
81
+ * The rejection is **logged** at debug. The status is right either way — a
82
+ * binding that cannot answer is not an identity — but a silently swallowed
83
+ * rejection makes a misconfigured `ACCESS` binding and a genuinely signed-out
84
+ * caller indistinguishable in the logs, and the first is an outage an operator
85
+ * can fix in a minute.
66
86
  */
67
87
  declare function identityFromBinding(binding: AccessBinding | undefined): Promise<string | null>;
68
88
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"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QAAQ,CAAC,EAAE,iBAAiB,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;EAeE;AACF,cAAM,eAAgB,SAAQ,iBAAiB;gBAC1B,OAAO,EAAE,MAAM;CAInC;AA0ED;;;;;;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;;;;;;;;;;;;;GAaG;AACH,iBAAe,mBAAmB,CAAC,OAAO,EAAE,aAAa,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAQ7F;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"}
@@ -1 +1 @@
1
- var h=Object.defineProperty;var s=(t,e)=>h(t,"name",{value:e,configurable:!0});import{createRemoteJWKSet as y,jwtVerify as A}from"jose";import{isValidEmailFormat as C}from"@rexezuge/shared";class a extends Error{static{s(this,"AccessAuthError")}constructor(e){super(e),this.name="AccessAuthError"}}const g=10,o=new Map;function v(t){let e=t.length;for(;e>0&&t.codePointAt(e-1)===47;)e-=1;return t.slice(0,e)}s(v,"trimTrailingSlashes");function f(t){return v(t.trim().toLowerCase())}s(f,"normalizeTeamDomain");function E(t){const e=f(t),i=o.get(e);if(i)return o.delete(e),o.set(e,i),i;const n=y(new URL(`${e}/cdn-cgi/access/certs`));if(o.size>=g){const r=o.keys().next().value;r!==void 0&&o.delete(r)}return o.set(e,n),n}s(E,"jwksFor");const L={async verify(t,e,i){const n=f(e),{payload:r}=await A(t,E(n),{issuer:n,audience:i});return typeof r.email=="string"?r.email:""}};function d(t){return!/\s/.test(t)&&C(t)}s(d,"isValidAuthEmail");async function p(t,e,i){if(i.bypassAllowed){if(i.isDemoMode&&i.demoUserEmail)return i.demoUserEmail.trim().toLowerCase();const c=i.devAuthEmail?.trim()??"";if(c&&d(c))return c.toLowerCase()}const n=i.teamDomain,r=i.policyAud;if(n&&r)try{return await w(t,n,r,i.verifier??L)}catch{}const u=await m(e);if(u!==null)return u;throw new a("Cloudflare Access authentication failed.")}s(p,"authenticateAccess");async function m(t){const e=await t?.getIdentity().catch(()=>{});if(e?.emailVerified===!1||e?.email_verified===!1)return null;const i=e?.email?.trim().toLowerCase()??"";return d(i)?i:null}s(m,"identityFromBinding");async function w(t,e,i,n){const r=t.headers.get("cf-access-jwt-assertion");if(!r)throw new a("No Cloudflare Access JWT token provided in request headers.");const u=f(e),c=i.trim();if(!c)throw new a("Missing required JWT verification configuration.");if(c.includes(","))throw new a("Multiple JWT audiences are not supported. Configure a single POLICY_AUD value.");try{const l=(await n.verify(r,u,c)).trim().toLowerCase();if(!d(l))throw new a("Cloudflare Access authentication failed.");return l}catch(l){throw l instanceof a?l:new a("Cloudflare Access authentication failed.")}}s(w,"verifyAccessJwt");export{a as AccessAuthError,p as authenticateAccess,m as identityFromBinding,w as verifyAccessJwt};
1
+ var h=Object.defineProperty;var a=(t,e)=>h(t,"name",{value:e,configurable:!0});import{createRemoteJWKSet as y,jwtVerify as A}from"jose";import{isValidEmailFormat as g}from"@rexezuge/shared";import{UnauthorizedError as C}from"@rexezuge/errors";class s extends C{static{a(this,"AccessAuthError")}constructor(e){super(e),this.name="AccessAuthError"}}const v=10,c=new Map;function E(t){let e=t.length;for(;e>0&&t.codePointAt(e-1)===47;)e-=1;return t.slice(0,e)}a(E,"trimTrailingSlashes");function u(t){return E(t.trim().toLowerCase())}a(u,"normalizeTeamDomain");function p(t){const e=u(t),i=c.get(e);if(i)return c.delete(e),c.set(e,i),i;const n=y(new URL(`${e}/cdn-cgi/access/certs`));if(c.size>=v){const r=c.keys().next().value;r!==void 0&&c.delete(r)}return c.set(e,n),n}a(p,"jwksFor");const L={async verify(t,e,i){const n=u(e),{payload:r}=await A(t,p(n),{issuer:n,audience:i});if(r.email_verified===!1)throw new s("Cloudflare Access authentication failed.");return typeof r.email=="string"?r.email:""}};function f(t){return!/\s/.test(t)&&g(t)}a(f,"isValidAuthEmail");async function j(t,e,i){if(i.bypassAllowed){if(i.isDemoMode&&i.demoUserEmail)return i.demoUserEmail.trim().toLowerCase();const o=i.devAuthEmail?.trim()??"";if(o&&f(o))return o.toLowerCase()}const n=i.teamDomain,r=i.policyAud;if(n&&r)try{return await w(t,n,r,i.verifier??L)}catch{}const d=await m(e);if(d!==null)return d;throw new s("Cloudflare Access authentication failed.")}a(j,"authenticateAccess");async function m(t){const e=a(r=>{console.debug("[accessAuth] the ACCESS binding getIdentity() rejected; treating it as no identity:",r)},"logRejected"),i=await t?.getIdentity().catch(e);if(i?.emailVerified===!1||i?.email_verified===!1)return null;const n=i?.email?.trim().toLowerCase()??"";return f(n)?n:null}a(m,"identityFromBinding");async function w(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 d=u(e),o=i.trim();if(!o)throw new s("Missing required JWT verification configuration.");if(o.includes(","))throw new s("Multiple JWT audiences are not supported. Configure a single POLICY_AUD value.");try{const l=(await n.verify(r,d,o)).trim().toLowerCase();if(!f(l))throw new s("Cloudflare Access authentication failed.");return l}catch(l){throw l instanceof s?l:new s("Cloudflare Access authentication failed.")}}a(w,"verifyAccessJwt");export{s as AccessAuthError,j as authenticateAccess,m as identityFromBinding,w as verifyAccessJwt};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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 type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier };\n"],
5
- "mappings": "+EAmCA,OAAS,sBAAAA,EAAoB,aAAAC,MAAiB,OAC9C,OAAS,sBAAAC,MAA0B,mBAqDnC,MAAMC,UAAwB,KAAK,CAzFnC,MAyFmC,CAAAC,EAAA,wBACjC,YAAmBC,EAAe,CAChC,MAAMA,CAAO,EACb,KAAK,KAAO,iBACd,EAWF,MAAMC,EAAmB,GACnBC,EAAY,IAAI,IAEtB,SAASC,EAAoBC,EAAa,CACxC,IAAIC,EAAMD,EAAM,OAChB,KAAOC,EAAM,GAAKD,EAAM,YAAYC,EAAM,CAAC,IAAM,IAAIA,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AIA,aAAiBlC,EAAuBkC,EACtC,IAAIlC,EAAgB,0CAA0C,CACtE,CACF,CArBeC,EAAA0B,EAAA",
6
- "names": ["createRemoteJWKSet", "jwtVerify", "isValidEmailFormat", "AccessAuthError", "__name", "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"]
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';\nimport { UnauthorizedError } from '@rexezuge/errors';\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.\n\nA `ServiceError` with `status: 401`, not a bare `Error`. Every error boundary\nin the family asks `error instanceof ServiceError` before deciding what to do,\nso an authentication failure that is *not* one arrives as an unexpected 500: a\nsigned-out operator is told the server broke, the boundary logs every ordinary\nsign-out as a bug, and the client's \"am I signed in?\" probe cannot distinguish\nthe two. This class extended `Error` and the comment above it claimed it did\nnot, which is how a 401 became a 500 without either statement being wrong about\nitself.\n\n`expose` is inherited: a 401 is a status the message is safe to show, and every\nmessage here is a single fixed sentence that tells an unauthenticated caller\nnothing about how far their token got.\n*/\nclass AccessAuthError extends UnauthorizedError {\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 // A signature that verifies over `email_verified: false` is a correctly\n // signed assertion that the address is *not* verified. Returning the address\n // anyway authenticates the exact case the claim exists to refuse. The\n // binding path below already refused it; this closed the JWT path only, so\n // a repo that authenticated by assertion while its sibling authenticated by\n // binding had one right answer and one wrong.\n if (payload.email_verified === false) {\n throw new AccessAuthError('Cloudflare Access authentication failed.');\n }\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 *\n * The rejection is **logged** at debug. The status is right either way — a\n * binding that cannot answer is not an identity — but a silently swallowed\n * rejection makes a misconfigured `ACCESS` binding and a genuinely signed-out\n * caller indistinguishable in the logs, and the first is an outage an operator\n * can fix in a minute.\n */\nasync function identityFromBinding(binding: AccessBinding | undefined): Promise<string | null> {\n const logRejected = (error: unknown): void => {\n console.debug('[accessAuth] the ACCESS binding getIdentity() rejected; treating it as no identity:', error);\n };\n const identity = await binding?.getIdentity().catch(logRejected);\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"],
5
+ "mappings": "+EAmCA,OAAS,sBAAAA,EAAoB,aAAAC,MAAiB,OAC9C,OAAS,sBAAAC,MAA0B,mBACnC,OAAS,qBAAAC,MAAyB,mBAkElC,MAAMC,UAAwBD,CAAiB,CAvG/C,MAuG+C,CAAAE,EAAA,wBAC7C,YAAmBC,EAAe,CAChC,MAAMA,CAAO,EACb,KAAK,KAAO,iBACd,EAWF,MAAMC,EAAmB,GACnBC,EAAY,IAAI,IAEtB,SAASC,EAAoBC,EAAa,CACxC,IAAIC,EAAMD,EAAM,OAChB,KAAOC,EAAM,GAAKD,EAAM,YAAY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AS,OAAOlB,EAAOE,EAAQiB,CAAQ,GAAG,KAAI,EAAG,YAAW,EACjF,GAAI,CAACf,EAAiBa,CAAK,EAAG,MAAM,IAAIjC,EAAgB,0CAA0C,EAClG,OAAOiC,CACT,OAASF,EAAO,CACd,MAAIA,aAAiB/B,EAAuB+B,EACtC,IAAI/B,EAAgB,0CAA0C,CACtE,CACF,CArBeC,EAAA0B,EAAA",
6
+ "names": ["createRemoteJWKSet", "jwtVerify", "isValidEmailFormat", "UnauthorizedError", "AccessAuthError", "__name", "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", "logRejected", "error", "identity", "email", "verifier", "audience"]
7
7
  }
package/dist/index.d.ts CHANGED
@@ -30,8 +30,8 @@
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.ts';
34
- export type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface } from './rateLimit.ts';
33
+ export { clientIp, getRateLimitBucketCountForTests, MAX_BUCKETS, rateLimit, resetRateLimitForTests } from './rateLimit.ts';
34
+ export type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';
35
35
  export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY, } from './securityHeaders.ts';
36
36
  export type { HeaderContext } from './securityHeaders.ts';
37
37
  export { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;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B,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 +1 @@
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};
1
+ import{clientIp as t,getRateLimitBucketCountForTests as o,MAX_BUCKETS as s,rateLimit as i,resetRateLimitForTests as E}from"./rateLimit.js";import{applySecurityHeaders as c,securityHeaders as T,sensitivePaths as a,CONTENT_SECURITY_POLICY as S,SECURITY_HEADERS as m,STRICT_TRANSPORT_SECURITY as n}from"./securityHeaders.js";import{AccessAuthError as A,authenticateAccess as u,identityFromBinding as C,verifyAccessJwt as _}from"./accessAuth.js";import{errorBody as d,toErrorResponse as f,toServiceError as y,INTERNAL_SERVER_MESSAGE as x}from"./ErrorMapper.js";import{BaseRoute as L,createRouteHandler as N}from"./routeBase.js";export{A as AccessAuthError,L as BaseRoute,S as CONTENT_SECURITY_POLICY,x as INTERNAL_SERVER_MESSAGE,s as MAX_BUCKETS,m as SECURITY_HEADERS,n as STRICT_TRANSPORT_SECURITY,c as applySecurityHeaders,u as authenticateAccess,t as clientIp,N as createRouteHandler,d as errorBody,o as getRateLimitBucketCountForTests,C as identityFromBinding,i as rateLimit,E as resetRateLimitForTests,T as securityHeaders,a as sensitivePaths,f as toErrorResponse,y as toServiceError,_ as verifyAccessJwt};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately. It is also the\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", "createRouteHandler"]
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, getRateLimitBucketCountForTests, MAX_BUCKETS, rateLimit, resetRateLimitForTests } from './rateLimit.ts';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions } from './rateLimit.ts';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders.ts';\nexport type { HeaderContext } from './securityHeaders.ts';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth.ts';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth.ts';\n\nexport { errorBody, 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,mCAAAC,EAAiC,eAAAC,EAAa,aAAAC,EAAW,0BAAAC,MAA8B,iBAG1G,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", "getRateLimitBucketCountForTests", "MAX_BUCKETS", "rateLimit", "resetRateLimitForTests", "applySecurityHeaders", "securityHeaders", "sensitivePaths", "CONTENT_SECURITY_POLICY", "SECURITY_HEADERS", "STRICT_TRANSPORT_SECURITY", "AccessAuthError", "authenticateAccess", "identityFromBinding", "verifyAccessJwt", "errorBody", "toErrorResponse", "toServiceError", "INTERNAL_SERVER_MESSAGE", "BaseRoute", "createRouteHandler"]
7
7
  }
@@ -73,25 +73,41 @@
73
73
  interface RateLimitContext {
74
74
  req: {
75
75
  header(name: string): string | undefined;
76
+ /**
77
+ * A query parameter, for a caller answering in a dialect its own clients parse.
78
+ *
79
+ * The Subsonic envelope is chosen by `?f=` and its callback name by
80
+ * `?callback=`, so a `onThrottled` that builds one has to read both. Without
81
+ * this the only way to answer in a protocol dialect was to cast the context —
82
+ * which is how the one caller that needed it ended up keeping a fork of the
83
+ * whole limiter.
84
+ */
85
+ query?(name: string): string | undefined;
76
86
  };
77
87
  get?(key: string): unknown;
88
+ /**
89
+ * The request's bindings.
90
+ *
91
+ * Present because `max` is a **resolver** over this same context: a limiter whose
92
+ * budget comes from configuration — and a per-stream or per-tenant budget has to
93
+ * come from configuration — has nowhere else to read it from. Without `env` the
94
+ * only way to size such a limit was to close over an ambient, or to cast.
95
+ */
96
+ env?: unknown;
78
97
  json(body: unknown, status?: number, headers?: Record<string, string>): Response;
79
98
  }
80
- type RateLimitSurface = 'rest' | 'user';
81
99
  interface RateLimitOptions {
82
100
  windowMs: number;
83
101
  max: number | ((c: RateLimitContext) => number);
84
102
  keyPrefix: string;
85
- /**
86
- * Which error dialect a 429 answers in. One surface, one dialect: a client
87
- * that parses a Subsonic envelope cannot read the user API's body, so a 429
88
- * carrying it renders as "server error" and the client retries immediately —
89
- * the opposite of what a throttle is for.
90
- */
91
- surface?: RateLimitSurface;
92
103
  /**
93
104
  * Builds the 429 for a surface that has its own envelope. Defaults to the
94
105
  * `{Exception:{Type,Message}}` shape from `@rexezuge/errors`.
106
+ *
107
+ * This is how one surface, one dialect is enforced. A client that parses a
108
+ * Subsonic envelope cannot read the user API's body, so a 429 carrying the
109
+ * wrong one renders as "server error" and the client retries immediately —
110
+ * the opposite of what a throttle is for.
95
111
  */
96
112
  onThrottled?(retryAfter: number, c: RateLimitContext): Response;
97
113
  }
@@ -113,7 +129,24 @@ type RateLimitHandler = (c: RateLimitContext, next: () => Promise<Response | voi
113
129
  * uses the same derivation.
114
130
  */
115
131
  declare function clientIp(header: (name: string) => string | undefined): string;
132
+ /**
133
+ * Upper bound on tracked buckets.
134
+ *
135
+ * Every distinct key costs memory for the isolate's lifetime, so an attacker
136
+ * rotating keys would otherwise grow the map without limit.
137
+ */
138
+ declare const MAX_BUCKETS = 5000;
139
+ /**
140
+ * Test seam: forget every bucket every limiter is holding, and re-arm their
141
+ * sweeps.
142
+ */
143
+ declare function resetRateLimitForTests(): void;
144
+ /**
145
+ * Test seam: how many buckets are tracked across every limiter, so a consumer
146
+ * can assert the cap rather than infer it.
147
+ */
148
+ declare function getRateLimitBucketCountForTests(): number;
116
149
  declare function rateLimit(opts: RateLimitOptions): RateLimitHandler;
117
- export { clientIp, rateLimit };
118
- export type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface };
150
+ export { clientIp, getRateLimitBucketCountForTests, rateLimit, resetRateLimitForTests, MAX_BUCKETS };
151
+ export type { RateLimitContext, RateLimitHandler, RateLimitOptions };
119
152
  //# sourceMappingURL=rateLimit.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rateLimit.d.ts","sourceRoot":"","sources":["../src/rateLimit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AAEH;;;;;;;GAOG;AACH,UAAU,gBAAgB;IACxB,GAAG,EAAE;QAAE,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;KAAE,CAAC;IAClD,GAAG,CAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IAC3B,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC;CAClF;AAED,KAAK,gBAAgB,GAAG,MAAM,GAAG,MAAM,CAAC;AAExC,UAAU,gBAAgB;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,gBAAgB,KAAK,MAAM,CAAC,CAAC;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,gBAAgB,CAAC;IAC3B;;;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AG,QAAQ,CAAC;CAClF;AAED,UAAU,gBAAgB;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,gBAAgB,KAAK,MAAM,CAAC,CAAC;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;;;OAQG;IACH,WAAW,CAAC,CAAC,UAAU,EAAE,MAAM,EAAE,CAAC,EAAE,gBAAgB,GAAG,QAAQ,CAAC;CACjE;AAED,KAAK,gBAAgB,GAAG,CAAC,CAAC,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;AAEhH;;;;;;;;;;;;;;;GAeG;AACH,iBAAS,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,GAAG,MAAM,CAEtE;AAOD;;;;;GAKG;AACH,QAAA,MAAM,WAAW,OAAO,CAAC;AA8FzB;;;GAGG;AACH,iBAAS,sBAAsB,IAAI,IAAI,CAKtC;AAED;;;GAGG;AACH,iBAAS,+BAA+B,IAAI,MAAM,CAIjD;AAED,iBAAS,SAAS,CAAC,IAAI,EAAE,gBAAgB,GAAG,gBAAgB,CA0D3D;AAgCD,OAAO,EAAE,QAAQ,EAAE,+BAA+B,EAAE,SAAS,EAAE,sBAAsB,EAAE,WAAW,EAAE,CAAC;AACrG,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC"}
package/dist/rateLimit.js CHANGED
@@ -1 +1 @@
1
- var l=Object.defineProperty;var o=(e,r)=>l(e,"name",{value:r,configurable:!0});function f(e){return e("CF-Connecting-IP")?.trim()||"unknown"}o(f,"clientIp");const w=5e3,g=1e3,h=3e4;let d=0;function y(e){let r=1/0;for(const[,t]of e)r=Math.min(r,t.resetAt);for(const[t,n]of e)if(n.resetAt===r){e.delete(t);return}}o(y,"evictOldestBucket");function A(e,r){let t=e.size-(w-1);for(;t>0;)y(e),t-=1;if(!(e.size<g)&&!(r-d<h)){d=r;for(const[n,i]of e)i.resetAt<=r&&e.delete(n)}}o(A,"cleanup");function M(e,r){if(typeof e=="number")return e;const t=e(r);if(!Number.isSafeInteger(t)||t<=0)throw new Error(`Invalid rateLimit budget: ${String(t)} (must be a positive integer)`);return t}o(M,"resolveBudget");function v(e){if(!Number.isSafeInteger(e.windowMs)||e.windowMs<=0)throw new Error(`Invalid rateLimit windowMs: ${String(e.windowMs)} (must be a positive integer)`);if(typeof e.max=="number"&&(!Number.isSafeInteger(e.max)||e.max<=0))throw new Error(`Invalid rateLimit max: ${String(e.max)} (must be a positive integer)`);if(!e.keyPrefix||e.keyPrefix.trim().length===0)throw new Error("Invalid rateLimit keyPrefix: must be a non-empty string");const r=new Map;return async(t,n)=>{try{const i=Date.now();A(r,i);const m=M(e.max,t);let u="anon";try{u=t.get?.("AuthenticatedUserEmailAddress")??`ip:${f(s=>t.req.header(s))}`}catch{u=`ip:${f(s=>t.req.header(s))}`}const c=`${e.keyPrefix}:${u}`,a=r.get(c);if(!a||a.resetAt<=i)return r.set(c,{count:1,resetAt:i+e.windowMs}),await n();if(a.count>=m){const s=Math.max(1,Math.ceil((a.resetAt-i)/1e3));return x(s,t,e)}return a.count+=1,await n()}catch{return await n()}}}o(v,"rateLimit");function x(e,r,t){const n={"Retry-After":String(e)};return t.onThrottled?t.onThrottled(e,r):r.json({Exception:{Type:"RateLimited",Message:`Too many requests. Retry after ${e}s.`}},429,n)}o(x,"throttled");export{f as clientIp,v as rateLimit};
1
+ var w=Object.defineProperty;var s=(e,r)=>w(e,"name",{value:r,configurable:!0});function f(e){return e("CF-Connecting-IP")?.trim()||"unknown"}s(f,"clientIp");const m=5e3,g=1e3,h=3e4;function y(e){let r=1/0;for(const[,t]of e)r=Math.min(r,t.resetAt);for(const[t,n]of e)if(n.resetAt===r){e.delete(t);return}}s(y,"evictOldestBucket");function b(e,r){const{buckets:t}=e;let n=t.size-(m-1);for(;n>0;)y(t),n-=1;if(!(t.size<g)&&!(r-e.lastCleanupAt<h)){e.lastCleanupAt=r;for(const[i,u]of t)u.resetAt<=r&&t.delete(i)}}s(b,"cleanup");function k(e,r){if(typeof e=="number")return e;const t=e(r);if(!Number.isSafeInteger(t)||t<=0)throw new Error(`Invalid rateLimit budget: ${String(t)} (must be a positive integer)`);return t}s(k,"resolveBudget");const l=[];function A(){for(const e of l)e.buckets.clear(),e.lastCleanupAt=0}s(A,"resetRateLimitForTests");function L(){let e=0;for(const r of l)e+=r.buckets.size;return e}s(L,"getRateLimitBucketCountForTests");function M(e){if(!Number.isSafeInteger(e.windowMs)||e.windowMs<=0)throw new Error(`Invalid rateLimit windowMs: ${String(e.windowMs)} (must be a positive integer)`);if(typeof e.max=="number"&&(!Number.isSafeInteger(e.max)||e.max<=0))throw new Error(`Invalid rateLimit max: ${String(e.max)} (must be a positive integer)`);if(!e.keyPrefix||e.keyPrefix.trim().length===0)throw new Error("Invalid rateLimit keyPrefix: must be a non-empty string");const r={buckets:new Map,lastCleanupAt:0};return l.push(r),async(t,n)=>{try{const i=Date.now();b(r,i);const u=k(e.max,t);let c="anon";try{c=t.get?.("AuthenticatedUserEmailAddress")??`ip:${f(a=>t.req.header(a))}`}catch{c=`ip:${f(a=>t.req.header(a))}`}const d=`${e.keyPrefix}:${c}`,o=r.buckets.get(d);if(!o||o.resetAt<=i)return r.buckets.set(d,{count:1,resetAt:i+e.windowMs}),await n();if(o.count>=u){const a=Math.max(1,Math.ceil((o.resetAt-i)/1e3));return v(a,t,e)}return o.count+=1,await n()}catch{return await n()}}}s(M,"rateLimit");function v(e,r,t){const n={"Retry-After":String(e)},i=t.onThrottled?t.onThrottled(e,r):r.json({Exception:{Type:"RateLimited",Message:`Too many requests. Retry after ${e}s.`}},429,n);return i.headers.has("Retry-After")||i.headers.set("Retry-After",String(e)),i}s(v,"throttled");export{m as MAX_BUCKETS,f as clientIp,L as getRateLimitBucketCountForTests,M as rateLimit,A as resetRateLimitForTests};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/rateLimit.ts"],
4
- "sourcesContent": ["/**\n * The family's per-isolate rate limiter.\n *\n * Converged from `apps/api/src/middleware/rateLimit.ts` in Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic. Edge-Sonic's was the one that\n * had solved the three defects the other three still carried, so this is that\n * one; the differences below are what each fix bought.\n *\n * ## Design decisions\n *\n * ### `max` may be a resolver, and why that is the only honest shape\n *\n * A budget read from the environment cannot be resolved at registration time:\n * the route table is built once in the worker constructor, where `env` does not\n * exist, so a `STREAM_RATE_LIMIT` read there would be a module-level constant\n * wearing a variable's name. That is how the variable came to be declared,\n * validated, shipped in the wrangler template and read by nothing while the\n * limiter used a literal — the knob was real and the code was not reading it.\n *\n * A resolver is evaluated per request from the context. The static check at\n * registration is skipped for one, because a limiter that throws *while being\n * installed* takes down every route it was attached to; an unusable answer is\n * caught per request instead.\n *\n * ### The sweep is time-triggered, not size-triggered\n *\n * It used to run on **every** request above a bucket threshold. Memory was\n * already bounded by the cap, so the cap was never the problem — the *cost* was,\n * and it was paid by every caller rather than by the one who filled the map. An\n * attacker rotating a thousand distinct keys turned every subsequent request on\n * that isolate into O(n) map work against the Free plan's 10 ms CPU budget: a\n * cheap way to make a rate limiter a denial-of-service vector against itself.\n *\n * So the **cap is enforced on every request** and only the **sweep is deferred**.\n * Those are different jobs with different failure modes: memory grows whether or\n * not a sweep runs, so deferring the cap would make the bound wrong, while the\n * sweep only reclaims memory the cap has already bounded. Nothing is lost by\n * deferring it — an expired bucket is already treated as absent by the request\n * path.\n *\n * ### An unusable budget fails **open**\n *\n * A resolver that throws must not produce an unlimited bucket: `count >= NaN` is\n * false, so a broken resolver silently turns the limiter **off** rather than\n * off-by-a-lot — the direction nobody notices. The call is therefore guarded, and\n * a throw propagates to the limiter's own fail-open path rather than to a bucket\n * check that no longer bounds anything.\n *\n * The value is only ever what the resolver returned. Deciding what an *unusable*\n * value falls back to belongs to whoever supplied it, because only they know the\n * limit's own default.\n *\n * ### `next()` runs exactly once\n *\n * The `try` encloses the limiter's own work and **not** `await next()`. It used\n * to enclose both, which caught anything the downstream chain rejected and\n * called `next()` a second time from the `catch`. A fail-open branch should not\n * enclose the thing it is failing open *for*.\n *\n * ## Per-isolate only\n *\n * Workers have no shared memory, so this bounds abuse per isolate and nothing\n * more. It is never a security control on its own.\n */\n\n/**\n * The slice of a Hono context this limiter reads.\n *\n * Structural rather than `Context<…>` so a caller can pass any framework\n * context (or a test double) without this package pinning the generic\n * parameters, and so a plain `Request`-dispatching surface can share the\n * derivation.\n */\ninterface RateLimitContext {\n req: { header(name: string): string | undefined };\n get?(key: string): unknown;\n json(body: unknown, status?: number, headers?: Record<string, string>): Response;\n}\n\ntype RateLimitSurface = 'rest' | 'user';\n\ninterface RateLimitOptions {\n windowMs: number;\n max: number | ((c: RateLimitContext) => number);\n keyPrefix: string;\n /**\n * Which error dialect a 429 answers in. One surface, one dialect: a client\n * that parses a Subsonic envelope cannot read the user API's body, so a 429\n * carrying it renders as \"server error\" and the client retries immediately —\n * the opposite of what a throttle is for.\n */\n surface?: RateLimitSurface;\n /**\n * Builds the 429 for a surface that has its own envelope. Defaults to the\n * `{Exception:{Type,Message}}` shape from `@rexezuge/errors`.\n */\n onThrottled?(retryAfter: number, c: RateLimitContext): Response;\n}\n\ntype RateLimitHandler = (c: RateLimitContext, next: () => Promise<Response | void>) => Promise<Response | void>;\n\n/**\n * The one trusted client address.\n *\n * Trust order is deliberately a single entry: Cloudflare sets\n * `CF-Connecting-IP` and it cannot be spoofed by a client. `X-Forwarded-For`,\n * `x-real-ip` and every other forwarding header are **not** consulted, because\n * they are client-controlled and let an attacker rotate buckets — or, on a\n * surface with an offline credential throttle, rotate the identity keying it and\n * brute-force forever.\n *\n * Local dev without CF headers shares the `unknown` bucket, which is fail-closed\n * grouping rather than per-spoofed-header isolation.\n *\n * Takes a header reader rather than a context so a bare-`Request` dispatcher\n * uses the same derivation.\n */\nfunction clientIp(header: (name: string) => string | undefined): string {\n return header('CF-Connecting-IP')?.trim() || 'unknown';\n}\n\ninterface Bucket {\n count: number;\n resetAt: number;\n}\n\n/**\n * Upper bound on tracked buckets.\n *\n * Every distinct key costs memory for the isolate's lifetime, so an attacker\n * rotating keys would otherwise grow the map without limit.\n */\nconst MAX_BUCKETS = 5000;\n\n/**\n * Below this many buckets, cleanup does nothing at all.\n *\n * The threshold rather than 0: sweeping a handful of entries on every request is\n * work for nothing, and below the threshold an expiry sweep cannot reclaim\n * enough to matter.\n */\nconst CLEANUP_THRESHOLD = 1000;\n\n/**\nThe sweep runs at most this often, regardless of bucket count.\n*/\nconst CLEANUP_INTERVAL_MS = 30_000;\n\nlet lastCleanupAt = 0;\n\nfunction evictOldestBucket(buckets: Map<string, Bucket>): void {\n let oldestReset = Infinity;\n for (const [, bucket] of buckets) {\n oldestReset = Math.min(oldestReset, bucket.resetAt);\n }\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt === oldestReset) {\n buckets.delete(key);\n return;\n }\n }\n}\n\nfunction cleanup(buckets: Map<string, Bucket>, now: number): void {\n // The cap is enforced here, on **every** request, and only the sweep is\n // deferred. Evicting *down* rather than clearing, so an attacker flooding new\n // keys cannot wipe out everyone else's buckets — and down to `MAX_BUCKETS - 1`\n // because the caller adds its own bucket immediately afterwards.\n let overflow = buckets.size - (MAX_BUCKETS - 1);\n while (overflow > 0) {\n evictOldestBucket(buckets);\n overflow -= 1;\n }\n\n // The sweep is amortised. An expired bucket is *already* treated as absent by\n // the request path, so the sweep only reclaims memory — and memory is what the\n // cap above already bounds. The cost moves from per-request to a fixed rate.\n if (buckets.size < CLEANUP_THRESHOLD) return;\n if (now - lastCleanupAt < CLEANUP_INTERVAL_MS) return;\n lastCleanupAt = now;\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt <= now) buckets.delete(key);\n }\n}\n\n/**\n * The budget to enforce for this request.\n *\n * A resolver that throws, or that answers something that is not a positive\n * integer, is rejected here — in one place — so the limiter's own `try` fails\n * open for both rather than only for the throw.\n */\nfunction resolveBudget(max: number | ((c: RateLimitContext) => number), c: RateLimitContext): number {\n if (typeof max === 'number') return max;\n const resolved = max(c);\n if (!Number.isSafeInteger(resolved) || resolved <= 0) {\n throw new Error(`Invalid rateLimit budget: ${String(resolved)} (must be a positive integer)`);\n }\n return resolved;\n}\n\nfunction rateLimit(opts: RateLimitOptions): RateLimitHandler {\n // Misconfiguration throws at registration rather than silently installing an\n // unlimited or immediately-tripping bucket. A resolver is exempt: an\n // unusable answer there is caught per request, because a limiter that throws\n // *while being installed* takes down every route it was attached to.\n if (!Number.isSafeInteger(opts.windowMs) || opts.windowMs <= 0) {\n throw new Error(`Invalid rateLimit windowMs: ${String(opts.windowMs)} (must be a positive integer)`);\n }\n if (typeof opts.max === 'number' && (!Number.isSafeInteger(opts.max) || opts.max <= 0)) {\n throw new Error(`Invalid rateLimit max: ${String(opts.max)} (must be a positive integer)`);\n }\n if (!opts.keyPrefix || opts.keyPrefix.trim().length === 0) {\n throw new Error('Invalid rateLimit keyPrefix: must be a non-empty string');\n }\n\n const buckets = new Map<string, Bucket>();\n\n return async (c: RateLimitContext, next: () => Promise<Response | void>): Promise<Response | void> => {\n // The limiter's own work, and **only** the limiter's own work, is inside\n // this `try`. `next()` runs from here or from a path below, never from both.\n try {\n const now = Date.now();\n cleanup(buckets, now);\n const max = resolveBudget(opts.max, c);\n\n // Prefer a resolved identity over the client address, so a bucket is per\n // operator rather than per address. Only read when the middleware can see\n // one — which is why the order of registration against auth is\n // load-bearing: a limiter installed before the identity exists silently\n // degrades to `ip:…` and every operator behind one NAT shares a budget.\n let identity = 'anon';\n try {\n identity = (c.get?.('AuthenticatedUserEmailAddress') as string | undefined) ?? `ip:${clientIp((name) => c.req.header(name))}`;\n } catch {\n identity = `ip:${clientIp((name) => c.req.header(name))}`;\n }\n\n const key = `${opts.keyPrefix}:${identity}`;\n const existing = buckets.get(key);\n if (!existing || existing.resetAt <= now) {\n buckets.set(key, { count: 1, resetAt: now + opts.windowMs });\n return await next();\n }\n\n if (existing.count >= max) {\n const retryAfter = Math.max(1, Math.ceil((existing.resetAt - now) / 1000));\n return throttled(retryAfter, c, opts);\n }\n\n existing.count += 1;\n return await next();\n } catch {\n // Fail open: the limiter could not size itself, and a request must not fail\n // because limiting could not be done.\n return await next();\n }\n };\n}\n\n/**\n * The 429 itself.\n *\n * `Retry-After` travels on the header as well as in the message: a client that\n * only reads the status has no other way to know how long to wait, and one that\n * retries immediately is the failure a throttle exists to prevent.\n */\nfunction throttled(retryAfter: number, c: RateLimitContext, opts: RateLimitOptions): Response {\n const headers = { 'Retry-After': String(retryAfter) };\n if (opts.onThrottled) return opts.onThrottled(retryAfter, c);\n\n // The family's canonical dialect, without importing the error taxonomy into the\n // limiter's hot path: a rate-limited request is a 429 carrying a `RateLimited`\n // type and the retry hint in its message.\n const response = c.json({ Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } }, 429, headers);\n return response;\n}\n\nexport { clientIp, rateLimit };\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface };\n"],
5
- "mappings": "+EAqHA,SAASA,EAASC,EAA4C,CAC5D,OAAOA,EAAO,kBAAkB,GAAG,KAAI,GAAM,SAC/C,CAFSC,EAAAF,EAAA,YAeT,MAAMG,EAAc,IASdC,EAAoB,IAKpBC,EAAsB,IAE5B,IAAIC,EAAgB,EAEpB,SAASC,EAAkBC,EAA4B,CACrD,IAAIC,EAAc,IAClB,SAAW,CAAC,CAAEC,CAAM,IAAKF,EACvBC,EAAc,KAAK,IAAIA,EAAaC,EAAO,OAAO,EAEpD,SAAW,CAACC,EAAKD,CAAM,IAAKF,EAC1B,GAAIE,EAAO,UAAYD,EAAa,CAClCD,EAAQ,OAAOG,CAAG,EAClB,MACF,CAEJ,CAXST,EAAAK,EAAA,qBAaT,SAASK,EAAQJ,EAA8B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AMjB,EAAUuB,GAASN,EAAE,IAAI,OAAOM,CAAI,CAAC,CAAC,EAC7H,MAAQ,CACND,EAAW,MAAMtB,EAAUuB,GAASN,EAAE,IAAI,OAAOM,CAAI,CAAC,CAAC,EACzD,CAEA,MAAMZ,EAAM,GAAGS,EAAK,SAAS,IAAIE,CAAQ,GACnCE,EAAWhB,EAAQ,IAAIG,CAAG,EAChC,GAAI,CAACa,GAAYA,EAAS,SAAWX,EACnC,OAAAL,EAAQ,IAAIG,EAAK,CAAE,MAAO,EAAG,QAASE,EAAMO,EAAK,QAAQ,CAAE,EACpD,MAAMC,EAAI,EAGnB,GAAIG,EAAS,OAASR,EAAK,CACzB,MAAMS,EAAa,KAAK,IAAI,EAAG,KAAK,MAAMD,EAAS,QAAUX,GAAO,GAAI,CAAC,EACzE,OAAOa,EAAUD,EAAYR,EAAGG,CAAI,CACtC,CAEA,OAAAI,EAAS,OAAS,EACX,MAAMH,EAAI,CACnB,MAAQ,CAGN,OAAO,MAAMA,EAAI,CACnB,CACF,CACF,CAzDSnB,EAAAiB,EAAA,aAkET,SAASO,EAAUD,EAAoBR,EAAqBG,EAAsB,CAChF,MAAMO,EAAU,CAAE,cAAe,OAAOF,CAAU,CAAC,EACnD,OAAIL,EAAK,YAAoBA,EAAK,YAAYK,EAAYR,CAAC,EAK1CA,EAAE,KAAK,CAAE,UAAW,CAAE,KAAM,cAAe,QAAS,kCAAkCQ,CAAU,IAAI,CAAE,EAAI,IAAKE,CAAO,CAEzI,CATSzB,EAAAwB,EAAA",
6
- "names": ["clientIp", "header", "__name", "MAX_BUCKETS", "CLEANUP_THRESHOLD", "CLEANUP_INTERVAL_MS", "lastCleanupAt", "evictOldestBucket", "buckets", "oldestReset", "bucket", "key", "cleanup", "now", "overflow", "resolveBudget", "max", "c", "resolved", "rateLimit", "opts", "next", "identity", "name", "existing", "retryAfter", "throttled", "headers"]
4
+ "sourcesContent": ["/**\n * The family's per-isolate rate limiter.\n *\n * Converged from `apps/api/src/middleware/rateLimit.ts` in Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic. Edge-Sonic's was the one that\n * had solved the three defects the other three still carried, so this is that\n * one; the differences below are what each fix bought.\n *\n * ## Design decisions\n *\n * ### `max` may be a resolver, and why that is the only honest shape\n *\n * A budget read from the environment cannot be resolved at registration time:\n * the route table is built once in the worker constructor, where `env` does not\n * exist, so a `STREAM_RATE_LIMIT` read there would be a module-level constant\n * wearing a variable's name. That is how the variable came to be declared,\n * validated, shipped in the wrangler template and read by nothing while the\n * limiter used a literal — the knob was real and the code was not reading it.\n *\n * A resolver is evaluated per request from the context. The static check at\n * registration is skipped for one, because a limiter that throws *while being\n * installed* takes down every route it was attached to; an unusable answer is\n * caught per request instead.\n *\n * ### The sweep is time-triggered, not size-triggered\n *\n * It used to run on **every** request above a bucket threshold. Memory was\n * already bounded by the cap, so the cap was never the problem — the *cost* was,\n * and it was paid by every caller rather than by the one who filled the map. An\n * attacker rotating a thousand distinct keys turned every subsequent request on\n * that isolate into O(n) map work against the Free plan's 10 ms CPU budget: a\n * cheap way to make a rate limiter a denial-of-service vector against itself.\n *\n * So the **cap is enforced on every request** and only the **sweep is deferred**.\n * Those are different jobs with different failure modes: memory grows whether or\n * not a sweep runs, so deferring the cap would make the bound wrong, while the\n * sweep only reclaims memory the cap has already bounded. Nothing is lost by\n * deferring it — an expired bucket is already treated as absent by the request\n * path.\n *\n * ### An unusable budget fails **open**\n *\n * A resolver that throws must not produce an unlimited bucket: `count >= NaN` is\n * false, so a broken resolver silently turns the limiter **off** rather than\n * off-by-a-lot — the direction nobody notices. The call is therefore guarded, and\n * a throw propagates to the limiter's own fail-open path rather than to a bucket\n * check that no longer bounds anything.\n *\n * The value is only ever what the resolver returned. Deciding what an *unusable*\n * value falls back to belongs to whoever supplied it, because only they know the\n * limit's own default.\n *\n * ### `next()` runs exactly once\n *\n * The `try` encloses the limiter's own work and **not** `await next()`. It used\n * to enclose both, which caught anything the downstream chain rejected and\n * called `next()` a second time from the `catch`. A fail-open branch should not\n * enclose the thing it is failing open *for*.\n *\n * ## Per-isolate only\n *\n * Workers have no shared memory, so this bounds abuse per isolate and nothing\n * more. It is never a security control on its own.\n */\n\n/**\n * The slice of a Hono context this limiter reads.\n *\n * Structural rather than `Context<…>` so a caller can pass any framework\n * context (or a test double) without this package pinning the generic\n * parameters, and so a plain `Request`-dispatching surface can share the\n * derivation.\n */\ninterface RateLimitContext {\n req: {\n header(name: string): string | undefined;\n /**\n * A query parameter, for a caller answering in a dialect its own clients parse.\n *\n * The Subsonic envelope is chosen by `?f=` and its callback name by\n * `?callback=`, so a `onThrottled` that builds one has to read both. Without\n * this the only way to answer in a protocol dialect was to cast the context —\n * which is how the one caller that needed it ended up keeping a fork of the\n * whole limiter.\n */\n query?(name: string): string | undefined;\n };\n get?(key: string): unknown;\n /**\n * The request's bindings.\n *\n * Present because `max` is a **resolver** over this same context: a limiter whose\n * budget comes from configuration — and a per-stream or per-tenant budget has to\n * come from configuration — has nowhere else to read it from. Without `env` the\n * only way to size such a limit was to close over an ambient, or to cast.\n */\n env?: unknown;\n json(body: unknown, status?: number, headers?: Record<string, string>): Response;\n}\n\ninterface RateLimitOptions {\n windowMs: number;\n max: number | ((c: RateLimitContext) => number);\n keyPrefix: string;\n /**\n * Builds the 429 for a surface that has its own envelope. Defaults to the\n * `{Exception:{Type,Message}}` shape from `@rexezuge/errors`.\n *\n * This is how one surface, one dialect is enforced. A client that parses a\n * Subsonic envelope cannot read the user API's body, so a 429 carrying the\n * wrong one renders as \"server error\" and the client retries immediately —\n * the opposite of what a throttle is for.\n */\n onThrottled?(retryAfter: number, c: RateLimitContext): Response;\n}\n\ntype RateLimitHandler = (c: RateLimitContext, next: () => Promise<Response | void>) => Promise<Response | void>;\n\n/**\n * The one trusted client address.\n *\n * Trust order is deliberately a single entry: Cloudflare sets\n * `CF-Connecting-IP` and it cannot be spoofed by a client. `X-Forwarded-For`,\n * `x-real-ip` and every other forwarding header are **not** consulted, because\n * they are client-controlled and let an attacker rotate buckets — or, on a\n * surface with an offline credential throttle, rotate the identity keying it and\n * brute-force forever.\n *\n * Local dev without CF headers shares the `unknown` bucket, which is fail-closed\n * grouping rather than per-spoofed-header isolation.\n *\n * Takes a header reader rather than a context so a bare-`Request` dispatcher\n * uses the same derivation.\n */\nfunction clientIp(header: (name: string) => string | undefined): string {\n return header('CF-Connecting-IP')?.trim() || 'unknown';\n}\n\ninterface Bucket {\n count: number;\n resetAt: number;\n}\n\n/**\n * Upper bound on tracked buckets.\n *\n * Every distinct key costs memory for the isolate's lifetime, so an attacker\n * rotating keys would otherwise grow the map without limit.\n */\nconst MAX_BUCKETS = 5000;\n\n/**\n * Below this many buckets, cleanup does nothing at all.\n *\n * The threshold rather than 0: sweeping a handful of entries on every request is\n * work for nothing, and below the threshold an expiry sweep cannot reclaim\n * enough to matter.\n */\nconst CLEANUP_THRESHOLD = 1000;\n\n/**\nThe sweep runs at most this often, regardless of bucket count.\n*/\nconst CLEANUP_INTERVAL_MS = 30_000;\n\n/**\n * One limiter's buckets, plus when it last swept.\n *\n * The timestamp lives **beside** the map rather than at module scope. It used to\n * be a module-level `let` next to a per-limiter `Map`, and the two disagreed:\n * limiter A's sweep set the timestamp and suppressed limiter B's for the next\n * 30 seconds, so a map B owned was left holding expired keys while A's map —\n * swept on the same clock — was clean. Two limiters with the same shape have\n * different traffic; the shared clock made one of them's memory bound the\n * other's.\n */\ninterface LimiterState {\n buckets: Map<string, Bucket>;\n lastCleanupAt: number;\n}\n\nfunction evictOldestBucket(buckets: Map<string, Bucket>): void {\n let oldestReset = Infinity;\n for (const [, bucket] of buckets) {\n oldestReset = Math.min(oldestReset, bucket.resetAt);\n }\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt === oldestReset) {\n buckets.delete(key);\n return;\n }\n }\n}\n\nfunction cleanup(state: LimiterState, now: number): void {\n const { buckets } = state;\n // The cap is enforced here, on **every** request, and only the sweep is\n // deferred. Evicting *down* rather than clearing, so an attacker flooding new\n // keys cannot wipe out everyone else's buckets — and down to `MAX_BUCKETS - 1`\n // because the caller adds its own bucket immediately afterwards.\n let overflow = buckets.size - (MAX_BUCKETS - 1);\n while (overflow > 0) {\n evictOldestBucket(buckets);\n overflow -= 1;\n }\n\n // The sweep is amortised. An expired bucket is *already* treated as absent by\n // the request path, so the sweep only reclaims memory — and memory is what the\n // cap above already bounds. The cost moves from per-request to a fixed rate.\n if (buckets.size < CLEANUP_THRESHOLD) return;\n if (now - state.lastCleanupAt < CLEANUP_INTERVAL_MS) return;\n state.lastCleanupAt = now;\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt <= now) buckets.delete(key);\n }\n}\n\n/**\n * The budget to enforce for this request.\n *\n * A resolver that throws, or that answers something that is not a positive\n * integer, is rejected here — in one place — so the limiter's own `try` fails\n * open for both rather than only for the throw.\n */\nfunction resolveBudget(max: number | ((c: RateLimitContext) => number), c: RateLimitContext): number {\n if (typeof max === 'number') return max;\n const resolved = max(c);\n if (!Number.isSafeInteger(resolved) || resolved <= 0) {\n throw new Error(`Invalid rateLimit budget: ${String(resolved)} (must be a positive integer)`);\n }\n return resolved;\n}\n\n/**\n * Every limiter registered in this isolate, for the test seams below.\n *\n * The bucket map is a closure local, so there was nothing outside `rateLimit()`\n * that could observe the cap or reset it — and a cap nothing measures is a cap\n * nothing has tested. A consumer asserting \"the bucket map never exceeded\n * {@link MAX_BUCKETS}\" had no way to.\n */\nconst registeredLimiters: LimiterState[] = [];\n\n/**\n * Test seam: forget every bucket every limiter is holding, and re-arm their\n * sweeps.\n */\nfunction resetRateLimitForTests(): void {\n for (const state of registeredLimiters) {\n state.buckets.clear();\n state.lastCleanupAt = 0;\n }\n}\n\n/**\n * Test seam: how many buckets are tracked across every limiter, so a consumer\n * can assert the cap rather than infer it.\n */\nfunction getRateLimitBucketCountForTests(): number {\n let total = 0;\n for (const state of registeredLimiters) total += state.buckets.size;\n return total;\n}\n\nfunction rateLimit(opts: RateLimitOptions): RateLimitHandler {\n // Misconfiguration throws at registration rather than silently installing an\n // unlimited or immediately-tripping bucket. A resolver is exempt: an\n // unusable answer there is caught per request, because a limiter that throws\n // *while being installed* takes down every route it was attached to.\n if (!Number.isSafeInteger(opts.windowMs) || opts.windowMs <= 0) {\n throw new Error(`Invalid rateLimit windowMs: ${String(opts.windowMs)} (must be a positive integer)`);\n }\n if (typeof opts.max === 'number' && (!Number.isSafeInteger(opts.max) || opts.max <= 0)) {\n throw new Error(`Invalid rateLimit max: ${String(opts.max)} (must be a positive integer)`);\n }\n if (!opts.keyPrefix || opts.keyPrefix.trim().length === 0) {\n throw new Error('Invalid rateLimit keyPrefix: must be a non-empty string');\n }\n\n const state: LimiterState = { buckets: new Map<string, Bucket>(), lastCleanupAt: 0 };\n registeredLimiters.push(state);\n\n return async (c: RateLimitContext, next: () => Promise<Response | void>): Promise<Response | void> => {\n // The limiter's own work, and **only** the limiter's own work, is inside\n // this `try`. `next()` runs from here or from a path below, never from both.\n try {\n const now = Date.now();\n cleanup(state, now);\n const max = resolveBudget(opts.max, c);\n\n // Prefer a resolved identity over the client address, so a bucket is per\n // operator rather than per address. Only read when the middleware can see\n // one — which is why the order of registration against auth is\n // load-bearing: a limiter installed before the identity exists silently\n // degrades to `ip:…` and every operator behind one NAT shares a budget.\n let identity = 'anon';\n try {\n identity = (c.get?.('AuthenticatedUserEmailAddress') as string | undefined) ?? `ip:${clientIp((name) => c.req.header(name))}`;\n } catch {\n identity = `ip:${clientIp((name) => c.req.header(name))}`;\n }\n\n const key = `${opts.keyPrefix}:${identity}`;\n const existing = state.buckets.get(key);\n if (!existing || existing.resetAt <= now) {\n state.buckets.set(key, { count: 1, resetAt: now + opts.windowMs });\n return await next();\n }\n\n if (existing.count >= max) {\n const retryAfter = Math.max(1, Math.ceil((existing.resetAt - now) / 1000));\n return throttled(retryAfter, c, opts);\n }\n\n existing.count += 1;\n return await next();\n } catch {\n // Fail open: the limiter could not size itself, and a request must not fail\n // because limiting could not be done.\n return await next();\n }\n };\n}\n\n/**\n * The 429 itself.\n *\n * `Retry-After` travels on the header as well as in the message: a client that\n * only reads the status has no other way to know how long to wait, and one that\n * retries immediately is the failure a throttle exists to prevent.\n *\n * The header is applied on **both** paths, including the `onThrottled` one. It\n * was computed and then discarded when a custom dialect was supplied, so a\n * limiter that had installed `onThrottled` to answer in a protocol envelope\n * silently dropped the one header the client's backoff depends on — and the\n * failure looks like the client ignoring a throttle rather than the server\n * forgetting to say when to resume. A custom body that cannot carry headers gets\n * them attached afterwards; nothing here can now forget to.\n */\nfunction throttled(retryAfter: number, c: RateLimitContext, opts: RateLimitOptions): Response {\n const headers = { 'Retry-After': String(retryAfter) };\n const response = opts.onThrottled\n ? opts.onThrottled(retryAfter, c)\n : // The family's canonical dialect, without importing the error taxonomy into\n // the limiter's hot path: a rate-limited request is a 429 carrying a\n // `RateLimited` type and the retry hint in its message.\n c.json({ Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } }, 429, headers);\n\n if (!response.headers.has('Retry-After')) {\n response.headers.set('Retry-After', String(retryAfter));\n }\n return response;\n}\n\nexport { clientIp, getRateLimitBucketCountForTests, rateLimit, resetRateLimitForTests, MAX_BUCKETS };\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions };\n"],
5
+ "mappings": "+EAsIA,SAASA,EAASC,EAA4C,CAC5D,OAAOA,EAAO,kBAAkB,GAAG,KAAI,GAAM,SAC/C,CAFSC,EAAAF,EAAA,YAeT,MAAMG,EAAc,IASdC,EAAoB,IAKpBC,EAAsB,IAkB5B,SAASC,EAAkBC,EAA4B,CACrD,IAAIC,EAAc,IAClB,SAAW,CAAC,CAAEC,CAAM,IAAKF,EACvBC,EAAc,KAAK,IAAIA,EAAaC,EAAO,OAAO,EAEpD,SAAW,CAACC,EAAKD,CAAM,IAAKF,EAC1B,GAAIE,EAAO,UAAYD,EAAa,CAClCD,EAAQ,OAAOG,CAAG,EAClB,MACF,CAEJ,CAXSR,EAAAI,EAAA,qBAaT,SAASK,EAAQC,EAAqBC,EA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E,KAAK,CAAE,UAAW,CAAE,KAAM,cAAe,QAAS,kCAAkCY,CAAU,IAAI,CAAE,EAAI,IAAKE,CAAO,EAE1H,OAAKC,EAAS,QAAQ,IAAI,aAAa,GACrCA,EAAS,QAAQ,IAAI,cAAe,OAAOH,CAAU,CAAC,EAEjDG,CACT,CAbS9B,EAAA4B,EAAA",
6
+ "names": ["clientIp", "header", "__name", "MAX_BUCKETS", "CLEANUP_THRESHOLD", "CLEANUP_INTERVAL_MS", "evictOldestBucket", "buckets", "oldestReset", "bucket", "key", "cleanup", "state", "now", "overflow", "resolveBudget", "max", "c", "resolved", "registeredLimiters", "resetRateLimitForTests", "getRateLimitBucketCountForTests", "total", "rateLimit", "opts", "next", "identity", "name", "existing", "retryAfter", "throttled", "headers", "response"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"routeBase.d.ts","sourceRoot":"","sources":["../src/routeBase.ts"],"names":[],"mappings":"AAmCA;;EAEE;AACF,UAAU,YAAY;IACpB,GAAG,EAAE;QAAE,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;QAAC,GAAG,EAAE,OAAO,CAAA;KAAE,CAAC;IAChD,GAAG,EAAE,OAAO,CAAC;IACb,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC;IACjF;;MAEE;IACF,GAAG,CAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CAC5B;AAED,KAAK,YAAY,GAAG,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAE3D,UAAU,mBAAmB;IAC3B;;MAEE;IACF,OAAO,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,YAAY,GAAG,QAAQ,CAAC;CACrD;AAMD;;;;;;;GAOG;AACH,QAAA,MAAM,SAAS;IACb;;;;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;IAQjD;;MAEE;oCACmB,OAAO,SAAS,MAAM,KAAG,MAAM;IAOpD;;MAEE;sCACqB,OAAO,KAAK,YAAY,YAAY,mBAAmB,KAAG,QAAQ;CAGjF,CAAC;AAEX;;;;;;GAMG;AACH,iBAAS,kBAAkB,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,GAAE,mBAAwB,GAAG,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,QAAQ,CAAC,CAQ3H;AAED,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC;AACzC,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,CAAC"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/routeBase.ts"],
4
- "sourcesContent": ["/**\n * Shared statics for Hono route handlers.\n *\n * Converged from `endpoints/IBaseRoute.ts` / `endpoints/BaseRoute.ts` in the\n * nine full-framework repos, which currently hold **three incompatible shapes**:\n * a chanfana `OpenAPIRoute` subclass, a Hono `Response`-returning base class, and\n * a namespace of statics. All three survive here, because the decision of which\n * to use is genuinely per-repo — but the *parts* they share no longer do.\n *\n * ## Why a namespace and not a base class\n *\n * Durable-DAV's Template Method (`abstract handleRequest` + `handle()` owning the\n * try/catch) had **zero** subclasses — `VolumeScopedRoute` reimplements the same\n * try/catch against the same `toErrorResponse` — so it advertised an inheritance\n * contract nothing was using, while its own doc comment claimed handlers \"stop\n * duplicating\" error mapping.\n *\n * So the shared surface is a namespace of statics. A repo that wants the Template\n * Method takes {@link createRouteHandler}; a repo that does not takes the statics\n * directly. Neither pays for the other's abstraction.\n *\n * ## Why both route bases ship\n *\n * Six of the nine repos build routes as chanfana `OpenAPIRoute` subclasses with\n * file-based routing and a zod schema registry. Edge-Git, Edge-Sonic and\n * Durable-DAV-Router register handlers imperatively against a `Hono` app and\n * return `Response` themselves.\n *\n * Both are here. `IBaseRoute` is the chanfana shape; {@link createRouteHandler}\n * builds the imperative one. Converging them would have meant picking a loser on a\n * decision that is not the kit's to make.\n */\nimport { BadRequestError } from '@rexezuge/errors';\nimport { toErrorResponse } from './ErrorMapper.ts';\n\n/**\nThe slice of a Hono context a route handler reads.\n*/\ninterface RouteContext {\n req: { json(): Promise<unknown>; raw: Request };\n env: unknown;\n json(body: unknown, status?: number, headers?: Record<string, string>): Response;\n /**\n Optional request scope, when the repo uses DI.\n */\n get?(key: string): unknown;\n}\n\ntype RouteHandler = (c: RouteContext) => Promise<Response>;\n\ninterface RouteHandlerOptions {\n /**\n A repo-specific mapper. Defaults to the canonical `{Exception:{…}}` dialect.\n */\n onError?(error: unknown, c: RouteContext): Response;\n}\n\nfunction defaultOnError(error: unknown, c: RouteContext): Response {\n return toErrorResponse(error, c.json.bind(c));\n}\n\n/**\n * The shared statics.\n *\n * `readJson` is deliberately total: a malformed body yields `{}` rather than\n * throwing, because a handler that wants to reject a malformed body validates it\n * and gets a 400 through the normal path. A parse error thrown from here would\n * bypass whatever validation error message the repo has.\n */\nconst BaseRoute = {\n /**\n * Read the JSON body, or `{}`.\n *\n * Bounded by the caller's schema, not here: an unbounded `req.json()` on a\n * worker is a memory ceiling, and each repo's limit is its own\n * `MAX_JSON_BODY_BYTES`.\n */\n async readJson(c: RouteContext): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n return {};\n }\n },\n\n /**\n A required string field, or the error that says which field was missing.\n */\n requireString(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new BadRequestError(`\\`${field}\\` is required and must be a non-empty string.`);\n }\n return value;\n },\n\n /**\n Map a caught value to a response, using the repo's dialect if it declared one.\n */\n toErrorResponse(error: unknown, c: RouteContext, options?: RouteHandlerOptions): Response {\n return (options?.onError ?? defaultOnError)(error, c);\n },\n} as const;\n\n/**\n * Build a Template-Method route handler.\n *\n * The shape Edge-Git and Edge-Sonic converged on: the handler owns only its\n * domain work, and the base owns the try/catch so a private repo's existence and\n * a 5xx's message are decided in exactly one place per app.\n */\nfunction createRouteHandler(handle: RouteHandler, options: RouteHandlerOptions = {}): (c: RouteContext) => Promise<Response> {\n return async (c: RouteContext): Promise<Response> => {\n try {\n return await handle(c);\n } catch (error: unknown) {\n return (options.onError ?? defaultOnError)(error, c);\n }\n };\n}\n\nexport { BaseRoute, createRouteHandler };\nexport type { RouteContext, RouteHandler, RouteHandlerOptions };\n"],
5
- "mappings": "+EAgCA,OAAS,mBAAAA,MAAuB,mBAChC,OAAS,mBAAAC,MAAuB,mBAwBhC,SAASC,EAAeC,EAAgBC,EAAe,CACrD,OAAOH,EAAgBE,EAAOC,EAAE,KAAK,KAAKA,CAAC,CAAC,CAC9C,CAFSC,EAAAH,EAAA,kBAYT,MAAMI,EAAY,CAQhB,MAAM,SAASF,EAAe,CAC5B,GAAI,CACF,OAAO,MAAMA,EAAE,IAAI,KAAI,CACzB,MAAQ,CACN,MAAO,CAAA,CACT,CACF,EAKA,cAAcG,EAAgBC,EAAa,CACzC,GAAI,OAAOD,GAAU,UAAYA,EAAM,KAAI,IAAO,GAChD,MAAM,IAAIP,EAAgB,KAAKQ,CAAK,gDAAgD,EAEtF,OAAOD,CACT,EAKA,gBAAgBJ,EAAgBC,EAAiBK,EAA6B,CAC5E,OAAQA,GAAS,SAAWP,GAAgBC,EAAOC,CAAC,CACtD,GAUF,SAASM,EAAmBC,EAAsBF,EAA+B,CAAA,EAAE,CACjF,MAAO,OAAOL,GAAsC,CAClD,GAAI,CACF,OAAO,MAAMO,EAAOP,CAAC,CACvB,OAASD,EAAgB,CACvB,OAAQM,EAAQ,SAAWP,GAAgBC,EAAOC,CAAC,CACrD,CACF,CACF,CARSC,EAAAK,EAAA",
4
+ "sourcesContent": ["/**\n * Shared statics for Hono route handlers.\n *\n * Converged from `endpoints/IBaseRoute.ts` / `endpoints/BaseRoute.ts` in the\n * nine full-framework repos, which hold **two incompatible shapes**: a Hono\n * `Response`-returning base class, and a namespace of statics. Both survive here,\n * because the decision of which to use is genuinely per-repo — but the *parts*\n * they share no longer do.\n *\n * ## Why a namespace and not a base class\n *\n * Durable-DAV's Template Method (`abstract handleRequest` + `handle()` owning the\n * try/catch) had **zero** subclasses — `VolumeScopedRoute` reimplements the same\n * try/catch against the same `toErrorResponse` — so it advertised an inheritance\n * contract nothing was using, while its own doc comment claimed handlers \"stop\n * duplicating\" error mapping.\n *\n * So the shared surface is a namespace of statics. A repo that wants the Template\n * Method takes {@link createRouteHandler}; a repo that does not takes the statics\n * directly. Neither pays for the other's abstraction.\n *\n * ## What this does not ship, and why that is not a gap\n *\n * Six of the nine repos build routes as chanfana `OpenAPIRoute` subclasses with\n * file-based routing and a zod schema registry. This header used to claim\n * \"both are here — `IBaseRoute` is the chanfana shape\". There is no\n * `IBaseRoute` in this package: not exported, not defined, not in the barrel.\n * Nothing chanfana-shaped was ever converged, so the paragraph named a symbol a\n * consumer could not import and would have spent an afternoon looking for.\n *\n * It is recorded here rather than dropped so the next repo to read this knows the\n * chanfana half is genuinely **unconverged** and not something it missed. A\n * shared statics block genuinely can be adopted underneath an `OpenAPIRoute`\n * subclass — `readJson`/`requireString` are framework-free — so the shape is\n * available to those six repos without a base class they would have to extend.\n */\nimport { BadRequestError } from '@rexezuge/errors';\nimport { toErrorResponse } from './ErrorMapper.ts';\n\n/**\nThe slice of a Hono context a route handler reads.\n*/\ninterface RouteContext {\n req: { json(): Promise<unknown>; raw: Request };\n env: unknown;\n json(body: unknown, status?: number, headers?: Record<string, string>): Response;\n /**\n Optional request scope, when the repo uses DI.\n */\n get?(key: string): unknown;\n}\n\ntype RouteHandler = (c: RouteContext) => Promise<Response>;\n\ninterface RouteHandlerOptions {\n /**\n A repo-specific mapper. Defaults to the canonical `{Exception:{…}}` dialect.\n */\n onError?(error: unknown, c: RouteContext): Response;\n}\n\nfunction defaultOnError(error: unknown, c: RouteContext): Response {\n return toErrorResponse(error, c.json.bind(c));\n}\n\n/**\n * The shared statics.\n *\n * `readJson` is deliberately total: a malformed body yields `{}` rather than\n * throwing, because a handler that wants to reject a malformed body validates it\n * and gets a 400 through the normal path. A parse error thrown from here would\n * bypass whatever validation error message the repo has.\n */\nconst BaseRoute = {\n /**\n * Read the JSON body, or `{}`.\n *\n * Bounded by the caller's schema, not here: an unbounded `req.json()` on a\n * worker is a memory ceiling, and each repo's limit is its own\n * `MAX_JSON_BODY_BYTES`.\n */\n async readJson(c: RouteContext): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n return {};\n }\n },\n\n /**\n A required string field, or the error that says which field was missing.\n */\n requireString(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new BadRequestError(`\\`${field}\\` is required and must be a non-empty string.`);\n }\n return value;\n },\n\n /**\n Map a caught value to a response, using the repo's dialect if it declared one.\n */\n toErrorResponse(error: unknown, c: RouteContext, options?: RouteHandlerOptions): Response {\n return (options?.onError ?? defaultOnError)(error, c);\n },\n} as const;\n\n/**\n * Build a Template-Method route handler.\n *\n * The shape Edge-Git and Edge-Sonic converged on: the handler owns only its\n * domain work, and the base owns the try/catch so a private repo's existence and\n * a 5xx's message are decided in exactly one place per app.\n */\nfunction createRouteHandler(handle: RouteHandler, options: RouteHandlerOptions = {}): (c: RouteContext) => Promise<Response> {\n return async (c: RouteContext): Promise<Response> => {\n try {\n return await handle(c);\n } catch (error: unknown) {\n return (options.onError ?? defaultOnError)(error, c);\n }\n };\n}\n\nexport { BaseRoute, createRouteHandler };\nexport type { RouteContext, RouteHandler, RouteHandlerOptions };\n"],
5
+ "mappings": "+EAoCA,OAAS,mBAAAA,MAAuB,mBAChC,OAAS,mBAAAC,MAAuB,mBAwBhC,SAASC,EAAeC,EAAgBC,EAAe,CACrD,OAAOH,EAAgBE,EAAOC,EAAE,KAAK,KAAKA,CAAC,CAAC,CAC9C,CAFSC,EAAAH,EAAA,kBAYT,MAAMI,EAAY,CAQhB,MAAM,SAASF,EAAe,CAC5B,GAAI,CACF,OAAO,MAAMA,EAAE,IAAI,KAAI,CACzB,MAAQ,CACN,MAAO,CAAA,CACT,CACF,EAKA,cAAcG,EAAgBC,EAAa,CACzC,GAAI,OAAOD,GAAU,UAAYA,EAAM,KAAI,IAAO,GAChD,MAAM,IAAIP,EAAgB,KAAKQ,CAAK,gDAAgD,EAEtF,OAAOD,CACT,EAKA,gBAAgBJ,EAAgBC,EAAiBK,EAA6B,CAC5E,OAAQA,GAAS,SAAWP,GAAgBC,EAAOC,CAAC,CACtD,GAUF,SAASM,EAAmBC,EAAsBF,EAA+B,CAAA,EAAE,CACjF,MAAO,OAAOL,GAAsC,CAClD,GAAI,CACF,OAAO,MAAMO,EAAOP,CAAC,CACvB,OAASD,EAAgB,CACvB,OAAQM,EAAQ,SAAWP,GAAgBC,EAAOC,CAAC,CACrD,CACF,CACF,CARSC,EAAAK,EAAA",
6
6
  "names": ["BadRequestError", "toErrorResponse", "defaultOnError", "error", "c", "__name", "BaseRoute", "value", "field", "options", "createRouteHandler", "handle"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/http",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,8 +28,8 @@
28
28
  "chanfana": "^3.4.0",
29
29
  "hono": "^4.13.13",
30
30
  "jose": "^6.2.12",
31
- "@rexezuge/shared": "1.6.1",
32
- "@rexezuge/errors": "1.6.1"
31
+ "@rexezuge/errors": "1.7.0",
32
+ "@rexezuge/shared": "1.7.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "26.6.4",