@vite-hub/rate-limit 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -0
- package/dist/cloudflare-BYZQ2tim.js +42 -0
- package/dist/drivers/cloudflare.d.ts +19 -0
- package/dist/drivers/cloudflare.js +2 -0
- package/dist/drivers/memory.d.ts +14 -0
- package/dist/drivers/memory.js +54 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +76 -0
- package/dist/limiter-CHaHluMr.js +118 -0
- package/dist/runtime.d.ts +7 -0
- package/dist/runtime.js +2 -0
- package/dist/state-DB4uJN5P.js +15 -0
- package/dist/types-BX4hSfYX.d.ts +97 -0
- package/dist/vite.d.ts +14 -0
- package/dist/vite.js +3954 -0
- package/package.json +65 -0
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# @vite-hub/rate-limit
|
|
2
|
+
|
|
3
|
+
`@vite-hub/rate-limit` provides atomic Rate Limit consumption without coupling policy to a storage provider.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @vite-hub/rate-limit
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Require a Rate Limit
|
|
12
|
+
|
|
13
|
+
Declare the Rate Limit beside the server code that consumes it. The stable ID and policy must use static literals so the Vite integration can generate provider infrastructure.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { requireRateLimit } from "@vite-hub/rate-limit"
|
|
17
|
+
|
|
18
|
+
export async function handleImageUpload(event): Promise<Response> {
|
|
19
|
+
await requireRateLimit(event, "image-upload", {
|
|
20
|
+
limit: 10,
|
|
21
|
+
window: "1m",
|
|
22
|
+
})
|
|
23
|
+
return new Response("Upload accepted", { status: 202 })
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`requireRateLimit()` can live inside any ordinary H3 handler. Its stable ID and provider policy must use static literals so the Vite integration can generate infrastructure; `event` and an optional dynamic `key` are runtime inputs. The guard defaults to the request's client address and throws an `HTTPError` with status `429` when the budget is exhausted. Pass `key: authenticatedUser.id` when a user or tenant is the correct budget boundary.
|
|
28
|
+
|
|
29
|
+
Provider unavailability follows the declared `failure` policy: fail-open guards continue, while fail-closed guards throw status `503` and preserve the provider cause. Invalid configuration and provider contract violations still throw normally. Use `createRateLimiter()` when the application needs a decision for a custom response or another transport.
|
|
30
|
+
|
|
31
|
+
Add the build integration:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { hubRateLimit } from "@vite-hub/rate-limit/vite"
|
|
35
|
+
import { defineConfig } from "vite"
|
|
36
|
+
|
|
37
|
+
export default defineConfig({
|
|
38
|
+
plugins: [hubRateLimit({ namespace: "acme-image-service-production" })],
|
|
39
|
+
})
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`hubRateLimit()` uses the memory driver during local Vite serve and infers Cloudflare from the production Nitro preset. Cloudflare deployments require a unique namespace for each Worker and environment so counters cannot leak across deployments. Unknown production hosts still require an explicit provider because process-local memory is unsafe for horizontally scaled deployments.
|
|
43
|
+
|
|
44
|
+
Native Cloudflare enforcement is best-effort and accepts only `10s` and `1m` windows, so incompatible policies fail during the build.
|
|
45
|
+
|
|
46
|
+
## Custom drivers
|
|
47
|
+
|
|
48
|
+
Use `createRateLimiter()` when the application supplies a driver directly and does not need managed provider output:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { createRateLimiter } from "@vite-hub/rate-limit"
|
|
52
|
+
import { memoryRateLimitDriver } from "@vite-hub/rate-limit/drivers/memory"
|
|
53
|
+
|
|
54
|
+
const limiter = createRateLimiter({
|
|
55
|
+
driver: memoryRateLimitDriver(),
|
|
56
|
+
enforcement: "strict",
|
|
57
|
+
limit: 10,
|
|
58
|
+
window: "1m",
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
const decision = await limiter.consume({ key: authenticatedUser.id })
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The memory driver is process-local and intended for development, tests, and single-process hosts. Production drivers must implement atomic `consume()`; generic KV `get()` and `set()` operations are insufficient.
|
|
65
|
+
|
|
66
|
+
Custom drivers return `[null, result]` after consuming the counter and `[error, undefined]` only for expected operational outages that the declared failure policy should govern. Invalid configuration, malformed provider responses, and implementation defects should throw normally.
|
|
67
|
+
|
|
68
|
+
Every direct limiter exposes its enforcement, counter scope, rejected-attempt behavior, and supported windows. The Vite integration writes those capabilities to `.vitehub/rate-limit/manifest.json` for agents and tooling to inspect.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
//#region ../internal/src/integrations/hex.ts
|
|
2
|
+
const textEncoder = new TextEncoder();
|
|
3
|
+
new TextDecoder();
|
|
4
|
+
function encodeNameHex(name) {
|
|
5
|
+
return [...textEncoder.encode(name)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/integrations/cloudflare.ts
|
|
9
|
+
const bindingPrefix = "RATE_LIMIT";
|
|
10
|
+
function getCloudflareRateLimitBindingName(name) {
|
|
11
|
+
const encoded = encodeNameHex(name).toUpperCase();
|
|
12
|
+
return encoded ? `${bindingPrefix}_${encoded}` : bindingPrefix;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/drivers/cloudflare.ts
|
|
16
|
+
function isBinding(value) {
|
|
17
|
+
return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
|
|
18
|
+
}
|
|
19
|
+
function cloudflareRateLimitDriver(options) {
|
|
20
|
+
if (!isBinding(options?.binding)) throw new TypeError("[vitehub] cloudflareRateLimitDriver() requires a Cloudflare Rate Limit binding.");
|
|
21
|
+
return {
|
|
22
|
+
capabilities: {
|
|
23
|
+
enforcement: "best-effort",
|
|
24
|
+
rejectedAttempts: "unknown",
|
|
25
|
+
scope: "location",
|
|
26
|
+
windows: [1e4, 6e4]
|
|
27
|
+
},
|
|
28
|
+
async consume(input) {
|
|
29
|
+
let result;
|
|
30
|
+
try {
|
|
31
|
+
result = await options.binding.limit({ key: input.key });
|
|
32
|
+
} catch (cause) {
|
|
33
|
+
return [new Error("[vitehub] Cloudflare Rate Limit binding failed.", { cause }), void 0];
|
|
34
|
+
}
|
|
35
|
+
if (!result || typeof result.success !== "boolean") throw new TypeError("[vitehub] Cloudflare Rate Limit binding returned an invalid result.");
|
|
36
|
+
return [null, { allowed: result.success }];
|
|
37
|
+
},
|
|
38
|
+
name: "cloudflare"
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { getCloudflareRateLimitBindingName as n, cloudflareRateLimitDriver as t };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { a as RateLimitDriver } from "../types-BX4hSfYX.js";
|
|
2
|
+
|
|
3
|
+
//#region src/integrations/cloudflare.d.ts
|
|
4
|
+
declare function getCloudflareRateLimitBindingName(name: string): string;
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/drivers/cloudflare.d.ts
|
|
7
|
+
interface CloudflareRateLimitBinding {
|
|
8
|
+
limit(input: {
|
|
9
|
+
key: string;
|
|
10
|
+
}): Promise<{
|
|
11
|
+
success: boolean;
|
|
12
|
+
}>;
|
|
13
|
+
}
|
|
14
|
+
interface CloudflareRateLimitDriverOptions {
|
|
15
|
+
binding: CloudflareRateLimitBinding;
|
|
16
|
+
}
|
|
17
|
+
declare function cloudflareRateLimitDriver(options: CloudflareRateLimitDriverOptions): RateLimitDriver;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { CloudflareRateLimitBinding, CloudflareRateLimitDriverOptions, cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { a as RateLimitDriver } from "../types-BX4hSfYX.js";
|
|
2
|
+
|
|
3
|
+
//#region src/drivers/memory.d.ts
|
|
4
|
+
interface MemoryRateLimitDriverOptions {
|
|
5
|
+
maxEntries?: number;
|
|
6
|
+
now?: () => number;
|
|
7
|
+
}
|
|
8
|
+
interface MemoryRateLimitDriver extends RateLimitDriver {
|
|
9
|
+
clear: () => void;
|
|
10
|
+
size: () => number;
|
|
11
|
+
}
|
|
12
|
+
declare function memoryRateLimitDriver(options?: MemoryRateLimitDriverOptions): MemoryRateLimitDriver;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { MemoryRateLimitDriver, MemoryRateLimitDriverOptions, memoryRateLimitDriver };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
//#region src/drivers/memory.ts
|
|
2
|
+
const defaultMaxEntries = 1e5;
|
|
3
|
+
function memoryRateLimitDriver(options = {}) {
|
|
4
|
+
const entries = /* @__PURE__ */ new Map();
|
|
5
|
+
const maxEntries = options.maxEntries ?? defaultMaxEntries;
|
|
6
|
+
if (!Number.isInteger(maxEntries) || maxEntries <= 0) throw new TypeError("[vitehub] Memory Rate Limit driver maxEntries must be a positive integer.");
|
|
7
|
+
const now = options.now ?? Date.now;
|
|
8
|
+
function prune(timestamp) {
|
|
9
|
+
for (const [key, entry] of entries) if (entry.resetAt <= timestamp) entries.delete(key);
|
|
10
|
+
}
|
|
11
|
+
return {
|
|
12
|
+
capabilities: {
|
|
13
|
+
enforcement: "strict",
|
|
14
|
+
rejectedAttempts: "not-counted",
|
|
15
|
+
scope: "process"
|
|
16
|
+
},
|
|
17
|
+
clear() {
|
|
18
|
+
entries.clear();
|
|
19
|
+
},
|
|
20
|
+
consume(input) {
|
|
21
|
+
const timestamp = now();
|
|
22
|
+
prune(timestamp);
|
|
23
|
+
const key = `${input.name ?? "default"}\0${input.key}`;
|
|
24
|
+
const resetAt = Math.floor(timestamp / input.windowMs) * input.windowMs + input.windowMs;
|
|
25
|
+
const current = entries.get(key);
|
|
26
|
+
if (!current && entries.size >= maxEntries) throw new Error(`[vitehub] Memory Rate Limit driver reached maxEntries (${maxEntries}) while active counters remain.`);
|
|
27
|
+
const entry = current && current.resetAt > timestamp ? current : {
|
|
28
|
+
count: 0,
|
|
29
|
+
resetAt
|
|
30
|
+
};
|
|
31
|
+
if (entry.count >= input.limit) return [null, {
|
|
32
|
+
allowed: false,
|
|
33
|
+
remaining: 0,
|
|
34
|
+
resetAt: entry.resetAt,
|
|
35
|
+
retryAfter: Math.max(1, Math.ceil((entry.resetAt - timestamp) / 1e3)),
|
|
36
|
+
used: entry.count
|
|
37
|
+
}];
|
|
38
|
+
entry.count += 1;
|
|
39
|
+
entries.set(key, entry);
|
|
40
|
+
return [null, {
|
|
41
|
+
allowed: true,
|
|
42
|
+
remaining: input.limit - entry.count,
|
|
43
|
+
resetAt: entry.resetAt,
|
|
44
|
+
used: entry.count
|
|
45
|
+
}];
|
|
46
|
+
},
|
|
47
|
+
name: "memory",
|
|
48
|
+
size() {
|
|
49
|
+
return entries.size;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
export { memoryRateLimitDriver };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { _ as RateLimitRuntimeConfig, a as RateLimitDriver, b as RequireRateLimitOptions, c as RateLimitDriverOutcome, d as RateLimitFailurePolicy, f as RateLimitModuleOptions, g as RateLimitRequestEvent, h as RateLimitRejectedAttemptBehavior, i as RateLimitDecision, l as RateLimitDriverResult, m as RateLimitProvider, n as RateLimitConsumeInput, o as RateLimitDriverCapabilities, p as RateLimitPolicy, r as RateLimitCounterScope, s as RateLimitDriverInput, t as CreateRateLimiterOptions, u as RateLimitEnforcement, v as RateLimitWindow, x as ResolvedRateLimitPolicy, y as RateLimiter } from "./types-BX4hSfYX.js";
|
|
2
|
+
|
|
3
|
+
//#region src/limiter.d.ts
|
|
4
|
+
declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/guard.d.ts
|
|
7
|
+
declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitDecision, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitModuleOptions, type RateLimitPolicy, type RateLimitProvider, type RateLimitRejectedAttemptBehavior, type RateLimitRequestEvent, type RateLimitRuntimeConfig, type RateLimitWindow, type RateLimiter, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, createRateLimiter, requireRateLimit };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-CHaHluMr.js";
|
|
2
|
+
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-BYZQ2tim.js";
|
|
3
|
+
import { memoryRateLimitDriver } from "./drivers/memory.js";
|
|
4
|
+
import { n as getRateLimitRuntimeConfig, t as getRateLimitLimiterCache } from "./state-DB4uJN5P.js";
|
|
5
|
+
import { HTTPError, getRequestIP } from "h3";
|
|
6
|
+
//#region src/guard.ts
|
|
7
|
+
const guardOptionKeys = new Set([...rateLimitPolicyKeys, "key"]);
|
|
8
|
+
function getCloudflareEventEnv(event) {
|
|
9
|
+
const target = event;
|
|
10
|
+
return target.env ?? target.context?.cloudflare?.env ?? target.context?._platform?.cloudflare?.env ?? target.req?.runtime?.cloudflare?.env ?? target.node?.req?.runtime?.cloudflare?.env;
|
|
11
|
+
}
|
|
12
|
+
function isCloudflareBinding(value) {
|
|
13
|
+
return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
|
|
14
|
+
}
|
|
15
|
+
function getRequestKey(event, provider) {
|
|
16
|
+
return provider === "cloudflare" ? event.req.headers.get("cf-connecting-ip") || getRequestIP(event) : getRequestIP(event);
|
|
17
|
+
}
|
|
18
|
+
function getMemoryRateLimiter(name, policy) {
|
|
19
|
+
const cache = getRateLimitLimiterCache();
|
|
20
|
+
const cacheKey = JSON.stringify([
|
|
21
|
+
name,
|
|
22
|
+
policy.enforcement,
|
|
23
|
+
policy.failure,
|
|
24
|
+
policy.limit,
|
|
25
|
+
policy.window
|
|
26
|
+
]);
|
|
27
|
+
const existing = cache.get(cacheKey);
|
|
28
|
+
if (existing) return existing;
|
|
29
|
+
const pending = Promise.resolve(createRateLimiter({
|
|
30
|
+
...policy,
|
|
31
|
+
driver: memoryRateLimitDriver(),
|
|
32
|
+
name
|
|
33
|
+
})).catch((error) => {
|
|
34
|
+
cache.delete(cacheKey);
|
|
35
|
+
throw error;
|
|
36
|
+
});
|
|
37
|
+
cache.set(cacheKey, pending);
|
|
38
|
+
return pending;
|
|
39
|
+
}
|
|
40
|
+
function getCloudflareRateLimiter(event, name, policy) {
|
|
41
|
+
const bindingName = getCloudflareRateLimitBindingName(name);
|
|
42
|
+
const binding = getCloudflareEventEnv(event)?.[bindingName];
|
|
43
|
+
if (!isCloudflareBinding(binding)) throw new Error(`[vitehub] Cloudflare Rate Limit binding "${bindingName}" was not found on the request event.`);
|
|
44
|
+
return createRateLimiter({
|
|
45
|
+
...policy,
|
|
46
|
+
driver: cloudflareRateLimitDriver({ binding }),
|
|
47
|
+
name
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
async function requireRateLimit(event, name, options) {
|
|
51
|
+
const id = typeof name === "string" ? name.trim() : "";
|
|
52
|
+
if (!id) throw new TypeError("`requireRateLimit()` requires a non-empty stable ID.");
|
|
53
|
+
const unknownKey = options && typeof options === "object" && !Array.isArray(options) ? Object.keys(options).find((key) => !guardOptionKeys.has(key)) : void 0;
|
|
54
|
+
if (unknownKey) throw new TypeError(`\`requireRateLimit()\` does not support the "${unknownKey}" option.`);
|
|
55
|
+
if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw new TypeError("`requireRateLimit()` key must be a non-empty string.");
|
|
56
|
+
const policy = declaredRateLimitPolicy(normalizeRateLimitPolicy(options));
|
|
57
|
+
const { provider } = getRateLimitRuntimeConfig();
|
|
58
|
+
const key = options.key ?? getRequestKey(event, provider);
|
|
59
|
+
if (!key) throw new Error("[vitehub] Rate Limit could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.");
|
|
60
|
+
const decision = await (provider === "cloudflare" ? getCloudflareRateLimiter(event, id, policy) : await getMemoryRateLimiter(id, policy)).consume({ key });
|
|
61
|
+
if (decision.allowed) return;
|
|
62
|
+
if (decision.reason === "unavailable") throw new HTTPError({
|
|
63
|
+
cause: decision.cause,
|
|
64
|
+
message: "Rate limiting is unavailable.",
|
|
65
|
+
status: 503,
|
|
66
|
+
statusText: "Service Unavailable"
|
|
67
|
+
});
|
|
68
|
+
throw new HTTPError({
|
|
69
|
+
headers: decision.retryAfter === void 0 ? void 0 : { "Retry-After": String(decision.retryAfter) },
|
|
70
|
+
message: "Rate limit exceeded.",
|
|
71
|
+
status: 429,
|
|
72
|
+
statusText: "Too Many Requests"
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
export { createRateLimiter, requireRateLimit };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
//#region src/policy.ts
|
|
2
|
+
const rateLimitPolicyKeys = new Set([
|
|
3
|
+
"enforcement",
|
|
4
|
+
"failure",
|
|
5
|
+
"limit",
|
|
6
|
+
"window"
|
|
7
|
+
]);
|
|
8
|
+
const unitMilliseconds = {
|
|
9
|
+
d: 864e5,
|
|
10
|
+
h: 36e5,
|
|
11
|
+
m: 6e4,
|
|
12
|
+
ms: 1,
|
|
13
|
+
s: 1e3
|
|
14
|
+
};
|
|
15
|
+
function parseRateLimitWindow(value) {
|
|
16
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(value);
|
|
17
|
+
if (!match) throw new TypeError("[vitehub] Rate Limit window must use a duration such as \"10s\", \"1m\", \"1h\", or \"1d\".");
|
|
18
|
+
const amount = Number(match[1]);
|
|
19
|
+
if (!Number.isFinite(amount) || amount <= 0) throw new TypeError("[vitehub] Rate Limit window must be greater than zero.");
|
|
20
|
+
return Math.ceil(amount * unitMilliseconds[match[2]]);
|
|
21
|
+
}
|
|
22
|
+
function normalizeRateLimitPolicy(policy) {
|
|
23
|
+
if (!policy || typeof policy !== "object" || Array.isArray(policy)) throw new TypeError("[vitehub] Rate Limit policy must be an object.");
|
|
24
|
+
if (!Number.isInteger(policy.limit) || policy.limit <= 0) throw new TypeError("[vitehub] Rate Limit limit must be a positive integer.");
|
|
25
|
+
if (policy.enforcement !== void 0 && policy.enforcement !== "best-effort" && policy.enforcement !== "strict") throw new TypeError("[vitehub] Rate Limit enforcement must be \"best-effort\" or \"strict\".");
|
|
26
|
+
if (policy.failure !== void 0 && policy.failure !== "allow" && policy.failure !== "deny") throw new TypeError("[vitehub] Rate Limit failure must be \"allow\" or \"deny\".");
|
|
27
|
+
return {
|
|
28
|
+
enforcement: policy.enforcement ?? "best-effort",
|
|
29
|
+
failure: policy.failure ?? "deny",
|
|
30
|
+
limit: policy.limit,
|
|
31
|
+
window: policy.window,
|
|
32
|
+
windowMs: parseRateLimitWindow(policy.window)
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function declaredRateLimitPolicy(policy) {
|
|
36
|
+
return {
|
|
37
|
+
enforcement: policy.enforcement,
|
|
38
|
+
failure: policy.failure,
|
|
39
|
+
limit: policy.limit,
|
|
40
|
+
window: policy.window
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/limiter.ts
|
|
45
|
+
function resolveDriverCapabilities(options) {
|
|
46
|
+
const capabilities = options.driver.capabilities;
|
|
47
|
+
if (!capabilities || typeof capabilities !== "object") throw new TypeError(`[vitehub] Rate Limit driver "${options.driver.name}" must declare capabilities.`);
|
|
48
|
+
if (capabilities.enforcement !== "best-effort" && capabilities.enforcement !== "strict") throw new TypeError(`[vitehub] Rate Limit driver "${options.driver.name}" must declare valid enforcement.`);
|
|
49
|
+
if (capabilities.scope !== "process" && capabilities.scope !== "location" && capabilities.scope !== "global") throw new TypeError(`[vitehub] Rate Limit driver "${options.driver.name}" must declare counter scope.`);
|
|
50
|
+
if (capabilities.rejectedAttempts !== "counted" && capabilities.rejectedAttempts !== "not-counted" && capabilities.rejectedAttempts !== "unknown") throw new TypeError(`[vitehub] Rate Limit driver "${options.driver.name}" must declare rejected-attempt behavior.`);
|
|
51
|
+
if (capabilities.windows?.some((window) => !Number.isInteger(window) || window <= 0)) throw new TypeError(`[vitehub] Rate Limit driver "${options.driver.name}" windows must contain positive integer milliseconds.`);
|
|
52
|
+
return {
|
|
53
|
+
enforcement: capabilities.enforcement,
|
|
54
|
+
rejectedAttempts: capabilities.rejectedAttempts,
|
|
55
|
+
scope: capabilities.scope,
|
|
56
|
+
...capabilities.windows ? { windows: [...capabilities.windows] } : {}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function normalizeOptionalInteger(value, label) {
|
|
60
|
+
if (value === void 0) return;
|
|
61
|
+
if (!Number.isInteger(value) || value < 0) throw new TypeError(`[vitehub] Rate Limit driver result ${label} must be a non-negative integer.`);
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
function normalizeDriverResult(result, limit, windowMs) {
|
|
65
|
+
if (!result || typeof result !== "object" || typeof result.allowed !== "boolean") throw new TypeError("[vitehub] Rate Limit driver consume() must return an object with an allowed boolean.");
|
|
66
|
+
const resetAt = result.resetAt;
|
|
67
|
+
if (resetAt !== void 0 && (!Number.isFinite(resetAt) || resetAt <= 0)) throw new TypeError("[vitehub] Rate Limit driver result resetAt must be a positive timestamp.");
|
|
68
|
+
const decision = {
|
|
69
|
+
limit,
|
|
70
|
+
remaining: normalizeOptionalInteger(result.remaining, "remaining"),
|
|
71
|
+
resetAt,
|
|
72
|
+
retryAfter: normalizeOptionalInteger(result.retryAfter, "retryAfter"),
|
|
73
|
+
used: normalizeOptionalInteger(result.used, "used"),
|
|
74
|
+
windowMs
|
|
75
|
+
};
|
|
76
|
+
return result.allowed ? {
|
|
77
|
+
...decision,
|
|
78
|
+
allowed: true
|
|
79
|
+
} : {
|
|
80
|
+
...decision,
|
|
81
|
+
allowed: false,
|
|
82
|
+
reason: "limited"
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function assertDriverSupportsPolicy(options, capabilities, windowMs) {
|
|
86
|
+
if ((options.enforcement ?? "best-effort") === "strict" && capabilities.enforcement !== "strict") throw new Error(`[vitehub] Rate Limit driver "${options.driver.name}" provides best-effort enforcement, but this policy requires strict enforcement.`);
|
|
87
|
+
const windows = capabilities.windows;
|
|
88
|
+
if (windows?.length && !windows.includes(windowMs)) throw new Error(`[vitehub] Rate Limit driver "${options.driver.name}" does not support a ${windowMs}ms window. Supported windows: ${windows.join(", ")}ms.`);
|
|
89
|
+
}
|
|
90
|
+
function createRateLimiter(options) {
|
|
91
|
+
if (!options.driver || typeof options.driver.consume !== "function") throw new TypeError("[vitehub] createRateLimiter() requires a Rate Limit driver.");
|
|
92
|
+
const policy = normalizeRateLimitPolicy(options);
|
|
93
|
+
const capabilities = resolveDriverCapabilities(options);
|
|
94
|
+
assertDriverSupportsPolicy(options, capabilities, policy.windowMs);
|
|
95
|
+
return {
|
|
96
|
+
capabilities,
|
|
97
|
+
async consume(input) {
|
|
98
|
+
if (!input || typeof input.key !== "string" || input.key.length === 0) throw new TypeError("[vitehub] Rate Limiter consume() requires a non-empty key.");
|
|
99
|
+
const [error, result] = await options.driver.consume({
|
|
100
|
+
key: input.key,
|
|
101
|
+
limit: policy.limit,
|
|
102
|
+
name: options.name,
|
|
103
|
+
windowMs: policy.windowMs
|
|
104
|
+
});
|
|
105
|
+
if (error) return {
|
|
106
|
+
allowed: policy.failure === "allow",
|
|
107
|
+
cause: error.cause ?? error,
|
|
108
|
+
limit: policy.limit,
|
|
109
|
+
reason: "unavailable",
|
|
110
|
+
windowMs: policy.windowMs
|
|
111
|
+
};
|
|
112
|
+
return normalizeDriverResult(result, policy.limit, policy.windowMs);
|
|
113
|
+
},
|
|
114
|
+
policy
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { rateLimitPolicyKeys as i, declaredRateLimitPolicy as n, normalizeRateLimitPolicy as r, createRateLimiter as t };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { _ as RateLimitRuntimeConfig } from "./types-BX4hSfYX.js";
|
|
2
|
+
|
|
3
|
+
//#region src/runtime/state.d.ts
|
|
4
|
+
declare function setRateLimitRuntimeConfig(config: RateLimitRuntimeConfig): void;
|
|
5
|
+
declare function getRateLimitRuntimeConfig(): RateLimitRuntimeConfig;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { getRateLimitRuntimeConfig, setRateLimitRuntimeConfig };
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//#region src/runtime/state.ts
|
|
2
|
+
let runtimeConfig = { provider: "memory" };
|
|
3
|
+
const limiterCache = /* @__PURE__ */ new Map();
|
|
4
|
+
function setRateLimitRuntimeConfig(config) {
|
|
5
|
+
runtimeConfig = config;
|
|
6
|
+
limiterCache.clear();
|
|
7
|
+
}
|
|
8
|
+
function getRateLimitRuntimeConfig() {
|
|
9
|
+
return runtimeConfig;
|
|
10
|
+
}
|
|
11
|
+
function getRateLimitLimiterCache() {
|
|
12
|
+
return limiterCache;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { getRateLimitRuntimeConfig as n, setRateLimitRuntimeConfig as r, getRateLimitLimiterCache as t };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
type MaybePromise<T> = Promise<T> | T;
|
|
3
|
+
type RateLimitWindow = `${number}ms` | `${number}s` | `${number}m` | `${number}h` | `${number}d`;
|
|
4
|
+
type RateLimitEnforcement = "best-effort" | "strict";
|
|
5
|
+
type RateLimitFailurePolicy = "allow" | "deny";
|
|
6
|
+
type RateLimitCounterScope = "global" | "location" | "process";
|
|
7
|
+
type RateLimitRejectedAttemptBehavior = "counted" | "not-counted" | "unknown";
|
|
8
|
+
interface RateLimitPolicy {
|
|
9
|
+
enforcement?: RateLimitEnforcement;
|
|
10
|
+
failure?: RateLimitFailurePolicy;
|
|
11
|
+
limit: number;
|
|
12
|
+
window: RateLimitWindow;
|
|
13
|
+
}
|
|
14
|
+
interface RequireRateLimitOptions extends RateLimitPolicy {
|
|
15
|
+
key?: string;
|
|
16
|
+
}
|
|
17
|
+
interface RateLimitRequestEvent {
|
|
18
|
+
readonly req: {
|
|
19
|
+
readonly headers: {
|
|
20
|
+
get: (name: string) => string | null;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
interface ResolvedRateLimitPolicy {
|
|
25
|
+
readonly enforcement: RateLimitEnforcement;
|
|
26
|
+
readonly failure: RateLimitFailurePolicy;
|
|
27
|
+
readonly limit: number;
|
|
28
|
+
readonly window: RateLimitWindow;
|
|
29
|
+
readonly windowMs: number;
|
|
30
|
+
}
|
|
31
|
+
interface RateLimitConsumeInput {
|
|
32
|
+
key: string;
|
|
33
|
+
}
|
|
34
|
+
interface RateLimitDriverInput extends RateLimitConsumeInput {
|
|
35
|
+
limit: number;
|
|
36
|
+
name?: string;
|
|
37
|
+
windowMs: number;
|
|
38
|
+
}
|
|
39
|
+
interface RateLimitDriverResult {
|
|
40
|
+
allowed: boolean;
|
|
41
|
+
remaining?: number;
|
|
42
|
+
resetAt?: number;
|
|
43
|
+
retryAfter?: number;
|
|
44
|
+
used?: number;
|
|
45
|
+
}
|
|
46
|
+
type RateLimitDriverOutcome = [error: null, value: RateLimitDriverResult] | [error: Error, value: undefined];
|
|
47
|
+
interface RateLimitDecisionBase extends RateLimitDriverResult {
|
|
48
|
+
limit: number;
|
|
49
|
+
windowMs: number;
|
|
50
|
+
}
|
|
51
|
+
interface RateLimitAllowedDecision extends RateLimitDecisionBase {
|
|
52
|
+
allowed: true;
|
|
53
|
+
cause?: never;
|
|
54
|
+
reason?: never;
|
|
55
|
+
}
|
|
56
|
+
interface RateLimitLimitedDecision extends RateLimitDecisionBase {
|
|
57
|
+
allowed: false;
|
|
58
|
+
cause?: never;
|
|
59
|
+
reason: "limited";
|
|
60
|
+
}
|
|
61
|
+
interface RateLimitUnavailableDecision extends RateLimitDecisionBase {
|
|
62
|
+
cause: unknown;
|
|
63
|
+
reason: "unavailable";
|
|
64
|
+
}
|
|
65
|
+
type RateLimitDecision = RateLimitAllowedDecision | RateLimitLimitedDecision | RateLimitUnavailableDecision;
|
|
66
|
+
interface RateLimitDriverCapabilities {
|
|
67
|
+
readonly enforcement: RateLimitEnforcement;
|
|
68
|
+
readonly rejectedAttempts: RateLimitRejectedAttemptBehavior;
|
|
69
|
+
readonly scope: RateLimitCounterScope;
|
|
70
|
+
readonly windows?: readonly number[];
|
|
71
|
+
}
|
|
72
|
+
interface RateLimitDriver {
|
|
73
|
+
capabilities: RateLimitDriverCapabilities;
|
|
74
|
+
consume: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverOutcome>;
|
|
75
|
+
name: string;
|
|
76
|
+
}
|
|
77
|
+
interface RateLimiter {
|
|
78
|
+
readonly capabilities: RateLimitDriverCapabilities;
|
|
79
|
+
consume: (input: RateLimitConsumeInput) => Promise<RateLimitDecision>;
|
|
80
|
+
policy: ResolvedRateLimitPolicy;
|
|
81
|
+
}
|
|
82
|
+
interface CreateRateLimiterOptions extends RateLimitPolicy {
|
|
83
|
+
driver: RateLimitDriver;
|
|
84
|
+
name?: string;
|
|
85
|
+
}
|
|
86
|
+
type RateLimitProvider = "auto" | "cloudflare" | "memory";
|
|
87
|
+
interface RateLimitModuleOptions {
|
|
88
|
+
namespace?: string;
|
|
89
|
+
provider?: RateLimitProvider;
|
|
90
|
+
projectRoot?: string;
|
|
91
|
+
scanDirs?: string[];
|
|
92
|
+
}
|
|
93
|
+
interface RateLimitRuntimeConfig {
|
|
94
|
+
provider: Exclude<RateLimitProvider, "auto">;
|
|
95
|
+
}
|
|
96
|
+
//#endregion
|
|
97
|
+
export { RateLimitRuntimeConfig as _, RateLimitDriver as a, RequireRateLimitOptions as b, RateLimitDriverOutcome as c, RateLimitFailurePolicy as d, RateLimitModuleOptions as f, RateLimitRequestEvent as g, RateLimitRejectedAttemptBehavior as h, RateLimitDecision as i, RateLimitDriverResult as l, RateLimitProvider as m, RateLimitConsumeInput as n, RateLimitDriverCapabilities as o, RateLimitPolicy as p, RateLimitCounterScope as r, RateLimitDriverInput as s, CreateRateLimiterOptions as t, RateLimitEnforcement as u, RateLimitWindow as v, ResolvedRateLimitPolicy as x, RateLimiter as y };
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { f as RateLimitModuleOptions } from "./types-BX4hSfYX.js";
|
|
2
|
+
import { Plugin } from "vite";
|
|
3
|
+
|
|
4
|
+
//#region src/vite.d.ts
|
|
5
|
+
type RateLimitVitePluginOptions = RateLimitModuleOptions;
|
|
6
|
+
type RateLimitVitePlugin = Plugin;
|
|
7
|
+
declare function hubRateLimit(options?: RateLimitVitePluginOptions): RateLimitVitePlugin;
|
|
8
|
+
declare module "vite" {
|
|
9
|
+
interface UserConfig {
|
|
10
|
+
rateLimit?: RateLimitModuleOptions;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
export { RateLimitVitePlugin, RateLimitVitePluginOptions, hubRateLimit };
|