@rexezuge/http 0.0.0-stage → 1.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAGlD,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAGzG,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAGpG,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC","sourcesContent":["/**\n * `@rexezuge/http` — the family's HTTP layer.\n *\n * ## Why this package exists\n *\n * Eight other packages in the kit are framework-free on purpose, and that is\n * what lets a repo adopt `shared` / `errors` / `runtime` without adopting a web\n * framework. The rate limiter, the security headers, the route bases and the\n * Access auth service cannot be framework-free: they are Hono- and\n * chanfana-shaped, and four repos shipped four copies of each while the kit's\n * zero-dependency rule silently prevented the fix.\n *\n * So this is the one package that breaks the rule, deliberately. It is also the\n * only one a repo can choose to skip — nothing in the other eight imports it.\n *\n * ## What converged here\n *\n * | Module | From |\n * | ----------------- | --------------------------------------------------------------------- |\n * | `rateLimit` | Edge-Sonic's — the copy that fixed the per-request sweep, the resolver `max`, and the `Retry-After` header |\n * | `securityHeaders` | Four byte-identical copies, with the `no-store` predicate made a **required** argument |\n * | `accessAuth` | Edge-Sonic's — the copy that replaced a `ctx.access` branch that could never execute |\n * | `ErrorMapper` | Edge-Sonic's — split by surface, not by convenience |\n * | `routeBase` | All three incompatible shapes, with their shared parts converged |\n *\n * ## The null rule\n *\n * `null` means absent, `undefined` means not supplied — see the kit's `AGENTS.md`.\n * The middleware in this package takes *structural* context types rather than\n * Hono's `Context<…>`, which keeps a `Request`-dispatching surface and a test\n * double usable without a framework import.\n */\n\nexport { clientIp, rateLimit } from './rateLimit';\nexport type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface } from './rateLimit';\n\nexport {\n applySecurityHeaders,\n securityHeaders,\n sensitivePaths,\n CONTENT_SECURITY_POLICY,\n SECURITY_HEADERS,\n STRICT_TRANSPORT_SECURITY,\n} from './securityHeaders';\nexport type { HeaderContext } from './securityHeaders';\n\nexport { AccessAuthError, authenticateAccess, identityFromBinding, verifyAccessJwt } from './accessAuth';\nexport type { AccessAuthOptions, AccessBinding, AccessIdentity, AccessJwtVerifier } from './accessAuth';\n\nexport { errorBody, toErrorResponse, toServiceError, INTERNAL_SERVER_MESSAGE } from './ErrorMapper';\nexport type { ErrorMapperOptions } from './ErrorMapper';\n\nexport { BaseRoute, createRouteHandler } from './routeBase';\nexport type { RouteContext, RouteHandler, RouteHandlerOptions } from './routeBase';\n"]}
@@ -0,0 +1,119 @@
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 slice of a Hono context this limiter reads.
67
+ *
68
+ * Structural rather than `Context<…>` so a caller can pass any framework
69
+ * context (or a test double) without this package pinning the generic
70
+ * parameters, and so a plain `Request`-dispatching surface can share the
71
+ * derivation.
72
+ */
73
+ interface RateLimitContext {
74
+ req: {
75
+ header(name: string): string | undefined;
76
+ };
77
+ get?(key: string): unknown;
78
+ json(body: unknown, status?: number, headers?: Record<string, string>): Response;
79
+ }
80
+ type RateLimitSurface = 'rest' | 'user';
81
+ interface RateLimitOptions {
82
+ windowMs: number;
83
+ max: number | ((c: RateLimitContext) => number);
84
+ keyPrefix: string;
85
+ /**
86
+ * Which error dialect a 429 answers in. One surface, one dialect: a client
87
+ * that parses a Subsonic envelope cannot read the user API's body, so a 429
88
+ * carrying it renders as "server error" and the client retries immediately —
89
+ * the opposite of what a throttle is for.
90
+ */
91
+ surface?: RateLimitSurface;
92
+ /**
93
+ * Builds the 429 for a surface that has its own envelope. Defaults to the
94
+ * `{Exception:{Type,Message}}` shape from `@rexezuge/errors`.
95
+ */
96
+ onThrottled?(retryAfter: number, c: RateLimitContext): Response;
97
+ }
98
+ type RateLimitHandler = (c: RateLimitContext, next: () => Promise<Response | void>) => Promise<Response | void>;
99
+ /**
100
+ * The one trusted client address.
101
+ *
102
+ * Trust order is deliberately a single entry: Cloudflare sets
103
+ * `CF-Connecting-IP` and it cannot be spoofed by a client. `X-Forwarded-For`,
104
+ * `x-real-ip` and every other forwarding header are **not** consulted, because
105
+ * they are client-controlled and let an attacker rotate buckets — or, on a
106
+ * surface with an offline credential throttle, rotate the identity keying it and
107
+ * brute-force forever.
108
+ *
109
+ * Local dev without CF headers shares the `unknown` bucket, which is fail-closed
110
+ * grouping rather than per-spoofed-header isolation.
111
+ *
112
+ * Takes a header reader rather than a context so a bare-`Request` dispatcher
113
+ * uses the same derivation.
114
+ */
115
+ declare function clientIp(header: (name: string) => string | undefined): string;
116
+ declare function rateLimit(opts: RateLimitOptions): RateLimitHandler;
117
+ export { clientIp, rateLimit };
118
+ export type { RateLimitContext, RateLimitHandler, RateLimitOptions, RateLimitSurface };
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AEtE;AAgFD,iBAAS,SAAS,CAAC,IAAI,EAAE,gBAAgB,GAAG,gBAAgB,CAyD3D;AAoBD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;AAC/B,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC"}
@@ -0,0 +1,225 @@
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
@@ -0,0 +1 @@
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,CAA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QAAQ,CAAC,OAAO,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;gBAC3E,OAAO,SAAS,CAAC,UAAU,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;YACxC,CAAC;YAED,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAC;YACpB,OAAO,MAAM,IAAI,EAAE,CAAC;QACtB,CAAC;QAAC,MAAM,CAAC;YACP,4EAA4E;YAC5E,sCAAsC;YACtC,OAAO,MAAM,IAAI,EAAE,CAAC;QACtB,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,SAAS,CAAC,UAAkB,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"]}
@@ -0,0 +1,49 @@
1
+ /** The slice of a Hono context a route handler reads. */
2
+ interface RouteContext {
3
+ req: {
4
+ json(): Promise<unknown>;
5
+ raw: Request;
6
+ };
7
+ env: unknown;
8
+ json(body: unknown, status?: number, headers?: Record<string, string>): Response;
9
+ /** Optional request scope, when the repo uses DI. */
10
+ get?(key: string): unknown;
11
+ }
12
+ type RouteHandler = (c: RouteContext) => Promise<Response>;
13
+ interface RouteHandlerOptions {
14
+ /** A repo-specific mapper. Defaults to the canonical `{Exception:{…}}` dialect. */
15
+ onError?(error: unknown, c: RouteContext): Response;
16
+ }
17
+ /**
18
+ * The shared statics.
19
+ *
20
+ * `readJson` is deliberately total: a malformed body yields `{}` rather than
21
+ * throwing, because a handler that wants to reject a malformed body validates it
22
+ * and gets a 400 through the normal path. A parse error thrown from here would
23
+ * bypass whatever validation error message the repo has.
24
+ */
25
+ declare const BaseRoute: {
26
+ /**
27
+ * Read the JSON body, or `{}`.
28
+ *
29
+ * Bounded by the caller's schema, not here: an unbounded `req.json()` on a
30
+ * worker is a memory ceiling, and each repo's limit is its own
31
+ * `MAX_JSON_BODY_BYTES`.
32
+ */
33
+ readonly readJson: (c: RouteContext) => Promise<unknown>;
34
+ /** A required string field, or the error that says which field was missing. */
35
+ readonly requireString: (value: unknown, field: string) => string;
36
+ /** Map a caught value to a response, using the repo's dialect if it declared one. */
37
+ readonly toErrorResponse: (error: unknown, c: RouteContext, options?: RouteHandlerOptions) => Response;
38
+ };
39
+ /**
40
+ * Build a Template-Method route handler.
41
+ *
42
+ * The shape Edge-Git and Edge-Sonic converged on: the handler owns only its
43
+ * domain work, and the base owns the try/catch so a private repo's existence and
44
+ * a 5xx's message are decided in exactly one place per app.
45
+ */
46
+ declare function createRouteHandler(handle: RouteHandler, options?: RouteHandlerOptions): (c: RouteContext) => Promise<Response>;
47
+ export { BaseRoute, createRouteHandler };
48
+ export type { RouteContext, RouteHandler, RouteHandlerOptions };
49
+ //# sourceMappingURL=routeBase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeBase.d.ts","sourceRoot":"","sources":["../src/routeBase.ts"],"names":[],"mappings":"AAmCA,yDAAyD;AACzD,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,qDAAqD;IACrD,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,mFAAmF;IACnF,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,+EAA+E;oCAC1D,OAAO,SAAS,MAAM,KAAG,MAAM;IAOpD,qFAAqF;sCAC9D,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"}
@@ -0,0 +1,92 @@
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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeBase.js","sourceRoot":"","sources":["../src/routeBase.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAC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AAC;QACvD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC","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, ServiceError } from '@rexezuge/errors';\nimport { toErrorResponse } from './ErrorMapper';\n\n/** The slice of a Hono context a route handler reads. */\ninterface RouteContext {\n req: { json(): Promise<unknown>; raw: Request };\n env: unknown;\n json(body: unknown, status?: number, headers?: Record<string, string>): Response;\n /** Optional request scope, when the repo uses DI. */\n get?(key: string): unknown;\n}\n\ntype RouteHandler = (c: RouteContext) => Promise<Response>;\n\ninterface RouteHandlerOptions {\n /** A repo-specific mapper. Defaults to the canonical `{Exception:{…}}` dialect. */\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 /** A required string field, or the error that says which field was missing. */\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 /** Map a caught value to a response, using the repo's dialect if it declared one. */\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"]}
@@ -0,0 +1,76 @@
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
+ /** The slice of a Hono context this middleware reads. */
22
+ interface HeaderContext {
23
+ header(name: string, value: string): void;
24
+ res: {
25
+ headers: Headers;
26
+ };
27
+ req: {
28
+ url: string;
29
+ };
30
+ }
31
+ /**
32
+ * Baseline headers for API JSON responses and the SPA shell.
33
+ *
34
+ * The SPA ships inline scripts and styles from the Vite build, so CSP allows
35
+ * 'unsafe-inline' for both, bounded by `same-origin` and `frame-ancestors`.
36
+ * Without it the shell breaks; hashes or nonces are a future tightening once the
37
+ * build emits stable hashes.
38
+ */
39
+ declare const SECURITY_HEADERS: Readonly<Record<string, string>>;
40
+ /**
41
+ * CSP for the HTML shell.
42
+ *
43
+ * Separate from {@link SECURITY_HEADERS} because it applies only to an HTML
44
+ * response — sending it on JSON is noise at best and a source of confusing
45
+ * violation reports at worst.
46
+ */
47
+ 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
+ /** HSTS. Only sent over HTTPS — sending it over plain HTTP risks local pinning. */
49
+ declare const STRICT_TRANSPORT_SECURITY = "max-age=31536000; includeSubDomains";
50
+ /**
51
+ * Apply the headers to a context.
52
+ *
53
+ * Each step is independently guarded: a header must never fail a request, and
54
+ * one unparseable URL should not cost the other headers.
55
+ */
56
+ declare function applySecurityHeaders(c: HeaderContext, isSensitive: (pathname: string) => boolean): void;
57
+ /**
58
+ * The middleware.
59
+ *
60
+ * `isSensitive` is **required**, and its parameter is required, so a caller
61
+ * cannot accidentally ship a predicate that returns `true` for everything
62
+ * (caching a credential response) or `false` for everything (the no-op above).
63
+ */
64
+ declare function securityHeaders(isSensitive: (pathname: string) => boolean): (c: HeaderContext, next: () => Promise<void>) => Promise<void>;
65
+ /**
66
+ * Build a predicate from this app's private path prefixes.
67
+ *
68
+ * A convenience over `securityHeaders`, not a default: it matches **exactly**
69
+ * these prefixes, so a caller still has to name its own paths. The returned
70
+ * function composes, so a repo with a second private surface can add its own
71
+ * test without editing this one.
72
+ */
73
+ declare function sensitivePaths(...prefixes: readonly string[]): (pathname: string) => boolean;
74
+ export { applySecurityHeaders, securityHeaders, sensitivePaths, CONTENT_SECURITY_POLICY, SECURITY_HEADERS, STRICT_TRANSPORT_SECURITY };
75
+ export type { HeaderContext };
76
+ //# sourceMappingURL=securityHeaders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"securityHeaders.d.ts","sourceRoot":"","sources":["../src/securityHeaders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,yDAAyD;AACzD,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,mFAAmF;AACnF,QAAA,MAAM,yBAAyB,wCAAwC,CAAC;AAExE;;;;;GAKG;AACH,iBAAS,oBA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