@rexezuge/http 1.5.1 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ErrorMapper.js +1 -1
- package/dist/ErrorMapper.js.map +2 -2
- package/dist/accessAuth.js +1 -1
- package/dist/accessAuth.js.map +2 -2
- package/dist/rateLimit.js +1 -1
- package/dist/rateLimit.js.map +2 -2
- package/dist/routeBase.js +1 -1
- package/dist/routeBase.js.map +2 -2
- package/dist/securityHeaders.js +1 -1
- package/dist/securityHeaders.js.map +2 -2
- package/package.json +3 -3
package/dist/ErrorMapper.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ServiceError as
|
|
1
|
+
var p=Object.defineProperty;var r=(e,n)=>p(e,"name",{value:n,configurable:!0});import{ServiceError as a}from"@rexezuge/errors";const u="The server encountered an internal error and was unable to complete your request.";function E(e){return e instanceof a?e:a.from(e)}r(E,"toServiceError");function i(e){return{Exception:{Type:e.type,Message:e.expose?e.message:u}}}r(i,"errorBody");function m(e,n,s={}){const t=E(e),o=t.status||s.fallbackStatus||500,c=s.toResponse?.(t,o);if(c)return c;const f=s.headers?.(o,t)??{};return n(i(t),o,f)}r(m,"toErrorResponse");export{u as INTERNAL_SERVER_MESSAGE,i as errorBody,m as toErrorResponse,E as toServiceError};
|
package/dist/ErrorMapper.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/ErrorMapper.ts"],
|
|
4
4
|
"sourcesContent": ["/**\n * Error → response mapping at the HTTP boundary.\n *\n * Converged from `errors/ErrorMapper.ts` in Durable-DAV-Router, Edge-Git and\n * Edge-Sonic. Edge-Sonic's split is the one that survived, because it is the\n * only one that states **why** it splits: by surface, not by convenience.\n *\n * ## One surface, one dialect\n *\n * The `{Exception:{Type,Message}}` envelope is the family's established wire\n * format and the one the SPAs decode. A protocol surface with its own envelope —\n * Subsonic, WebDAV, CalDAV — must answer in *that* envelope, because a client\n * parsing that surface has no way to interpret anything else: a 401 carrying an\n * unrecognized body renders as \"server error\" and the client retries.\n *\n * So the split is by surface, and a caller declares which one it is on rather\n * than each handler deciding for itself. A surface that has its own dialect\n * supplies {@link ErrorMapperOptions.toResponse}; everything else gets the\n * canonical envelope.\n *\n * ## A 5xx never carries its own message\n *\n * `expose` in `@rexezuge/errors` already decides this, and this mapper is where\n * that decision becomes bytes. A D1 error names tables and columns; an upstream\n * body can carry a stack. The substitution lives here once rather than in every\n * boundary mapper.\n *\n * ## A 404 is a 404\n *\n * `NotFoundError` maps to 404 and stays 404. A surface that needs a protocol code\n * for absence (Subsonic's `code=70`) supplies its own mapper; this one does not\n * second-guess the taxonomy into something a client can misread.\n */\nimport { ServiceError } from '@rexezuge/errors';\n\ninterface ErrorMapperOptions {\n /**\n * The HTTP status when the error carries none it should publish. Defaults to\n * 500 — a non-`ServiceError` that reached the boundary is an unknown failure.\n */\n fallbackStatus?: number;\n /**\n A surface-specific dialect. Returns `undefined` to fall through to the default.\n */\n toResponse?(error: ServiceError, status: number): Response | undefined;\n /**\n Adds headers to the response (e.g. `Retry-After` on a 429).\n */\n headers?(status: number, error: ServiceError): Record<string, string>;\n}\n\nconst INTERNAL_SERVER_MESSAGE = 'The server encountered an internal error and was unable to complete your request.';\n\n/**\n * Normalize an unknown catch value into the taxonomy.\n *\n * Re-wrapping a `ServiceError` would bury its context, so it passes through\n * untouched and the caller can rely on `instanceof` downstream.\n */\nfunction toServiceError(error: unknown): ServiceError {\n return error instanceof ServiceError ? error : ServiceError.from(error);\n}\n\n/**\n * The canonical wire body.\n *\n * A 4xx keeps its message; a 5xx is masked. This is the `{Exception:{…}}`\n * envelope every SPA in the family decodes, and the one a surface with no\n * dialect of its own should answer in.\n */\nfunction errorBody(error: ServiceError): { Exception: { Type: string; Message: string } } {\n return {\n Exception: {\n Type: error.type,\n Message: error.expose ? error.message : INTERNAL_SERVER_MESSAGE,\n },\n };\n}\n\n/**\n * Map a caught value to a `Response`.\n *\n * The `json`-shaped callback is injected rather than imported from Hono so this\n * module stays free of the `Context` generic: a caller passes its own `c.json`,\n * which is what makes it usable from a bare-`Request` dispatcher as well.\n */\nfunction toErrorResponse(\n error: unknown,\n json: (body: unknown, status: number, headers?: Record<string, string>) => Response,\n options: ErrorMapperOptions = {},\n): Response {\n const serviceError = toServiceError(error);\n const status = serviceError.status || options.fallbackStatus || 500;\n\n const custom = options.toResponse?.(serviceError, status);\n if (custom) return custom;\n\n const headers = options.headers?.(status, serviceError) ?? {};\n return json(errorBody(serviceError), status, headers);\n}\n\nexport { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE };\nexport type { ErrorMapperOptions };\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["ServiceError", "INTERNAL_SERVER_MESSAGE", "toServiceError", "error", "errorBody", "toErrorResponse", "json", "options", "serviceError", "status", "custom", "headers"]
|
|
5
|
+
"mappings": "+EAiCA,OAAS,gBAAAA,MAAoB,mBAkB7B,MAAMC,EAA0B,oFAQhC,SAASC,EAAeC,EAAc,CACpC,OAAOA,aAAiBH,EAAeG,EAAQH,EAAa,KAAKG,CAAK,CACxE,CAFSC,EAAAF,EAAA,kBAWT,SAASG,EAAUF,EAAmB,CACpC,MAAO,CACL,UAAW,CACT,KAAMA,EAAM,KACZ,QAASA,EAAM,OAASA,EAAM,QAAUF,GAG9C,CAPSG,EAAAC,EAAA,aAgBT,SAASC,EACPH,EACAI,EACAC,EAA8B,CAAA,EAAE,CAEhC,MAAMC,EAAeP,EAAeC,CAAK,EACnCO,EAASD,EAAa,QAAUD,EAAQ,gBAAkB,IAE1DG,EAASH,EAAQ,aAAaC,EAAcC,CAAM,EACxD,GAAIC,EAAQ,OAAOA,EAEnB,MAAMC,EAAUJ,EAAQ,UAAUE,EAAQD,CAAY,GAAK,CAAA,EAC3D,OAAOF,EAAKF,EAAUI,CAAY,EAAGC,EAAQE,CAAO,CACtD,CAbSR,EAAAE,EAAA",
|
|
6
|
+
"names": ["ServiceError", "INTERNAL_SERVER_MESSAGE", "toServiceError", "error", "__name", "errorBody", "toErrorResponse", "json", "options", "serviceError", "status", "custom", "headers"]
|
|
7
7
|
}
|
package/dist/accessAuth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRemoteJWKSet as
|
|
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};
|
package/dist/accessAuth.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/accessAuth.ts"],
|
|
4
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": "
|
|
6
|
-
"names": ["createRemoteJWKSet", "jwtVerify", "isValidEmailFormat", "AccessAuthError", "message", "JWKS_CACHE_LIMIT", "jwksCache", "trimTrailingSlashes", "value", "end", "normalizeTeamDomain", "teamDomain", "jwksFor", "normalized", "cached", "created", "oldest", "joseVerifier", "token", "policyAud", "issuer", "payload", "isValidAuthEmail", "raw", "authenticateAccess", "request", "binding", "options", "dev", "verifyAccessJwt", "fromBinding", "identityFromBinding", "identity", "email", "verifier", "audience", "error"]
|
|
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,GAAO,EAC5D,OAAOD,EAAM,MAAM,EAAGC,CAAG,CAC3B,CAJSN,EAAAI,EAAA,uBAMT,SAASG,EAAoBC,EAAkB,CAC7C,OAAOJ,EAAoBI,EAAW,KAAI,EAAG,YAAW,CAAE,CAC5D,CAFSR,EAAAO,EAAA,uBAIT,SAASE,EAAQD,EAAkB,CACjC,MAAME,EAAaH,EAAoBC,CAAU,EAC3CG,EAASR,EAAU,IAAIO,CAAU,EACvC,GAAIC,EACF,OAAAR,EAAU,OAAOO,CAAU,EAC3BP,EAAU,IAAIO,EAAYC,CAAM,EACzBA,EAET,MAAMC,EAAUhB,EAAmB,IAAI,IAAI,GAAGc,CAAU,uBAA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M,EAAW,MAAMN,GAAS,YAAW,EAAG,MAAM,IAAK,CAAE,CAAC,EAC5D,GAAIM,GAAU,gBAAkB,IAASA,GAAU,iBAAmB,GAAO,OAAO,KACpF,MAAMC,EAAQD,GAAU,OAAO,KAAI,EAAG,YAAW,GAAM,GACvD,OAAOV,EAAiBW,CAAK,EAAIA,EAAQ,IAC3C,CALe9B,EAAA4B,EAAA,uBAaf,eAAeF,EAAgBJ,EAAkBd,EAAoBQ,EAAmBe,EAA2B,CACjH,MAAMhB,EAAQO,EAAQ,QAAQ,IAAI,yBAAyB,EAC3D,GAAI,CAACP,EAAO,MAAM,IAAIhB,EAAgB,6DAA6D,EAEnG,MAAMkB,EAASV,EAAoBC,CAAU,EACvCwB,EAAWhB,EAAU,KAAI,EAC/B,GAAI,CAACgB,EAAU,MAAM,IAAIjC,EAAgB,kDAAkD,EAG3F,GAAIiC,EAAS,SAAS,GAAG,EACvB,MAAM,IAAIjC,EAAgB,gFAAgF,EAG5G,GAAI,CACF,MAAM+B,GAAS,MAAMC,EAAS,OAAOhB,EAAOE,EAAQe,CAAQ,GAAG,KAAI,EAAG,YAAW,EACjF,GAAI,CAACb,EAAiBW,CAAK,EAAG,MAAM,IAAI/B,EAAgB,0CAA0C,EAClG,OAAO+B,CACT,OAASG,EAAO,CACd,MAAIA,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"]
|
|
7
7
|
}
|
package/dist/rateLimit.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
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};
|
package/dist/rateLimit.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/rateLimit.ts"],
|
|
4
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": "
|
|
6
|
-
"names": ["clientIp", "header", "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"]
|
|
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,SAAS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",
|
|
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"]
|
|
7
7
|
}
|
package/dist/routeBase.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BadRequestError as
|
|
1
|
+
var i=Object.defineProperty;var e=(r,t)=>i(r,"name",{value:t,configurable:!0});import{BadRequestError as u}from"@rexezuge/errors";import{toErrorResponse as a}from"./ErrorMapper.js";function o(r,t){return a(r,t.json.bind(t))}e(o,"defaultOnError");const c={async readJson(r){try{return await r.req.json()}catch{return{}}},requireString(r,t){if(typeof r!="string"||r.trim()==="")throw new u(`\`${t}\` is required and must be a non-empty string.`);return r},toErrorResponse(r,t,n){return(n?.onError??o)(r,t)}};function d(r,t={}){return async n=>{try{return await r(n)}catch(s){return(t.onError??o)(s,n)}}}e(d,"createRouteHandler");export{c as BaseRoute,d as createRouteHandler};
|
package/dist/routeBase.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/routeBase.ts"],
|
|
4
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": "
|
|
6
|
-
"names": ["BadRequestError", "toErrorResponse", "defaultOnError", "error", "c", "BaseRoute", "value", "field", "options", "createRouteHandler", "handle"]
|
|
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",
|
|
6
|
+
"names": ["BadRequestError", "toErrorResponse", "defaultOnError", "error", "c", "__name", "BaseRoute", "value", "field", "options", "createRouteHandler", "handle"]
|
|
7
7
|
}
|
package/dist/securityHeaders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
var f=Object.defineProperty;var s=(e,t)=>f(e,"name",{value:t,configurable:!0});const i={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"same-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=(), payment=(), usb=()","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Resource-Policy":"same-origin","Cross-Origin-Embedder-Policy":"require-corp","Origin-Agent-Cluster":"?1"},o="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests",a="max-age=31536000; includeSubDomains";function c(e,t){for(const[l,u]of Object.entries(i))e.header(l,u);(e.res.headers.get("content-type")??"").includes("text/html")&&e.header("Content-Security-Policy",o);let r;try{r=new URL(e.req.url).pathname}catch{}r!==void 0&&t(r)&&e.header("Cache-Control","no-store");try{new URL(e.req.url).protocol==="https:"&&e.header("Strict-Transport-Security",a)}catch{}}s(c,"applySecurityHeaders");function y(e){return async(t,n)=>{await n();try{c(t,e)}catch{}}}s(y,"securityHeaders");function m(...e){if(e.length===0)return()=>!1;const t=e.map(n=>n.endsWith("/")?n:`${n}/`);return n=>t.some(r=>n.startsWith(r))}s(m,"sensitivePaths");export{o as CONTENT_SECURITY_POLICY,i as SECURITY_HEADERS,a as STRICT_TRANSPORT_SECURITY,c as applySecurityHeaders,y as securityHeaders,m as sensitivePaths};
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/securityHeaders.ts"],
|
|
4
4
|
"sourcesContent": ["/**\n * Baseline response security headers.\n *\n * Converged from `apps/api/src/middleware/securityHeaders.ts` in Durable-DAV,\n * Durable-DAV-Router, Edge-Git and Edge-Sonic, where the four copies are\n * byte-identical apart from one predicate — which is exactly why it is a\n * parameter here rather than a constant.\n *\n * ## Why `isSensitive` is a required argument\n *\n * The copies each shipped a `startsWith('/user/')` predicate, inherited from a\n * reference project. In one repo that worker serves **no `/user/` route**, so the\n * predicate could never return `true` and `Cache-Control: no-store` was never\n * applied to anything: the operator's own address and every user's address\n * shipped with no `Cache-Control` at all.\n *\n * A predicate copied from another router's route table is not a conservative\n * default; it is an unconditional no-op. So a caller states its own private\n * prefixes, and the compiler asks for them rather than letting them be omitted.\n */\n\n/**\nThe slice of a Hono context this middleware reads.\n*/\ninterface HeaderContext {\n header(name: string, value: string): void;\n res: { headers: Headers };\n req: { url: string };\n}\n\n/**\n * Baseline headers for API JSON responses and the SPA shell.\n *\n * The SPA ships inline scripts and styles from the Vite build, so CSP allows\n * 'unsafe-inline' for both, bounded by `same-origin` and `frame-ancestors`.\n * Without it the shell breaks; hashes or nonces are a future tightening once the\n * build emits stable hashes.\n */\nconst SECURITY_HEADERS: Readonly<Record<string, string>> = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'same-origin',\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'require-corp',\n 'Origin-Agent-Cluster': '?1',\n} as const;\n\n/**\n * CSP for the HTML shell.\n *\n * Separate from {@link SECURITY_HEADERS} because it applies only to an HTML\n * response — sending it on JSON is noise at best and a source of confusing\n * violation reports at worst.\n */\nconst CONTENT_SECURITY_POLICY =\n \"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests\";\n\n/**\nHSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning.\n*/\nconst STRICT_TRANSPORT_SECURITY = 'max-age=31536000; includeSubDomains';\n\n/**\n * Apply the headers to a context.\n *\n * Each step is independently guarded: a header must never fail a request, and\n * one unparseable URL should not cost the other headers.\n */\nfunction applySecurityHeaders(c: HeaderContext, isSensitive: (pathname: string) => boolean): void {\n for (const [key, value] of Object.entries(SECURITY_HEADERS)) {\n c.header(key, value);\n }\n\n const contentType = c.res.headers.get('content-type') ?? '';\n if (contentType.includes('text/html')) {\n c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);\n }\n\n let pathname: string | undefined;\n try {\n pathname = new URL(c.req.url).pathname;\n } catch {\n // URL parsing must never fail the request; the `no-store` step is skipped.\n }\n if (pathname !== undefined && isSensitive(pathname)) {\n c.header('Cache-Control', 'no-store');\n }\n\n try {\n if (new URL(c.req.url).protocol === 'https:') {\n c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);\n }\n } catch {\n // URL parsing must never fail the request.\n }\n}\n\n/**\n * The middleware.\n *\n * `isSensitive` is **required**, and its parameter is required, so a caller\n * cannot accidentally ship a predicate that returns `true` for everything\n * (caching a credential response) or `false` for everything (the no-op above).\n */\nfunction securityHeaders(isSensitive: (pathname: string) => boolean): (c: HeaderContext, next: () => Promise<void>) => Promise<void> {\n return async (c: HeaderContext, next: () => Promise<void>): Promise<void> => {\n await next();\n try {\n applySecurityHeaders(c, isSensitive);\n } catch {\n // Headers must never fail the request.\n }\n };\n}\n\n/**\n * Build a predicate from this app's private path prefixes.\n *\n * A convenience over `securityHeaders`, not a default: it matches **exactly**\n * these prefixes, so a caller still has to name its own paths. The returned\n * function composes, so a repo with a second private surface can add its own\n * test without editing this one.\n */\nfunction sensitivePaths(...prefixes: readonly string[]): (pathname: string) => boolean {\n if (prefixes.length === 0) {\n // Not a throw: a repo with nothing private is a legitimate state, and the\n // failure mode to avoid is silently caching a credential, which an empty\n // list cannot do. What it must not do is *look* like it protected something.\n return () => false;\n }\n const normalized = prefixes.map((prefix) => (prefix.endsWith('/') ? prefix : `${prefix}/`));\n return (pathname: string): boolean => normalized.some((prefix) => pathname.startsWith(prefix));\n}\n\nexport { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY };\nexport type { HeaderContext };\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["SECURITY_HEADERS", "CONTENT_SECURITY_POLICY", "STRICT_TRANSPORT_SECURITY", "applySecurityHeaders", "c", "isSensitive", "key", "value", "pathname", "securityHeaders", "next", "sensitivePaths", "prefixes", "normalized", "prefix"]
|
|
5
|
+
"mappings": "+EAsCA,MAAMA,EAAqD,CACzD,yBAA0B,UAC1B,kBAAmB,OACnB,kBAAmB,cACnB,qBAAsB,+DACtB,6BAA8B,cAC9B,+BAAgC,cAChC,+BAAgC,eAChC,uBAAwB,MAUpBC,EACJ,2NAKIC,EAA4B,sCAQlC,SAASC,EAAqBC,EAAkBC,EAA0C,CACxF,SAAW,CAACC,EAAKC,CAAK,IAAK,OAAO,QAAQP,CAAgB,EACxDI,EAAE,OAAOE,EAAKC,CAAK,GAGDH,EAAE,IAAI,QAAQ,IAAI,cAAc,GAAK,IACzC,SAAS,WAAW,GAClCA,EAAE,OAAO,0BAA2BH,CAAuB,EAG7D,IAAIO,EACJ,GAAI,CACFA,EAAW,IAAI,IAAIJ,EAAE,IAAI,GAAG,EAAE,QAChC,MAAQ,CAER,CACII,IAAa,QAAaH,EAAYG,CAAQ,GAChDJ,EAAE,OAAO,gBAAiB,UAAU,EAGtC,GAAI,CACE,IAAI,IAAIA,EAAE,IAAI,GAAG,EAAE,WAAa,UAClCA,EAAE,OAAO,4BAA6BF,CAAyB,CAEnE,MAAQ,CAER,CACF,CA3BSO,EAAAN,EAAA,wBAoCT,SAASO,EAAgBL,EAA0C,CACjE,MAAO,OAAOD,EAAkBO,IAA4C,CAC1E,MAAMA,EAAI,EACV,GAAI,CACFR,EAAqBC,EAAGC,CAAW,CACrC,MAAQ,CAER,CACF,CACF,CATSI,EAAAC,EAAA,mBAmBT,SAASE,KAAkBC,EAA2B,CACpD,GAAIA,EAAS,SAAW,EAItB,MAAO,IAAM,GAEf,MAAMC,EAAaD,EAAS,IAAKE,GAAYA,EAAO,SAAS,GAAG,EAAIA,EAAS,GAAGA,CAAM,GAAI,EAC1F,OAAQP,GAA8BM,EAAW,KAAMC,GAAWP,EAAS,WAAWO,CAAM,CAAC,CAC/F,CATSN,EAAAG,EAAA",
|
|
6
|
+
"names": ["SECURITY_HEADERS", "CONTENT_SECURITY_POLICY", "STRICT_TRANSPORT_SECURITY", "applySecurityHeaders", "c", "isSensitive", "key", "value", "pathname", "__name", "securityHeaders", "next", "sensitivePaths", "prefixes", "normalized", "prefix"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/http",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.2",
|
|
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/errors": "1.5.
|
|
32
|
-
"@rexezuge/shared": "1.5.
|
|
31
|
+
"@rexezuge/errors": "1.5.2",
|
|
32
|
+
"@rexezuge/shared": "1.5.2"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@types/node": "26.6.4",
|