@rexezuge/http 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ErrorMapper.d.ts +6 -2
- package/dist/ErrorMapper.d.ts.map +1 -1
- package/dist/ErrorMapper.js +1 -77
- package/dist/ErrorMapper.js.map +7 -1
- package/dist/accessAuth.d.ts +15 -5
- package/dist/accessAuth.d.ts.map +1 -1
- package/dist/accessAuth.js +1 -182
- package/dist/accessAuth.js.map +7 -1
- package/dist/index.d.ts +10 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -38
- package/dist/index.js.map +7 -1
- package/dist/rateLimit.d.ts.map +1 -1
- package/dist/rateLimit.js +1 -225
- package/dist/rateLimit.js.map +7 -1
- package/dist/routeBase.d.ts +15 -5
- package/dist/routeBase.d.ts.map +1 -1
- package/dist/routeBase.js +1 -92
- package/dist/routeBase.js.map +7 -1
- package/dist/securityHeaders.d.ts +6 -2
- package/dist/securityHeaders.d.ts.map +1 -1
- package/dist/securityHeaders.js +1 -119
- package/dist/securityHeaders.js.map +7 -1
- package/package.json +4 -4
package/dist/rateLimit.js
CHANGED
|
@@ -1,225 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* The family's per-isolate rate limiter.
|
|
3
|
-
*
|
|
4
|
-
* Converged from `apps/api/src/middleware/rateLimit.ts` in Durable-DAV,
|
|
5
|
-
* Durable-DAV-Router, Edge-Git and Edge-Sonic. Edge-Sonic's was the one that
|
|
6
|
-
* had solved the three defects the other three still carried, so this is that
|
|
7
|
-
* one; the differences below are what each fix bought.
|
|
8
|
-
*
|
|
9
|
-
* ## Design decisions
|
|
10
|
-
*
|
|
11
|
-
* ### `max` may be a resolver, and why that is the only honest shape
|
|
12
|
-
*
|
|
13
|
-
* A budget read from the environment cannot be resolved at registration time:
|
|
14
|
-
* the route table is built once in the worker constructor, where `env` does not
|
|
15
|
-
* exist, so a `STREAM_RATE_LIMIT` read there would be a module-level constant
|
|
16
|
-
* wearing a variable's name. That is how the variable came to be declared,
|
|
17
|
-
* validated, shipped in the wrangler template and read by nothing while the
|
|
18
|
-
* limiter used a literal — the knob was real and the code was not reading it.
|
|
19
|
-
*
|
|
20
|
-
* A resolver is evaluated per request from the context. The static check at
|
|
21
|
-
* registration is skipped for one, because a limiter that throws *while being
|
|
22
|
-
* installed* takes down every route it was attached to; an unusable answer is
|
|
23
|
-
* caught per request instead.
|
|
24
|
-
*
|
|
25
|
-
* ### The sweep is time-triggered, not size-triggered
|
|
26
|
-
*
|
|
27
|
-
* It used to run on **every** request above a bucket threshold. Memory was
|
|
28
|
-
* already bounded by the cap, so the cap was never the problem — the *cost* was,
|
|
29
|
-
* and it was paid by every caller rather than by the one who filled the map. An
|
|
30
|
-
* attacker rotating a thousand distinct keys turned every subsequent request on
|
|
31
|
-
* that isolate into O(n) map work against the Free plan's 10 ms CPU budget: a
|
|
32
|
-
* cheap way to make a rate limiter a denial-of-service vector against itself.
|
|
33
|
-
*
|
|
34
|
-
* So the **cap is enforced on every request** and only the **sweep is deferred**.
|
|
35
|
-
* Those are different jobs with different failure modes: memory grows whether or
|
|
36
|
-
* not a sweep runs, so deferring the cap would make the bound wrong, while the
|
|
37
|
-
* sweep only reclaims memory the cap has already bounded. Nothing is lost by
|
|
38
|
-
* deferring it — an expired bucket is already treated as absent by the request
|
|
39
|
-
* path.
|
|
40
|
-
*
|
|
41
|
-
* ### An unusable budget fails **open**
|
|
42
|
-
*
|
|
43
|
-
* A resolver that throws must not produce an unlimited bucket: `count >= NaN` is
|
|
44
|
-
* false, so a broken resolver silently turns the limiter **off** rather than
|
|
45
|
-
* off-by-a-lot — the direction nobody notices. The call is therefore guarded, and
|
|
46
|
-
* a throw propagates to the limiter's own fail-open path rather than to a bucket
|
|
47
|
-
* check that no longer bounds anything.
|
|
48
|
-
*
|
|
49
|
-
* The value is only ever what the resolver returned. Deciding what an *unusable*
|
|
50
|
-
* value falls back to belongs to whoever supplied it, because only they know the
|
|
51
|
-
* limit's own default.
|
|
52
|
-
*
|
|
53
|
-
* ### `next()` runs exactly once
|
|
54
|
-
*
|
|
55
|
-
* The `try` encloses the limiter's own work and **not** `await next()`. It used
|
|
56
|
-
* to enclose both, which caught anything the downstream chain rejected and
|
|
57
|
-
* called `next()` a second time from the `catch`. A fail-open branch should not
|
|
58
|
-
* enclose the thing it is failing open *for*.
|
|
59
|
-
*
|
|
60
|
-
* ## Per-isolate only
|
|
61
|
-
*
|
|
62
|
-
* Workers have no shared memory, so this bounds abuse per isolate and nothing
|
|
63
|
-
* more. It is never a security control on its own.
|
|
64
|
-
*/
|
|
65
|
-
/**
|
|
66
|
-
* The one trusted client address.
|
|
67
|
-
*
|
|
68
|
-
* Trust order is deliberately a single entry: Cloudflare sets
|
|
69
|
-
* `CF-Connecting-IP` and it cannot be spoofed by a client. `X-Forwarded-For`,
|
|
70
|
-
* `x-real-ip` and every other forwarding header are **not** consulted, because
|
|
71
|
-
* they are client-controlled and let an attacker rotate buckets — or, on a
|
|
72
|
-
* surface with an offline credential throttle, rotate the identity keying it and
|
|
73
|
-
* brute-force forever.
|
|
74
|
-
*
|
|
75
|
-
* Local dev without CF headers shares the `unknown` bucket, which is fail-closed
|
|
76
|
-
* grouping rather than per-spoofed-header isolation.
|
|
77
|
-
*
|
|
78
|
-
* Takes a header reader rather than a context so a bare-`Request` dispatcher
|
|
79
|
-
* uses the same derivation.
|
|
80
|
-
*/
|
|
81
|
-
function clientIp(header) {
|
|
82
|
-
return header('CF-Connecting-IP')?.trim() || 'unknown';
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Upper bound on tracked buckets.
|
|
86
|
-
*
|
|
87
|
-
* Every distinct key costs memory for the isolate's lifetime, so an attacker
|
|
88
|
-
* rotating keys would otherwise grow the map without limit.
|
|
89
|
-
*/
|
|
90
|
-
const MAX_BUCKETS = 5000;
|
|
91
|
-
/**
|
|
92
|
-
* Below this many buckets, cleanup does nothing at all.
|
|
93
|
-
*
|
|
94
|
-
* The threshold rather than 0: sweeping a handful of entries on every request is
|
|
95
|
-
* work for nothing, and below the threshold an expiry sweep cannot reclaim
|
|
96
|
-
* enough to matter.
|
|
97
|
-
*/
|
|
98
|
-
const CLEANUP_THRESHOLD = 1000;
|
|
99
|
-
/** The sweep runs at most this often, regardless of bucket count. */
|
|
100
|
-
const CLEANUP_INTERVAL_MS = 30_000;
|
|
101
|
-
let lastCleanupAt = 0;
|
|
102
|
-
function evictOldestBucket(buckets) {
|
|
103
|
-
let oldestReset = Infinity;
|
|
104
|
-
for (const [, bucket] of buckets) {
|
|
105
|
-
oldestReset = Math.min(oldestReset, bucket.resetAt);
|
|
106
|
-
}
|
|
107
|
-
for (const [key, bucket] of buckets) {
|
|
108
|
-
if (bucket.resetAt === oldestReset) {
|
|
109
|
-
buckets.delete(key);
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
function cleanup(buckets, now) {
|
|
115
|
-
// The cap is enforced here, on **every** request, and only the sweep is
|
|
116
|
-
// deferred. Evicting *down* rather than clearing, so an attacker flooding new
|
|
117
|
-
// keys cannot wipe out everyone else's buckets — and down to `MAX_BUCKETS - 1`
|
|
118
|
-
// because the caller adds its own bucket immediately afterwards.
|
|
119
|
-
let overflow = buckets.size - (MAX_BUCKETS - 1);
|
|
120
|
-
while (overflow > 0) {
|
|
121
|
-
evictOldestBucket(buckets);
|
|
122
|
-
overflow -= 1;
|
|
123
|
-
}
|
|
124
|
-
// The sweep is amortised. An expired bucket is *already* treated as absent by
|
|
125
|
-
// the request path, so the sweep only reclaims memory — and memory is what the
|
|
126
|
-
// cap above already bounds. The cost moves from per-request to a fixed rate.
|
|
127
|
-
if (buckets.size < CLEANUP_THRESHOLD)
|
|
128
|
-
return;
|
|
129
|
-
if (now - lastCleanupAt < CLEANUP_INTERVAL_MS)
|
|
130
|
-
return;
|
|
131
|
-
lastCleanupAt = now;
|
|
132
|
-
for (const [key, bucket] of buckets) {
|
|
133
|
-
if (bucket.resetAt <= now)
|
|
134
|
-
buckets.delete(key);
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* The budget to enforce for this request.
|
|
139
|
-
*
|
|
140
|
-
* A resolver that throws, or that answers something that is not a positive
|
|
141
|
-
* integer, is rejected here — in one place — so the limiter's own `try` fails
|
|
142
|
-
* open for both rather than only for the throw.
|
|
143
|
-
*/
|
|
144
|
-
function resolveBudget(max, c) {
|
|
145
|
-
if (typeof max === 'number')
|
|
146
|
-
return max;
|
|
147
|
-
const resolved = max(c);
|
|
148
|
-
if (!Number.isSafeInteger(resolved) || resolved <= 0) {
|
|
149
|
-
throw new Error(`Invalid rateLimit budget: ${String(resolved)} (must be a positive integer)`);
|
|
150
|
-
}
|
|
151
|
-
return resolved;
|
|
152
|
-
}
|
|
153
|
-
function rateLimit(opts) {
|
|
154
|
-
// Misconfiguration throws at registration rather than silently installing an
|
|
155
|
-
// unlimited or immediately-tripping bucket. A resolver is exempt: an
|
|
156
|
-
// unusable answer there is caught per request, because a limiter that throws
|
|
157
|
-
// *while being installed* takes down every route it was attached to.
|
|
158
|
-
if (!Number.isSafeInteger(opts.windowMs) || opts.windowMs <= 0) {
|
|
159
|
-
throw new Error(`Invalid rateLimit windowMs: ${String(opts.windowMs)} (must be a positive integer)`);
|
|
160
|
-
}
|
|
161
|
-
if (typeof opts.max === 'number' && (!Number.isSafeInteger(opts.max) || opts.max <= 0)) {
|
|
162
|
-
throw new Error(`Invalid rateLimit max: ${String(opts.max)} (must be a positive integer)`);
|
|
163
|
-
}
|
|
164
|
-
if (!opts.keyPrefix || opts.keyPrefix.trim().length === 0) {
|
|
165
|
-
throw new Error('Invalid rateLimit keyPrefix: must be a non-empty string');
|
|
166
|
-
}
|
|
167
|
-
const buckets = new Map();
|
|
168
|
-
return async (c, next) => {
|
|
169
|
-
// The limiter's own work, and **only** the limiter's own work, is inside
|
|
170
|
-
// this `try`. `next()` runs from here or from a path below, never from both.
|
|
171
|
-
try {
|
|
172
|
-
const now = Date.now();
|
|
173
|
-
cleanup(buckets, now);
|
|
174
|
-
const max = resolveBudget(opts.max, c);
|
|
175
|
-
// Prefer a resolved identity over the client address, so a bucket is per
|
|
176
|
-
// operator rather than per address. Only read when the middleware can see
|
|
177
|
-
// one — which is why the order of registration against auth is
|
|
178
|
-
// load-bearing: a limiter installed before the identity exists silently
|
|
179
|
-
// degrades to `ip:…` and every operator behind one NAT shares a budget.
|
|
180
|
-
let identity = 'anon';
|
|
181
|
-
try {
|
|
182
|
-
identity = c.get?.('AuthenticatedUserEmailAddress') ?? `ip:${clientIp((name) => c.req.header(name))}`;
|
|
183
|
-
}
|
|
184
|
-
catch {
|
|
185
|
-
identity = `ip:${clientIp((name) => c.req.header(name))}`;
|
|
186
|
-
}
|
|
187
|
-
const key = `${opts.keyPrefix}:${identity}`;
|
|
188
|
-
const existing = buckets.get(key);
|
|
189
|
-
if (!existing || existing.resetAt <= now) {
|
|
190
|
-
buckets.set(key, { count: 1, resetAt: now + opts.windowMs });
|
|
191
|
-
return await next();
|
|
192
|
-
}
|
|
193
|
-
if (existing.count >= max) {
|
|
194
|
-
const retryAfter = Math.max(1, Math.ceil((existing.resetAt - now) / 1000));
|
|
195
|
-
return throttled(retryAfter, c, opts);
|
|
196
|
-
}
|
|
197
|
-
existing.count += 1;
|
|
198
|
-
return await next();
|
|
199
|
-
}
|
|
200
|
-
catch {
|
|
201
|
-
// Fail open: the limiter could not size itself, and a request must not fail
|
|
202
|
-
// because limiting could not be done.
|
|
203
|
-
return await next();
|
|
204
|
-
}
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
/**
|
|
208
|
-
* The 429 itself.
|
|
209
|
-
*
|
|
210
|
-
* `Retry-After` travels on the header as well as in the message: a client that
|
|
211
|
-
* only reads the status has no other way to know how long to wait, and one that
|
|
212
|
-
* retries immediately is the failure a throttle exists to prevent.
|
|
213
|
-
*/
|
|
214
|
-
function throttled(retryAfter, c, opts) {
|
|
215
|
-
const headers = { 'Retry-After': String(retryAfter) };
|
|
216
|
-
if (opts.onThrottled)
|
|
217
|
-
return opts.onThrottled(retryAfter, c);
|
|
218
|
-
// The family's canonical dialect, without importing the error taxonomy into the
|
|
219
|
-
// limiter's hot path: a rate-limited request is a 429 carrying a `RateLimited`
|
|
220
|
-
// type and the retry hint in its message.
|
|
221
|
-
const response = c.json({ Exception: { Type: 'RateLimited', Message: `Too many requests. Retry after ${retryAfter}s.` } }, 429, headers);
|
|
222
|
-
return response;
|
|
223
|
-
}
|
|
224
|
-
export { clientIp, rateLimit };
|
|
225
|
-
//# sourceMappingURL=rateLimit.js.map
|
|
1
|
+
function u(e){return e("CF-Connecting-IP")?.trim()||"unknown"}const m=5e3,l=1e3,w=3e4;let c=0;function g(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}}function h(e,r){let t=e.size-(m-1);for(;t>0;)g(e),t-=1;if(!(e.size<l)&&!(r-c<w)){c=r;for(const[n,i]of e)i.resetAt<=r&&e.delete(n)}}function y(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}function A(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();h(r,i);const d=y(e.max,t);let s="anon";try{s=t.get?.("AuthenticatedUserEmailAddress")??`ip:${u(a=>t.req.header(a))}`}catch{s=`ip:${u(a=>t.req.header(a))}`}const f=`${e.keyPrefix}:${s}`,o=r.get(f);if(!o||o.resetAt<=i)return r.set(f,{count:1,resetAt:i+e.windowMs}),await n();if(o.count>=d){const a=Math.max(1,Math.ceil((o.resetAt-i)/1e3));return M(a,t,e)}return o.count+=1,await n()}catch{return await n()}}}function M(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)}export{u as clientIp,A as rateLimit};
|
package/dist/rateLimit.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{"version":3,"file":"rateLimit.js","sourceRoot":"","sources":["../src/rateLimit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AAsCH;;;;;;;;;;;;;;;GAeG;AACH,SAAS,QAAQ,CAAC,MAA4C;IAC5D,OAAO,MAAM,CAAC,kBAAkB,CAAC,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;AACzD,CAAC;AAOD;;;;;GAKG;AACH,MAAM,WAAW,GAAG,IAAI,CAAC;AAEzB;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAE/B,qEAAqE;AACrE,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAEnC,IAAI,aAAa,GAAG,CAAC,CAAC;AAEtB,SAAS,iBAAiB,CAAC,OAA4B;IACrD,IAAI,WAAW,GAAG,QAAQ,CAAC;IAC3B,KAAK,MAAM,CAAC,EAAE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACjC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IACtD,CAAC;IACD,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACpC,IAAI,MAAM,CAAC,OAAO,KAAK,WAAW,EAAE,CAAC;YACnC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CA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,EAAE,CAAmB,EAAE,IAAsB;IAChF,MAAM,OAAO,GAAG,EAAE,aAAa,EAAE,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;IACtD,IAAI,IAAI,CAAC,WAAW;QAAE,OAAO,IAAI,CAAC,WAAW,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;IAE7D,gFAAgF;IAChF,+EAA+E;IAC/E,0CAA0C;IAC1C,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,kCAAkC,UAAU,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IACzI,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC","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/** The sweep runs at most this often, regardless of bucket count. */\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"]}
|
|
1
|
+
{
|
|
2
|
+
"version": 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": "AAqHA,SAASA,EAASC,EAA4C,CAC5D,OAAOA,EAAO,kBAAkB,GAAG,KAAI,GAAM,SAC/C,CAaA,MAAMC,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,CAEA,SAASC,EAAQJ,EAA8BK,EAAW,CAKxD,IAAIC,EAAWN,EAAQ,MAAQL,EAAc,GAC7C,KAAOW,EAAW,GAChBP,EAAkBC,CAAO,EACzBM,GAAY,EAMd,GAAI,EAAAN,EAAQ,KAAOJ,IACf,EAAAS,EAAMP,EAAgBD,GAC1B,CAAA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Q,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,CASA,SAASK,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",
|
|
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"]
|
|
7
|
+
}
|
package/dist/routeBase.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
The slice of a Hono context a route handler reads.
|
|
3
|
+
*/
|
|
2
4
|
interface RouteContext {
|
|
3
5
|
req: {
|
|
4
6
|
json(): Promise<unknown>;
|
|
@@ -6,12 +8,16 @@ interface RouteContext {
|
|
|
6
8
|
};
|
|
7
9
|
env: unknown;
|
|
8
10
|
json(body: unknown, status?: number, headers?: Record<string, string>): Response;
|
|
9
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
Optional request scope, when the repo uses DI.
|
|
13
|
+
*/
|
|
10
14
|
get?(key: string): unknown;
|
|
11
15
|
}
|
|
12
16
|
type RouteHandler = (c: RouteContext) => Promise<Response>;
|
|
13
17
|
interface RouteHandlerOptions {
|
|
14
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
A repo-specific mapper. Defaults to the canonical `{Exception:{…}}` dialect.
|
|
20
|
+
*/
|
|
15
21
|
onError?(error: unknown, c: RouteContext): Response;
|
|
16
22
|
}
|
|
17
23
|
/**
|
|
@@ -31,9 +37,13 @@ declare const BaseRoute: {
|
|
|
31
37
|
* `MAX_JSON_BODY_BYTES`.
|
|
32
38
|
*/
|
|
33
39
|
readonly readJson: (c: RouteContext) => Promise<unknown>;
|
|
34
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
A required string field, or the error that says which field was missing.
|
|
42
|
+
*/
|
|
35
43
|
readonly requireString: (value: unknown, field: string) => string;
|
|
36
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
Map a caught value to a response, using the repo's dialect if it declared one.
|
|
46
|
+
*/
|
|
37
47
|
readonly toErrorResponse: (error: unknown, c: RouteContext, options?: RouteHandlerOptions) => Response;
|
|
38
48
|
};
|
|
39
49
|
/**
|
package/dist/routeBase.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routeBase.d.ts","sourceRoot":"","sources":["../src/routeBase.ts"],"names":[],"mappings":"AAmCA
|
|
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;;;;;;OAMG;2BACe,YAAY,KAAG,OAAO,CAAC,OAAO,CAAC;IAQjD;;MAEE;oCACmB,OAAO,SAAS,MAAM,KAAG,MAAM;IAOpD;;MAEE;sCACqB,OAAO,KAAK,YAAY,YAAY,mBAAmB,KAAG,QAAQ;CAGjF,CAAC;AAEX;;;;;;GAMG;AACH,iBAAS,kBAAkB,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,GAAE,mBAAwB,GAAG,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,QAAQ,CAAC,CAQ3H;AAED,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC;AACzC,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,CAAC"}
|
package/dist/routeBase.js
CHANGED
|
@@ -1,92 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* Shared statics for Hono route handlers.
|
|
3
|
-
*
|
|
4
|
-
* Converged from `endpoints/IBaseRoute.ts` / `endpoints/BaseRoute.ts` in the
|
|
5
|
-
* nine full-framework repos, which currently hold **three incompatible shapes**:
|
|
6
|
-
* a chanfana `OpenAPIRoute` subclass, a Hono `Response`-returning base class, and
|
|
7
|
-
* a namespace of statics. All three survive here, because the decision of which
|
|
8
|
-
* to use is genuinely per-repo — but the *parts* they share no longer do.
|
|
9
|
-
*
|
|
10
|
-
* ## Why a namespace and not a base class
|
|
11
|
-
*
|
|
12
|
-
* Durable-DAV's Template Method (`abstract handleRequest` + `handle()` owning the
|
|
13
|
-
* try/catch) had **zero** subclasses — `VolumeScopedRoute` reimplements the same
|
|
14
|
-
* try/catch against the same `toErrorResponse` — so it advertised an inheritance
|
|
15
|
-
* contract nothing was using, while its own doc comment claimed handlers "stop
|
|
16
|
-
* duplicating" error mapping.
|
|
17
|
-
*
|
|
18
|
-
* So the shared surface is a namespace of statics. A repo that wants the Template
|
|
19
|
-
* Method takes {@link createRouteHandler}; a repo that does not takes the statics
|
|
20
|
-
* directly. Neither pays for the other's abstraction.
|
|
21
|
-
*
|
|
22
|
-
* ## Why both route bases ship
|
|
23
|
-
*
|
|
24
|
-
* Six of the nine repos build routes as chanfana `OpenAPIRoute` subclasses with
|
|
25
|
-
* file-based routing and a zod schema registry. Edge-Git, Edge-Sonic and
|
|
26
|
-
* Durable-DAV-Router register handlers imperatively against a `Hono` app and
|
|
27
|
-
* return `Response` themselves.
|
|
28
|
-
*
|
|
29
|
-
* Both are here. `IBaseRoute` is the chanfana shape; {@link createRouteHandler}
|
|
30
|
-
* builds the imperative one. Converging them would have meant picking a loser on a
|
|
31
|
-
* decision that is not the kit's to make.
|
|
32
|
-
*/
|
|
33
|
-
import { BadRequestError } from '@rexezuge/errors';
|
|
34
|
-
import { toErrorResponse } from './ErrorMapper';
|
|
35
|
-
function defaultOnError(error, c) {
|
|
36
|
-
return toErrorResponse(error, c.json.bind(c));
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* The shared statics.
|
|
40
|
-
*
|
|
41
|
-
* `readJson` is deliberately total: a malformed body yields `{}` rather than
|
|
42
|
-
* throwing, because a handler that wants to reject a malformed body validates it
|
|
43
|
-
* and gets a 400 through the normal path. A parse error thrown from here would
|
|
44
|
-
* bypass whatever validation error message the repo has.
|
|
45
|
-
*/
|
|
46
|
-
const BaseRoute = {
|
|
47
|
-
/**
|
|
48
|
-
* Read the JSON body, or `{}`.
|
|
49
|
-
*
|
|
50
|
-
* Bounded by the caller's schema, not here: an unbounded `req.json()` on a
|
|
51
|
-
* worker is a memory ceiling, and each repo's limit is its own
|
|
52
|
-
* `MAX_JSON_BODY_BYTES`.
|
|
53
|
-
*/
|
|
54
|
-
async readJson(c) {
|
|
55
|
-
try {
|
|
56
|
-
return await c.req.json();
|
|
57
|
-
}
|
|
58
|
-
catch {
|
|
59
|
-
return {};
|
|
60
|
-
}
|
|
61
|
-
},
|
|
62
|
-
/** A required string field, or the error that says which field was missing. */
|
|
63
|
-
requireString(value, field) {
|
|
64
|
-
if (typeof value !== 'string' || value.trim() === '') {
|
|
65
|
-
throw new BadRequestError(`\`${field}\` is required and must be a non-empty string.`);
|
|
66
|
-
}
|
|
67
|
-
return value;
|
|
68
|
-
},
|
|
69
|
-
/** Map a caught value to a response, using the repo's dialect if it declared one. */
|
|
70
|
-
toErrorResponse(error, c, options) {
|
|
71
|
-
return (options?.onError ?? defaultOnError)(error, c);
|
|
72
|
-
},
|
|
73
|
-
};
|
|
74
|
-
/**
|
|
75
|
-
* Build a Template-Method route handler.
|
|
76
|
-
*
|
|
77
|
-
* The shape Edge-Git and Edge-Sonic converged on: the handler owns only its
|
|
78
|
-
* domain work, and the base owns the try/catch so a private repo's existence and
|
|
79
|
-
* a 5xx's message are decided in exactly one place per app.
|
|
80
|
-
*/
|
|
81
|
-
function createRouteHandler(handle, options = {}) {
|
|
82
|
-
return async (c) => {
|
|
83
|
-
try {
|
|
84
|
-
return await handle(c);
|
|
85
|
-
}
|
|
86
|
-
catch (error) {
|
|
87
|
-
return (options.onError ?? defaultOnError)(error, c);
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
export { BaseRoute, createRouteHandler };
|
|
92
|
-
//# sourceMappingURL=routeBase.js.map
|
|
1
|
+
import{BadRequestError as s}from"@rexezuge/errors";import{toErrorResponse as i}from"./ErrorMapper.js";function e(r,t){return i(r,t.json.bind(t))}const u={async readJson(r){try{return await r.req.json()}catch{return{}}},requireString(r,t){if(typeof r!="string"||r.trim()==="")throw new s(`\`${t}\` is required and must be a non-empty string.`);return r},toErrorResponse(r,t,n){return(n?.onError??e)(r,t)}};function a(r,t={}){return async n=>{try{return await r(n)}catch(o){return(t.onError??e)(o,n)}}}export{u as BaseRoute,a as createRouteHandler};
|
package/dist/routeBase.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 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": "AAgCA,OAAS,mBAAAA,MAAuB,mBAChC,OAAS,mBAAAC,MAAuB,mBAwBhC,SAASC,EAAeC,EAAgBC,EAAe,CACrD,OAAOH,EAAgBE,EAAOC,EAAE,KAAK,KAAKA,CAAC,CAAC,CAC9C,CAUA,MAAMC,EAAY,CAQhB,MAAM,SAASD,EAAe,CAC5B,GAAI,CACF,OAAO,MAAMA,EAAE,IAAI,KAAI,CACzB,MAAQ,CACN,MAAO,CAAA,CACT,CACF,EAKA,cAAcE,EAAgBC,EAAa,CACzC,GAAI,OAAOD,GAAU,UAAYA,EAAM,KAAI,IAAO,GAChD,MAAM,IAAIN,EAAgB,KAAKO,CAAK,gDAAgD,EAEtF,OAAOD,CACT,EAKA,gBAAgBH,EAAgBC,EAAiBI,EAA6B,CAC5E,OAAQA,GAAS,SAAWN,GAAgBC,EAAOC,CAAC,CACtD,GAUF,SAASK,EAAmBC,EAAsBF,EAA+B,CAAA,EAAE,CACjF,MAAO,OAAOJ,GAAsC,CAClD,GAAI,CACF,OAAO,MAAMM,EAAON,CAAC,CACvB,OAASD,EAAgB,CACvB,OAAQK,EAAQ,SAAWN,GAAgBC,EAAOC,CAAC,CACrD,CACF,CACF",
|
|
6
|
+
"names": ["BadRequestError", "toErrorResponse", "defaultOnError", "error", "c", "BaseRoute", "value", "field", "options", "createRouteHandler", "handle"]
|
|
7
|
+
}
|
|
@@ -18,7 +18,9 @@
|
|
|
18
18
|
* default; it is an unconditional no-op. So a caller states its own private
|
|
19
19
|
* prefixes, and the compiler asks for them rather than letting them be omitted.
|
|
20
20
|
*/
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
The slice of a Hono context this middleware reads.
|
|
23
|
+
*/
|
|
22
24
|
interface HeaderContext {
|
|
23
25
|
header(name: string, value: string): void;
|
|
24
26
|
res: {
|
|
@@ -45,7 +47,9 @@ declare const SECURITY_HEADERS: Readonly<Record<string, string>>;
|
|
|
45
47
|
* violation reports at worst.
|
|
46
48
|
*/
|
|
47
49
|
declare const CONTENT_SECURITY_POLICY = "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";
|
|
48
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
HSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning.
|
|
52
|
+
*/
|
|
49
53
|
declare const STRICT_TRANSPORT_SECURITY = "max-age=31536000; includeSubDomains";
|
|
50
54
|
/**
|
|
51
55
|
* Apply the headers to a context.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"securityHeaders.d.ts","sourceRoot":"","sources":["../src/securityHeaders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH
|
|
1
|
+
{"version":3,"file":"securityHeaders.d.ts","sourceRoot":"","sources":["../src/securityHeaders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;EAEE;AACF,UAAU,aAAa;IACrB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,GAAG,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;IAC1B,GAAG,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,QAAA,MAAM,gBAAgB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAS7C,CAAC;AAEX;;;;;;GAMG;AACH,QAAA,MAAM,uBAAuB,6NAC+L,CAAC;AAE7N;;EAEE;AACF,QAAA,MAAM,yBAAyB,wCAAwC,CAAC;AAExE;;;;;GAKG;AACH,iBAAS,oBAAoB,CAAC,CAAC,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,GAAG,IAAI,CA2BhG;AAED;;;;;;GAMG;AACH,iBAAS,eAAe,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,GAAG,CAAC,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CASnI;AAED;;;;;;;GAOG;AACH,iBAAS,cAAc,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CASrF;AAED,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,CAAC;AACvI,YAAY,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/securityHeaders.js
CHANGED
|
@@ -1,119 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* Baseline response security headers.
|
|
3
|
-
*
|
|
4
|
-
* Converged from `apps/api/src/middleware/securityHeaders.ts` in Durable-DAV,
|
|
5
|
-
* Durable-DAV-Router, Edge-Git and Edge-Sonic, where the four copies are
|
|
6
|
-
* byte-identical apart from one predicate — which is exactly why it is a
|
|
7
|
-
* parameter here rather than a constant.
|
|
8
|
-
*
|
|
9
|
-
* ## Why `isSensitive` is a required argument
|
|
10
|
-
*
|
|
11
|
-
* The copies each shipped a `startsWith('/user/')` predicate, inherited from a
|
|
12
|
-
* reference project. In one repo that worker serves **no `/user/` route**, so the
|
|
13
|
-
* predicate could never return `true` and `Cache-Control: no-store` was never
|
|
14
|
-
* applied to anything: the operator's own address and every user's address
|
|
15
|
-
* shipped with no `Cache-Control` at all.
|
|
16
|
-
*
|
|
17
|
-
* A predicate copied from another router's route table is not a conservative
|
|
18
|
-
* default; it is an unconditional no-op. So a caller states its own private
|
|
19
|
-
* prefixes, and the compiler asks for them rather than letting them be omitted.
|
|
20
|
-
*/
|
|
21
|
-
/**
|
|
22
|
-
* Baseline headers for API JSON responses and the SPA shell.
|
|
23
|
-
*
|
|
24
|
-
* The SPA ships inline scripts and styles from the Vite build, so CSP allows
|
|
25
|
-
* 'unsafe-inline' for both, bounded by `same-origin` and `frame-ancestors`.
|
|
26
|
-
* Without it the shell breaks; hashes or nonces are a future tightening once the
|
|
27
|
-
* build emits stable hashes.
|
|
28
|
-
*/
|
|
29
|
-
const SECURITY_HEADERS = {
|
|
30
|
-
'X-Content-Type-Options': 'nosniff',
|
|
31
|
-
'X-Frame-Options': 'DENY',
|
|
32
|
-
'Referrer-Policy': 'same-origin',
|
|
33
|
-
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
|
|
34
|
-
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
35
|
-
'Cross-Origin-Resource-Policy': 'same-origin',
|
|
36
|
-
'Cross-Origin-Embedder-Policy': 'require-corp',
|
|
37
|
-
'Origin-Agent-Cluster': '?1',
|
|
38
|
-
};
|
|
39
|
-
/**
|
|
40
|
-
* CSP for the HTML shell.
|
|
41
|
-
*
|
|
42
|
-
* Separate from {@link SECURITY_HEADERS} because it applies only to an HTML
|
|
43
|
-
* response — sending it on JSON is noise at best and a source of confusing
|
|
44
|
-
* violation reports at worst.
|
|
45
|
-
*/
|
|
46
|
-
const CONTENT_SECURITY_POLICY = "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";
|
|
47
|
-
/** HSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning. */
|
|
48
|
-
const STRICT_TRANSPORT_SECURITY = 'max-age=31536000; includeSubDomains';
|
|
49
|
-
/**
|
|
50
|
-
* Apply the headers to a context.
|
|
51
|
-
*
|
|
52
|
-
* Each step is independently guarded: a header must never fail a request, and
|
|
53
|
-
* one unparseable URL should not cost the other headers.
|
|
54
|
-
*/
|
|
55
|
-
function applySecurityHeaders(c, isSensitive) {
|
|
56
|
-
for (const [key, value] of Object.entries(SECURITY_HEADERS)) {
|
|
57
|
-
c.header(key, value);
|
|
58
|
-
}
|
|
59
|
-
const contentType = c.res.headers.get('content-type') ?? '';
|
|
60
|
-
if (contentType.includes('text/html')) {
|
|
61
|
-
c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);
|
|
62
|
-
}
|
|
63
|
-
let pathname;
|
|
64
|
-
try {
|
|
65
|
-
pathname = new URL(c.req.url).pathname;
|
|
66
|
-
}
|
|
67
|
-
catch {
|
|
68
|
-
// URL parsing must never fail the request; the `no-store` step is skipped.
|
|
69
|
-
}
|
|
70
|
-
if (pathname !== undefined && isSensitive(pathname)) {
|
|
71
|
-
c.header('Cache-Control', 'no-store');
|
|
72
|
-
}
|
|
73
|
-
try {
|
|
74
|
-
if (new URL(c.req.url).protocol === 'https:') {
|
|
75
|
-
c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
catch {
|
|
79
|
-
// URL parsing must never fail the request.
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* The middleware.
|
|
84
|
-
*
|
|
85
|
-
* `isSensitive` is **required**, and its parameter is required, so a caller
|
|
86
|
-
* cannot accidentally ship a predicate that returns `true` for everything
|
|
87
|
-
* (caching a credential response) or `false` for everything (the no-op above).
|
|
88
|
-
*/
|
|
89
|
-
function securityHeaders(isSensitive) {
|
|
90
|
-
return async (c, next) => {
|
|
91
|
-
await next();
|
|
92
|
-
try {
|
|
93
|
-
applySecurityHeaders(c, isSensitive);
|
|
94
|
-
}
|
|
95
|
-
catch {
|
|
96
|
-
// Headers must never fail the request.
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Build a predicate from this app's private path prefixes.
|
|
102
|
-
*
|
|
103
|
-
* A convenience over `securityHeaders`, not a default: it matches **exactly**
|
|
104
|
-
* these prefixes, so a caller still has to name its own paths. The returned
|
|
105
|
-
* function composes, so a repo with a second private surface can add its own
|
|
106
|
-
* test without editing this one.
|
|
107
|
-
*/
|
|
108
|
-
function sensitivePaths(...prefixes) {
|
|
109
|
-
if (prefixes.length === 0) {
|
|
110
|
-
// Not a throw: a repo with nothing private is a legitimate state, and the
|
|
111
|
-
// failure mode to avoid is silently caching a credential, which an empty
|
|
112
|
-
// list cannot do. What it must not do is *look* like it protected something.
|
|
113
|
-
return () => false;
|
|
114
|
-
}
|
|
115
|
-
const normalized = prefixes.map((prefix) => (prefix.endsWith('/') ? prefix : `${prefix}/`));
|
|
116
|
-
return (pathname) => normalized.some((prefix) => pathname.startsWith(prefix));
|
|
117
|
-
}
|
|
118
|
-
export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY };
|
|
119
|
-
//# sourceMappingURL=securityHeaders.js.map
|
|
1
|
+
const s={"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"},i="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",o="max-age=31536000; includeSubDomains";function a(e,t){for(const[c,l]of Object.entries(s))e.header(c,l);(e.res.headers.get("content-type")??"").includes("text/html")&&e.header("Content-Security-Policy",i);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",o)}catch{}}function u(e){return async(t,n)=>{await n();try{a(t,e)}catch{}}}function f(...e){if(e.length===0)return()=>!1;const t=e.map(n=>n.endsWith("/")?n:`${n}/`);return n=>t.some(r=>n.startsWith(r))}export{i as CONTENT_SECURITY_POLICY,s as SECURITY_HEADERS,o as STRICT_TRANSPORT_SECURITY,a as applySecurityHeaders,u as securityHeaders,f as sensitivePaths};
|