@vantedev/groundwork 0.0.0-stage → 0.2.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/CHANGELOG.md +87 -0
- package/LICENSE +21 -0
- package/README.md +350 -2
- package/dist/api-keys/api-keys.d.ts +56 -0
- package/dist/api-keys/api-keys.d.ts.map +1 -0
- package/dist/api-keys/api-keys.js +619 -0
- package/dist/api-keys/api-keys.js.map +1 -0
- package/dist/api-keys/audit.d.ts +17 -0
- package/dist/api-keys/audit.d.ts.map +1 -0
- package/dist/api-keys/audit.js +76 -0
- package/dist/api-keys/audit.js.map +1 -0
- package/dist/api-keys/format.d.ts +32 -0
- package/dist/api-keys/format.d.ts.map +1 -0
- package/dist/api-keys/format.js +92 -0
- package/dist/api-keys/format.js.map +1 -0
- package/dist/api-keys/index.d.ts +25 -0
- package/dist/api-keys/index.d.ts.map +1 -0
- package/dist/api-keys/index.js +23 -0
- package/dist/api-keys/index.js.map +1 -0
- package/dist/api-keys/policy.d.ts +16 -0
- package/dist/api-keys/policy.d.ts.map +1 -0
- package/dist/api-keys/policy.js +95 -0
- package/dist/api-keys/policy.js.map +1 -0
- package/dist/api-keys/responses.d.ts +6 -0
- package/dist/api-keys/responses.d.ts.map +1 -0
- package/dist/api-keys/responses.js +54 -0
- package/dist/api-keys/responses.js.map +1 -0
- package/dist/api-keys/scopes.d.ts +13 -0
- package/dist/api-keys/scopes.d.ts.map +1 -0
- package/dist/api-keys/scopes.js +49 -0
- package/dist/api-keys/scopes.js.map +1 -0
- package/dist/api-keys/types.d.ts +173 -0
- package/dist/api-keys/types.d.ts.map +1 -0
- package/dist/api-keys/types.js +2 -0
- package/dist/api-keys/types.js.map +1 -0
- package/dist/audit/audit-log.d.ts +35 -0
- package/dist/audit/audit-log.d.ts.map +1 -0
- package/dist/audit/audit-log.js +277 -0
- package/dist/audit/audit-log.js.map +1 -0
- package/dist/audit/cursor.d.ts +13 -0
- package/dist/audit/cursor.d.ts.map +1 -0
- package/dist/audit/cursor.js +26 -0
- package/dist/audit/cursor.js.map +1 -0
- package/dist/audit/diff.d.ts +19 -0
- package/dist/audit/diff.d.ts.map +1 -0
- package/dist/audit/diff.js +59 -0
- package/dist/audit/diff.js.map +1 -0
- package/dist/audit/index.d.ts +25 -0
- package/dist/audit/index.d.ts.map +1 -0
- package/dist/audit/index.js +24 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/json.d.ts +23 -0
- package/dist/audit/json.d.ts.map +1 -0
- package/dist/audit/json.js +120 -0
- package/dist/audit/json.js.map +1 -0
- package/dist/audit/types.d.ts +118 -0
- package/dist/audit/types.d.ts.map +1 -0
- package/dist/audit/types.js +2 -0
- package/dist/audit/types.js.map +1 -0
- package/dist/idempotency/http.d.ts +27 -0
- package/dist/idempotency/http.d.ts.map +1 -0
- package/dist/idempotency/http.js +130 -0
- package/dist/idempotency/http.js.map +1 -0
- package/dist/idempotency/idempotency.d.ts +45 -0
- package/dist/idempotency/idempotency.d.ts.map +1 -0
- package/dist/idempotency/idempotency.js +302 -0
- package/dist/idempotency/idempotency.js.map +1 -0
- package/dist/idempotency/index.d.ts +25 -0
- package/dist/idempotency/index.d.ts.map +1 -0
- package/dist/idempotency/index.js +24 -0
- package/dist/idempotency/index.js.map +1 -0
- package/dist/idempotency/keys.d.ts +13 -0
- package/dist/idempotency/keys.d.ts.map +1 -0
- package/dist/idempotency/keys.js +9 -0
- package/dist/idempotency/keys.js.map +1 -0
- package/dist/idempotency/types.d.ts +92 -0
- package/dist/idempotency/types.d.ts.map +1 -0
- package/dist/idempotency/types.js +2 -0
- package/dist/idempotency/types.js.map +1 -0
- package/dist/index.d.ts +122 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +201 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/cidr.d.ts +21 -0
- package/dist/internal/cidr.d.ts.map +1 -0
- package/dist/internal/cidr.js +159 -0
- package/dist/internal/cidr.js.map +1 -0
- package/dist/internal/clock.d.ts +6 -0
- package/dist/internal/clock.d.ts.map +1 -0
- package/dist/internal/clock.js +4 -0
- package/dist/internal/clock.js.map +1 -0
- package/dist/internal/crypto.d.ts +44 -0
- package/dist/internal/crypto.d.ts.map +1 -0
- package/dist/internal/crypto.js +97 -0
- package/dist/internal/crypto.js.map +1 -0
- package/dist/internal/db.d.ts +14 -0
- package/dist/internal/db.d.ts.map +1 -0
- package/dist/internal/db.js +20 -0
- package/dist/internal/db.js.map +1 -0
- package/dist/internal/duration.d.ts +25 -0
- package/dist/internal/duration.d.ts.map +1 -0
- package/dist/internal/duration.js +39 -0
- package/dist/internal/duration.js.map +1 -0
- package/dist/internal/errors.d.ts +33 -0
- package/dist/internal/errors.d.ts.map +1 -0
- package/dist/internal/errors.js +29 -0
- package/dist/internal/errors.js.map +1 -0
- package/dist/internal/logger.d.ts +37 -0
- package/dist/internal/logger.d.ts.map +1 -0
- package/dist/internal/logger.js +54 -0
- package/dist/internal/logger.js.map +1 -0
- package/dist/internal/standard-schema.d.ts +49 -0
- package/dist/internal/standard-schema.d.ts.map +1 -0
- package/dist/internal/standard-schema.js +16 -0
- package/dist/internal/standard-schema.js.map +1 -0
- package/dist/internal/table.d.ts +7 -0
- package/dist/internal/table.d.ts.map +1 -0
- package/dist/internal/table.js +20 -0
- package/dist/internal/table.js.map +1 -0
- package/dist/jobs/backoff.d.ts +7 -0
- package/dist/jobs/backoff.d.ts.map +1 -0
- package/dist/jobs/backoff.js +10 -0
- package/dist/jobs/backoff.js.map +1 -0
- package/dist/jobs/index.d.ts +31 -0
- package/dist/jobs/index.d.ts.map +1 -0
- package/dist/jobs/index.js +29 -0
- package/dist/jobs/index.js.map +1 -0
- package/dist/jobs/jobs.d.ts +42 -0
- package/dist/jobs/jobs.d.ts.map +1 -0
- package/dist/jobs/jobs.js +741 -0
- package/dist/jobs/jobs.js.map +1 -0
- package/dist/jobs/types.d.ts +199 -0
- package/dist/jobs/types.d.ts.map +1 -0
- package/dist/jobs/types.js +2 -0
- package/dist/jobs/types.js.map +1 -0
- package/dist/next/client-ip.d.ts +42 -0
- package/dist/next/client-ip.d.ts.map +1 -0
- package/dist/next/client-ip.js +59 -0
- package/dist/next/client-ip.js.map +1 -0
- package/dist/next/index.d.ts +29 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +29 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/jobs-route.d.ts +31 -0
- package/dist/next/jobs-route.d.ts.map +1 -0
- package/dist/next/jobs-route.js +53 -0
- package/dist/next/jobs-route.js.map +1 -0
- package/dist/next/response.d.ts +6 -0
- package/dist/next/response.d.ts.map +1 -0
- package/dist/next/response.js +25 -0
- package/dist/next/response.js.map +1 -0
- package/dist/next/route-helpers.d.ts +67 -0
- package/dist/next/route-helpers.d.ts.map +1 -0
- package/dist/next/route-helpers.js +93 -0
- package/dist/next/route-helpers.js.map +1 -0
- package/dist/rate-limit/index.d.ts +19 -0
- package/dist/rate-limit/index.d.ts.map +1 -0
- package/dist/rate-limit/index.js +18 -0
- package/dist/rate-limit/index.js.map +1 -0
- package/dist/rate-limit/limiter.d.ts +60 -0
- package/dist/rate-limit/limiter.d.ts.map +1 -0
- package/dist/rate-limit/limiter.js +147 -0
- package/dist/rate-limit/limiter.js.map +1 -0
- package/dist/rate-limit/memory-store.d.ts +23 -0
- package/dist/rate-limit/memory-store.d.ts.map +1 -0
- package/dist/rate-limit/memory-store.js +77 -0
- package/dist/rate-limit/memory-store.js.map +1 -0
- package/dist/rate-limit/policy.d.ts +31 -0
- package/dist/rate-limit/policy.d.ts.map +1 -0
- package/dist/rate-limit/policy.js +174 -0
- package/dist/rate-limit/policy.js.map +1 -0
- package/dist/rate-limit/postgres-store.d.ts +13 -0
- package/dist/rate-limit/postgres-store.d.ts.map +1 -0
- package/dist/rate-limit/postgres-store.js +129 -0
- package/dist/rate-limit/postgres-store.js.map +1 -0
- package/dist/rate-limit/redis-store.d.ts +24 -0
- package/dist/rate-limit/redis-store.d.ts.map +1 -0
- package/dist/rate-limit/redis-store.js +97 -0
- package/dist/rate-limit/redis-store.js.map +1 -0
- package/dist/rate-limit/types.d.ts +140 -0
- package/dist/rate-limit/types.d.ts.map +1 -0
- package/dist/rate-limit/types.js +2 -0
- package/dist/rate-limit/types.js.map +1 -0
- package/dist/schema/api-keys.d.ts +545 -0
- package/dist/schema/api-keys.d.ts.map +1 -0
- package/dist/schema/api-keys.js +83 -0
- package/dist/schema/api-keys.js.map +1 -0
- package/dist/schema/audit-log.d.ts +248 -0
- package/dist/schema/audit-log.d.ts.map +1 -0
- package/dist/schema/audit-log.js +56 -0
- package/dist/schema/audit-log.js.map +1 -0
- package/dist/schema/factory.d.ts +19 -0
- package/dist/schema/factory.d.ts.map +1 -0
- package/dist/schema/factory.js +39 -0
- package/dist/schema/factory.js.map +1 -0
- package/dist/schema/idempotency-keys.d.ts +178 -0
- package/dist/schema/idempotency-keys.d.ts.map +1 -0
- package/dist/schema/idempotency-keys.js +41 -0
- package/dist/schema/idempotency-keys.js.map +1 -0
- package/dist/schema/index.d.ts +61 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +28 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/jobs.d.ts +487 -0
- package/dist/schema/jobs.d.ts.map +1 -0
- package/dist/schema/jobs.js +103 -0
- package/dist/schema/jobs.js.map +1 -0
- package/dist/schema/rate-limits.d.ts +108 -0
- package/dist/schema/rate-limits.d.ts.map +1 -0
- package/dist/schema/rate-limits.js +27 -0
- package/dist/schema/rate-limits.js.map +1 -0
- package/dist/testing/index.d.ts +25 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +37 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +117 -4
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { hmacSha256Parts } from "../internal/crypto.js";
|
|
2
|
+
import { parseDuration } from "../internal/duration.js";
|
|
3
|
+
import { GroundworkError } from "../internal/errors.js";
|
|
4
|
+
/** Slack for floating-point error in token arithmetic. Shared by every store. */
|
|
5
|
+
export const EPSILON = 1e-9;
|
|
6
|
+
// Header-safe: a structured-field String may only hold printable ASCII, and the name is also used
|
|
7
|
+
// in logs and as a Redis key component.
|
|
8
|
+
const RULE_NAME_PATTERN = /^[A-Za-z0-9_.:/-]{1,128}$/;
|
|
9
|
+
const ON_ERROR_MODES = ["memory", "allow", "deny"];
|
|
10
|
+
function positiveInteger(value, label) {
|
|
11
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
|
|
12
|
+
throw new GroundworkError("invalid_config", `Invalid ${label} ${JSON.stringify(value)}: it must be a positive integer.`);
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
export function validateOnError(value, label) {
|
|
17
|
+
if (value === undefined)
|
|
18
|
+
return undefined;
|
|
19
|
+
if (!ON_ERROR_MODES.includes(value)) {
|
|
20
|
+
throw new GroundworkError("invalid_config", `Invalid ${label} ${JSON.stringify(value)}: use "memory", "allow" or "deny".`);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
/** Validates rule options once, when the rule is defined, so `check` never has to. */
|
|
25
|
+
export function normalizeRule(options) {
|
|
26
|
+
if (typeof options !== "object" || options === null) {
|
|
27
|
+
throw new GroundworkError("invalid_config", "Rate-limit rule options must be an object.");
|
|
28
|
+
}
|
|
29
|
+
const { name } = options;
|
|
30
|
+
if (typeof name !== "string" || !RULE_NAME_PATTERN.test(name)) {
|
|
31
|
+
throw new GroundworkError("invalid_config", `Invalid rule name ${JSON.stringify(name)}: use 1 to 128 letters, digits or _ . : / - (for example "login:ip").`);
|
|
32
|
+
}
|
|
33
|
+
const onError = validateOnError(options.onError, `onError for rule "${name}"`);
|
|
34
|
+
const algorithm = options.algorithm ?? "fixed-window";
|
|
35
|
+
if (algorithm === "fixed-window") {
|
|
36
|
+
const fixed = options;
|
|
37
|
+
return {
|
|
38
|
+
name,
|
|
39
|
+
algorithm,
|
|
40
|
+
onError,
|
|
41
|
+
policy: {
|
|
42
|
+
algorithm,
|
|
43
|
+
limit: positiveInteger(fixed.limit, `limit for rule "${name}"`),
|
|
44
|
+
windowMs: parseDuration(fixed.window, { label: `window for rule "${name}"`, minMs: 1 }),
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (algorithm === "token-bucket") {
|
|
49
|
+
const bucket = options;
|
|
50
|
+
const rate = positiveInteger(bucket.rate, `rate for rule "${name}"`);
|
|
51
|
+
const perMs = parseDuration(bucket.per, { label: `per for rule "${name}"`, minMs: 1 });
|
|
52
|
+
const burst = bucket.burst === undefined ? rate : positiveInteger(bucket.burst, `burst for rule "${name}"`);
|
|
53
|
+
return {
|
|
54
|
+
name,
|
|
55
|
+
algorithm,
|
|
56
|
+
onError,
|
|
57
|
+
policy: { algorithm, rate, perMs, burst, ratePerMs: rate / perMs },
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
throw new GroundworkError("invalid_config", `Invalid algorithm ${JSON.stringify(algorithm)} for rule "${name}": use "fixed-window" or "token-bucket".`);
|
|
61
|
+
}
|
|
62
|
+
export function validateCost(cost) {
|
|
63
|
+
if (typeof cost !== "number" || !Number.isFinite(cost) || cost < 0) {
|
|
64
|
+
throw new GroundworkError("invalid_argument", `Invalid cost ${JSON.stringify(cost)}: it must be a finite number of 0 or more.`);
|
|
65
|
+
}
|
|
66
|
+
return cost;
|
|
67
|
+
}
|
|
68
|
+
export function validateSubject(subject) {
|
|
69
|
+
if (typeof subject !== "string") {
|
|
70
|
+
throw new GroundworkError("invalid_argument", "The rate-limit subject must be a string.");
|
|
71
|
+
}
|
|
72
|
+
return subject;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The stored key: HMAC over the algorithm, rule name and subject, so raw subjects (IP addresses,
|
|
76
|
+
* user ids) never reach the store. The "rl1" tag versions the format.
|
|
77
|
+
*/
|
|
78
|
+
export function storageKey(subkey, algorithm, rule, subject) {
|
|
79
|
+
return hmacSha256Parts(subkey, ["rl1", algorithm, rule, subject]).toString("base64url");
|
|
80
|
+
}
|
|
81
|
+
/** Capacity of the rule: the window's limit or the bucket's size. */
|
|
82
|
+
export function capacityOf(policy) {
|
|
83
|
+
return policy.algorithm === "fixed-window" ? policy.limit : policy.burst;
|
|
84
|
+
}
|
|
85
|
+
/** How much is in use at `now`, given the stored row. */
|
|
86
|
+
export function levelAt(policy, state) {
|
|
87
|
+
const { row, now } = state;
|
|
88
|
+
if (!row)
|
|
89
|
+
return 0;
|
|
90
|
+
if (policy.algorithm === "fixed-window")
|
|
91
|
+
return row.expiresAt > now ? row.used : 0;
|
|
92
|
+
const refilled = Math.max(0, now - row.updatedAt) * policy.ratePerMs;
|
|
93
|
+
return Math.max(0, row.used - refilled);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Rounds a duration up to whole milliseconds, ignoring floating-point noise: refilling 99ms at
|
|
97
|
+
* 0.01 tokens/ms leaves a 1.0000000000000016ms wait, which is 1ms, not 2.
|
|
98
|
+
*/
|
|
99
|
+
function ceilMs(value) {
|
|
100
|
+
return Math.ceil(value - 1e-6);
|
|
101
|
+
}
|
|
102
|
+
/** Whether `cost` fits on top of `level`. Every store uses this exact comparison. */
|
|
103
|
+
export function fits(level, cost, capacity) {
|
|
104
|
+
return level + cost <= capacity + EPSILON;
|
|
105
|
+
}
|
|
106
|
+
function headersFor(name, policy, remaining, resetInSeconds, retryAfterMs, allowed) {
|
|
107
|
+
let quota;
|
|
108
|
+
let windowSeconds;
|
|
109
|
+
if (policy.algorithm === "fixed-window") {
|
|
110
|
+
quota = policy.limit;
|
|
111
|
+
windowSeconds = Math.max(1, Math.ceil(policy.windowMs / 1000));
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
// The sustained rate, rescaled to a whole number of seconds as the draft requires.
|
|
115
|
+
windowSeconds = Math.max(1, Math.ceil(policy.perMs / 1000));
|
|
116
|
+
quota = Math.max(1, Math.floor((policy.rate * windowSeconds * 1000) / policy.perMs));
|
|
117
|
+
}
|
|
118
|
+
const retryAfterSeconds = Math.max(1, Math.ceil(retryAfterMs / 1000));
|
|
119
|
+
const headers = {
|
|
120
|
+
"RateLimit-Policy": `"${name}";q=${quota};w=${windowSeconds}`,
|
|
121
|
+
// When denied, the effective window ends when the client may retry (draft-11 section 6).
|
|
122
|
+
RateLimit: `"${name}";r=${remaining};t=${allowed ? resetInSeconds : retryAfterSeconds}`,
|
|
123
|
+
};
|
|
124
|
+
if (!allowed)
|
|
125
|
+
headers["Retry-After"] = String(retryAfterSeconds);
|
|
126
|
+
return headers;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Turns what a store reported into the public result. Shared by every store.
|
|
130
|
+
* `retryAfterOverrideMs` replaces the computed wait on a denial (used by `onError: "deny"`).
|
|
131
|
+
*/
|
|
132
|
+
export function resultFor(rule, state, cost, degraded = false, retryAfterOverrideMs) {
|
|
133
|
+
const { policy } = rule;
|
|
134
|
+
const { now, allowed } = state;
|
|
135
|
+
const capacity = capacityOf(policy);
|
|
136
|
+
const level = levelAt(policy, state);
|
|
137
|
+
let remaining = Math.max(0, Math.floor(capacity - level + EPSILON));
|
|
138
|
+
let resetAt;
|
|
139
|
+
let retryAfterMs = 0;
|
|
140
|
+
if (policy.algorithm === "fixed-window") {
|
|
141
|
+
const active = state.row !== null && state.row.expiresAt > now;
|
|
142
|
+
resetAt = active && state.row ? state.row.expiresAt : now + policy.windowMs;
|
|
143
|
+
if (!allowed)
|
|
144
|
+
retryAfterMs = resetAt - now;
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
resetAt = now + ceilMs(level / policy.ratePerMs);
|
|
148
|
+
if (!allowed) {
|
|
149
|
+
retryAfterMs =
|
|
150
|
+
cost > capacity + EPSILON
|
|
151
|
+
? // Never fits. Say "at least a full refill" rather than suggesting it soon will.
|
|
152
|
+
Math.max(resetAt - now, ceilMs(capacity / policy.ratePerMs))
|
|
153
|
+
: ceilMs((level + cost - capacity) / policy.ratePerMs);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (!allowed) {
|
|
157
|
+
if (retryAfterOverrideMs !== undefined)
|
|
158
|
+
retryAfterMs = retryAfterOverrideMs;
|
|
159
|
+
retryAfterMs = Math.max(1, ceilMs(retryAfterMs));
|
|
160
|
+
// A denial means less than `cost` was left, even if the row we read back was a moment stale.
|
|
161
|
+
remaining = Math.min(remaining, Math.max(0, Math.ceil(cost) - 1));
|
|
162
|
+
}
|
|
163
|
+
const resetInSeconds = Math.max(0, Math.ceil((resetAt - now) / 1000));
|
|
164
|
+
return {
|
|
165
|
+
allowed,
|
|
166
|
+
limit: capacity,
|
|
167
|
+
remaining,
|
|
168
|
+
resetAt: new Date(resetAt),
|
|
169
|
+
retryAfterMs,
|
|
170
|
+
headers: headersFor(rule.name, policy, remaining, resetInSeconds, retryAfterMs, allowed),
|
|
171
|
+
degraded,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
//# sourceMappingURL=policy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"policy.js","sourceRoot":"","sources":["../../src/rate-limit/policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAYxD,iFAAiF;AACjF,MAAM,CAAC,MAAM,OAAO,GAAG,IAAI,CAAC;AAE5B,kGAAkG;AAClG,wCAAwC;AACxC,MAAM,iBAAiB,GAAG,2BAA2B,CAAC;AAEtD,MAAM,cAAc,GAAuB,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AASvE,SAAS,eAAe,CAAC,KAAc,EAAE,KAAa;IACpD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAA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EAAE,cAAc,EAAE,YAAY,EAAE,OAAO,CAAC;QACxF,QAAQ;KACT,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type GroundworkDatabase } from "../internal/db.ts";
|
|
2
|
+
import { type RateLimitsTable } from "../schema/rate-limits.ts";
|
|
3
|
+
import type { RateLimitStore } from "./types.ts";
|
|
4
|
+
export interface PostgresStoreOptions {
|
|
5
|
+
readonly db: GroundworkDatabase;
|
|
6
|
+
/** The `rateLimits` table from `groundworkTables()`. */
|
|
7
|
+
readonly table: RateLimitsTable;
|
|
8
|
+
}
|
|
9
|
+
/** The default store: counters in your Postgres, in the table from `groundworkTables()`. */
|
|
10
|
+
export declare function postgresStore(options: PostgresStoreOptions): RateLimitStore & {
|
|
11
|
+
kind: "postgres";
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=postgres-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-store.d.ts","sourceRoot":"","sources":["../../src/rate-limit/postgres-store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAAoB,MAAM,mBAAmB,CAAC;AAG9E,OAAO,EAAsB,KAAK,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAEpF,OAAO,KAAK,EAAgB,cAAc,EAA4B,MAAM,YAAY,CAAC;AAEzF,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,EAAE,EAAE,kBAAkB,CAAC;IAChC,wDAAwD;IACxD,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC;CACjC;AAkFD,4FAA4F;AAC5F,wBAAgB,aAAa,CAC3B,OAAO,EAAE,oBAAoB,GAC5B,cAAc,GAAG;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAsDvC"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { rowsOf, toNumber } from "../internal/db.js";
|
|
3
|
+
import { GroundworkError } from "../internal/errors.js";
|
|
4
|
+
import { assertTableColumns } from "../internal/table.js";
|
|
5
|
+
import { RATE_LIMIT_COLUMNS } from "../schema/rate-limits.js";
|
|
6
|
+
import { EPSILON } from "./policy.js";
|
|
7
|
+
const CLEANUP_BATCH = 5_000;
|
|
8
|
+
/** Epoch milliseconds as float8, which every driver returns as a JS number. */
|
|
9
|
+
const ms = (column) => sql `(extract(epoch from ${column}) * 1000)::float8`;
|
|
10
|
+
/** The decision's time: the injected clock if there is one, else the database's. */
|
|
11
|
+
const nowParam = (now) => sql `coalesce(${now === null ? null : new Date(now).toISOString()}::timestamptz, clock_timestamp())`;
|
|
12
|
+
/**
|
|
13
|
+
* One statement per check:
|
|
14
|
+
*
|
|
15
|
+
* 1. `consumed` upserts the row only if the cost fits. `ON CONFLICT … DO UPDATE … WHERE` locks the
|
|
16
|
+
* existing row and re-checks against its latest committed version, so concurrent checks for
|
|
17
|
+
* the same subject serialise on that row and can never overspend.
|
|
18
|
+
* 2. If nothing was consumed, the outer query reads the current row instead, so a denial still
|
|
19
|
+
* reports remaining and reset times without a second round trip.
|
|
20
|
+
*/
|
|
21
|
+
function consumeQuery(table, input) {
|
|
22
|
+
const { policy, key, rule, cost } = input;
|
|
23
|
+
const capacity = policy.algorithm === "fixed-window" ? policy.limit : policy.burst;
|
|
24
|
+
let insertExpires;
|
|
25
|
+
let setClause;
|
|
26
|
+
let fitsExisting;
|
|
27
|
+
if (policy.algorithm === "fixed-window") {
|
|
28
|
+
// At or after expires_at the window is over: the row counts as empty and a new window starts.
|
|
29
|
+
const over = sql `r.expires_at <= excluded.updated_at`;
|
|
30
|
+
insertExpires = sql `input.now + ${policy.windowMs}::float8 * interval '1 millisecond'`;
|
|
31
|
+
setClause = sql `
|
|
32
|
+
used = case when ${over} then excluded.used else r.used + excluded.used end,
|
|
33
|
+
expires_at = case when ${over} then excluded.expires_at else r.expires_at end,
|
|
34
|
+
updated_at = excluded.updated_at,
|
|
35
|
+
rule = excluded.rule`;
|
|
36
|
+
fitsExisting = sql `(case when ${over} then 0 else r.used end) + excluded.used <= ${capacity}::float8 + ${EPSILON}::float8`;
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
const rate = sql `${policy.ratePerMs}::float8`;
|
|
40
|
+
// Tokens still taken after refilling for the time since updated_at (never negative).
|
|
41
|
+
const drained = sql `greatest(0::float8, r.used - greatest(0::float8, extract(epoch from (excluded.updated_at - r.updated_at))::float8 * 1000) * ${rate})`;
|
|
42
|
+
insertExpires = sql `input.now + (${cost}::float8 / ${rate}) * interval '1 millisecond'`;
|
|
43
|
+
setClause = sql `
|
|
44
|
+
used = ${drained} + excluded.used,
|
|
45
|
+
updated_at = excluded.updated_at,
|
|
46
|
+
expires_at = excluded.updated_at + ((${drained} + excluded.used) / ${rate}) * interval '1 millisecond',
|
|
47
|
+
rule = excluded.rule`;
|
|
48
|
+
fitsExisting = sql `${drained} + excluded.used <= ${capacity}::float8 + ${EPSILON}::float8`;
|
|
49
|
+
}
|
|
50
|
+
return sql `
|
|
51
|
+
with input as materialized (
|
|
52
|
+
select ${nowParam(input.now)} as now
|
|
53
|
+
),
|
|
54
|
+
consumed as (
|
|
55
|
+
insert into ${table} as r (key, rule, used, updated_at, expires_at)
|
|
56
|
+
select ${key}::text, ${rule}::text, ${cost}::float8, input.now, ${insertExpires}
|
|
57
|
+
from input
|
|
58
|
+
where ${cost}::float8 <= ${capacity}::float8 + ${EPSILON}::float8
|
|
59
|
+
on conflict (key) do update set ${setClause}
|
|
60
|
+
where ${fitsExisting}
|
|
61
|
+
returning r.used, r.updated_at, r.expires_at
|
|
62
|
+
)
|
|
63
|
+
select
|
|
64
|
+
(c.used is not null) as allowed,
|
|
65
|
+
coalesce(c.used, existing.used) as used,
|
|
66
|
+
${ms(sql `coalesce(c.updated_at, existing.updated_at)`)} as updated_at,
|
|
67
|
+
${ms(sql `coalesce(c.expires_at, existing.expires_at)`)} as expires_at,
|
|
68
|
+
${ms(sql `input.now`)} as now
|
|
69
|
+
from input
|
|
70
|
+
left join consumed c on true
|
|
71
|
+
left join ${table} existing on c.used is null and existing.key = ${key}::text`;
|
|
72
|
+
}
|
|
73
|
+
/** The default store: counters in your Postgres, in the table from `groundworkTables()`. */
|
|
74
|
+
export function postgresStore(options) {
|
|
75
|
+
const { db, table } = options;
|
|
76
|
+
if (!db || typeof db.execute !== "function") {
|
|
77
|
+
throw new GroundworkError("invalid_config", "db must be a Drizzle Postgres database.");
|
|
78
|
+
}
|
|
79
|
+
assertTableColumns(table, RATE_LIMIT_COLUMNS, "rateLimits table from groundworkTables()");
|
|
80
|
+
return {
|
|
81
|
+
kind: "postgres",
|
|
82
|
+
async consume(input) {
|
|
83
|
+
const [row] = rowsOf(await db.execute(consumeQuery(table, input)));
|
|
84
|
+
if (!row)
|
|
85
|
+
throw new Error("rate-limit query returned no row");
|
|
86
|
+
const now = toNumber(row.now);
|
|
87
|
+
if (row.used === null || row.used === undefined)
|
|
88
|
+
return { allowed: false, now, row: null };
|
|
89
|
+
return {
|
|
90
|
+
allowed: row.allowed === true,
|
|
91
|
+
now,
|
|
92
|
+
row: {
|
|
93
|
+
used: toNumber(row.used),
|
|
94
|
+
updatedAt: toNumber(row.updated_at),
|
|
95
|
+
expiresAt: toNumber(row.expires_at),
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
async reset(key, resetOptions) {
|
|
100
|
+
const target = resetOptions?.tx ?? db;
|
|
101
|
+
await target.execute(sql `delete from ${table} where key = ${key}::text`);
|
|
102
|
+
},
|
|
103
|
+
async cleanup(now) {
|
|
104
|
+
let total = 0;
|
|
105
|
+
for (;;) {
|
|
106
|
+
// Skip rows other checks are updating right now; re-check expiry on the row we delete.
|
|
107
|
+
const [row] = rowsOf(await db.execute(sql `
|
|
108
|
+
with input as materialized (select ${nowParam(now)} as now),
|
|
109
|
+
doomed as (
|
|
110
|
+
select candidate.key from ${table} candidate, input
|
|
111
|
+
where candidate.expires_at <= input.now
|
|
112
|
+
limit ${CLEANUP_BATCH}
|
|
113
|
+
for update of candidate skip locked
|
|
114
|
+
),
|
|
115
|
+
deleted as (
|
|
116
|
+
delete from ${table} t using doomed, input
|
|
117
|
+
where t.key = doomed.key and t.expires_at <= input.now
|
|
118
|
+
returning 1
|
|
119
|
+
)
|
|
120
|
+
select count(*)::int as deleted from deleted`));
|
|
121
|
+
const deleted = row ? toNumber(row.deleted) : 0;
|
|
122
|
+
total += deleted;
|
|
123
|
+
if (deleted < CLEANUP_BATCH)
|
|
124
|
+
return total;
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=postgres-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-store.js","sourceRoot":"","sources":["../../src/rate-limit/postgres-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,GAAG,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAA2B,MAAM,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAwB,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAStC,MAAM,aAAa,GAAG,KAAK,CAAC;AAU5B,+EAA+E;AAC/E,MAAM,EAAE,GAAG,CAAC,MAAW,EAAO,EAAE,CAAC,GAAG,CAAA,uBAAuB,MAAM,mBAAmB,CAAC;AAErF,oFAAoF;AACpF,MAAM,QAAQ,GAAG,CAAC,GAAkB,EAAO,EAAE,CAC3C,GAAG,CAAA,YAAY,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,mCAAmC,CAAC;AAEtG;;;;;;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EAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC;oBACxB,SAAS,EAAE,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC;oBACnC,SAAS,EAAE,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC;iBACpC;aACF,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,YAA2B;YAC1C,MAAM,MAAM,GAAG,YAAY,EAAE,EAAE,IAAI,EAAE,CAAC;YACtC,MAAM,MAAM,CAAC,OAAO,CAAC,GAAG,CAAA,eAAe,KAAK,gBAAgB,GAAG,QAAQ,CAAC,CAAC;QAC3E,CAAC;QACD,KAAK,CAAC,OAAO,CAAC,GAAG;YACf,IAAI,KAAK,GAAG,CAAC,CAAC;YACd,SAAS,CAAC;gBACR,uFAAuF;gBACvF,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAClB,MAAM,EAAE,CAAC,OAAO,CAAC,GAAG,CAAA;iDACmB,QAAQ,CAAC,GAAG,CAAC;;0CAEpB,KAAK;;sBAEzB,aAAa;;;;4BAIP,KAAK;;;;yDAIwB,CAAC,CACjD,CAAC;gBACF,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;gBAChD,KAAK,IAAI,OAAO,CAAC;gBACjB,IAAI,OAAO,GAAG,aAAa;oBAAE,OAAO,KAAK,CAAC;YAC5C,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { RateLimitStore } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* The one Redis capability the store needs: running a Lua script. Adapt your client in one line:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* // ioredis
|
|
7
|
+
* const client = { eval: (script, keys, args) => redis.eval(script, keys.length, ...keys, ...args) };
|
|
8
|
+
* // node-redis
|
|
9
|
+
* const client = { eval: (script, keys, args) => redis.eval(script, { keys, arguments: args }) };
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export interface RedisEvalClient {
|
|
13
|
+
eval(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
14
|
+
}
|
|
15
|
+
export interface RedisStoreOptions {
|
|
16
|
+
readonly client: RedisEvalClient;
|
|
17
|
+
/** Prepended to every Redis key. Defaults to `"gw:rl:"`. */
|
|
18
|
+
readonly prefix?: string | undefined;
|
|
19
|
+
}
|
|
20
|
+
/** Counters in Redis, for apps that already run it. Postgres stays the default. */
|
|
21
|
+
export declare function redisStore(options: RedisStoreOptions): RateLimitStore & {
|
|
22
|
+
kind: "redis";
|
|
23
|
+
};
|
|
24
|
+
//# sourceMappingURL=redis-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-store.d.ts","sourceRoot":"","sources":["../../src/rate-limit/redis-store.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAgB,cAAc,EAAc,MAAM,YAAY,CAAC;AAE3E;;;;;;;;;GASG;AACH,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACxE;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;IACjC,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC;AAmED,mFAAmF;AACnF,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,GAAG;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAsCzF"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { toNumber } from "../internal/db.js";
|
|
2
|
+
import { GroundworkError } from "../internal/errors.js";
|
|
3
|
+
import { capacityOf, EPSILON } from "./policy.js";
|
|
4
|
+
// Same semantics as the Postgres store and memory store: a cost that doesn't fit uses nothing.
|
|
5
|
+
// Replies are strings, because Redis truncates Lua numbers to integers.
|
|
6
|
+
const CONSUME_SCRIPT = `
|
|
7
|
+
local now
|
|
8
|
+
if ARGV[5] == "" then
|
|
9
|
+
local t = redis.call("TIME")
|
|
10
|
+
now = tonumber(t[1]) * 1000 + tonumber(t[2]) / 1000
|
|
11
|
+
else
|
|
12
|
+
now = tonumber(ARGV[5])
|
|
13
|
+
end
|
|
14
|
+
local fixed = ARGV[1] == "fixed-window"
|
|
15
|
+
local cost = tonumber(ARGV[2])
|
|
16
|
+
local capacity = tonumber(ARGV[3])
|
|
17
|
+
local param = tonumber(ARGV[4])
|
|
18
|
+
local epsilon = tonumber(ARGV[6])
|
|
19
|
+
local stored = redis.call("HMGET", KEYS[1], "used", "updated", "expires")
|
|
20
|
+
local used = tonumber(stored[1])
|
|
21
|
+
local updated = tonumber(stored[2])
|
|
22
|
+
local expires = tonumber(stored[3])
|
|
23
|
+
local level = 0
|
|
24
|
+
local active = false
|
|
25
|
+
if used then
|
|
26
|
+
if fixed then
|
|
27
|
+
active = expires > now
|
|
28
|
+
if active then level = used end
|
|
29
|
+
else
|
|
30
|
+
level = math.max(0, used - math.max(0, now - updated) * param)
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
if level + cost > capacity + epsilon then
|
|
34
|
+
if used then
|
|
35
|
+
return {"0", tostring(now), tostring(used), tostring(updated), tostring(expires)}
|
|
36
|
+
end
|
|
37
|
+
return {"0", tostring(now)}
|
|
38
|
+
end
|
|
39
|
+
local newUsed = level + cost
|
|
40
|
+
local newExpires
|
|
41
|
+
if fixed then
|
|
42
|
+
if active then newExpires = expires else newExpires = now + param end
|
|
43
|
+
else
|
|
44
|
+
newExpires = now + newUsed / param
|
|
45
|
+
end
|
|
46
|
+
redis.call("HSET", KEYS[1], "used", tostring(newUsed), "updated", tostring(now), "expires", tostring(newExpires))
|
|
47
|
+
-- Relative, with a second of slack: an injected clock may be far from the server's.
|
|
48
|
+
redis.call("PEXPIRE", KEYS[1], math.max(1, math.ceil(newExpires - now)) + 1000)
|
|
49
|
+
return {"1", tostring(now), tostring(newUsed), tostring(now), tostring(newExpires)}
|
|
50
|
+
`;
|
|
51
|
+
const RESET_SCRIPT = `return redis.call("DEL", KEYS[1])`;
|
|
52
|
+
function parseReply(reply) {
|
|
53
|
+
if (!Array.isArray(reply) || reply.length < 2) {
|
|
54
|
+
throw new Error("Unexpected reply from the rate-limit Redis script.");
|
|
55
|
+
}
|
|
56
|
+
const [allowed, now, used, updated, expires] = reply;
|
|
57
|
+
return {
|
|
58
|
+
allowed: String(allowed) === "1",
|
|
59
|
+
now: toNumber(now),
|
|
60
|
+
row: used === undefined
|
|
61
|
+
? null
|
|
62
|
+
: { used: toNumber(used), updatedAt: toNumber(updated), expiresAt: toNumber(expires) },
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Counters in Redis, for apps that already run it. Postgres stays the default. */
|
|
66
|
+
export function redisStore(options) {
|
|
67
|
+
const { client } = options;
|
|
68
|
+
if (!client || typeof client.eval !== "function") {
|
|
69
|
+
throw new GroundworkError("invalid_config", "redisStore needs a client with eval(script, keys, args). See the RedisEvalClient docs for one-line adapters.");
|
|
70
|
+
}
|
|
71
|
+
const prefix = options.prefix ?? "gw:rl:";
|
|
72
|
+
if (typeof prefix !== "string") {
|
|
73
|
+
throw new GroundworkError("invalid_config", "redisStore prefix must be a string.");
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
kind: "redis",
|
|
77
|
+
async consume(input) {
|
|
78
|
+
const { policy } = input;
|
|
79
|
+
const param = policy.algorithm === "fixed-window" ? policy.windowMs : policy.ratePerMs;
|
|
80
|
+
const reply = await client.eval(CONSUME_SCRIPT, [`${prefix}${input.key}`], [
|
|
81
|
+
policy.algorithm,
|
|
82
|
+
String(input.cost),
|
|
83
|
+
String(capacityOf(policy)),
|
|
84
|
+
String(param),
|
|
85
|
+
input.now === null ? "" : String(input.now),
|
|
86
|
+
String(EPSILON),
|
|
87
|
+
]);
|
|
88
|
+
return parseReply(reply);
|
|
89
|
+
},
|
|
90
|
+
async reset(key) {
|
|
91
|
+
await client.eval(RESET_SCRIPT, [`${prefix}${key}`], []);
|
|
92
|
+
},
|
|
93
|
+
// Redis expires keys itself.
|
|
94
|
+
cleanup: async () => 0,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=redis-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-store.js","sourceRoot":"","sources":["../../src/rate-limit/redis-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAuBlD,+FAA+F;AAC/F,wEAAwE;AACxE,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CtB,CAAC;AAEF,MAAM,YAAY,GAAG,mCAAmC,CAAC;AAEzD,SAAS,UAAU,CAAC,KAAc;IAChC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9C,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IACD,MAAM,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,KAAkB,CAAC;IAClE,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,KAAK,GAAG;QAChC,GAAG,EAAE,QAAQ,CAAC,GAAG,CAAC;QAClB,GAAG,EACD,IAAI,KAAK,SAAS;YAChB,CAAC,CAAC,IAAI;YACN,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AAC,KAAK,CAAC,GAAG,CAAC;gBAC3C,MAAM,CAAC,OAAO,CAAC;aAChB,CACF,CAAC;YACF,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,GAAG;YACb,MAAM,MAAM,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,GAAG,MAAM,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAC3D,CAAC;QACD,6BAA6B;QAC7B,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;KACvB,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { GroundworkDatabase } from "../internal/db.ts";
|
|
2
|
+
import type { Duration } from "../internal/duration.ts";
|
|
3
|
+
/**
|
|
4
|
+
* What a rule does when its store (Postgres or Redis) fails or times out:
|
|
5
|
+
*
|
|
6
|
+
* - `"memory"`: count in this process's memory until the store is back. Limits hold per instance.
|
|
7
|
+
* - `"allow"`: let every request through (fail open).
|
|
8
|
+
* - `"deny"`: reject every request (fail closed).
|
|
9
|
+
*/
|
|
10
|
+
export type OnError = "memory" | "allow" | "deny";
|
|
11
|
+
export type RateLimitAlgorithm = "fixed-window" | "token-bucket";
|
|
12
|
+
interface RuleOptionsBase {
|
|
13
|
+
/**
|
|
14
|
+
* Identifies the rule, for example `"login:ip"`. It is part of every stored key and is sent in
|
|
15
|
+
* the `RateLimit-Policy` header, so it may use letters, digits and `_ . : / -` only.
|
|
16
|
+
*/
|
|
17
|
+
readonly name: string;
|
|
18
|
+
/** Overrides the limiter's `onError` for this rule. */
|
|
19
|
+
readonly onError?: OnError | undefined;
|
|
20
|
+
}
|
|
21
|
+
/** At most `limit` cost per `window`. The window starts at a subject's first request. */
|
|
22
|
+
export interface FixedWindowRuleOptions extends RuleOptionsBase {
|
|
23
|
+
readonly algorithm?: "fixed-window" | undefined;
|
|
24
|
+
/** Cost allowed per window. A positive integer. */
|
|
25
|
+
readonly limit: number;
|
|
26
|
+
readonly window: Duration;
|
|
27
|
+
readonly rate?: never;
|
|
28
|
+
readonly per?: never;
|
|
29
|
+
readonly burst?: never;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A bucket of `burst` tokens that refills at `rate` tokens per `per`. Allows short bursts while
|
|
33
|
+
* holding the long-run rate.
|
|
34
|
+
*/
|
|
35
|
+
export interface TokenBucketRuleOptions extends RuleOptionsBase {
|
|
36
|
+
readonly algorithm: "token-bucket";
|
|
37
|
+
/** Tokens added per `per`. A positive integer. */
|
|
38
|
+
readonly rate: number;
|
|
39
|
+
readonly per: Duration;
|
|
40
|
+
/** Bucket size: the most cost allowed at once. A positive integer. Defaults to `rate`. */
|
|
41
|
+
readonly burst?: number | undefined;
|
|
42
|
+
readonly limit?: never;
|
|
43
|
+
readonly window?: never;
|
|
44
|
+
}
|
|
45
|
+
export type RuleOptions = FixedWindowRuleOptions | TokenBucketRuleOptions;
|
|
46
|
+
export interface CheckOptions {
|
|
47
|
+
/**
|
|
48
|
+
* How much this request uses, for example the number of events in a batch. Defaults to 1.
|
|
49
|
+
* `0` reads the current state without using anything. A request whose cost does not fit is
|
|
50
|
+
* rejected without using anything, so one oversized request never burns the rest of a window.
|
|
51
|
+
*/
|
|
52
|
+
readonly cost?: number | undefined;
|
|
53
|
+
}
|
|
54
|
+
export interface ResetOptions {
|
|
55
|
+
/** Run the reset inside this transaction (Postgres store only). */
|
|
56
|
+
readonly tx?: GroundworkDatabase | undefined;
|
|
57
|
+
}
|
|
58
|
+
export interface RateLimitResult {
|
|
59
|
+
readonly allowed: boolean;
|
|
60
|
+
/** The window's limit, or the bucket's burst size. */
|
|
61
|
+
readonly limit: number;
|
|
62
|
+
/** Cost still available right now, after this request. */
|
|
63
|
+
readonly remaining: number;
|
|
64
|
+
/** When the window ends, or when the bucket will be full again. */
|
|
65
|
+
readonly resetAt: Date;
|
|
66
|
+
/** How long to wait before this request would be allowed. 0 when allowed. */
|
|
67
|
+
readonly retryAfterMs: number;
|
|
68
|
+
/**
|
|
69
|
+
* `RateLimit-Policy` and `RateLimit` (draft-ietf-httpapi-ratelimit-headers-11), plus
|
|
70
|
+
* `Retry-After` when denied. Pass straight to a `Response`.
|
|
71
|
+
*/
|
|
72
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
73
|
+
/** `false` normally. When the store failed, the `onError` mode that produced this result. */
|
|
74
|
+
readonly degraded: false | OnError;
|
|
75
|
+
}
|
|
76
|
+
export interface RateLimitRule {
|
|
77
|
+
readonly name: string;
|
|
78
|
+
readonly algorithm: RateLimitAlgorithm;
|
|
79
|
+
/** Uses `cost` (default 1) for `subject`, an IP address, user id or API key id. One round trip. */
|
|
80
|
+
check(subject: string, options?: CheckOptions): Promise<RateLimitResult>;
|
|
81
|
+
/** Forgets `subject`'s usage, for example after a successful login. */
|
|
82
|
+
reset(subject: string, options?: ResetOptions): Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
export interface RateLimiter {
|
|
85
|
+
/**
|
|
86
|
+
* Defines a rule. It does no I/O, so a rule can be defined per request when its limit varies.
|
|
87
|
+
* Rules with the same algorithm and name share counters.
|
|
88
|
+
*/
|
|
89
|
+
rule(options: RuleOptions): RateLimitRule;
|
|
90
|
+
/** Deletes expired rows. Run it every hour or so; returns how many rows it deleted. */
|
|
91
|
+
cleanup(): Promise<number>;
|
|
92
|
+
}
|
|
93
|
+
/** A rule in normalised form, as stores see it. */
|
|
94
|
+
export type Policy = {
|
|
95
|
+
readonly algorithm: "fixed-window";
|
|
96
|
+
readonly limit: number;
|
|
97
|
+
readonly windowMs: number;
|
|
98
|
+
} | {
|
|
99
|
+
readonly algorithm: "token-bucket";
|
|
100
|
+
readonly burst: number;
|
|
101
|
+
readonly rate: number;
|
|
102
|
+
readonly perMs: number;
|
|
103
|
+
/** Tokens added per millisecond. */
|
|
104
|
+
readonly ratePerMs: number;
|
|
105
|
+
};
|
|
106
|
+
export interface ConsumeInput {
|
|
107
|
+
/** HMAC of the algorithm, rule name and subject. Never the raw subject. */
|
|
108
|
+
readonly key: string;
|
|
109
|
+
readonly rule: string;
|
|
110
|
+
readonly cost: number;
|
|
111
|
+
readonly policy: Policy;
|
|
112
|
+
/** Epoch milliseconds from the injected clock, or `null` to use the store's own time. */
|
|
113
|
+
readonly now: number | null;
|
|
114
|
+
}
|
|
115
|
+
/** What a store reports after `consume`. Times are epoch milliseconds. */
|
|
116
|
+
export interface StoreState {
|
|
117
|
+
readonly allowed: boolean;
|
|
118
|
+
/** The time the store used for this decision. */
|
|
119
|
+
readonly now: number;
|
|
120
|
+
/** The stored row, after the update when allowed, or `null` if there is none. */
|
|
121
|
+
readonly row: {
|
|
122
|
+
readonly used: number;
|
|
123
|
+
readonly updatedAt: number;
|
|
124
|
+
readonly expiresAt: number;
|
|
125
|
+
} | null;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Where counters live. `postgresStore` (the default when you pass `db` and `table`) and
|
|
129
|
+
* `redisStore` ship with groundwork. The interface may still change before 1.0.
|
|
130
|
+
*/
|
|
131
|
+
export interface RateLimitStore {
|
|
132
|
+
readonly kind: string;
|
|
133
|
+
/** Atomically uses `cost` if it fits. Must never use anything when it doesn't. */
|
|
134
|
+
consume(input: ConsumeInput): Promise<StoreState>;
|
|
135
|
+
reset(key: string, options?: ResetOptions): Promise<void>;
|
|
136
|
+
/** Deletes rows that expired before `now` (or the store's own time). */
|
|
137
|
+
cleanup(now: number | null): Promise<number>;
|
|
138
|
+
}
|
|
139
|
+
export {};
|
|
140
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/rate-limit/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAExD;;;;;;GAMG;AACH,MAAM,MAAM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