@vite-hub/rate-limit 0.1.0 → 0.3.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.
Files changed (39) hide show
  1. package/README.md +18 -14
  2. package/dist/cli-szm60zN5.d.ts +163 -0
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +12 -26
  5. package/dist/{cloudflare-DUDRACVB.js → cloudflare-otBvOPv4.js} +5 -4
  6. package/dist/{counters-pKORpgGd.d.ts → counters-DXpF67J_.d.ts} +3 -3
  7. package/dist/{counters-wdEMxDEY.js → counters-DgVdHwdL.js} +13 -6
  8. package/dist/dev-peer-CHafxbtj.js +238 -0
  9. package/dist/drivers/cloudflare.d.ts +1 -1
  10. package/dist/drivers/cloudflare.js +1 -1
  11. package/dist/drivers/kv.d.ts +2 -0
  12. package/dist/drivers/kv.js +92 -0
  13. package/dist/drivers/memory.d.ts +1 -1
  14. package/dist/drivers/memory.js +5 -5
  15. package/dist/durability.d.ts +12 -0
  16. package/dist/durability.js +35 -0
  17. package/dist/error-diagnostics-MgAnhRTP.js +234 -0
  18. package/dist/index.d.ts +16 -7
  19. package/dist/index.js +108 -38
  20. package/dist/{inspect-D-FzyM_x.js → inspect-B6gTdgy9.js} +7 -1
  21. package/dist/kv-C1wpLulE.d.ts +29 -0
  22. package/dist/{limiter-DBrMI4vi.js → kv-provider-C1S6dRTR.js} +16 -9
  23. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  24. package/dist/operations-BYRa7wpx.js +1355 -0
  25. package/dist/{operations-Bu-xulNd.js → operations-CLI9w3rO.js} +9 -14
  26. package/dist/operations.d.ts +9 -4
  27. package/dist/operations.js +51 -23
  28. package/dist/runtime.d.ts +21 -3
  29. package/dist/runtime.js +2 -2
  30. package/dist/state-BU-zcLNY.js +89 -0
  31. package/dist/{types-CQEJpgtz.d.ts → types-CMyR1JeW.d.ts} +43 -23
  32. package/dist/vite.d.ts +131 -21
  33. package/dist/vite.js +349 -2479
  34. package/package.json +21 -17
  35. package/dist/cli-Cniq99iX.d.ts +0 -85
  36. package/dist/error-diagnostics-CTAC_bbr.js +0 -56
  37. package/dist/h3-v1-request-qoGwJr5-.js +0 -235
  38. package/dist/operations-B09NnEjT.js +0 -1438
  39. package/dist/state-Ct7zR8fD.js +0 -43
@@ -0,0 +1,238 @@
1
+ //#region ../internal/src/dev-peer.ts
2
+ /**
3
+ * Proof that a development request came from this machine, for dev servers that run the app behind a proxy.
4
+ *
5
+ * Nitro 3 runs the app in a worker behind an env-runner proxy. The worker never sees the client's address
6
+ * (https://github.com/unjs/env-runner/issues/113):
7
+ * over a Unix socket it sees none, and over TCP it sees the proxy on `127.0.0.1`. The proxy forwards a client
8
+ * `x-forwarded-for` as is. The front process sees the real socket, so its Nitro dev handler removes any client copy
9
+ * of {@link viteHubDevPeerHeader} and, for a loopback socket only, adds an HMAC over the method, the path, a
10
+ * timestamp, and a nonce. The key is random for each process and reaches the worker only through its environment
11
+ * ({@link viteHubDevPeerKeyEnv}), never through a header. The worker takes the key out of its environment, so the
12
+ * processes that the app starts do not inherit it.
13
+ *
14
+ * A tunnel or a reverse proxy on this machine, such as `cloudflared`, `ngrok`, `tailscale serve`, or Caddy, connects
15
+ * from a loopback socket too. Such a request is not from this machine, so the front process signs no request that
16
+ * names another host or carries a forwarding header ({@link isViteHubForwardedRequest}). A forwarder that copies raw
17
+ * TCP bytes, such as `ssh -R`, sends no such sign. Only sign-in protects a dev server behind one.
18
+ *
19
+ * The worker calls {@link verifyViteHubDevPeer}. Each piece of evidence is valid once, for one method and path, for a
20
+ * short time. This module uses Web Crypto and no Node import, so the check also runs in Worker runtimes.
21
+ */
22
+ /** The request header that carries the evidence from the front process to the worker. */
23
+ const viteHubDevPeerHeader = "x-vitehub-dev-peer";
24
+ /** The environment variable that carries the per-process key from the front process to the worker. */
25
+ const viteHubDevPeerKeyEnv = "VITEHUB_DEV_PEER_KEY";
26
+ /** How long evidence stays valid. A dev worker that is still starting can hold a request for some seconds. */
27
+ const viteHubDevPeerMaxAgeMs = 6e4;
28
+ const futureSkewMs = 5e3;
29
+ const version = "v1";
30
+ const evidencePattern = /^v1\.(\d{13})\.([\w-]{22})\.([\w-]{43})$/;
31
+ const encoder = new TextEncoder();
32
+ const stateKey = Symbol.for("vitehub.dev-peer");
33
+ const scope = globalThis;
34
+ const state = scope[stateKey] ??= {
35
+ keys: /* @__PURE__ */ new Map(),
36
+ nonces: /* @__PURE__ */ new Map(),
37
+ verified: /* @__PURE__ */ new WeakMap()
38
+ };
39
+ function base64url(bytes) {
40
+ let binary = "";
41
+ for (const byte of bytes) binary += String.fromCharCode(byte);
42
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
43
+ }
44
+ function fromBase64url(value) {
45
+ const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/"));
46
+ const bytes = new Uint8Array(binary.length);
47
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
48
+ return bytes;
49
+ }
50
+ function random(length) {
51
+ return base64url(crypto.getRandomValues(new Uint8Array(length)));
52
+ }
53
+ function importKey(key) {
54
+ let imported = state.keys.get(key);
55
+ if (!imported) {
56
+ imported = crypto.subtle.importKey("raw", encoder.encode(key), {
57
+ hash: "SHA-256",
58
+ name: "HMAC"
59
+ }, false, ["sign", "verify"]);
60
+ state.keys.set(key, imported);
61
+ }
62
+ return imported;
63
+ }
64
+ function pathnameOf(path) {
65
+ return new URL(`http://localhost${path}`).pathname;
66
+ }
67
+ function payload(method, path, timestamp, nonce) {
68
+ return encoder.encode(`vitehub-dev-peer\n${version}\n${method.toUpperCase()}\n${pathnameOf(path)}\n${timestamp}\n${nonce}`);
69
+ }
70
+ /** Whether a socket address is a loopback address. A missing address, such as a Unix socket peer, is not. */
71
+ function isViteHubLoopbackAddress(address) {
72
+ if (!address) return false;
73
+ const v4 = address.toLowerCase().startsWith("::ffff:") ? address.slice(7) : address;
74
+ return v4 === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v4);
75
+ }
76
+ /**
77
+ * The key of this process, created on the first call and written to `process.env` so a dev worker that starts later
78
+ * inherits it. A value that the process inherited, for example from a parent process or a shell, is replaced.
79
+ * Call it only in the front process of a development server.
80
+ */
81
+ function useViteHubDevPeerKey() {
82
+ state.key ??= random(32);
83
+ process.env[viteHubDevPeerKeyEnv] = state.key;
84
+ return state.key;
85
+ }
86
+ /**
87
+ * The key that this process verifies with: its own key in the front process, or the key that a dev worker inherited
88
+ * from its front process. `undefined` when no front process set one.
89
+ *
90
+ * A dev worker removes the key from its `process.env` on the first read, so a child process that the app starts, such
91
+ * as a shell command of an Agent, does not inherit it. The module also reads once when it loads.
92
+ */
93
+ function readViteHubDevPeerKey() {
94
+ const env = globalThis.process?.env;
95
+ const value = env?.[viteHubDevPeerKeyEnv];
96
+ if (state.key && value === state.key) return state.key;
97
+ if (env && value !== void 0) {
98
+ Reflect.deleteProperty(env, viteHubDevPeerKeyEnv);
99
+ state.inherited = typeof value === "string" && value.length >= 32 ? value : void 0;
100
+ }
101
+ return state.inherited;
102
+ }
103
+ /** Create the evidence for one request that came from a loopback socket. */
104
+ async function signViteHubDevPeer(key, request, now = Date.now()) {
105
+ const timestamp = String(Math.trunc(now)).padStart(13, "0");
106
+ const nonce = random(16);
107
+ const signature = await crypto.subtle.sign("HMAC", await importKey(key), payload(request.method, request.path, timestamp, nonce));
108
+ return `${version}.${timestamp}.${nonce}.${base64url(new Uint8Array(signature))}`;
109
+ }
110
+ function forgetExpiredNonces(now) {
111
+ for (const [nonce, expires] of state.nonces) if (expires <= now) state.nonces.delete(nonce);
112
+ }
113
+ /**
114
+ * Whether `request` carries valid evidence from the front process: signed with `key`, for this method and path, not
115
+ * older than {@link viteHubDevPeerMaxAgeMs}, and not used by another request. A second check of the same `Request`
116
+ * object gives the same answer. Missing, malformed, tampered, expired, and replayed evidence gives `false`.
117
+ */
118
+ async function verifyViteHubDevPeer(request, key, now = Date.now()) {
119
+ const known = state.verified.get(request);
120
+ if (known !== void 0) return known;
121
+ const verified = await verify(request, key, now);
122
+ state.verified.set(request, verified);
123
+ return verified;
124
+ }
125
+ async function verify(request, key, now) {
126
+ const match = evidencePattern.exec(request.headers.get("x-vitehub-dev-peer") ?? "");
127
+ if (!match) return false;
128
+ const [, timestamp = "", nonce = "", signature = ""] = match;
129
+ const issued = Number(timestamp);
130
+ if (issued < now - 6e4 || issued > now + futureSkewMs) return false;
131
+ forgetExpiredNonces(now);
132
+ if (state.nonces.has(nonce)) return false;
133
+ const bytes = fromBase64url(signature);
134
+ if (base64url(bytes) !== signature) return false;
135
+ const path = new URL(request.url).pathname;
136
+ if (!await crypto.subtle.verify("HMAC", await importKey(key), bytes, payload(request.method, path, timestamp, nonce))) return false;
137
+ if (state.nonces.has(nonce)) return false;
138
+ state.nonces.set(nonce, issued + viteHubDevPeerMaxAgeMs + futureSkewMs);
139
+ return true;
140
+ }
141
+ /**
142
+ * Whether a development request came from this machine. The socket or signed front-process evidence proves the peer.
143
+ * - A dev server whose front process signs loopback requests gives its worker a key. The worker then trusts only
144
+ * that evidence, because its own peer is the proxy of the front process.
145
+ * - Without a key, require a loopback `remoteAddress` from the host adapter and no forwarding headers. An unknown
146
+ * peer is refused. A signed request can carry forwarding headers that Nitro's own proxy added after signing.
147
+ */
148
+ async function isViteHubLoopbackPeer(request, remoteAddress) {
149
+ if (remoteAddress && !isViteHubLoopbackAddress(remoteAddress)) return false;
150
+ const key = readViteHubDevPeerKey();
151
+ return key ? verifyViteHubDevPeer(request, key) : isViteHubLoopbackAddress(remoteAddress) && !isViteHubForwardedRequest(Object.fromEntries(request.headers));
152
+ }
153
+ const forwardingHeaders = /* @__PURE__ */ new Set([
154
+ "cdn-loop",
155
+ "fastly-client-ip",
156
+ "fly-client-ip",
157
+ "forwarded",
158
+ "true-client-ip",
159
+ "via",
160
+ "x-client-ip",
161
+ "x-cluster-client-ip",
162
+ "x-original-forwarded-for",
163
+ "x-real-ip",
164
+ "x-vercel-forwarded-for"
165
+ ]);
166
+ const forwardingHeaderPrefixes = [
167
+ "x-forwarded-",
168
+ "cf-",
169
+ "ngrok-",
170
+ "tailscale-"
171
+ ];
172
+ /**
173
+ * Whether a request carries a header that a proxy, a tunnel, or a CDN adds for the client that it forwards. The front
174
+ * process signs no such request, because it came from somewhere else through a program on this machine.
175
+ */
176
+ function isViteHubForwardedRequest(headers) {
177
+ return Object.keys(headers).some((name) => {
178
+ const lower = name.toLowerCase();
179
+ return forwardingHeaders.has(lower) || forwardingHeaderPrefixes.some((prefix) => lower.startsWith(prefix));
180
+ });
181
+ }
182
+ /** Whether a `Host` header names this machine: `localhost`, a `.localhost` name, a `127.0.0.0/8` address, or `[::1]`. */
183
+ function isViteHubLoopbackHost(host) {
184
+ if (!host || /[/?#@\\]/.test(host)) return false;
185
+ let name;
186
+ try {
187
+ name = new URL(`http://${host}`).hostname;
188
+ } catch {
189
+ return false;
190
+ }
191
+ return name === "localhost" || name.endsWith(".localhost") || name === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name);
192
+ }
193
+ /**
194
+ * Remove a client copy of the evidence. Returns the request to sign when it came from a loopback socket, names this
195
+ * machine in `Host`, and carries no forwarding header.
196
+ */
197
+ function takeSignableRequest(node) {
198
+ delete node.headers[viteHubDevPeerHeader];
199
+ if (!isViteHubLoopbackAddress(node.socket?.remoteAddress) || !node.method || !node.url?.startsWith("/")) return;
200
+ const authority = node.headers[":authority"];
201
+ if (authority !== void 0 && node.headers.host !== void 0 && node.headers.host !== authority) return;
202
+ const host = authority ?? node.headers.host;
203
+ if (typeof host !== "string" || !isViteHubLoopbackHost(host) || isViteHubForwardedRequest(node.headers)) return;
204
+ return {
205
+ method: node.method,
206
+ path: node.url
207
+ };
208
+ }
209
+ /**
210
+ * The Nitro dev handler that runs in the front process before Nitro forwards a request to its worker. It never
211
+ * answers a request itself.
212
+ */
213
+ async function viteHubDevPeerDevHandler(event) {
214
+ const node = event.runtime?.node?.req;
215
+ const web = node ? event.req?.headers : void 0;
216
+ web?.delete(viteHubDevPeerHeader);
217
+ if (!node) return;
218
+ const request = takeSignableRequest(node);
219
+ if (!request) return;
220
+ const evidence = await signViteHubDevPeer(useViteHubDevPeerKey(), request);
221
+ node.headers[viteHubDevPeerHeader] = evidence;
222
+ web?.set(viteHubDevPeerHeader, evidence);
223
+ }
224
+ const devHandlerMark = Symbol.for("vitehub.dev-peer.dev-handler");
225
+ const devHandler = Object.assign(viteHubDevPeerDevHandler, { [devHandlerMark]: true });
226
+ /**
227
+ * Put the dev handler first in Nitro's `devHandlers`, once, and create the key of this process. Call it while Nitro
228
+ * is configured for development, before its worker starts.
229
+ */
230
+ function addViteHubDevPeerDevHandler(devHandlers) {
231
+ useViteHubDevPeerKey();
232
+ const index = devHandlers.findIndex((entry) => typeof entry.handler === "function" && devHandlerMark in entry.handler);
233
+ if (index !== -1) devHandlers.splice(index, 1);
234
+ devHandlers.unshift({ handler: devHandler });
235
+ }
236
+ readViteHubDevPeerKey();
237
+ //#endregion
238
+ export { isViteHubLoopbackPeer as n, addViteHubDevPeerDevHandler as t };
@@ -1,4 +1,4 @@
1
- import { o as RateLimitDriver } from "../types-CQEJpgtz.js";
1
+ import { c as RateLimitDriver } from "../types-CMyR1JeW.js";
2
2
  //#region src/integrations/cloudflare.d.ts
3
3
  export declare function getCloudflareRateLimitBindingName(name: string): string;
4
4
  //#endregion
@@ -1,2 +1,2 @@
1
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-DUDRACVB.js";
1
+ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-otBvOPv4.js";
2
2
  export { cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
@@ -0,0 +1,2 @@
1
+ import { i as kvRateLimitDriver, n as KVRateLimitDriverOptions, r as RateLimitKVStorage, t as KVRateLimitDriver } from "../kv-C1wpLulE.js";
2
+ export { KVRateLimitDriver, KVRateLimitDriverOptions, RateLimitKVStorage, kvRateLimitDriver };
@@ -0,0 +1,92 @@
1
+ import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-MgAnhRTP.js";
2
+ import { toResultError } from "@vite-hub/runtime";
3
+ //#region src/drivers/kv.ts
4
+ function isStorage(value) {
5
+ if (!value || typeof value !== "object") return false;
6
+ return typeof Reflect.get(value, "increment") === "function" && typeof Reflect.get(value, "get") === "function" && typeof Reflect.get(value, "delete") === "function";
7
+ }
8
+ /** Bound the request wait without hiding configuration errors thrown by KV. */
9
+ async function withKVDeadline(operation) {
10
+ let timer;
11
+ const deadline = new Promise((resolve) => {
12
+ timer = setTimeout(() => resolve([toResultError(rateLimitErrorDiagnostics.RATE_LIMIT_KV_TIMEOUT()), void 0]), 1e3);
13
+ });
14
+ try {
15
+ return await Promise.race([operation, deadline]);
16
+ } finally {
17
+ clearTimeout(timer);
18
+ }
19
+ }
20
+ /**
21
+ * KV keys use `/` and `:` as separators and reject a `.` or `..` segment, so encode the parts that come from the app.
22
+ * Without it, a client key such as `..` makes every increment fail, and `failure: "allow"` then lets it through.
23
+ */
24
+ function keySegment(value) {
25
+ return encodeURIComponent(value).replaceAll(".", "%2E");
26
+ }
27
+ /**
28
+ * One counter for each Rate Limit, window duration, key, and window start. A new window uses a new key, so no reset is
29
+ * necessary. The duration keeps a `1m` and a `1h` limiter of one name apart when their window starts align.
30
+ */
31
+ function fixedWindow(input, timestamp) {
32
+ const start = Math.floor(timestamp / input.windowMs) * input.windowMs;
33
+ const resetAt = start + input.windowMs;
34
+ if (!Number.isFinite(resetAt) || resetAt <= 0 || resetAt > 864e13) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0045({ message: "[vitehub] KV Rate Limit fixed-window end must be a positive timestamp at most 8640000000000000 milliseconds." });
35
+ return {
36
+ key: `rate-limit:${keySegment(input.name ?? "default")}:${input.windowMs}:${keySegment(input.key)}:${start}`,
37
+ resetAt,
38
+ start
39
+ };
40
+ }
41
+ /**
42
+ * Counts fixed windows in a KV store with one atomic `increment` for each request. Every server process that uses the
43
+ * same store shares the counters. Rejected requests also increment the counter.
44
+ */
45
+ function kvRateLimitDriver(options) {
46
+ if (!isStorage(options?.storage)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0046({ message: "[vitehub] kvRateLimitDriver() requires a KV store with increment(), get(), and delete()." });
47
+ const storage = options.storage;
48
+ const now = options.now ?? Date.now;
49
+ return {
50
+ capabilities: {
51
+ enforcement: "strict",
52
+ rejectedAttempts: "counted",
53
+ scope: "global"
54
+ },
55
+ async consume(input) {
56
+ const timestamp = now();
57
+ const window = fixedWindow(input, timestamp);
58
+ const [error, used] = await withKVDeadline(storage.increment(window.key, input.windowMs / 1e3));
59
+ if (error) return [error, void 0];
60
+ if (used > input.limit) return [void 0, {
61
+ allowed: false,
62
+ remaining: 0,
63
+ resetAt: window.resetAt,
64
+ retryAfter: Math.max(1, Math.ceil((window.resetAt - timestamp) / 1e3)),
65
+ used
66
+ }];
67
+ return [void 0, {
68
+ allowed: true,
69
+ remaining: input.limit - used,
70
+ resetAt: window.resetAt,
71
+ used
72
+ }];
73
+ },
74
+ name: "kv",
75
+ async peek(input) {
76
+ const window = fixedWindow(input, now());
77
+ const [error, value] = await withKVDeadline(storage.get(window.key));
78
+ if (error) return [error, void 0];
79
+ const used = typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : 0;
80
+ return [void 0, {
81
+ resetAt: used ? window.resetAt : void 0,
82
+ used
83
+ }];
84
+ },
85
+ async reset(input) {
86
+ const [error] = await withKVDeadline(storage.delete(fixedWindow(input, now()).key));
87
+ return error ? [error, void 0] : [void 0, void 0];
88
+ }
89
+ };
90
+ }
91
+ //#endregion
92
+ export { kvRateLimitDriver };
@@ -1,4 +1,4 @@
1
- import { o as RateLimitDriver } from "../types-CQEJpgtz.js";
1
+ import { c as RateLimitDriver } from "../types-CMyR1JeW.js";
2
2
  //#region src/drivers/memory.d.ts
3
3
  export interface MemoryRateLimitDriverOptions {
4
4
  maxEntries?: number;
@@ -1,4 +1,4 @@
1
- import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-CTAC_bbr.js";
1
+ import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-MgAnhRTP.js";
2
2
  //#region src/drivers/memory.ts
3
3
  const defaultMaxEntries = 1e5;
4
4
  function memoryRateLimitDriver(options = {}) {
@@ -38,7 +38,7 @@ function memoryRateLimitDriver(options = {}) {
38
38
  resetAt
39
39
  };
40
40
  }
41
- if (entry.count >= input.limit) return [null, {
41
+ if (entry.count >= input.limit) return [void 0, {
42
42
  allowed: false,
43
43
  remaining: 0,
44
44
  resetAt: entry.resetAt,
@@ -48,7 +48,7 @@ function memoryRateLimitDriver(options = {}) {
48
48
  entry.count += 1;
49
49
  entries.set(key, entry);
50
50
  nextExpiry = Math.min(nextExpiry, entry.resetAt);
51
- return [null, {
51
+ return [void 0, {
52
52
  allowed: true,
53
53
  remaining: input.limit - entry.count,
54
54
  resetAt: entry.resetAt,
@@ -60,7 +60,7 @@ function memoryRateLimitDriver(options = {}) {
60
60
  prune(timestamp);
61
61
  const key = JSON.stringify([input.name ?? "default", input.key]);
62
62
  const entry = entries.get(key);
63
- return [null, {
63
+ return [void 0, {
64
64
  resetAt: entry && entry.resetAt > timestamp ? entry.resetAt : void 0,
65
65
  used: entry && entry.resetAt > timestamp ? entry.count : 0
66
66
  }];
@@ -69,7 +69,7 @@ function memoryRateLimitDriver(options = {}) {
69
69
  reset(input) {
70
70
  const key = JSON.stringify([input.name ?? "default", input.key]);
71
71
  entries.delete(key);
72
- return [null];
72
+ return [void 0, void 0];
73
73
  },
74
74
  size() {
75
75
  return entries.size;
@@ -0,0 +1,12 @@
1
+ import { Durability, DurabilityContext } from "@vite-hub/runtime/durability";
2
+ //#region src/durability.d.ts
3
+ /** What the build passes to `rateLimitDurability()`. */
4
+ export interface RateLimitDurabilityInput {
5
+ driver: string;
6
+ }
7
+ /**
8
+ * The durability of Rate Limit counters, from the driver. The `kv` driver counts in the default KV store when that
9
+ * store is a database, Redis, or Upstash store, and falls back to memory otherwise.
10
+ */
11
+ export declare function rateLimitDurability(input: RateLimitDurabilityInput, context: DurabilityContext): Durability[];
12
+ //#endregion
@@ -0,0 +1,35 @@
1
+ //#region src/durability.ts
2
+ const memory = {
3
+ primitive: "rate-limit",
4
+ store: "memory",
5
+ scope: "process",
6
+ reason: "Counters live in the memory of this process. Each instance counts on its own.",
7
+ fix: "Use a shared default KV store, such as Redis or a Postgres Default Database, with the `kv` driver."
8
+ };
9
+ /**
10
+ * The durability of Rate Limit counters, from the driver. The `kv` driver counts in the default KV store when that
11
+ * store is a database, Redis, or Upstash store, and falls back to memory otherwise.
12
+ */
13
+ function rateLimitDurability(input, context) {
14
+ if (input.driver === "cloudflare") return [{
15
+ primitive: "rate-limit",
16
+ store: "cloudflare",
17
+ scope: "shared",
18
+ reason: "Cloudflare Rate Limiting bindings count for every Worker."
19
+ }];
20
+ if (input.driver !== "kv") return [memory];
21
+ const kv = context.find("kv");
22
+ if (!kv || !/^(?:database|redis|upstash)\b/.test(kv.store)) return [{
23
+ ...memory,
24
+ reason: `The default KV store is ${kv ? kv.store : "off"}, so counters live in the memory of this process.`
25
+ }];
26
+ return [{
27
+ primitive: "rate-limit",
28
+ store: `kv (${kv.store})`,
29
+ scope: kv.scope,
30
+ reason: `Counters in the default KV store. ${kv.reason}`,
31
+ ...kv.fix ? { fix: kv.fix } : {}
32
+ }];
33
+ }
34
+ //#endregion
35
+ export { rateLimitDurability };