@vite-hub/rate-limit 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -13
- package/dist/cli.js +14 -4
- package/dist/{cloudflare-otBvOPv4.js → cloudflare-_Tz3DcpB.js} +9 -2
- package/dist/{counters-DgVdHwdL.js → counters-D4LANMAi.js} +4 -3
- package/dist/{counters-DXpF67J_.d.ts → counters-d8FaLiE1.d.ts} +3 -2
- package/dist/drivers/cloudflare.d.ts +1 -1
- package/dist/drivers/cloudflare.js +1 -1
- package/dist/drivers/kv.d.ts +1 -1
- package/dist/drivers/kv.js +54 -15
- package/dist/drivers/memory.d.ts +2 -1
- package/dist/drivers/memory.js +6 -1
- package/dist/{error-diagnostics-MgAnhRTP.js → error-diagnostics-DRuEG4wu.js} +6 -2
- package/dist/index.d.ts +10 -3
- package/dist/index.js +38 -10
- package/dist/{kv-C1wpLulE.d.ts → kv-Cw_jK6Gu.d.ts} +6 -3
- package/dist/{kv-provider-C1S6dRTR.js → kv-provider-DlgNQC-o.js} +28 -57
- package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
- package/dist/{operations-CLI9w3rO.js → operations-B1MnA9cW.js} +2 -2
- package/dist/{operations-BYRa7wpx.js → operations-q0ieloSJ.js} +218 -207
- package/dist/operations.d.ts +2 -2
- package/dist/operations.js +3 -2
- package/dist/policy-BeyQ0vnc.js +51 -0
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.js +1 -1
- package/dist/{state-BU-zcLNY.js → state-Fq3rGFO3.js} +9 -12
- package/dist/{types-CMyR1JeW.d.ts → types-OzukEqHf.d.ts} +30 -5
- package/dist/vite.d.ts +4 -2
- package/dist/vite.js +122 -68
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# @vite-hub/rate-limit
|
|
2
2
|
|
|
3
|
-
[](https://npmx.dev/package/@vite-hub/rate-limit)
|
|
4
|
+
[](https://npmx.dev/package/@vite-hub/rate-limit)
|
|
5
|
+
[](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
|
|
6
|
+
[](https://vitehub.dev/docs)
|
|
7
7
|
|
|
8
8
|
`@vite-hub/rate-limit` gives server code one atomic consume-and-decide operation for fixed-window request budgets. It keeps policy separate from the driver that stores and updates each counter.
|
|
9
9
|
|
|
@@ -15,7 +15,7 @@ Install this owner package when you need a direct Rate Limiter, a custom driver,
|
|
|
15
15
|
pnpm add @vite-hub/rate-limit
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
The package requires Node.js
|
|
18
|
+
The package requires Node.js 24.15 or newer. Vite is an optional peer dependency and is needed only for the managed Vite integration.
|
|
19
19
|
|
|
20
20
|
## Get the first decision
|
|
21
21
|
|
|
@@ -105,7 +105,7 @@ An allowed request continues. An exhausted budget throws an H3 `HTTPError` with
|
|
|
105
105
|
|
|
106
106
|
Local Vite development uses the process-local memory driver. `driver: "kv"` counts in the default KV store of `@vite-hub/kv` with one atomic `increment` for each request. The Nitro plugin asks KV at boot which driver the store uses: with `redis`, `database`, or `upstash`, every server process shares the counts. An explicit `driver: "kv"` on another driver, such as `fs-lite`, fails the build with `RATE_LIMIT_KV_STORE_UNSUPPORTED`; `vite dev` counts in memory. With ViteHub, a `node` build selects `kv` when KV is on, and `memory` otherwise; when ViteHub selected `kv` and the store cannot share counts, it counts in memory and prints a warning. A build that counts declared Rate Limits in memory prints a warning, and fails with `RATE_LIMIT_MEMORY_STRICT_UNSUPPORTED` for a Rate Limit with `enforcement: "strict"`. A Cloudflare Nitro preset selects Cloudflare Rate Limiting, and every deployed Worker and environment needs a unique namespace. ViteHub has no native Rate Limit driver for Vercel, Netlify, or Deno. Automatic driver selection fails for an unknown production host instead of falling back to unsafe per-instance memory. Select memory explicitly only for a known single-process deployment; otherwise supply a direct production driver. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before choosing a deployment target.
|
|
107
107
|
|
|
108
|
-
Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and `1m` windows. It does not report portable remaining, reset, or retry metadata. A policy that requests strict enforcement
|
|
108
|
+
Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and `1m` windows. It does not report portable remaining, reset, or retry metadata. A Rate Limit with another window counts in the default KV store, which needs a shared atomic `increment`, such as `kv: { driver: "upstash" }`; without one, the build fails with `RATE_LIMIT_R0016`. A `10s` or `1m` policy that requests strict enforcement fails with `RATE_LIMIT_R0015`. `vite dev` fails the same way when the build targets Cloudflare, although the dev server counts in memory. The [Cloudflare host guide](https://vitehub.dev/docs/frameworks-hosts/cloudflare#rate-limiting-bindings) covers generated bindings and deployment verification.
|
|
109
109
|
|
|
110
110
|
## Supply a direct driver
|
|
111
111
|
|
|
@@ -117,15 +117,17 @@ Drivers return a `Result`: `[undefined, result]` after consuming the counter, an
|
|
|
117
117
|
|
|
118
118
|
The limiter exposes its resolved `policy` and the driver's declared `capabilities`, including enforcement, counter scope, rejected-attempt behavior, and supported windows. Inspect them when deciding whether a driver fits a deployment.
|
|
119
119
|
|
|
120
|
-
## Read or reset a counter
|
|
120
|
+
## Read, refund, or reset a counter
|
|
121
121
|
|
|
122
|
-
`limiter.peek({ key })` reads the counter of a key without consuming a token. `limiter.reset({ key })`
|
|
122
|
+
`limiter.peek({ key })` reads the counter of a key without consuming a token. `limiter.refund({ key })` gives back one request in the current window, for example when the work that the request paid for failed. Refund only a request that was allowed. `limiter.reset({ key })` clears the count. A driver supports them through optional `peek(input)`, `refund(input)`, and `reset(input)` methods. Like `consume()`, `peek()` returns `[undefined, value]` or `[error, undefined]`. The `refund()` and `reset()` methods return `[undefined, undefined]` or `[error, undefined]`. When the driver omits a method, the result has `status: "unsupported"` and a `reason`.
|
|
123
123
|
|
|
124
|
-
| Driver | `peek()` | `reset()` |
|
|
125
|
-
| ---------- | ------------------------------------------------------------------------- | --------------------- |
|
|
126
|
-
| memory | `used`, `remaining`, and `resetAt` in this process. `used: 0` when no counter exists. | Deletes the counter. |
|
|
127
|
-
| kv | `used`, `remaining`, and `resetAt` of the current window, shared by every process. | Deletes the
|
|
128
|
-
| cloudflare | `unsupported`. The binding exposes only `limit()`, which consumes a token. | `unsupported`. |
|
|
124
|
+
| Driver | `peek()` | `refund()` | `reset()` |
|
|
125
|
+
| ---------- | ------------------------------------------------------------------------- | ---------- | --------------------- |
|
|
126
|
+
| memory | `used`, `remaining`, and `resetAt` in this process. `used: 0` when no counter exists. | Removes one request from the counter. | Deletes the counter. |
|
|
127
|
+
| kv | `used`, `remaining`, and `resetAt` of the current window, shared by every process. | Adds one to a second counter that `consume()` subtracts at the limit. | Deletes the counters of the current window. |
|
|
128
|
+
| cloudflare | `unsupported`. The binding exposes only `limit()`, which consumes a token. | `unsupported`. | `unsupported`. |
|
|
129
|
+
|
|
130
|
+
For a managed guard, `refundRateLimit(event, id, options)` takes the same arguments as `checkRateLimit()` and returns `[error, result]`. The build discovers it like the other guards.
|
|
129
131
|
|
|
130
132
|
For managed guards, `peekRateLimit(id, key)` and `resetRateLimit(id, key)` use the counters of `requireRateLimit()` in the current runtime. `vitehub rate-limit peek <id> <key>` and `vitehub rate-limit reset <id> <key>` (which asks on a terminal, or needs `--yes`) run the `rate-limit.peek` and `rate-limit.reset` operations of the running app, on the dev server or with `--url` on a deployed app that enables the Console. The Console **Rate Limits** page runs the same operations.
|
|
131
133
|
|
package/dist/cli.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
|
|
2
|
+
import { r as parseRateLimitWindow } from "./policy-BeyQ0vnc.js";
|
|
2
3
|
import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
|
|
3
|
-
import { A as writeCliFailure, E as askOnTerminal, O as readViteHubDevTargetOption, n as callOperationFromCli, u as table } from "./operations-
|
|
4
|
+
import { A as writeCliFailure, E as askOnTerminal, O as readViteHubDevTargetOption, n as callOperationFromCli, u as table } from "./operations-q0ieloSJ.js";
|
|
4
5
|
import * as v from "valibot";
|
|
5
6
|
//#region src/cli.ts
|
|
6
7
|
const rateLimitDevTargetErrors = {
|
|
7
8
|
invalidInlineTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
|
|
8
9
|
invalidTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
|
|
9
|
-
missingValue: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message })
|
|
10
|
+
missingValue: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message }),
|
|
11
|
+
unknownOption: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message })
|
|
10
12
|
};
|
|
11
13
|
const rateLimitCommands = [{
|
|
12
14
|
description: "Show the counter of one key without consuming a token.",
|
|
@@ -106,7 +108,15 @@ function formatReset(result) {
|
|
|
106
108
|
if (result.status !== "reset") return `Rate Limit ${result.name}, key ${result.key}\nProvider: ${result.provider}\nNot reset: ${result.reason}\n`;
|
|
107
109
|
return `Reset Rate Limit ${result.name} for key ${result.key}.\nProvider: ${result.provider}\n${scopeNotice(result.scope)}\n`;
|
|
108
110
|
}
|
|
109
|
-
const windowSchema = v.custom((value) =>
|
|
111
|
+
const windowSchema = v.custom((value) => {
|
|
112
|
+
if (typeof value !== "string") return false;
|
|
113
|
+
try {
|
|
114
|
+
parseRateLimitWindow(value);
|
|
115
|
+
return true;
|
|
116
|
+
} catch {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
});
|
|
110
120
|
const finiteNumber = v.pipe(v.number(), v.finite());
|
|
111
121
|
const targetFields = {
|
|
112
122
|
key: v.string(),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
|
|
2
2
|
import { toResultError } from "@vite-hub/runtime";
|
|
3
3
|
//#region ../internal/src/integrations/hex.ts
|
|
4
4
|
const textEncoder = new TextEncoder();
|
|
@@ -13,6 +13,13 @@ function getCloudflareRateLimitBindingName(name) {
|
|
|
13
13
|
const encoded = encodeNameHex(name).toUpperCase();
|
|
14
14
|
return encoded ? `${bindingPrefix}_${encoded}` : bindingPrefix;
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Cloudflare documents `period` as 10 or 60 seconds: https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/
|
|
18
|
+
* A Rate Limit with another window counts in KV on Cloudflare.
|
|
19
|
+
*/
|
|
20
|
+
function isCloudflareRateLimitWindow(windowMs) {
|
|
21
|
+
return windowMs === 1e4 || windowMs === 6e4;
|
|
22
|
+
}
|
|
16
23
|
//#endregion
|
|
17
24
|
//#region src/drivers/cloudflare.ts
|
|
18
25
|
function isBinding(value) {
|
|
@@ -44,4 +51,4 @@ function cloudflareRateLimitDriver(options) {
|
|
|
44
51
|
};
|
|
45
52
|
}
|
|
46
53
|
//#endregion
|
|
47
|
-
export { getCloudflareRateLimitBindingName as n, cloudflareRateLimitDriver as t };
|
|
54
|
+
export { getCloudflareRateLimitBindingName as n, isCloudflareRateLimitWindow as r, cloudflareRateLimitDriver as t };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { i as resolveRateLimitDriver, r as listRuntimeRateLimiters } from "./state-
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
|
|
2
|
+
import { i as resolveRateLimitDriver, r as listRuntimeRateLimiters } from "./state-Fq3rGFO3.js";
|
|
3
3
|
import * as v from "valibot";
|
|
4
4
|
//#region src/counters.ts
|
|
5
5
|
/** Reason that Cloudflare counters are not readable. The binding exposes only `limit({ key })`. */
|
|
@@ -15,7 +15,8 @@ function assertTarget(name, key) {
|
|
|
15
15
|
if (!v.is(v.string(), key) || !key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0039({ message: "[vitehub] Rate Limit key must be a non-empty string." });
|
|
16
16
|
}
|
|
17
17
|
function limitersFor(target) {
|
|
18
|
-
|
|
18
|
+
const limiters = listRuntimeRateLimiters(target.name);
|
|
19
|
+
return target.provider === "cloudflare" && limiters.length === 0 ? void 0 : limiters;
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
22
|
* Reads the counter of one key without consuming a token. The result reports `unsupported` when the configured
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { O as RateLimitRuntimeConfig, a as RateLimitCounterScope } from "./types-OzukEqHf.js";
|
|
2
|
+
import { Duration } from "@vite-hub/runtime";
|
|
2
3
|
//#region src/counters.d.ts
|
|
3
4
|
type RateLimitRuntimeDriver = RateLimitRuntimeConfig["driver"];
|
|
4
5
|
/** Counter of one key for one policy. `peekRateLimit()` reads it without consuming a token. */
|
|
@@ -8,7 +9,7 @@ interface RateLimitCounterSnapshot {
|
|
|
8
9
|
/** End of the current window in epoch milliseconds. Absent when the key has no active counter. */
|
|
9
10
|
resetAt?: number;
|
|
10
11
|
used: number;
|
|
11
|
-
window:
|
|
12
|
+
window: Duration;
|
|
12
13
|
windowMs: number;
|
|
13
14
|
}
|
|
14
15
|
interface RateLimitCounterTarget {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-
|
|
1
|
+
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-_Tz3DcpB.js";
|
|
2
2
|
export { cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
|
package/dist/drivers/kv.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as kvRateLimitDriver, n as KVRateLimitDriverOptions, r as RateLimitKVStorage, t as KVRateLimitDriver } from "../kv-
|
|
1
|
+
import { i as kvRateLimitDriver, n as KVRateLimitDriverOptions, r as RateLimitKVStorage, t as KVRateLimitDriver } from "../kv-Cw_jK6Gu.js";
|
|
2
2
|
export { KVRateLimitDriver, KVRateLimitDriverOptions, RateLimitKVStorage, kvRateLimitDriver };
|
package/dist/drivers/kv.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-DRuEG4wu.js";
|
|
2
2
|
import { toResultError } from "@vite-hub/runtime";
|
|
3
3
|
//#region src/drivers/kv.ts
|
|
4
4
|
function isStorage(value) {
|
|
5
5
|
if (!value || typeof value !== "object") return false;
|
|
6
|
-
return typeof Reflect.get(value, "increment") === "function" && typeof Reflect.get(value, "get") === "function"
|
|
6
|
+
return typeof Reflect.get(value, "increment") === "function" && typeof Reflect.get(value, "get") === "function";
|
|
7
7
|
}
|
|
8
8
|
/** Bound the request wait without hiding configuration errors thrown by KV. */
|
|
9
9
|
async function withKVDeadline(operation) {
|
|
@@ -28,24 +28,43 @@ function keySegment(value) {
|
|
|
28
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
29
|
* necessary. The duration keeps a `1m` and a `1h` limiter of one name apart when their window starts align.
|
|
30
30
|
*/
|
|
31
|
-
function fixedWindow(input, timestamp) {
|
|
31
|
+
function fixedWindow(input, timestamp, prefix) {
|
|
32
32
|
const start = Math.floor(timestamp / input.windowMs) * input.windowMs;
|
|
33
33
|
const resetAt = start + input.windowMs;
|
|
34
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
35
|
return {
|
|
36
|
-
key:
|
|
37
|
-
resetAt
|
|
38
|
-
start
|
|
36
|
+
key: `${prefix}:${keySegment(input.name ?? "default")}:${input.windowMs}:${keySegment(input.key)}:${start}`,
|
|
37
|
+
resetAt
|
|
39
38
|
};
|
|
40
39
|
}
|
|
40
|
+
function storedCount(value) {
|
|
41
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : 0;
|
|
42
|
+
}
|
|
41
43
|
/**
|
|
42
44
|
* 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.
|
|
45
|
+
* same store shares the counters. Rejected requests also increment the counter. KV has no atomic decrement, so
|
|
46
|
+
* `refund()` increments a second counter, and `consume()` reads it only when the first counter passes the limit.
|
|
44
47
|
*/
|
|
45
48
|
function kvRateLimitDriver(options) {
|
|
46
|
-
if (!isStorage(options?.storage)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0046({ message: "[vitehub] kvRateLimitDriver() requires a KV store with increment()
|
|
49
|
+
if (!isStorage(options?.storage)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0046({ message: "[vitehub] kvRateLimitDriver() requires a KV store with increment() and get()." });
|
|
47
50
|
const storage = options.storage;
|
|
48
51
|
const now = options.now ?? Date.now;
|
|
52
|
+
const prefix = options.namespace ? `rate-limit-deployment:${keySegment(options.namespace)}` : "rate-limit";
|
|
53
|
+
async function counterKey(window) {
|
|
54
|
+
const [error, value] = await withKVDeadline(storage.get(`${window.key}:generation`));
|
|
55
|
+
if (error) return [error, void 0];
|
|
56
|
+
const generation = storedCount(value);
|
|
57
|
+
return [void 0, generation === 0 ? window.key : `${window.key}:g:${generation}`];
|
|
58
|
+
}
|
|
59
|
+
async function readCounts(key) {
|
|
60
|
+
const [[countError, count], [refundsError, refunds]] = await Promise.all([withKVDeadline(storage.get(key)), withKVDeadline(storage.get(`${key}:refunds`))]);
|
|
61
|
+
const error = countError ?? refundsError;
|
|
62
|
+
if (error) return [error, void 0];
|
|
63
|
+
return [void 0, {
|
|
64
|
+
count: storedCount(count),
|
|
65
|
+
refunds: storedCount(refunds)
|
|
66
|
+
}];
|
|
67
|
+
}
|
|
49
68
|
return {
|
|
50
69
|
capabilities: {
|
|
51
70
|
enforcement: "strict",
|
|
@@ -54,9 +73,17 @@ function kvRateLimitDriver(options) {
|
|
|
54
73
|
},
|
|
55
74
|
async consume(input) {
|
|
56
75
|
const timestamp = now();
|
|
57
|
-
const window = fixedWindow(input, timestamp);
|
|
58
|
-
const [
|
|
76
|
+
const window = fixedWindow(input, timestamp, prefix);
|
|
77
|
+
const [keyError, key] = await counterKey(window);
|
|
78
|
+
if (keyError) return [keyError, void 0];
|
|
79
|
+
const [error, count] = await withKVDeadline(storage.increment(key, input.windowMs / 1e3));
|
|
59
80
|
if (error) return [error, void 0];
|
|
81
|
+
let used = count;
|
|
82
|
+
if (count > input.limit) {
|
|
83
|
+
const [refundsError, refunds] = await withKVDeadline(storage.get(`${key}:refunds`));
|
|
84
|
+
if (refundsError) return [refundsError, void 0];
|
|
85
|
+
used = Math.max(0, count - storedCount(refunds));
|
|
86
|
+
}
|
|
60
87
|
if (used > input.limit) return [void 0, {
|
|
61
88
|
allowed: false,
|
|
62
89
|
remaining: 0,
|
|
@@ -73,17 +100,29 @@ function kvRateLimitDriver(options) {
|
|
|
73
100
|
},
|
|
74
101
|
name: "kv",
|
|
75
102
|
async peek(input) {
|
|
76
|
-
const window = fixedWindow(input, now());
|
|
77
|
-
const [
|
|
103
|
+
const window = fixedWindow(input, now(), prefix);
|
|
104
|
+
const [keyError, key] = await counterKey(window);
|
|
105
|
+
if (keyError) return [keyError, void 0];
|
|
106
|
+
const [error, counts] = await readCounts(key);
|
|
78
107
|
if (error) return [error, void 0];
|
|
79
|
-
const used =
|
|
108
|
+
const used = Math.max(0, counts.count - counts.refunds);
|
|
80
109
|
return [void 0, {
|
|
81
|
-
resetAt:
|
|
110
|
+
resetAt: counts.count ? window.resetAt : void 0,
|
|
82
111
|
used
|
|
83
112
|
}];
|
|
84
113
|
},
|
|
114
|
+
async refund(input) {
|
|
115
|
+
const [keyError, key] = await counterKey(fixedWindow(input, now(), prefix));
|
|
116
|
+
if (keyError) return [keyError, void 0];
|
|
117
|
+
const [error, counts] = await readCounts(key);
|
|
118
|
+
if (error) return [error, void 0];
|
|
119
|
+
if (counts.count <= counts.refunds) return [void 0, void 0];
|
|
120
|
+
const [refundError] = await withKVDeadline(storage.increment(`${key}:refunds`, input.windowMs / 1e3));
|
|
121
|
+
return refundError ? [refundError, void 0] : [void 0, void 0];
|
|
122
|
+
},
|
|
85
123
|
async reset(input) {
|
|
86
|
-
const
|
|
124
|
+
const window = fixedWindow(input, now(), prefix);
|
|
125
|
+
const [error] = await withKVDeadline(storage.increment(`${window.key}:generation`, input.windowMs / 1e3));
|
|
87
126
|
return error ? [error, void 0] : [void 0, void 0];
|
|
88
127
|
}
|
|
89
128
|
};
|
package/dist/drivers/memory.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as RateLimitDriver } from "../types-
|
|
1
|
+
import { c as RateLimitDriver } from "../types-OzukEqHf.js";
|
|
2
2
|
//#region src/drivers/memory.d.ts
|
|
3
3
|
export interface MemoryRateLimitDriverOptions {
|
|
4
4
|
maxEntries?: number;
|
|
@@ -7,6 +7,7 @@ export interface MemoryRateLimitDriverOptions {
|
|
|
7
7
|
export interface MemoryRateLimitDriver extends RateLimitDriver {
|
|
8
8
|
clear: () => void;
|
|
9
9
|
peek: NonNullable<RateLimitDriver["peek"]>;
|
|
10
|
+
refund: NonNullable<RateLimitDriver["refund"]>;
|
|
10
11
|
reset: NonNullable<RateLimitDriver["reset"]>;
|
|
11
12
|
size: () => number;
|
|
12
13
|
}
|
package/dist/drivers/memory.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-DRuEG4wu.js";
|
|
2
2
|
//#region src/drivers/memory.ts
|
|
3
3
|
const defaultMaxEntries = 1e5;
|
|
4
4
|
function memoryRateLimitDriver(options = {}) {
|
|
@@ -66,6 +66,11 @@ function memoryRateLimitDriver(options = {}) {
|
|
|
66
66
|
}];
|
|
67
67
|
},
|
|
68
68
|
name: "memory",
|
|
69
|
+
refund(input) {
|
|
70
|
+
const entry = entries.get(JSON.stringify([input.name ?? "default", input.key]));
|
|
71
|
+
if (entry && entry.resetAt > now() && entry.count > 0) entry.count -= 1;
|
|
72
|
+
return [void 0, void 0];
|
|
73
|
+
},
|
|
69
74
|
reset(input) {
|
|
70
75
|
const key = JSON.stringify([input.name ?? "default", input.key]);
|
|
71
76
|
entries.delete(key);
|
|
@@ -66,7 +66,7 @@ const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
66
66
|
},
|
|
67
67
|
RATE_LIMIT_R0016: {
|
|
68
68
|
...dynamicError,
|
|
69
|
-
fix: "
|
|
69
|
+
fix: "Give the app a KV store with a shared atomic increment, such as `kv: { driver: \"upstash\" }`, so that Rate Limit counts this window in KV. Cloudflare KV has no such increment. Or set `window` to \"10s\" or \"1m\" to use the Cloudflare binding."
|
|
70
70
|
},
|
|
71
71
|
RATE_LIMIT_R0019: {
|
|
72
72
|
...dynamicError,
|
|
@@ -146,7 +146,7 @@ const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
146
146
|
},
|
|
147
147
|
RATE_LIMIT_R0038: {
|
|
148
148
|
...dynamicError,
|
|
149
|
-
fix: "Pass `peek({ key })` or `reset({ key })` a non-empty string `key`."
|
|
149
|
+
fix: "Pass `peek({ key })`, `refund({ key })`, or `reset({ key })` a non-empty string `key`."
|
|
150
150
|
},
|
|
151
151
|
RATE_LIMIT_R0039: {
|
|
152
152
|
...dynamicError,
|
|
@@ -220,6 +220,10 @@ const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
220
220
|
...dynamicError,
|
|
221
221
|
fix: "Count in a shared store: on Node, set `rateLimit: { driver: 'kv' }` with a Redis or Postgres KV store. Or set `enforcement: 'best-effort'` on the Rate Limit."
|
|
222
222
|
},
|
|
223
|
+
RATE_LIMIT_REFUND_RESULT_INVALID: {
|
|
224
|
+
why: "A custom Rate Limit driver returned a value from `refund()` that is not `[undefined, undefined]` or `[error, undefined]`.",
|
|
225
|
+
fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, undefined]` from `refund()`, or `[error, undefined]` for an outage."
|
|
226
|
+
},
|
|
223
227
|
RATE_LIMIT_REFUSAL_OPTION_INVALID: {
|
|
224
228
|
...dynamicError,
|
|
225
229
|
fix: "Pass `message` and `code` of `requireRateLimit()` as non-empty strings, such as `message: \"Too many tries. Wait a minute.\"`, or remove them to use the default `429` error."
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-
|
|
1
|
+
import { A as RefundRateLimitErrorCode, C as RateLimitRefundResult, D as RateLimitResetResult, E as RateLimitRequestEvent, M as ResolvedRateLimitPolicy, O as RateLimitRuntimeConfig, S as RateLimitPolicy, T as RateLimitRequest, _ as RateLimitDriverResult, a as RateLimitCounterScope, b as RateLimitOptions, c as RateLimitDriver, d as RateLimitDriverName, f as RateLimitDriverOutcome, g as RateLimitDriverResetOutcome, h as RateLimitDriverRefundOutcome, i as RateLimitConsumeInput, j as RequireRateLimitOptions, k as RateLimiter, l as RateLimitDriverCapabilities, m as RateLimitDriverPeekResult, n as CheckRateLimitOptions, o as RateLimitDecision, p as RateLimitDriverPeekOutcome, r as CreateRateLimiterOptions, s as RateLimitDeclaration, t as CheckRateLimitErrorCode, u as RateLimitDriverInput, v as RateLimitEnforcement, w as RateLimitRejectedAttemptBehavior, x as RateLimitPeekResult, y as RateLimitFailurePolicy } from "./types-OzukEqHf.js";
|
|
2
|
+
import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-d8FaLiE1.js";
|
|
3
3
|
import { Result } from "@vite-hub/runtime";
|
|
4
4
|
//#region src/limiter.d.ts
|
|
5
5
|
export declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
|
|
@@ -13,6 +13,13 @@ export declare function createRateLimiter(options: CreateRateLimiterOptions): Ra
|
|
|
13
13
|
* options throw.
|
|
14
14
|
*/
|
|
15
15
|
export declare function checkRateLimit(event: RateLimitRequestEvent, name: string, options: CheckRateLimitOptions): Promise<Result<RateLimitDecision, CheckRateLimitErrorCode>>;
|
|
16
|
+
/**
|
|
17
|
+
* Gives back one request of a managed Rate Limit in the current window, for example when the work that the request
|
|
18
|
+
* paid for failed. Pass the same ID, policy, and `key` as the `requireRateLimit()` or `checkRateLimit()` call. Refund
|
|
19
|
+
* only a request that was allowed. The result is `refunded`, `unsupported` for the Cloudflare Rate Limiting binding,
|
|
20
|
+
* or `unavailable` when the driver failed. `error` is `RATE_LIMIT_R0013` for a request without a key.
|
|
21
|
+
*/
|
|
22
|
+
export declare function refundRateLimit(event: RateLimitRequestEvent, name: string, options: CheckRateLimitOptions): Promise<Result<RateLimitRefundResult, RefundRateLimitErrorCode>>;
|
|
16
23
|
/**
|
|
17
24
|
* Consumes one request from a managed Rate Limit inside a handler. Returns when the request is allowed. Otherwise
|
|
18
25
|
* it throws an HTTP error: `429` with `Retry-After` when the limit is reached, `503` when the limiter is unavailable.
|
|
@@ -21,4 +28,4 @@ export declare function checkRateLimit(event: RateLimitRequestEvent, name: strin
|
|
|
21
28
|
*/
|
|
22
29
|
export declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
|
|
23
30
|
//#endregion
|
|
24
|
-
export { type CheckRateLimitErrorCode, type CheckRateLimitOptions, type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitCounterSnapshot, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverName, type RateLimitDriverOutcome, type RateLimitDriverPeekOutcome, type RateLimitDriverPeekResult, type RateLimitDriverResetOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitOptions, type RateLimitPeekInspection, type RateLimitPeekResult, type RateLimitPolicy, type RateLimitRejectedAttemptBehavior, type RateLimitRequest, type RateLimitRequestEvent, type RateLimitResetInspection, type RateLimitResetResult, type RateLimitRuntimeConfig, type
|
|
31
|
+
export { type CheckRateLimitErrorCode, type CheckRateLimitOptions, type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitCounterSnapshot, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverName, type RateLimitDriverOutcome, type RateLimitDriverPeekOutcome, type RateLimitDriverPeekResult, type RateLimitDriverRefundOutcome, type RateLimitDriverResetOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitOptions, type RateLimitPeekInspection, type RateLimitPeekResult, type RateLimitPolicy, type RateLimitRefundResult, type RateLimitRejectedAttemptBehavior, type RateLimitRequest, type RateLimitRequestEvent, type RateLimitResetInspection, type RateLimitResetResult, type RateLimitRuntimeConfig, type RateLimiter, type RefundRateLimitErrorCode, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, peekRateLimit, resetRateLimit };
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { a as rateLimitPolicyKeys,
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { n as
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
|
|
2
|
+
import { a as rateLimitPolicyKeys, n as normalizeRateLimitPolicy, t as declaredRateLimitPolicy } from "./policy-BeyQ0vnc.js";
|
|
3
|
+
import { n as createRateLimiter } from "./kv-provider-DlgNQC-o.js";
|
|
4
|
+
import { i as resolveRateLimitDriver, n as getRuntimeRateLimiter } from "./state-Fq3rGFO3.js";
|
|
5
|
+
import { n as resetRateLimit, t as peekRateLimit } from "./counters-D4LANMAi.js";
|
|
6
|
+
import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-_Tz3DcpB.js";
|
|
6
7
|
import { toResultError } from "@vite-hub/runtime";
|
|
7
8
|
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
8
9
|
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
@@ -25,6 +26,7 @@ function getActiveCloudflareEnv() {
|
|
|
25
26
|
//#region src/guard.ts
|
|
26
27
|
const guardOptionKeys = {
|
|
27
28
|
checkRateLimit: /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]),
|
|
29
|
+
refundRateLimit: /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]),
|
|
28
30
|
requireRateLimit: /* @__PURE__ */ new Set([
|
|
29
31
|
...rateLimitPolicyKeys,
|
|
30
32
|
"code",
|
|
@@ -83,20 +85,31 @@ function getCloudflareRateLimiter(scope, name, policy) {
|
|
|
83
85
|
name
|
|
84
86
|
})];
|
|
85
87
|
}
|
|
86
|
-
async function
|
|
88
|
+
async function resolveRateLimitCall(event, name, options, guard) {
|
|
87
89
|
const id = typeof name === "string" ? name.trim() : "";
|
|
88
90
|
if (!id) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0010({ message: `\`${guard}()\` requires a non-empty stable ID.` });
|
|
89
91
|
const unknownKey = options && typeof options === "object" && !Array.isArray(options) ? Object.keys(options).find((key) => !guardOptionKeys[guard].has(key)) : void 0;
|
|
90
92
|
if (unknownKey) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0011({ message: `\`${guard}()\` does not support the "${unknownKey}" option.` });
|
|
91
93
|
if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0012({ message: `\`${guard}()\` key must be a non-empty string.` });
|
|
92
|
-
const
|
|
94
|
+
const resolved = normalizeRateLimitPolicy(options);
|
|
93
95
|
const driver = await resolveRateLimitDriver();
|
|
94
96
|
const scope = getRequestScope(event);
|
|
95
97
|
const key = options.key ?? getRequestKey(scope, driver) ?? (getViteHubTestMode() ? "test-client" : void 0);
|
|
96
98
|
if (!key) return [checkError("RATE_LIMIT_R0013", `[vitehub] \`${guard}()\` could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.`), void 0];
|
|
97
|
-
|
|
99
|
+
return [void 0, {
|
|
100
|
+
counter: driver === "cloudflare" && !isCloudflareRateLimitWindow(resolved.windowMs) ? "kv" : driver,
|
|
101
|
+
id,
|
|
102
|
+
key,
|
|
103
|
+
policy: declaredRateLimitPolicy(resolved),
|
|
104
|
+
scope
|
|
105
|
+
}];
|
|
106
|
+
}
|
|
107
|
+
async function consumeRateLimit(event, name, options, guard) {
|
|
108
|
+
const [callError, call] = await resolveRateLimitCall(event, name, options, guard);
|
|
109
|
+
if (callError) return [callError, void 0];
|
|
110
|
+
const [error, limiter] = call.counter === "cloudflare" ? getCloudflareRateLimiter(call.scope, call.id, call.policy) : [void 0, getRuntimeRateLimiter(call.counter, call.id, call.policy)];
|
|
98
111
|
if (error) return [error, void 0];
|
|
99
|
-
return [void 0, await limiter.consume({ key })];
|
|
112
|
+
return [void 0, await limiter.consume({ key: call.key })];
|
|
100
113
|
}
|
|
101
114
|
/**
|
|
102
115
|
* Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
|
|
@@ -108,6 +121,21 @@ async function consumeRateLimit(event, name, options, guard) {
|
|
|
108
121
|
async function checkRateLimit(event, name, options) {
|
|
109
122
|
return await consumeRateLimit(event, name, options, "checkRateLimit");
|
|
110
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Gives back one request of a managed Rate Limit in the current window, for example when the work that the request
|
|
126
|
+
* paid for failed. Pass the same ID, policy, and `key` as the `requireRateLimit()` or `checkRateLimit()` call. Refund
|
|
127
|
+
* only a request that was allowed. The result is `refunded`, `unsupported` for the Cloudflare Rate Limiting binding,
|
|
128
|
+
* or `unavailable` when the driver failed. `error` is `RATE_LIMIT_R0013` for a request without a key.
|
|
129
|
+
*/
|
|
130
|
+
async function refundRateLimit(event, name, options) {
|
|
131
|
+
const [error, call] = await resolveRateLimitCall(event, name, options, "refundRateLimit");
|
|
132
|
+
if (error) return [error, void 0];
|
|
133
|
+
if (call.counter === "cloudflare") return [void 0, {
|
|
134
|
+
reason: "The Cloudflare Rate Limiting binding exposes only limit(), which consumes a token. It cannot give back a request.",
|
|
135
|
+
status: "unsupported"
|
|
136
|
+
}];
|
|
137
|
+
return [void 0, await getRuntimeRateLimiter(call.counter, call.id, call.policy).refund({ key: call.key })];
|
|
138
|
+
}
|
|
111
139
|
function refusalText(options, option) {
|
|
112
140
|
const value = options?.[option];
|
|
113
141
|
if (value === void 0) return;
|
|
@@ -141,4 +169,4 @@ async function requireRateLimit(event, name, options) {
|
|
|
141
169
|
});
|
|
142
170
|
}
|
|
143
171
|
//#endregion
|
|
144
|
-
export { checkRateLimit, createRateLimiter, peekRateLimit, requireRateLimit, resetRateLimit };
|
|
172
|
+
export { checkRateLimit, createRateLimiter, peekRateLimit, refundRateLimit, requireRateLimit, resetRateLimit };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as RateLimitDriver } from "./types-
|
|
1
|
+
import { c as RateLimitDriver } from "./types-OzukEqHf.js";
|
|
2
2
|
import { Result } from "@vite-hub/runtime";
|
|
3
3
|
//#region src/drivers/kv.d.ts
|
|
4
4
|
/** `[error, data]`, as KV operations return it. */
|
|
@@ -8,21 +8,24 @@ type KVOperationResult<T> = Result<T>;
|
|
|
8
8
|
* atomic and set the TTL with the first increment, as the `redis`, `database`, and `upstash` drivers do.
|
|
9
9
|
*/
|
|
10
10
|
interface RateLimitKVStorage {
|
|
11
|
-
delete
|
|
11
|
+
delete?: (key: string) => Promise<KVOperationResult<void>>;
|
|
12
12
|
get: (key: string) => Promise<KVOperationResult<unknown>>;
|
|
13
13
|
increment: (key: string, ttl: number) => Promise<KVOperationResult<number>>;
|
|
14
14
|
}
|
|
15
15
|
interface KVRateLimitDriverOptions {
|
|
16
|
+
namespace?: string;
|
|
16
17
|
now?: () => number;
|
|
17
18
|
storage: RateLimitKVStorage;
|
|
18
19
|
}
|
|
19
20
|
interface KVRateLimitDriver extends RateLimitDriver {
|
|
20
21
|
peek: NonNullable<RateLimitDriver["peek"]>;
|
|
22
|
+
refund: NonNullable<RateLimitDriver["refund"]>;
|
|
21
23
|
reset: NonNullable<RateLimitDriver["reset"]>;
|
|
22
24
|
}
|
|
23
25
|
/**
|
|
24
26
|
* Counts fixed windows in a KV store with one atomic `increment` for each request. Every server process that uses the
|
|
25
|
-
* same store shares the counters. Rejected requests also increment the counter.
|
|
27
|
+
* same store shares the counters. Rejected requests also increment the counter. KV has no atomic decrement, so
|
|
28
|
+
* `refund()` increments a second counter, and `consume()` reads it only when the first counter passes the limit.
|
|
26
29
|
*/
|
|
27
30
|
declare function kvRateLimitDriver(options: KVRateLimitDriverOptions): KVRateLimitDriver;
|
|
28
31
|
//#endregion
|