@vite-hub/rate-limit 0.0.4 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -10
- package/dist/cli-Cniq99iX.d.ts +85 -0
- package/dist/cli.d.ts +16 -0
- package/dist/cli.js +273 -0
- package/dist/{cloudflare-BYZQ2tim.js → cloudflare-DUDRACVB.js} +7 -3
- package/dist/counters-pKORpgGd.d.ts +47 -0
- package/dist/counters-wdEMxDEY.js +106 -0
- package/dist/drivers/cloudflare.d.ts +6 -8
- package/dist/drivers/cloudflare.js +1 -1
- package/dist/drivers/memory.d.ts +7 -7
- package/dist/drivers/memory.js +34 -8
- package/dist/error-diagnostics-CTAC_bbr.js +56 -0
- package/dist/h3-v1-request-qoGwJr5-.js +235 -0
- package/dist/index.d.ts +11 -5
- package/dist/index.js +39 -41
- package/dist/inspect-D-FzyM_x.js +112 -0
- package/dist/limiter-DBrMI4vi.js +286 -0
- package/dist/operations-B09NnEjT.js +1438 -0
- package/dist/operations-Bu-xulNd.js +38 -0
- package/dist/operations-tNUdj3G4.d.ts +212 -0
- package/dist/operations.d.ts +14 -0
- package/dist/operations.js +244 -0
- package/dist/runtime.d.ts +4 -6
- package/dist/runtime.js +1 -1
- package/dist/state-Ct7zR8fD.js +43 -0
- package/dist/{types-DoyUiUt1.d.ts → types-CQEJpgtz.d.ts} +57 -3
- package/dist/vite.d.ts +325 -7
- package/dist/vite.js +467 -2137
- package/package.json +49 -14
- package/dist/limiter-CHaHluMr.js +0 -118
- package/dist/state-DB4uJN5P.js +0 -15
package/README.md
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
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
|
+
|
|
3
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.
|
|
4
9
|
|
|
5
|
-
Install this owner package when you need a direct Rate Limiter, a custom driver, or the
|
|
10
|
+
Install this owner package when you need a direct Rate Limiter, a custom driver, or the Vite integration without the full framework. If your application already uses the `vite-hub` framework distribution, enable Rate Limit there and import from `vite-hub/rate-limit` instead. See the [Rate Limit guide](https://vitehub.dev/docs/rate-limit) for that application setup.
|
|
6
11
|
|
|
7
12
|
## Install the owner package
|
|
8
13
|
|
|
@@ -42,6 +47,10 @@ node rate-limit.mjs
|
|
|
42
47
|
|
|
43
48
|
The first two calls consume the budget. The third call returns a limited decision.
|
|
44
49
|
|
|
50
|
+
The window must resolve to finite milliseconds greater than zero, up to JavaScript's timestamp limit of `8.64e15` milliseconds. Invalid policies fail when you create the limiter.
|
|
51
|
+
|
|
52
|
+
Reset timestamps must also be positive and at most `8.64e15`. The memory driver rejects a fixed window whose end exceeds that range before it stores a counter. It preserves the configured duration. Custom driver timestamps outside that range throw regardless of the failure policy.
|
|
53
|
+
|
|
45
54
|
```text
|
|
46
55
|
1: allowed
|
|
47
56
|
2: allowed
|
|
@@ -54,21 +63,23 @@ Direct Rate Limiters return a decision. Your code must stop the operation when `
|
|
|
54
63
|
|
|
55
64
|
| Need | Use |
|
|
56
65
|
| -------------------------------------------------------------------------------------- | ------------------------------------------ |
|
|
57
|
-
| Enforce a discovered Rate Limit in an H3 handler and let
|
|
66
|
+
| Enforce a discovered Rate Limit in an H3 handler and let Nitro generate host bindings | `requireRateLimit()` with `hubRateLimit()` |
|
|
67
|
+
| The same managed limit, but answer a limited request yourself, such as with a fallback | `checkRateLimit()` with `hubRateLimit()` |
|
|
58
68
|
| Return a custom response, use another transport, or supply storage yourself | `createRateLimiter()` with a direct driver |
|
|
59
69
|
|
|
60
70
|
The managed path selects and configures a driver. The direct path gives your code the decision and leaves deployment integration to the application.
|
|
61
71
|
|
|
62
72
|
## Let Vite manage an H3 guard
|
|
63
73
|
|
|
64
|
-
Register the
|
|
74
|
+
Register the integration with the Nitro Vite plugin. Nitro is the only host output:
|
|
65
75
|
|
|
66
76
|
```ts
|
|
67
77
|
import { hubRateLimit } from "@vite-hub/rate-limit/vite";
|
|
78
|
+
import { nitro } from "nitro/vite";
|
|
68
79
|
import { defineConfig } from "vite";
|
|
69
80
|
|
|
70
81
|
export default defineConfig({
|
|
71
|
-
plugins: [hubRateLimit({ namespace: "acme-image-service-production" })],
|
|
82
|
+
plugins: [hubRateLimit({ namespace: "acme-image-service-production" }), nitro()],
|
|
72
83
|
});
|
|
73
84
|
```
|
|
74
85
|
|
|
@@ -100,24 +111,35 @@ Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and
|
|
|
100
111
|
|
|
101
112
|
Use `createRateLimiter()` when the application selects the driver and handles the decision. A production driver must implement one atomic `consume()` operation for its backend. A generic KV `get()` followed by `set()` is not safe under concurrent requests.
|
|
102
113
|
|
|
103
|
-
Drivers return `[null, result]` after consuming the counter. They return `[error, undefined]` only for an expected operational outage. The limiter then returns `reason: "unavailable"` and sets `allowed` from the failure policy, which defaults to deny.
|
|
114
|
+
Drivers return `[null, result]` after consuming the counter. They return `[error, undefined]` only for an expected operational outage. The limiter then returns `reason: "unavailable"` and sets `allowed` from the failure policy, which defaults to deny. ViteHub-owned configuration errors, malformed provider results, and implementation defects throw Nostics diagnostics with `RATE_LIMIT_B####` or `RATE_LIMIT_R####` codes. Application driver errors keep their identity. See [Errors and diagnostics](https://vitehub.dev/docs/reference/errors-diagnostics).
|
|
104
115
|
|
|
105
116
|
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.
|
|
106
117
|
|
|
118
|
+
## Read or reset a counter
|
|
119
|
+
|
|
120
|
+
`limiter.peek({ key })` reads the counter of a key without consuming a token. `limiter.reset({ key })` deletes the counter. A driver supports them through optional `peek(input)` and `reset(input)` methods. Like `consume()`, `peek()` returns `[null, value]` or `[error, undefined]`. The `reset()` method returns a one-element tuple, `[null]` or `[error]`. When the driver omits a method, the result has `status: "unsupported"` and a `reason`.
|
|
121
|
+
|
|
122
|
+
| Driver | `peek()` | `reset()` |
|
|
123
|
+
| ---------- | ------------------------------------------------------------------------- | --------------------- |
|
|
124
|
+
| memory | `used`, `remaining`, and `resetAt` in this process. `used: 0` when no counter exists. | Deletes the counter. |
|
|
125
|
+
| cloudflare | `unsupported`. The binding exposes only `limit()`, which consumes a token. | `unsupported`. |
|
|
126
|
+
|
|
127
|
+
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.
|
|
128
|
+
|
|
107
129
|
## Public imports
|
|
108
130
|
|
|
109
131
|
| Import | Purpose |
|
|
110
132
|
| ----------------------------------------- | ------------------------------------------------------------------------- |
|
|
111
|
-
| `@vite-hub/rate-limit` | `requireRateLimit()`, `createRateLimiter()`, and public contract types
|
|
133
|
+
| `@vite-hub/rate-limit` | `requireRateLimit()`, `checkRateLimit()`, `createRateLimiter()`, `peekRateLimit()`, `resetRateLimit()`, and public contract types |
|
|
112
134
|
| `@vite-hub/rate-limit/drivers/memory` | Process-local fixed-window driver |
|
|
113
135
|
| `@vite-hub/rate-limit/drivers/cloudflare` | Direct adapter for a request-scoped Cloudflare Rate Limiting binding |
|
|
114
|
-
| `@vite-hub/rate-limit/vite` | Source discovery, runtime setup, manifest generation, and
|
|
136
|
+
| `@vite-hub/rate-limit/vite` | Source discovery, Nitro runtime setup, manifest generation, and Cloudflare bindings |
|
|
115
137
|
|
|
116
|
-
`@vite-hub/rate-limit/runtime`
|
|
138
|
+
`@vite-hub/rate-limit/runtime`, `@vite-hub/rate-limit/operations`, and `@vite-hub/rate-limit/cli` are reserved for framework integrations. Application code should use the guard or a direct Rate Limiter.
|
|
117
139
|
|
|
118
140
|
## Go deeper
|
|
119
141
|
|
|
120
|
-
- [Rate Limit guide](https://vitehub.dev/docs/
|
|
121
|
-
- [Rate Limit Capability for Agents](https://vitehub.dev/docs/
|
|
142
|
+
- [Rate Limit guide](https://vitehub.dev/docs/rate-limit)
|
|
143
|
+
- [Rate Limit Capability for Agents](https://vitehub.dev/docs/rate-limit/agent-capability)
|
|
122
144
|
- [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
|
|
123
145
|
- [Public import paths](https://vitehub.dev/docs/reference/import-paths)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Diagnostic } from "nostics";
|
|
2
|
+
//#region ../internal/src/provision.d.ts
|
|
3
|
+
type ProvisionProvider = "cloudflare" | "vercel";
|
|
4
|
+
interface ProvisionLogger {
|
|
5
|
+
log: (message: string) => void;
|
|
6
|
+
warn: (message: string) => void;
|
|
7
|
+
}
|
|
8
|
+
interface ProvisionContext {
|
|
9
|
+
env: Record<string, string | undefined>;
|
|
10
|
+
fetch: typeof globalThis.fetch;
|
|
11
|
+
logger: ProvisionLogger;
|
|
12
|
+
markPlanUnchecked?: () => void;
|
|
13
|
+
}
|
|
14
|
+
interface ProvisionState {
|
|
15
|
+
cloudflare?: Record<string, Record<string, string>>;
|
|
16
|
+
vercel?: Record<string, Record<string, string>>;
|
|
17
|
+
}
|
|
18
|
+
interface ProvisionResult {
|
|
19
|
+
ids?: ProvisionState;
|
|
20
|
+
}
|
|
21
|
+
interface ProvisionAction {
|
|
22
|
+
kind: string;
|
|
23
|
+
name: string;
|
|
24
|
+
exists: boolean;
|
|
25
|
+
pending?: boolean;
|
|
26
|
+
apply: () => Promise<ProvisionResult>;
|
|
27
|
+
}
|
|
28
|
+
interface ProvisionStep {
|
|
29
|
+
id: string;
|
|
30
|
+
provider: ProvisionProvider;
|
|
31
|
+
plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region ../internal/src/cli.d.ts
|
|
35
|
+
interface ViteHubCliStreams {
|
|
36
|
+
stderr: {
|
|
37
|
+
write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
|
|
38
|
+
};
|
|
39
|
+
stdout: {
|
|
40
|
+
write: (chunk: string | Uint8Array) => unknown;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
interface ViteHubCliSpawnResult {
|
|
44
|
+
exitCode: number | null;
|
|
45
|
+
signal?: NodeJS.Signals | null;
|
|
46
|
+
}
|
|
47
|
+
interface ViteHubCliSpawnOptions {
|
|
48
|
+
cwd?: string;
|
|
49
|
+
env?: NodeJS.ProcessEnv;
|
|
50
|
+
stderr?: "inherit" | "pipe";
|
|
51
|
+
stdout?: "inherit" | "pipe";
|
|
52
|
+
}
|
|
53
|
+
type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
|
|
54
|
+
interface ViteHubCliContext extends ViteHubCliStreams {
|
|
55
|
+
cwd: string;
|
|
56
|
+
env: NodeJS.ProcessEnv;
|
|
57
|
+
/** Replaces `fetch` for commands that call a running app, so tests need no server. */
|
|
58
|
+
fetch?: typeof fetch;
|
|
59
|
+
rootDir: string;
|
|
60
|
+
spawn: ViteHubCliSpawn;
|
|
61
|
+
}
|
|
62
|
+
interface ViteHubCliFeature {
|
|
63
|
+
description?: string;
|
|
64
|
+
name: string;
|
|
65
|
+
run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
|
|
66
|
+
usage?: string;
|
|
67
|
+
}
|
|
68
|
+
interface ViteHubCliCommandNamespace {
|
|
69
|
+
/** The feature that `vitehub <name>` runs when no feature is named. */
|
|
70
|
+
defaultFeature?: string;
|
|
71
|
+
description?: string;
|
|
72
|
+
features: ViteHubCliFeature[];
|
|
73
|
+
name: string;
|
|
74
|
+
}
|
|
75
|
+
interface ViteHubCliContributor {
|
|
76
|
+
namespaces: ViteHubCliCommandNamespace[];
|
|
77
|
+
provision?: ProvisionStep[];
|
|
78
|
+
}
|
|
79
|
+
type ViteHubCliContributorFactory = () => ViteHubCliContributor | undefined | Promise<ViteHubCliContributor | undefined>;
|
|
80
|
+
interface ViteHubCliPluginMetadata {
|
|
81
|
+
cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
|
|
82
|
+
}
|
|
83
|
+
type StdoutWriteCallback = (error?: Error | null) => void;
|
|
84
|
+
//#endregion
|
|
85
|
+
export { ViteHubCliStreams as i, ViteHubCliContributor as n, ViteHubCliPluginMetadata as r, ViteHubCliContext as t };
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-Cniq99iX.js";
|
|
2
|
+
//#region src/cli.d.ts
|
|
3
|
+
export type RateLimitCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
|
|
4
|
+
export interface RateLimitCliOptions {
|
|
5
|
+
/** Asks whether `reset` may delete a counter. Defaults to a prompt on a terminal, and refuses without one. */
|
|
6
|
+
confirm?: (question: string) => boolean | Promise<boolean>;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Runs one `vitehub rate-limit` command through the `rate-limit.*` operations, on the dev server of this project or on a
|
|
11
|
+
* deployed app with `--url`.
|
|
12
|
+
* `args[0]` is the command name, `peek` or `reset`.
|
|
13
|
+
*/
|
|
14
|
+
export declare function runRateLimitCli(args: string[], context: RateLimitCliContext, options?: RateLimitCliOptions): Promise<number>;
|
|
15
|
+
export declare function createRateLimitCliContributor(options?: RateLimitCliOptions): ViteHubCliContributor;
|
|
16
|
+
//#endregion
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
|
|
2
|
+
import { t as redactInspectionText } from "./inspect-D-FzyM_x.js";
|
|
3
|
+
import { n as callOperationFromCli, y as readViteHubDevTargetOption } from "./operations-B09NnEjT.js";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
//#region src/cli.ts
|
|
7
|
+
const rateLimitDevTargetErrors = {
|
|
8
|
+
invalidInlineTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
|
|
9
|
+
invalidTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
|
|
10
|
+
missingValue: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message })
|
|
11
|
+
};
|
|
12
|
+
const rateLimitCommands = [{
|
|
13
|
+
description: "Show the counter of one key without consuming a token.",
|
|
14
|
+
name: "peek"
|
|
15
|
+
}, {
|
|
16
|
+
description: "Delete the counter of one key, where the provider supports it.",
|
|
17
|
+
name: "reset"
|
|
18
|
+
}];
|
|
19
|
+
function commandUsage(command) {
|
|
20
|
+
return `vitehub rate-limit ${command.name} <id> <key> [--json]${command.name === "reset" ? " [--yes]" : ""} [--url <url>]`;
|
|
21
|
+
}
|
|
22
|
+
function writeUsage(command, stream) {
|
|
23
|
+
stream.write([
|
|
24
|
+
`Usage: ${commandUsage(command)}`,
|
|
25
|
+
"",
|
|
26
|
+
command.description,
|
|
27
|
+
"The command runs the rate-limit operation of the app: on the dev server of this project, or on a deployed app with --url.",
|
|
28
|
+
"`<id>` is the stable ID of `requireRateLimit()`. `<key>` is the limited key, for example a client IP or user ID.",
|
|
29
|
+
"",
|
|
30
|
+
"Use -- before a key that starts with a dash.",
|
|
31
|
+
"",
|
|
32
|
+
"Options:",
|
|
33
|
+
...command.name === "reset" ? [" --yes, -y Reset without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
|
|
34
|
+
" --json Print JSON.",
|
|
35
|
+
" --url <url> Deployed app URL. Credentials come from VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_*. Defaults to the dev server of this project.",
|
|
36
|
+
" --timeout <ms> Request timeout.",
|
|
37
|
+
" -h, --help Show this help.",
|
|
38
|
+
""
|
|
39
|
+
].join("\n"));
|
|
40
|
+
}
|
|
41
|
+
function parseArgs(args) {
|
|
42
|
+
const parsed = {
|
|
43
|
+
help: false,
|
|
44
|
+
json: false,
|
|
45
|
+
yes: false
|
|
46
|
+
};
|
|
47
|
+
let positionalOnly = false;
|
|
48
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
49
|
+
const arg = args[index];
|
|
50
|
+
if (!positionalOnly && arg === "--") {
|
|
51
|
+
positionalOnly = true;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (!positionalOnly && (arg === "-h" || arg === "--help")) {
|
|
55
|
+
parsed.help = true;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (!positionalOnly && (arg === "--yes" || arg === "-y")) {
|
|
59
|
+
parsed.yes = true;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (!positionalOnly && arg === "--json") {
|
|
63
|
+
parsed.json = true;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const targetOption = positionalOnly ? void 0 : readViteHubDevTargetOption(args, index, parsed, rateLimitDevTargetErrors);
|
|
67
|
+
if (targetOption !== void 0) {
|
|
68
|
+
index += targetOption;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (!positionalOnly && arg.startsWith("-")) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: `Unknown option: ${arg}.` });
|
|
72
|
+
if (parsed.name === void 0) {
|
|
73
|
+
parsed.name = arg;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (parsed.key === void 0) {
|
|
77
|
+
parsed.key = arg;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: `Unexpected argument: ${arg}.` });
|
|
81
|
+
}
|
|
82
|
+
if (!parsed.help && !parsed.name) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: "Missing Rate Limit ID." });
|
|
83
|
+
if (!parsed.help && !parsed.key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: "Missing Rate Limit key." });
|
|
84
|
+
return parsed;
|
|
85
|
+
}
|
|
86
|
+
function table(rows) {
|
|
87
|
+
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
88
|
+
return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")).join("\n");
|
|
89
|
+
}
|
|
90
|
+
function scopeNotice(scope) {
|
|
91
|
+
return scope === "process" ? "Scope: process. The counter exists only in this server process." : `Scope: ${scope}.`;
|
|
92
|
+
}
|
|
93
|
+
function formatPeek(result) {
|
|
94
|
+
const header = `Rate Limit ${result.name}, key ${result.key}\nProvider: ${result.provider}\n`;
|
|
95
|
+
if (result.status !== "known") return `${header}${result.status === "unused" ? "No counter" : "Counter unknown"}: ${result.reason}\n`;
|
|
96
|
+
return `${header}${scopeNotice(result.scope)}\n${table([[
|
|
97
|
+
"LIMIT",
|
|
98
|
+
"WINDOW",
|
|
99
|
+
"USED",
|
|
100
|
+
"REMAINING",
|
|
101
|
+
"RESETS AT"
|
|
102
|
+
], ...result.counters.map((counter) => [
|
|
103
|
+
String(counter.limit),
|
|
104
|
+
counter.window,
|
|
105
|
+
String(counter.used),
|
|
106
|
+
String(counter.remaining),
|
|
107
|
+
counter.resetAt === void 0 ? "-" : new Date(counter.resetAt).toISOString()
|
|
108
|
+
])])}\n`;
|
|
109
|
+
}
|
|
110
|
+
function formatReset(result) {
|
|
111
|
+
if (result.status !== "reset") return `Rate Limit ${result.name}, key ${result.key}\nProvider: ${result.provider}\nNot reset: ${result.reason}\n`;
|
|
112
|
+
return `Reset Rate Limit ${result.name} for key ${result.key}.\nProvider: ${result.provider}\n${scopeNotice(result.scope)}\n`;
|
|
113
|
+
}
|
|
114
|
+
const windowSchema = v.custom((value) => v.is(v.pipe(v.string(), v.regex(/^\d+(?:\.\d+)?(?:ms|s|m|h|d)$/)), value));
|
|
115
|
+
const finiteNumber = v.pipe(v.number(), v.finite());
|
|
116
|
+
const targetFields = {
|
|
117
|
+
key: v.string(),
|
|
118
|
+
name: v.string(),
|
|
119
|
+
provider: v.picklist(["memory", "cloudflare"])
|
|
120
|
+
};
|
|
121
|
+
const scopeSchema = v.picklist([
|
|
122
|
+
"global",
|
|
123
|
+
"location",
|
|
124
|
+
"process"
|
|
125
|
+
]);
|
|
126
|
+
const counterSchema = v.object({
|
|
127
|
+
limit: finiteNumber,
|
|
128
|
+
remaining: finiteNumber,
|
|
129
|
+
resetAt: v.optional(v.pipe(finiteNumber, v.minValue(-864e13), v.maxValue(864e13))),
|
|
130
|
+
used: finiteNumber,
|
|
131
|
+
window: windowSchema,
|
|
132
|
+
windowMs: finiteNumber
|
|
133
|
+
});
|
|
134
|
+
const unavailableSchema = v.object({
|
|
135
|
+
...targetFields,
|
|
136
|
+
reason: v.string(),
|
|
137
|
+
status: v.literal("unavailable")
|
|
138
|
+
});
|
|
139
|
+
const unsupportedSchema = v.object({
|
|
140
|
+
...targetFields,
|
|
141
|
+
reason: v.string(),
|
|
142
|
+
status: v.literal("unsupported")
|
|
143
|
+
});
|
|
144
|
+
const peekSchema = v.variant("status", [
|
|
145
|
+
v.object({
|
|
146
|
+
...targetFields,
|
|
147
|
+
counters: v.array(counterSchema),
|
|
148
|
+
scope: scopeSchema,
|
|
149
|
+
status: v.literal("known")
|
|
150
|
+
}),
|
|
151
|
+
v.object({
|
|
152
|
+
...targetFields,
|
|
153
|
+
reason: v.string(),
|
|
154
|
+
status: v.literal("unused")
|
|
155
|
+
}),
|
|
156
|
+
unavailableSchema,
|
|
157
|
+
unsupportedSchema
|
|
158
|
+
]);
|
|
159
|
+
const resetSchema = v.variant("status", [
|
|
160
|
+
v.object({
|
|
161
|
+
...targetFields,
|
|
162
|
+
scope: scopeSchema,
|
|
163
|
+
status: v.literal("reset")
|
|
164
|
+
}),
|
|
165
|
+
unavailableSchema,
|
|
166
|
+
unsupportedSchema
|
|
167
|
+
]);
|
|
168
|
+
function parseInspection(operation, value) {
|
|
169
|
+
if (operation === "peek") {
|
|
170
|
+
const parsed = v.safeParse(peekSchema, value);
|
|
171
|
+
return parsed.success ? {
|
|
172
|
+
operation,
|
|
173
|
+
value: parsed.output
|
|
174
|
+
} : void 0;
|
|
175
|
+
}
|
|
176
|
+
const parsed = v.safeParse(resetSchema, value);
|
|
177
|
+
return parsed.success ? {
|
|
178
|
+
operation,
|
|
179
|
+
value: parsed.output
|
|
180
|
+
} : void 0;
|
|
181
|
+
}
|
|
182
|
+
function writeFailure(parsed, context, failure) {
|
|
183
|
+
const message = redactInspectionText(failure.message);
|
|
184
|
+
if (parsed.json) context.stdout.write(`${JSON.stringify({ error: {
|
|
185
|
+
...failure,
|
|
186
|
+
message
|
|
187
|
+
} }, null, 2)}\n`);
|
|
188
|
+
else context.stderr.write(`${message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
|
|
189
|
+
return 1;
|
|
190
|
+
}
|
|
191
|
+
async function askOnTerminal(question) {
|
|
192
|
+
const terminal = createInterface({
|
|
193
|
+
input: process.stdin,
|
|
194
|
+
output: process.stderr
|
|
195
|
+
});
|
|
196
|
+
try {
|
|
197
|
+
return /^y(es)?$/i.test((await terminal.question(question)).trim());
|
|
198
|
+
} finally {
|
|
199
|
+
terminal.close();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async function runRateLimitCommand(command, args, context, options) {
|
|
203
|
+
let parsed;
|
|
204
|
+
try {
|
|
205
|
+
parsed = parseArgs(args);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
const terminator = args.indexOf("--");
|
|
208
|
+
if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeFailure({ json: true }, context, { message: error instanceof Error ? error.message : String(error) });
|
|
209
|
+
writeFailure({ json: false }, context, { message: error instanceof Error ? error.message : String(error) });
|
|
210
|
+
writeUsage(command, context.stderr);
|
|
211
|
+
return 1;
|
|
212
|
+
}
|
|
213
|
+
if (parsed.help) {
|
|
214
|
+
writeUsage(command, context.stdout);
|
|
215
|
+
return 0;
|
|
216
|
+
}
|
|
217
|
+
if (command.name === "reset" && !parsed.yes) {
|
|
218
|
+
const question = `Reset the Rate Limit ${parsed.name} for key ${redactInspectionText(parsed.key)}? The next request starts a new window. [y/N] `;
|
|
219
|
+
if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return writeFailure(parsed, context, {
|
|
220
|
+
code: "RATE_LIMIT_NOT_CONFIRMED",
|
|
221
|
+
fix: "Run it again with --yes.",
|
|
222
|
+
message: "rate-limit reset deletes a counter and was not confirmed."
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
const called = await callOperationFromCli({
|
|
226
|
+
env: context.env,
|
|
227
|
+
fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
|
|
228
|
+
rootDir: context.rootDir,
|
|
229
|
+
...parsed.timeout ? { timeout: parsed.timeout } : {},
|
|
230
|
+
...parsed.url ? { url: parsed.url } : {}
|
|
231
|
+
}, `rate-limit.${command.name}`, {
|
|
232
|
+
key: parsed.key,
|
|
233
|
+
name: parsed.name
|
|
234
|
+
});
|
|
235
|
+
if (!called.ok) return writeFailure(parsed, context, {
|
|
236
|
+
code: called.code,
|
|
237
|
+
message: called.message,
|
|
238
|
+
...called.fix ? { fix: called.fix } : {}
|
|
239
|
+
});
|
|
240
|
+
const result = parseInspection(command.name, called.value);
|
|
241
|
+
if (!result) return writeFailure(parsed, context, { message: "The rate-limit operation answered with an invalid result." });
|
|
242
|
+
const output = result.operation === "peek" ? formatPeek(result.value) : formatReset(result.value);
|
|
243
|
+
context.stdout.write(parsed.json ? `${JSON.stringify(result.value, null, 2)}\n` : output);
|
|
244
|
+
return result.value.status === "unsupported" || result.value.status === "unavailable" ? 1 : 0;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Runs one `vitehub rate-limit` command through the `rate-limit.*` operations, on the dev server of this project or on a
|
|
248
|
+
* deployed app with `--url`.
|
|
249
|
+
* `args[0]` is the command name, `peek` or `reset`.
|
|
250
|
+
*/
|
|
251
|
+
async function runRateLimitCli(args, context, options = {}) {
|
|
252
|
+
const [name, ...rest] = args;
|
|
253
|
+
const command = rateLimitCommands.find((entry) => entry.name === name);
|
|
254
|
+
if (!command) {
|
|
255
|
+
context.stderr.write(`${name ? `Unknown rate-limit command: ${redactInspectionText(name)}\n` : ""}Commands: ${rateLimitCommands.map((entry) => entry.name).join(", ")}\n`);
|
|
256
|
+
return 1;
|
|
257
|
+
}
|
|
258
|
+
return await runRateLimitCommand(command, rest, context, options);
|
|
259
|
+
}
|
|
260
|
+
function createRateLimitCliContributor(options = {}) {
|
|
261
|
+
return { namespaces: [{
|
|
262
|
+
description: "Read and reset Rate Limit counters in the running app.",
|
|
263
|
+
features: rateLimitCommands.map((command) => ({
|
|
264
|
+
description: command.description,
|
|
265
|
+
name: command.name,
|
|
266
|
+
run: async (args, context) => await runRateLimitCommand(command, args, context, options),
|
|
267
|
+
usage: commandUsage(command)
|
|
268
|
+
})),
|
|
269
|
+
name: "rate-limit"
|
|
270
|
+
}] };
|
|
271
|
+
}
|
|
272
|
+
//#endregion
|
|
273
|
+
export { createRateLimitCliContributor, runRateLimitCli };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
|
|
1
2
|
//#region ../internal/src/integrations/hex.ts
|
|
2
3
|
const textEncoder = new TextEncoder();
|
|
3
4
|
new TextDecoder();
|
|
@@ -17,7 +18,7 @@ function isBinding(value) {
|
|
|
17
18
|
return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
|
|
18
19
|
}
|
|
19
20
|
function cloudflareRateLimitDriver(options) {
|
|
20
|
-
if (!isBinding(options?.binding)) throw
|
|
21
|
+
if (!isBinding(options?.binding)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0004({ message: "[vitehub] cloudflareRateLimitDriver() requires a Cloudflare Rate Limit binding." });
|
|
21
22
|
return {
|
|
22
23
|
capabilities: {
|
|
23
24
|
enforcement: "best-effort",
|
|
@@ -30,9 +31,12 @@ function cloudflareRateLimitDriver(options) {
|
|
|
30
31
|
try {
|
|
31
32
|
result = await options.binding.limit({ key: input.key });
|
|
32
33
|
} catch (cause) {
|
|
33
|
-
return [
|
|
34
|
+
return [rateLimitErrorDiagnostics.RATE_LIMIT_R0005({
|
|
35
|
+
message: "[vitehub] Cloudflare Rate Limit binding failed.",
|
|
36
|
+
cause
|
|
37
|
+
}), void 0];
|
|
34
38
|
}
|
|
35
|
-
if (!result || typeof result.success !== "boolean") throw
|
|
39
|
+
if (!result || typeof result.success !== "boolean") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0006({ message: "[vitehub] Cloudflare Rate Limit binding returned an invalid result." });
|
|
36
40
|
return [null, { allowed: result.success }];
|
|
37
41
|
},
|
|
38
42
|
name: "cloudflare"
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { C as RateLimitRuntimeConfig, r as RateLimitCounterScope, w as RateLimitWindow } from "./types-CQEJpgtz.js";
|
|
2
|
+
//#region src/counters.d.ts
|
|
3
|
+
type RateLimitRuntimeProvider = RateLimitRuntimeConfig["provider"];
|
|
4
|
+
/** Counter of one key for one policy. `peekRateLimit()` reads it without consuming a token. */
|
|
5
|
+
interface RateLimitCounterSnapshot {
|
|
6
|
+
limit: number;
|
|
7
|
+
remaining: number;
|
|
8
|
+
/** End of the current window in epoch milliseconds. Absent when the key has no active counter. */
|
|
9
|
+
resetAt?: number;
|
|
10
|
+
used: number;
|
|
11
|
+
window: RateLimitWindow;
|
|
12
|
+
windowMs: number;
|
|
13
|
+
}
|
|
14
|
+
interface RateLimitCounterTarget {
|
|
15
|
+
key: string;
|
|
16
|
+
name: string;
|
|
17
|
+
provider: RateLimitRuntimeProvider;
|
|
18
|
+
}
|
|
19
|
+
type RateLimitPeekInspection = (RateLimitCounterTarget & {
|
|
20
|
+
/** One entry for each policy that requests used with this name. Usually one. */
|
|
21
|
+
counters: RateLimitCounterSnapshot[];
|
|
22
|
+
/** Where the counter lives. A `process` counter exists only in the current server process. */
|
|
23
|
+
scope: RateLimitCounterScope;
|
|
24
|
+
status: "known";
|
|
25
|
+
}) | (RateLimitCounterTarget & {
|
|
26
|
+
reason: string;
|
|
27
|
+
status: "unavailable" | "unsupported" | "unused";
|
|
28
|
+
});
|
|
29
|
+
type RateLimitResetInspection = (RateLimitCounterTarget & {
|
|
30
|
+
scope: RateLimitCounterScope;
|
|
31
|
+
status: "reset";
|
|
32
|
+
}) | (RateLimitCounterTarget & {
|
|
33
|
+
reason: string;
|
|
34
|
+
status: "unavailable" | "unsupported";
|
|
35
|
+
});
|
|
36
|
+
/**
|
|
37
|
+
* Reads the counter of one key without consuming a token. The result reports `unsupported` when the configured
|
|
38
|
+
* provider cannot read counters, and `unused` when no request used the Rate Limit in this process.
|
|
39
|
+
*/
|
|
40
|
+
declare function peekRateLimit(name: string, key: string): Promise<RateLimitPeekInspection>;
|
|
41
|
+
/**
|
|
42
|
+
* Deletes the counter of one key, so the next request starts a new window. A key without a counter also returns
|
|
43
|
+
* `reset`. The result reports `unsupported` when the configured provider cannot reset counters.
|
|
44
|
+
*/
|
|
45
|
+
declare function resetRateLimit(name: string, key: string): Promise<RateLimitResetInspection>;
|
|
46
|
+
//#endregion
|
|
47
|
+
export { resetRateLimit as a, peekRateLimit as i, RateLimitPeekInspection as n, RateLimitResetInspection as r, RateLimitCounterSnapshot as t };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
|
|
2
|
+
import { n as getRateLimitRuntimeConfig, r as listMemoryRateLimiters } from "./state-Ct7zR8fD.js";
|
|
3
|
+
import * as v from "valibot";
|
|
4
|
+
//#region src/counters.ts
|
|
5
|
+
/** Reason that Cloudflare counters are not readable. The binding exposes only `limit({ key })`. */
|
|
6
|
+
const cloudflareRateLimitCounterUnsupportedReason = "The Cloudflare Rate Limiting binding exposes only limit(), which consumes a token. It cannot read or reset a counter.";
|
|
7
|
+
const unusedReason = "No request used this Rate Limit in this process since it started, so no counter exists.";
|
|
8
|
+
function unavailableReason(cause) {
|
|
9
|
+
return `The Rate Limit driver failed: ${cause instanceof Error ? cause.message : String(cause)}`;
|
|
10
|
+
}
|
|
11
|
+
function assertTarget(name, key) {
|
|
12
|
+
if (!v.is(v.string(), name) || !name.trim()) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0039({ message: "[vitehub] Rate Limit name must be a non-empty string." });
|
|
13
|
+
if (!v.is(v.string(), key) || !key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0039({ message: "[vitehub] Rate Limit key must be a non-empty string." });
|
|
14
|
+
}
|
|
15
|
+
function limitersFor(target) {
|
|
16
|
+
return target.provider === "memory" ? listMemoryRateLimiters(target.name) : void 0;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Reads the counter of one key without consuming a token. The result reports `unsupported` when the configured
|
|
20
|
+
* provider cannot read counters, and `unused` when no request used the Rate Limit in this process.
|
|
21
|
+
*/
|
|
22
|
+
async function peekRateLimit(name, key) {
|
|
23
|
+
assertTarget(name, key);
|
|
24
|
+
const target = {
|
|
25
|
+
key,
|
|
26
|
+
name: name.trim(),
|
|
27
|
+
provider: getRateLimitRuntimeConfig().provider
|
|
28
|
+
};
|
|
29
|
+
const limiters = limitersFor(target);
|
|
30
|
+
if (!limiters) return {
|
|
31
|
+
...target,
|
|
32
|
+
reason: cloudflareRateLimitCounterUnsupportedReason,
|
|
33
|
+
status: "unsupported"
|
|
34
|
+
};
|
|
35
|
+
if (limiters.length === 0) return {
|
|
36
|
+
...target,
|
|
37
|
+
reason: unusedReason,
|
|
38
|
+
status: "unused"
|
|
39
|
+
};
|
|
40
|
+
const counters = [];
|
|
41
|
+
for (const limiter of limiters) {
|
|
42
|
+
const result = await limiter.peek({ key });
|
|
43
|
+
if (result.status === "unsupported") return {
|
|
44
|
+
...target,
|
|
45
|
+
reason: result.reason,
|
|
46
|
+
status: "unsupported"
|
|
47
|
+
};
|
|
48
|
+
if (result.status === "unavailable") return {
|
|
49
|
+
...target,
|
|
50
|
+
reason: unavailableReason(result.cause),
|
|
51
|
+
status: "unavailable"
|
|
52
|
+
};
|
|
53
|
+
counters.push({
|
|
54
|
+
limit: result.limit,
|
|
55
|
+
remaining: result.remaining,
|
|
56
|
+
...result.resetAt === void 0 ? {} : { resetAt: result.resetAt },
|
|
57
|
+
used: result.used,
|
|
58
|
+
window: limiter.policy.window,
|
|
59
|
+
windowMs: result.windowMs
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
...target,
|
|
64
|
+
counters,
|
|
65
|
+
scope: limiters[0].capabilities.scope,
|
|
66
|
+
status: "known"
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Deletes the counter of one key, so the next request starts a new window. A key without a counter also returns
|
|
71
|
+
* `reset`. The result reports `unsupported` when the configured provider cannot reset counters.
|
|
72
|
+
*/
|
|
73
|
+
async function resetRateLimit(name, key) {
|
|
74
|
+
assertTarget(name, key);
|
|
75
|
+
const target = {
|
|
76
|
+
key,
|
|
77
|
+
name: name.trim(),
|
|
78
|
+
provider: getRateLimitRuntimeConfig().provider
|
|
79
|
+
};
|
|
80
|
+
const limiters = limitersFor(target);
|
|
81
|
+
if (!limiters) return {
|
|
82
|
+
...target,
|
|
83
|
+
reason: cloudflareRateLimitCounterUnsupportedReason,
|
|
84
|
+
status: "unsupported"
|
|
85
|
+
};
|
|
86
|
+
for (const limiter of limiters) {
|
|
87
|
+
const result = await limiter.reset({ key });
|
|
88
|
+
if (result.status === "unsupported") return {
|
|
89
|
+
...target,
|
|
90
|
+
reason: result.reason,
|
|
91
|
+
status: "unsupported"
|
|
92
|
+
};
|
|
93
|
+
if (result.status === "unavailable") return {
|
|
94
|
+
...target,
|
|
95
|
+
reason: unavailableReason(result.cause),
|
|
96
|
+
status: "unavailable"
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
...target,
|
|
101
|
+
scope: limiters[0]?.capabilities.scope ?? "process",
|
|
102
|
+
status: "reset"
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { resetRateLimit as n, peekRateLimit as t };
|