@vite-hub/rate-limit 0.0.4 → 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.
- package/README.md +46 -20
- package/dist/cli-szm60zN5.d.ts +163 -0
- package/dist/cli.d.ts +16 -0
- package/dist/cli.js +259 -0
- package/dist/{cloudflare-BYZQ2tim.js → cloudflare-otBvOPv4.js} +9 -4
- package/dist/counters-DXpF67J_.d.ts +47 -0
- package/dist/counters-DgVdHwdL.js +113 -0
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/drivers/cloudflare.d.ts +6 -8
- package/dist/drivers/cloudflare.js +1 -1
- package/dist/drivers/kv.d.ts +2 -0
- package/dist/drivers/kv.js +92 -0
- package/dist/drivers/memory.d.ts +7 -7
- package/dist/drivers/memory.js +36 -10
- package/dist/durability.d.ts +12 -0
- package/dist/durability.js +35 -0
- package/dist/error-diagnostics-MgAnhRTP.js +234 -0
- package/dist/index.d.ts +20 -5
- package/dist/index.js +119 -51
- package/dist/inspect-B6gTdgy9.js +118 -0
- package/dist/kv-C1wpLulE.d.ts +29 -0
- package/dist/kv-provider-C1S6dRTR.js +293 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-BYRa7wpx.js +1355 -0
- package/dist/operations-CLI9w3rO.js +33 -0
- package/dist/operations.d.ts +19 -0
- package/dist/operations.js +272 -0
- package/dist/runtime.d.ts +21 -5
- package/dist/runtime.js +2 -2
- package/dist/state-BU-zcLNY.js +89 -0
- package/dist/types-CMyR1JeW.d.ts +180 -0
- package/dist/vite.d.ts +441 -13
- package/dist/vite.js +1024 -4824
- package/package.json +56 -17
- package/dist/limiter-CHaHluMr.js +0 -118
- package/dist/state-DB4uJN5P.js +0 -15
- package/dist/types-DoyUiUt1.d.ts +0 -106
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
|
|
2
|
+
import { n as resetRateLimit, t as peekRateLimit } from "./counters-DgVdHwdL.js";
|
|
3
|
+
import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
|
|
4
|
+
//#region src/runtime/operations.ts
|
|
5
|
+
/** Removes credentials from the echoed key and from driver error text before the result leaves the runtime. */
|
|
6
|
+
function redact(result) {
|
|
7
|
+
return {
|
|
8
|
+
...result,
|
|
9
|
+
key: redactInspectionText(result.key),
|
|
10
|
+
..."reason" in result ? { reason: redactInspectionText(result.reason) } : {}
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
async function guarded(run) {
|
|
14
|
+
try {
|
|
15
|
+
return redact(await run());
|
|
16
|
+
} catch (error) {
|
|
17
|
+
const failure = rateLimitErrorDiagnostics.RATE_LIMIT_OPERATION_FAILED({ cause: error });
|
|
18
|
+
throw Object.assign(failure, {
|
|
19
|
+
status: 500,
|
|
20
|
+
statusMessage: redactInspectionText(error instanceof Error ? error.message : failure.message)
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Reads the counter of one key without consuming a token. */
|
|
25
|
+
async function peekRateLimitOperation(name, key) {
|
|
26
|
+
return await guarded(() => peekRateLimit(name, key));
|
|
27
|
+
}
|
|
28
|
+
/** Deletes the counter of one key, where the provider supports it. */
|
|
29
|
+
async function resetRateLimitOperation(name, key) {
|
|
30
|
+
return await guarded(() => resetRateLimit(name, key));
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
export { peekRateLimitOperation, resetRateLimitOperation };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { n as RateLimitPeekInspection, r as RateLimitResetInspection } from "./counters-DXpF67J_.js";
|
|
2
|
+
import { t as AnyOperation } from "./operation-definition-8gOe-ubD.js";
|
|
3
|
+
//#region ../internal/src/operations-dev.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
|
|
6
|
+
* `context.event`, so owner hooks such as `identify` of Comments read its Standard Context.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createStandaloneOperationHandler(sources: {
|
|
9
|
+
operations: unknown;
|
|
10
|
+
plugin: string;
|
|
11
|
+
}[], root: string): {
|
|
12
|
+
fetch(request: Request): Promise<Response>;
|
|
13
|
+
};
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/operations.d.ts
|
|
16
|
+
/** The `rate-limit.*` operations: peek and reset. The Console, `vitehub rate-limit`, and agents run them. */
|
|
17
|
+
export declare const rateLimitOperations: readonly AnyOperation[];
|
|
18
|
+
//#endregion
|
|
19
|
+
export type { RateLimitPeekInspection, RateLimitResetInspection };
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { a as operationRootHeader, c as projectRootHash, d as toOperationFailure, f as defineOperation, g as readOperationRpcCall, h as operationRpcRefusal, i as createOperationRegistry, l as runOperation, o as operationRpcHeader, p as answerOperationRpc, s as operationsOf, t as assertOperationProject, v as internalErrorDiagnostics } from "./operations-BYRa7wpx.js";
|
|
2
|
+
import { n as isViteHubLoopbackPeer } from "./dev-peer-CHafxbtj.js";
|
|
3
|
+
import * as v from "valibot";
|
|
4
|
+
//#region ../internal/src/secret.ts
|
|
5
|
+
const secretEncoder = new TextEncoder();
|
|
6
|
+
/**
|
|
7
|
+
* Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
|
|
8
|
+
* when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
|
|
9
|
+
*/
|
|
10
|
+
function isViteHubSecretEqual(actual, expected) {
|
|
11
|
+
if (!actual || !expected) return false;
|
|
12
|
+
const left = secretEncoder.encode(actual);
|
|
13
|
+
const right = secretEncoder.encode(expected);
|
|
14
|
+
let difference = left.length ^ right.length;
|
|
15
|
+
for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
|
|
16
|
+
return difference === 0;
|
|
17
|
+
}
|
|
18
|
+
Object.freeze({ prefix: "sha256=" });
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region ../internal/src/dev-endpoint.ts
|
|
21
|
+
const viteHubDevRequestGrantBrand = Symbol("vitehub.devRequestGrant");
|
|
22
|
+
const devRequestGrants = /* @__PURE__ */ new WeakMap();
|
|
23
|
+
function grantDevRequest(request, label) {
|
|
24
|
+
const grant = Object.freeze({
|
|
25
|
+
[viteHubDevRequestGrantBrand]: true,
|
|
26
|
+
label
|
|
27
|
+
});
|
|
28
|
+
devRequestGrants.set(grant, request);
|
|
29
|
+
return { grant };
|
|
30
|
+
}
|
|
31
|
+
function rejectDevRequest(rejection) {
|
|
32
|
+
return { rejection };
|
|
33
|
+
}
|
|
34
|
+
const fileOrExtensionProtocol = /^(?:file|.+-extension):/i;
|
|
35
|
+
const ipv4Octet = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)";
|
|
36
|
+
const ipv4Literal = new RegExp(`^${ipv4Octet}(?:\\.${ipv4Octet}){3}$`);
|
|
37
|
+
/**
|
|
38
|
+
* Tests IP literals like `node:net` `isIP`, without a Node import, so the Nitro-side check also runs in Worker
|
|
39
|
+
* runtimes. IPv4 uses the Node pattern (dotted decimal, no leading zeros). IPv6 uses the WHATWG URL parser, which
|
|
40
|
+
* rejects zone IDs. Browsers do not send zone IDs in `Host`.
|
|
41
|
+
*/
|
|
42
|
+
function isIPv4Literal(value) {
|
|
43
|
+
return ipv4Literal.test(value);
|
|
44
|
+
}
|
|
45
|
+
function isIPv6Literal(value) {
|
|
46
|
+
if (!value.includes(":") || !/^[\d.:a-f]+$/i.test(value)) return false;
|
|
47
|
+
try {
|
|
48
|
+
return new URL(`http://[${value}]/`).hostname !== "";
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function hostHeaderAllowed(host, allowedHosts) {
|
|
54
|
+
if (fileOrExtensionProtocol.test(host)) return true;
|
|
55
|
+
const trimmed = host.trim();
|
|
56
|
+
if (trimmed.startsWith("[")) {
|
|
57
|
+
const end = trimmed.indexOf("]");
|
|
58
|
+
return end > 0 && isIPv6Literal(trimmed.slice(1, end));
|
|
59
|
+
}
|
|
60
|
+
const colon = trimmed.indexOf(":");
|
|
61
|
+
const hostname = (colon === -1 ? trimmed : trimmed.slice(0, colon)).toLowerCase();
|
|
62
|
+
if (isIPv4Literal(hostname)) return true;
|
|
63
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
|
|
64
|
+
return allowedHosts.some((allowed) => {
|
|
65
|
+
const normalized = allowed.toLowerCase();
|
|
66
|
+
return normalized === hostname || normalized.startsWith(".") && (normalized.slice(1) === hostname || hostname.endsWith(normalized));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Checks the host of a request that reaches the Nitro dev handler.
|
|
71
|
+
*
|
|
72
|
+
* {@link forwardViteHubDevRequestToNitro} always calls `http://localhost`, so a forwarded request passes. The Nitro
|
|
73
|
+
* route is also reachable over HTTP on the dev server, and the Nitro runtime does not know `server.allowedHosts`.
|
|
74
|
+
* This check therefore accepts only `localhost`, `*.localhost`, and IP literals in the request URL and in the `Host`
|
|
75
|
+
* header. A DNS rebinding page uses another host name, so it gets `403`.
|
|
76
|
+
*/
|
|
77
|
+
function isViteHubNitroDevHostAllowed(request) {
|
|
78
|
+
const host = request.headers.get("host");
|
|
79
|
+
return hostHeaderAllowed(new URL(request.url).host, []) && (host === null || hostHeaderAllowed(host, []));
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Checks a request inside the Nitro dev handler: the host, the guard header, the request origin, `POST`, the JSON
|
|
83
|
+
* content type, and the optional owner `authorize` callback. Returns a grant bound to `request`, or the rejection
|
|
84
|
+
* response. The Nitro route exists only in `vite dev`, but it is reachable on the dev server origin, so it checks the
|
|
85
|
+
* same guard as the Vite endpoint.
|
|
86
|
+
*/
|
|
87
|
+
async function validateViteHubNitroDevRequest(request, guard) {
|
|
88
|
+
if (!isViteHubNitroDevHostAllowed(request)) return rejectDevRequest(new Response(`Forbidden ${guard.label} host.`, { status: 403 }));
|
|
89
|
+
if (!isViteHubSecretEqual(request.headers.get(guard.header), guard.headerValue)) return rejectDevRequest(new Response(`Forbidden ${guard.label} request.`, { status: 403 }));
|
|
90
|
+
const origin = request.headers.get("origin");
|
|
91
|
+
if (origin && origin !== new URL(request.url).origin) return rejectDevRequest(new Response(`Forbidden ${guard.label} origin.`, { status: 403 }));
|
|
92
|
+
if (request.method !== "POST") return rejectDevRequest(new Response("Method not allowed.", {
|
|
93
|
+
headers: { allow: "POST" },
|
|
94
|
+
status: 405
|
|
95
|
+
}));
|
|
96
|
+
if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) return rejectDevRequest(new Response(`${guard.label} requests must use application/json.`, { status: 415 }));
|
|
97
|
+
const rejection = await guard.authorize?.(request);
|
|
98
|
+
return rejection ? rejectDevRequest(rejection) : grantDevRequest(request, guard.label);
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region ../internal/src/operations-dev.ts
|
|
102
|
+
function readPath(value, ...path) {
|
|
103
|
+
for (const key of path) value = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
/** The Cloudflare bindings of a Request: from the Standard Context that Nitro sets, else where srvx puts them. */
|
|
107
|
+
function requestEnv(request) {
|
|
108
|
+
const env = readPath(request, "~standard", "runtime", "cloudflare", "env") ?? readPath(request, "runtime", "cloudflare", "env");
|
|
109
|
+
return env !== null && typeof env === "object" ? env : void 0;
|
|
110
|
+
}
|
|
111
|
+
/** The `waitUntil` of a Request: from its Standard Context, else from the Request or its Worker ExecutionContext. */
|
|
112
|
+
function requestWaitUntil(request) {
|
|
113
|
+
for (const owner of [
|
|
114
|
+
readPath(request, "~standard"),
|
|
115
|
+
request,
|
|
116
|
+
readPath(request, "runtime", "cloudflare", "context")
|
|
117
|
+
]) {
|
|
118
|
+
const waitUntil = readPath(owner, "waitUntil");
|
|
119
|
+
if (typeof waitUntil === "function") return waitUntil.bind(owner);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function localHost(host) {
|
|
123
|
+
try {
|
|
124
|
+
const name = new URL(`http://${host}`).hostname;
|
|
125
|
+
return name === "localhost" || name.endsWith(".localhost") || name === "127.0.0.1" || name === "[::1]";
|
|
126
|
+
} catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function reject(status, message) {
|
|
131
|
+
throw Object.assign(new Error(message), {
|
|
132
|
+
code: "OPERATION_DEV_REQUEST",
|
|
133
|
+
status
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
|
|
138
|
+
* `context.event`, so owner hooks such as `identify` of Comments read its Standard Context.
|
|
139
|
+
*/
|
|
140
|
+
function createStandaloneOperationHandler(sources, root) {
|
|
141
|
+
const registry = createOperationRegistry(sources.map((source) => ({
|
|
142
|
+
...source,
|
|
143
|
+
operations: operationsOf(source.operations)
|
|
144
|
+
})));
|
|
145
|
+
const defaultLimit = 65536;
|
|
146
|
+
const maximum = Math.max(defaultLimit, ...registry.list().map((operation) => operation.maxRequestBytes ?? defaultLimit));
|
|
147
|
+
const operations = Object.fromEntries(registry.list().map((operation) => [operation.name, operation]));
|
|
148
|
+
return { async fetch(request) {
|
|
149
|
+
const headers = {
|
|
150
|
+
"cache-control": "no-store",
|
|
151
|
+
"x-content-type-options": "nosniff",
|
|
152
|
+
[operationRootHeader]: projectRootHash(root)
|
|
153
|
+
};
|
|
154
|
+
try {
|
|
155
|
+
const address = [
|
|
156
|
+
readPath(request, "ip"),
|
|
157
|
+
readPath(request, "context", "clientAddress"),
|
|
158
|
+
readPath(request, "runtime", "node", "req", "socket", "remoteAddress")
|
|
159
|
+
].find((value) => typeof value === "string" && value !== "");
|
|
160
|
+
const forwarded = request.headers.get("x-forwarded-host");
|
|
161
|
+
if (!localHost(request.headers.get("host") ?? new URL(request.url).host) || forwarded && !localHost(forwarded) || !await isViteHubLoopbackPeer(request, address)) reject(403, "Standalone development operations accept only local requests.");
|
|
162
|
+
const site = request.headers.get("sec-fetch-site");
|
|
163
|
+
if (site === "cross-site" || site === "same-site") reject(403, "Cross-origin operation requests are not allowed.");
|
|
164
|
+
const checked = await validateViteHubNitroDevRequest(request, {
|
|
165
|
+
header: operationRpcHeader,
|
|
166
|
+
headerValue: "1",
|
|
167
|
+
label: "Operation RPC"
|
|
168
|
+
});
|
|
169
|
+
if (checked.rejection) reject(checked.rejection.status, await checked.rejection.text());
|
|
170
|
+
assertOperationProject(request, root);
|
|
171
|
+
const reader = request.body?.getReader();
|
|
172
|
+
const decoder = new TextDecoder();
|
|
173
|
+
let text = "";
|
|
174
|
+
let bytes = 0;
|
|
175
|
+
try {
|
|
176
|
+
if (reader) while (true) {
|
|
177
|
+
const chunk = await reader.read();
|
|
178
|
+
if (chunk.done) break;
|
|
179
|
+
bytes += chunk.value.byteLength;
|
|
180
|
+
if (bytes > maximum) reject(413, "Operation request exceeds the byte limit.");
|
|
181
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
182
|
+
}
|
|
183
|
+
text += decoder.decode();
|
|
184
|
+
} catch (error) {
|
|
185
|
+
await reader?.cancel();
|
|
186
|
+
throw error;
|
|
187
|
+
} finally {
|
|
188
|
+
reader?.releaseLock();
|
|
189
|
+
}
|
|
190
|
+
let payload;
|
|
191
|
+
try {
|
|
192
|
+
payload = JSON.parse(text);
|
|
193
|
+
} catch {
|
|
194
|
+
reject(400, "Malformed operation request.");
|
|
195
|
+
}
|
|
196
|
+
const call = readOperationRpcCall(payload);
|
|
197
|
+
if (!call) reject(400, "Invalid operation request.");
|
|
198
|
+
if (bytes > (registry.get(call.m)?.maxRequestBytes ?? defaultLimit)) reject(413, "Operation request exceeds the byte limit.");
|
|
199
|
+
const response = {};
|
|
200
|
+
const context = {
|
|
201
|
+
access: {
|
|
202
|
+
mode: "local",
|
|
203
|
+
sections: "all"
|
|
204
|
+
},
|
|
205
|
+
development: true,
|
|
206
|
+
surface: "cli",
|
|
207
|
+
user: null,
|
|
208
|
+
request,
|
|
209
|
+
event: request,
|
|
210
|
+
response,
|
|
211
|
+
env: requestEnv(request),
|
|
212
|
+
waitUntil: requestWaitUntil(request)
|
|
213
|
+
};
|
|
214
|
+
const reply = await answerOperationRpc(call, {
|
|
215
|
+
failure: toOperationFailure,
|
|
216
|
+
operations,
|
|
217
|
+
run: async (operation, input) => {
|
|
218
|
+
const result = await runOperation(registry, operation.name, input, context);
|
|
219
|
+
if (!result.ok) throw Object.assign(new Error(result.message), result);
|
|
220
|
+
return result.value;
|
|
221
|
+
},
|
|
222
|
+
unknown: (name) => Object.assign(internalErrorDiagnostics.INTERNAL_R0021({ message: `No operation is named ${JSON.stringify(name)}.` }), { status: 404 })
|
|
223
|
+
});
|
|
224
|
+
return Response.json(reply, {
|
|
225
|
+
headers,
|
|
226
|
+
status: "e" in reply ? reply.e.status : response.status ?? 200
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
const failure = toOperationFailure(error);
|
|
230
|
+
return Response.json(operationRpcRefusal(failure), {
|
|
231
|
+
headers,
|
|
232
|
+
status: failure.status
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
} };
|
|
236
|
+
}
|
|
237
|
+
//#endregion
|
|
238
|
+
//#region src/operations.ts
|
|
239
|
+
const runtime = () => import("./operations-CLI9w3rO.js");
|
|
240
|
+
const target = v.object({
|
|
241
|
+
key: v.pipe(v.string(), v.minLength(1, "Name the limited key, for example a client IP or user ID.")),
|
|
242
|
+
name: v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name the stable ID of `requireRateLimit()`."))
|
|
243
|
+
});
|
|
244
|
+
function defineRateLimitOperation(definition) {
|
|
245
|
+
return defineOperation({
|
|
246
|
+
...definition,
|
|
247
|
+
cli: {
|
|
248
|
+
namespace: "rate-limit",
|
|
249
|
+
...definition.cli
|
|
250
|
+
},
|
|
251
|
+
section: "rate-limits",
|
|
252
|
+
user: false
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
/** The `rate-limit.*` operations: peek and reset. The Console, `vitehub rate-limit`, and agents run them. */
|
|
256
|
+
const rateLimitOperations = [defineRateLimitOperation({
|
|
257
|
+
cli: { positional: ["name", "key"] },
|
|
258
|
+
description: "Show the counter of one key without consuming a token.",
|
|
259
|
+
input: target,
|
|
260
|
+
kind: "read",
|
|
261
|
+
name: "rate-limit.peek",
|
|
262
|
+
run: async (input) => await (await runtime()).peekRateLimitOperation(input.name, input.key)
|
|
263
|
+
}), defineRateLimitOperation({
|
|
264
|
+
cli: { positional: ["name", "key"] },
|
|
265
|
+
description: "Delete the counter of one key, where the provider supports it.",
|
|
266
|
+
input: target,
|
|
267
|
+
kind: "destructive",
|
|
268
|
+
name: "rate-limit.reset",
|
|
269
|
+
run: async (input) => await (await runtime()).resetRateLimitOperation(input.name, input.key)
|
|
270
|
+
})];
|
|
271
|
+
//#endregion
|
|
272
|
+
export { createStandaloneOperationHandler, rateLimitOperations };
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { E as RateLimitRuntimeConfig } from "./types-CMyR1JeW.js";
|
|
2
|
+
import { r as RateLimitKVStorage } from "./kv-C1wpLulE.js";
|
|
3
3
|
//#region src/runtime/state.d.ts
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
/** The KV store of the `kv` driver. The generated Nitro plugin passes it from `@vite-hub/kv`. */
|
|
5
|
+
interface RateLimitKVRuntime {
|
|
6
|
+
/** The KV driver that the store uses in this process, for example `getKVStoreDriver()` of `@vite-hub/kv`. */
|
|
7
|
+
driver: () => Promise<string>;
|
|
8
|
+
storage: RateLimitKVStorage;
|
|
9
|
+
/** The KV store name, for the boot log. */
|
|
10
|
+
store: string;
|
|
11
|
+
}
|
|
12
|
+
/** `kv` needs the KV store of the app in `kv`. Other drivers ignore it. */
|
|
13
|
+
export declare function setRateLimitRuntimeConfig(config: RateLimitRuntimeConfig, kv?: RateLimitKVRuntime): void;
|
|
14
|
+
/** In app tests, Rate Limit counts in memory for the current test, whatever the host. */
|
|
15
|
+
export declare function getRateLimitRuntimeConfig(): RateLimitRuntimeConfig;
|
|
16
|
+
/**
|
|
17
|
+
* The driver that counts in this process. For `kv`, the first call asks KV for its configured driver
|
|
18
|
+
* and prints the choice: `kv` with a shared driver. Another driver fails, or counts in `memory` with `memoryFallback`.
|
|
19
|
+
* The generated Nitro plugin calls it at boot.
|
|
20
|
+
*/
|
|
21
|
+
export declare function resolveRateLimitDriver(): Promise<RateLimitRuntimeConfig["driver"]>;
|
|
6
22
|
//#endregion
|
|
7
|
-
export {
|
|
23
|
+
export type { RateLimitKVRuntime };
|
package/dist/runtime.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { getRateLimitRuntimeConfig, setRateLimitRuntimeConfig };
|
|
1
|
+
import { a as setRateLimitRuntimeConfig, i as resolveRateLimitDriver, t as getRateLimitRuntimeConfig } from "./state-BU-zcLNY.js";
|
|
2
|
+
export { getRateLimitRuntimeConfig, resolveRateLimitDriver, setRateLimitRuntimeConfig };
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
|
|
2
|
+
import { i as normalizeRateLimitPolicy, n as createRateLimiter, t as resolveKVRateLimitDriver } from "./kv-provider-C1S6dRTR.js";
|
|
3
|
+
import { kvRateLimitDriver } from "./drivers/kv.js";
|
|
4
|
+
import { memoryRateLimitDriver } from "./drivers/memory.js";
|
|
5
|
+
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
6
|
+
//#region src/runtime/state.ts
|
|
7
|
+
let runtimeConfig = { driver: "memory" };
|
|
8
|
+
let kvRuntime;
|
|
9
|
+
let activeDriver;
|
|
10
|
+
const runtimeLimiters = /* @__PURE__ */ new Map();
|
|
11
|
+
/** The counters of this process, or in app tests the counters of the current test. */
|
|
12
|
+
function limiters() {
|
|
13
|
+
const test = getViteHubTestMode();
|
|
14
|
+
return test ? test.backend("rate-limit", () => /* @__PURE__ */ new Map()) : runtimeLimiters;
|
|
15
|
+
}
|
|
16
|
+
/** `kv` needs the KV store of the app in `kv`. Other drivers ignore it. */
|
|
17
|
+
function setRateLimitRuntimeConfig(config, kv) {
|
|
18
|
+
runtimeConfig = config;
|
|
19
|
+
kvRuntime = kv;
|
|
20
|
+
activeDriver = void 0;
|
|
21
|
+
runtimeLimiters.clear();
|
|
22
|
+
}
|
|
23
|
+
/** In app tests, Rate Limit counts in memory for the current test, whatever the host. */
|
|
24
|
+
function getRateLimitRuntimeConfig() {
|
|
25
|
+
return getViteHubTestMode() ? { driver: "memory" } : runtimeConfig;
|
|
26
|
+
}
|
|
27
|
+
function requireKVRuntime() {
|
|
28
|
+
if (kvRuntime) return kvRuntime;
|
|
29
|
+
throw rateLimitErrorDiagnostics.RATE_LIMIT_R0047({ message: "[vitehub] The kv Rate Limit driver needs KV. Enable KV in the app, or pass a KV store to setRateLimitRuntimeConfig()." });
|
|
30
|
+
}
|
|
31
|
+
async function resolveKVDriver(kv, memoryFallback) {
|
|
32
|
+
const driver = await kv.driver();
|
|
33
|
+
if (resolveKVRateLimitDriver(driver) === "kv") {
|
|
34
|
+
console.info(`[vitehub] Rate Limit counts in the KV store "${kv.store}" (${driver}). Every server process that uses this store shares the counts.`);
|
|
35
|
+
return "kv";
|
|
36
|
+
}
|
|
37
|
+
if (!memoryFallback) throw rateLimitErrorDiagnostics.RATE_LIMIT_KV_RUNTIME_STORE_UNSUPPORTED({ message: `[vitehub] The kv Rate Limit driver needs a KV store that every server process shares, but the KV store "${kv.store}" uses ${driver}, which has no shared atomic increment.` });
|
|
38
|
+
console.warn(`[vitehub] Rate Limit counts in the memory of this process, because the KV store "${kv.store}" uses ${driver}, which has no shared atomic increment. Each server process allows the full limit. Configure a Redis KV store or use a Postgres Database to share the counts.`);
|
|
39
|
+
return "memory";
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The driver that counts in this process. For `kv`, the first call asks KV for its configured driver
|
|
43
|
+
* and prints the choice: `kv` with a shared driver. Another driver fails, or counts in `memory` with `memoryFallback`.
|
|
44
|
+
* The generated Nitro plugin calls it at boot.
|
|
45
|
+
*/
|
|
46
|
+
async function resolveRateLimitDriver() {
|
|
47
|
+
const { driver, memoryFallback = false } = getRateLimitRuntimeConfig();
|
|
48
|
+
if (driver !== "kv") return driver;
|
|
49
|
+
if (activeDriver) return await activeDriver;
|
|
50
|
+
const pending = resolveKVDriver(requireKVRuntime(), memoryFallback);
|
|
51
|
+
activeDriver = pending;
|
|
52
|
+
pending.catch(() => {
|
|
53
|
+
if (activeDriver === pending) activeDriver = void 0;
|
|
54
|
+
});
|
|
55
|
+
return await pending;
|
|
56
|
+
}
|
|
57
|
+
function policyKey(policy) {
|
|
58
|
+
return JSON.stringify([
|
|
59
|
+
policy.enforcement,
|
|
60
|
+
policy.failure,
|
|
61
|
+
policy.limit,
|
|
62
|
+
normalizeRateLimitPolicy(policy).windowMs
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
/** The Rate Limiter of one name and policy in this process. `kv` limiters share their counters through KV. */
|
|
66
|
+
function getRuntimeRateLimiter(driver, name, policy) {
|
|
67
|
+
const all = limiters();
|
|
68
|
+
let policies = all.get(name);
|
|
69
|
+
const key = policyKey(policy);
|
|
70
|
+
const existing = policies?.get(key);
|
|
71
|
+
if (existing) return existing;
|
|
72
|
+
const limiter = createRateLimiter({
|
|
73
|
+
...policy,
|
|
74
|
+
driver: driver === "kv" ? kvRateLimitDriver({ storage: requireKVRuntime().storage }) : memoryRateLimitDriver(),
|
|
75
|
+
name
|
|
76
|
+
});
|
|
77
|
+
if (!policies) {
|
|
78
|
+
policies = /* @__PURE__ */ new Map();
|
|
79
|
+
all.set(name, policies);
|
|
80
|
+
}
|
|
81
|
+
policies.set(key, limiter);
|
|
82
|
+
return limiter;
|
|
83
|
+
}
|
|
84
|
+
/** Lists each policy used by this name in this process. */
|
|
85
|
+
function listRuntimeRateLimiters(name) {
|
|
86
|
+
return [...limiters().get(name)?.values() ?? []];
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
export { setRateLimitRuntimeConfig as a, resolveRateLimitDriver as i, getRuntimeRateLimiter as n, listRuntimeRateLimiters as r, getRateLimitRuntimeConfig as t };
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { Result, ViteHubContext } from "@vite-hub/runtime";
|
|
2
|
+
//#region src/types.d.ts
|
|
3
|
+
type MaybePromise<T> = Promise<T> | T;
|
|
4
|
+
type RateLimitWindow = `${number}ms` | `${number}s` | `${number}m` | `${number}h` | `${number}d`;
|
|
5
|
+
type RateLimitEnforcement = "best-effort" | "strict";
|
|
6
|
+
type RateLimitFailurePolicy = "allow" | "deny";
|
|
7
|
+
type RateLimitCounterScope = "global" | "location" | "process";
|
|
8
|
+
type RateLimitRejectedAttemptBehavior = "counted" | "not-counted" | "unknown";
|
|
9
|
+
interface RateLimitPolicy {
|
|
10
|
+
enforcement?: RateLimitEnforcement;
|
|
11
|
+
failure?: RateLimitFailurePolicy;
|
|
12
|
+
limit: number;
|
|
13
|
+
window: RateLimitWindow;
|
|
14
|
+
}
|
|
15
|
+
interface CheckRateLimitOptions extends RateLimitPolicy {
|
|
16
|
+
key?: string;
|
|
17
|
+
}
|
|
18
|
+
interface RequireRateLimitOptions extends CheckRateLimitOptions {
|
|
19
|
+
/** `data.code` of the `429` error, such as a translation key that the client reads. */
|
|
20
|
+
code?: string;
|
|
21
|
+
/** Message of the `429` error, which the client can show. Defaults to `"Rate limit exceeded."`. */
|
|
22
|
+
message?: string;
|
|
23
|
+
}
|
|
24
|
+
/** A Web `Request`. The guard reads only its headers. */
|
|
25
|
+
type RateLimitRequest = Pick<Request, "headers">;
|
|
26
|
+
/**
|
|
27
|
+
* The request that a guard limits: a request event with Standard Context properties, such as an H3 2 event in a
|
|
28
|
+
* ViteHub app, or a Web `Request`. From an event, the guard reads the client address, the request headers, and
|
|
29
|
+
* the Cloudflare bindings from `event["~standard"]`. A `Request` has no client address, so pass `key`. On Cloudflare,
|
|
30
|
+
* the guard reads `cf-connecting-ip` from its headers and the bindings of the request that runs.
|
|
31
|
+
*/
|
|
32
|
+
type RateLimitRequestEvent = RateLimitRequest | ViteHubContext;
|
|
33
|
+
interface ResolvedRateLimitPolicy {
|
|
34
|
+
readonly enforcement: RateLimitEnforcement;
|
|
35
|
+
readonly failure: RateLimitFailurePolicy;
|
|
36
|
+
readonly limit: number;
|
|
37
|
+
readonly window: RateLimitWindow;
|
|
38
|
+
readonly windowMs: number;
|
|
39
|
+
}
|
|
40
|
+
interface RateLimitConsumeInput {
|
|
41
|
+
key: string;
|
|
42
|
+
}
|
|
43
|
+
interface RateLimitDriverInput extends RateLimitConsumeInput {
|
|
44
|
+
limit: number;
|
|
45
|
+
name?: string;
|
|
46
|
+
windowMs: number;
|
|
47
|
+
}
|
|
48
|
+
interface RateLimitDriverResult {
|
|
49
|
+
allowed: boolean;
|
|
50
|
+
remaining?: number;
|
|
51
|
+
/** Positive Unix timestamp in milliseconds, at most `8.64e15`. */
|
|
52
|
+
resetAt?: number;
|
|
53
|
+
retryAfter?: number;
|
|
54
|
+
used?: number;
|
|
55
|
+
}
|
|
56
|
+
/** `[undefined, result]` after the driver consumed the counter, or `[error, undefined]` for an outage. */
|
|
57
|
+
type RateLimitDriverOutcome = Result<RateLimitDriverResult>;
|
|
58
|
+
interface RateLimitDecisionBase extends RateLimitDriverResult {
|
|
59
|
+
limit: number;
|
|
60
|
+
windowMs: number;
|
|
61
|
+
}
|
|
62
|
+
interface RateLimitAllowedDecision extends RateLimitDecisionBase {
|
|
63
|
+
allowed: true;
|
|
64
|
+
cause?: never;
|
|
65
|
+
reason?: never;
|
|
66
|
+
}
|
|
67
|
+
interface RateLimitLimitedDecision extends RateLimitDecisionBase {
|
|
68
|
+
allowed: false;
|
|
69
|
+
cause?: never;
|
|
70
|
+
reason: "limited";
|
|
71
|
+
}
|
|
72
|
+
interface RateLimitUnavailableDecision extends RateLimitDecisionBase {
|
|
73
|
+
cause: unknown;
|
|
74
|
+
reason: "unavailable";
|
|
75
|
+
}
|
|
76
|
+
type RateLimitDecision = RateLimitAllowedDecision | RateLimitLimitedDecision | RateLimitUnavailableDecision;
|
|
77
|
+
/**
|
|
78
|
+
* The errors that `checkRateLimit()` returns. `RATE_LIMIT_R0013`: the request has no client address and the call has
|
|
79
|
+
* no `key`. `RATE_LIMIT_R0009`: the Cloudflare Rate Limiting binding of the policy is not on the request.
|
|
80
|
+
*/
|
|
81
|
+
type CheckRateLimitErrorCode = "RATE_LIMIT_R0009" | "RATE_LIMIT_R0013";
|
|
82
|
+
interface RateLimitDriverCapabilities {
|
|
83
|
+
readonly enforcement: RateLimitEnforcement;
|
|
84
|
+
readonly rejectedAttempts: RateLimitRejectedAttemptBehavior;
|
|
85
|
+
readonly scope: RateLimitCounterScope;
|
|
86
|
+
readonly windows?: readonly number[];
|
|
87
|
+
}
|
|
88
|
+
/** Counter state that a driver reads without consuming a token. */
|
|
89
|
+
interface RateLimitDriverPeekResult {
|
|
90
|
+
/** Positive window-end timestamp in milliseconds, at most `8.64e15`. Omit it when no counter is active. */
|
|
91
|
+
resetAt?: number;
|
|
92
|
+
/** Tokens consumed in the current window. `0` when the key has no active counter. */
|
|
93
|
+
used: number;
|
|
94
|
+
}
|
|
95
|
+
/** `[undefined, result]` with the counter state, or `[error, undefined]` for an outage. */
|
|
96
|
+
type RateLimitDriverPeekOutcome = Result<RateLimitDriverPeekResult>;
|
|
97
|
+
/** `[undefined, undefined]` after the driver deleted the counter, or `[error, undefined]` for an outage. */
|
|
98
|
+
type RateLimitDriverResetOutcome = Result<void>;
|
|
99
|
+
interface RateLimitDriver {
|
|
100
|
+
capabilities: RateLimitDriverCapabilities;
|
|
101
|
+
consume: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverOutcome>;
|
|
102
|
+
name: string;
|
|
103
|
+
/**
|
|
104
|
+
* Reads the counter of a key without consuming a token. Omit it when the provider cannot read a counter. The
|
|
105
|
+
* Rate Limiter then reports `unsupported`.
|
|
106
|
+
*/
|
|
107
|
+
peek?: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverPeekOutcome>;
|
|
108
|
+
/** Deletes the counter of a key. Omit it when the provider cannot reset a counter. */
|
|
109
|
+
reset?: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverResetOutcome>;
|
|
110
|
+
}
|
|
111
|
+
interface RateLimitPeekBase {
|
|
112
|
+
limit: number;
|
|
113
|
+
windowMs: number;
|
|
114
|
+
}
|
|
115
|
+
/** Counter state of one key. `peek()` does not consume a token. */
|
|
116
|
+
type RateLimitPeekResult = (RateLimitPeekBase & {
|
|
117
|
+
remaining: number;
|
|
118
|
+
resetAt?: number;
|
|
119
|
+
status: "known";
|
|
120
|
+
used: number;
|
|
121
|
+
}) | (RateLimitPeekBase & {
|
|
122
|
+
reason: string;
|
|
123
|
+
status: "unsupported";
|
|
124
|
+
}) | (RateLimitPeekBase & {
|
|
125
|
+
cause: unknown;
|
|
126
|
+
status: "unavailable";
|
|
127
|
+
});
|
|
128
|
+
type RateLimitResetResult = {
|
|
129
|
+
status: "reset";
|
|
130
|
+
} | {
|
|
131
|
+
reason: string;
|
|
132
|
+
status: "unsupported";
|
|
133
|
+
} | {
|
|
134
|
+
cause: unknown;
|
|
135
|
+
status: "unavailable";
|
|
136
|
+
};
|
|
137
|
+
interface RateLimiter {
|
|
138
|
+
readonly capabilities: RateLimitDriverCapabilities;
|
|
139
|
+
consume: (input: RateLimitConsumeInput) => Promise<RateLimitDecision>;
|
|
140
|
+
/** Reads the counter of a key without consuming a token. */
|
|
141
|
+
peek: (input: RateLimitConsumeInput) => Promise<RateLimitPeekResult>;
|
|
142
|
+
policy: ResolvedRateLimitPolicy;
|
|
143
|
+
/** Deletes the counter of a key, so the next request starts a new window. */
|
|
144
|
+
reset: (input: RateLimitConsumeInput) => Promise<RateLimitResetResult>;
|
|
145
|
+
}
|
|
146
|
+
interface RateLimitDeclaration {
|
|
147
|
+
name: string;
|
|
148
|
+
policy: RateLimitPolicy;
|
|
149
|
+
source: {
|
|
150
|
+
column: number;
|
|
151
|
+
file: string;
|
|
152
|
+
line: number;
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
interface CreateRateLimiterOptions extends RateLimitPolicy {
|
|
156
|
+
driver: RateLimitDriver;
|
|
157
|
+
name?: string;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* `kv` counts in the default KV store, shared by every server process when KV uses `redis`, `database`, or `upstash`.
|
|
161
|
+
* With another KV driver, it counts in process memory and prints a warning at boot.
|
|
162
|
+
*/
|
|
163
|
+
type RateLimitDriverName = "auto" | "cloudflare" | "kv" | "memory";
|
|
164
|
+
interface RateLimitOptions {
|
|
165
|
+
/** The driver of the counters. Defaults to `auto`. */
|
|
166
|
+
driver?: RateLimitDriverName;
|
|
167
|
+
namespace?: string;
|
|
168
|
+
projectRoot?: string;
|
|
169
|
+
scanDirs?: string[];
|
|
170
|
+
}
|
|
171
|
+
interface RateLimitRuntimeConfig {
|
|
172
|
+
driver: Exclude<RateLimitDriverName, "auto">;
|
|
173
|
+
/**
|
|
174
|
+
* With the `kv` driver: count in the memory of this process, with a warning, when the KV store cannot share counts.
|
|
175
|
+
* Without it, such a store fails with `RATE_LIMIT_KV_RUNTIME_STORE_UNSUPPORTED`. ViteHub sets it in `vite dev` and when it selects `kv` itself.
|
|
176
|
+
*/
|
|
177
|
+
memoryFallback?: boolean;
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
|
180
|
+
export { ResolvedRateLimitPolicy as A, RateLimitRequest as C, RateLimitWindow as D, RateLimitRuntimeConfig as E, RateLimiter as O, RateLimitRejectedAttemptBehavior as S, RateLimitResetResult as T, RateLimitEnforcement as _, RateLimitCounterScope as a, RateLimitPeekResult as b, RateLimitDriver as c, RateLimitDriverName as d, RateLimitDriverOutcome as f, RateLimitDriverResult as g, RateLimitDriverResetOutcome as h, RateLimitConsumeInput as i, RequireRateLimitOptions as k, RateLimitDriverCapabilities as l, RateLimitDriverPeekResult as m, CheckRateLimitOptions as n, RateLimitDecision as o, RateLimitDriverPeekOutcome as p, CreateRateLimiterOptions as r, RateLimitDeclaration as s, CheckRateLimitErrorCode as t, RateLimitDriverInput as u, RateLimitFailurePolicy as v, RateLimitRequestEvent as w, RateLimitPolicy as x, RateLimitOptions as y };
|