@upstash/ratelimit 2.1.0 → 2.2.1-canary.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 +2 -0
- package/dist/index.d.mts +31 -1
- package/dist/index.d.ts +31 -1
- package/dist/index.js +50 -27
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +50 -27
- package/dist/index.mjs.map +1 -1
- package/docs/algorithms.mdx +169 -0
- package/docs/costs.mdx +112 -0
- package/docs/features.mdx +262 -0
- package/docs/gettingstarted.mdx +220 -0
- package/docs/methods.mdx +206 -0
- package/docs/overview.mdx +159 -0
- package/docs/traffic-protection.mdx +110 -0
- package/package.json +1 -1
- package/src/analytics.ts +110 -0
- package/src/cache.ts +55 -0
- package/src/constants.ts +14 -0
- package/src/deny-list/deny-list.ts +124 -0
- package/src/deny-list/index.ts +1 -0
- package/src/deny-list/ip-deny-list.ts +131 -0
- package/src/deny-list/scripts.ts +26 -0
- package/src/deny-list/time.ts +20 -0
- package/src/duration.ts +37 -0
- package/src/hash.ts +29 -0
- package/src/index.ts +18 -0
- package/src/lua-scripts/hash.ts +95 -0
- package/src/lua-scripts/multi.ts +86 -0
- package/src/lua-scripts/reset.ts +23 -0
- package/src/lua-scripts/single.ts +237 -0
- package/src/multi.ts +610 -0
- package/src/ratelimit.ts +506 -0
- package/src/single.ts +676 -0
- package/src/telemetry.ts +43 -0
- package/src/types.ts +132 -0
- package/src/version.ts +1 -0
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "name": "@upstash/ratelimit", "version": "2.1.0", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "repository": { "type": "git", "url": "git+https://github.com/upstash/ratelimit-js.git" }, "scripts": { "build": "tsup", "test": "bun test src --coverage", "fmt": "prettier --write .", "lint": "eslint \"src/**/*.{js,ts,tsx}\" --quiet --fix" }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^8.4.0", "bun-types": "latest", "eslint": "^9.10.0", "eslint-plugin-unicorn": "^55.0.0", "tsup": "^7.2.0", "turbo": "^1.10.15", "typescript": "^5.0.0" }, "peerDependencies": { "@upstash/redis": "^1.38.2" }, "license": "MIT", "dependencies": { "@upstash/core-analytics": "^0.0.10" }, "bugs": { "url": "https://github.com/upstash/ratelimit-js/issues" }, "homepage": "https://github.com/upstash/ratelimit-js#readme" }
|
|
1
|
+
{ "name": "@upstash/ratelimit", "version": "2.2.1-canary.0", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist", "src", "docs", "!src/**/*.test.*", "!src/**/*.test-d.*", "!src/**/*.spec.*", "!src/**/test-utils.*", "!src/**/__tests__/**", "!src/**/__snapshots__/**", "!src/**/test_utils.*", "!src/tools/**" ], "repository": { "type": "git", "url": "git+https://github.com/upstash/ratelimit-js.git" }, "scripts": { "build": "tsup", "test": "bun test src --coverage", "fmt": "prettier --write .", "lint": "eslint \"src/**/*.{js,ts,tsx}\" --quiet --fix", "prepack": "giget gh:upstash/docs/redis/sdks/ratelimit-ts docs --force-clean 1>&2" }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^8.4.0", "bun-types": "latest", "eslint": "^9.10.0", "eslint-plugin-unicorn": "^55.0.0", "giget": "3.3.1", "tsup": "^7.2.0", "turbo": "^1.10.15", "typescript": "^5.0.0" }, "peerDependencies": { "@upstash/redis": "^1.38.2" }, "license": "MIT", "dependencies": { "@upstash/core-analytics": "^0.0.10" }, "bugs": { "url": "https://github.com/upstash/ratelimit-js/issues" }, "homepage": "https://github.com/upstash/ratelimit-js#readme", "directories": { "doc": "./docs" } }
|
package/src/analytics.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { Aggregate } from "@upstash/core-analytics";
|
|
2
|
+
import { Analytics as CoreAnalytics } from "@upstash/core-analytics";
|
|
3
|
+
import type { Redis } from "./types";
|
|
4
|
+
|
|
5
|
+
export type Geo = {
|
|
6
|
+
country?: string;
|
|
7
|
+
city?: string;
|
|
8
|
+
region?: string;
|
|
9
|
+
ip?: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* denotes the success field in the analytics submission.
|
|
14
|
+
* Set to true when ratelimit check passes. False when request is ratelimited.
|
|
15
|
+
* Set to "denied" when some request value is in deny list.
|
|
16
|
+
*/
|
|
17
|
+
export type EventSuccess = boolean | "denied"
|
|
18
|
+
|
|
19
|
+
export type Event = Geo & {
|
|
20
|
+
identifier: string;
|
|
21
|
+
time: number;
|
|
22
|
+
success: EventSuccess;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type AnalyticsConfig = {
|
|
26
|
+
redis: Redis;
|
|
27
|
+
prefix?: string;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The Analytics package is experimental and can change at any time.
|
|
32
|
+
*
|
|
33
|
+
* @see node_modules/@upstash/ratelimit/docs/features.mdx
|
|
34
|
+
*/
|
|
35
|
+
export class Analytics {
|
|
36
|
+
private readonly analytics: CoreAnalytics;
|
|
37
|
+
private readonly table = "events";
|
|
38
|
+
|
|
39
|
+
constructor(config: AnalyticsConfig) {
|
|
40
|
+
this.analytics = new CoreAnalytics({
|
|
41
|
+
// @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk
|
|
42
|
+
redis: config.redis,
|
|
43
|
+
window: "1h",
|
|
44
|
+
prefix: config.prefix ?? "@upstash/ratelimit",
|
|
45
|
+
retention: "90d",
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Try to extract the geo information from the request
|
|
51
|
+
*
|
|
52
|
+
* This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties
|
|
53
|
+
* @param req
|
|
54
|
+
* @returns
|
|
55
|
+
*/
|
|
56
|
+
public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {
|
|
57
|
+
if (req.geo !== undefined) {
|
|
58
|
+
return req.geo;
|
|
59
|
+
}
|
|
60
|
+
if (req.cf !== undefined) {
|
|
61
|
+
return req.cf;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
public async record(event: Event): Promise<void> {
|
|
68
|
+
await this.analytics.ingest(this.table, event);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
public async series<TFilter extends keyof Omit<Event, "time">>(
|
|
72
|
+
filter: TFilter,
|
|
73
|
+
cutoff: number,
|
|
74
|
+
): Promise<Aggregate[]> {
|
|
75
|
+
const timestampCount = Math.min(
|
|
76
|
+
(
|
|
77
|
+
this.analytics.getBucket(Date.now())
|
|
78
|
+
- this.analytics.getBucket(cutoff)
|
|
79
|
+
) / (60 * 60 * 1000),
|
|
80
|
+
256
|
|
81
|
+
)
|
|
82
|
+
return this.analytics.aggregateBucketsWithPipeline(this.table, filter, timestampCount)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {
|
|
86
|
+
|
|
87
|
+
const timestampCount = Math.min(
|
|
88
|
+
(
|
|
89
|
+
this.analytics.getBucket(Date.now())
|
|
90
|
+
- this.analytics.getBucket(cutoff)
|
|
91
|
+
) / (60 * 60 * 1000),
|
|
92
|
+
256
|
|
93
|
+
)
|
|
94
|
+
const records = await this.analytics.getAllowedBlocked(this.table, timestampCount)
|
|
95
|
+
return records;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
public async getUsageOverTime<TFilter extends keyof Omit<Event, "time">>(
|
|
99
|
+
timestampCount: number, groupby: TFilter
|
|
100
|
+
): Promise<Aggregate[]> {
|
|
101
|
+
const result = await this.analytics.aggregateBucketsWithPipeline(this.table, groupby, timestampCount)
|
|
102
|
+
return result
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
public async getMostAllowedBlocked(timestampCount: number, getTop?: number, checkAtMost?: number) {
|
|
106
|
+
getTop = getTop ?? 5
|
|
107
|
+
const timestamp = undefined // let the analytics handle getting the timestamp
|
|
108
|
+
return this.analytics.getMostAllowedBlocked(this.table, timestampCount, getTop, timestamp, checkAtMost)
|
|
109
|
+
}
|
|
110
|
+
}
|
package/src/cache.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { EphemeralCache } from "./types";
|
|
2
|
+
|
|
3
|
+
export class Cache implements EphemeralCache {
|
|
4
|
+
/**
|
|
5
|
+
* Stores identifier -> reset (in milliseconds)
|
|
6
|
+
*/
|
|
7
|
+
private readonly cache: Map<string, number>;
|
|
8
|
+
|
|
9
|
+
constructor(cache: Map<string, number>) {
|
|
10
|
+
this.cache = cache;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
public isBlocked(identifier: string): { blocked: boolean; reset: number } {
|
|
14
|
+
if (!this.cache.has(identifier)) {
|
|
15
|
+
return { blocked: false, reset: 0 };
|
|
16
|
+
}
|
|
17
|
+
const reset = this.cache.get(identifier)!;
|
|
18
|
+
if (reset < Date.now()) {
|
|
19
|
+
this.cache.delete(identifier);
|
|
20
|
+
return { blocked: false, reset: 0 };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return { blocked: true, reset: reset };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
public blockUntil(identifier: string, reset: number): void {
|
|
27
|
+
this.cache.set(identifier, reset);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public set(key: string, value: number): void {
|
|
31
|
+
this.cache.set(key, value);
|
|
32
|
+
}
|
|
33
|
+
public get(key: string): number | null {
|
|
34
|
+
return this.cache.get(key) || null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public incr(key: string, incrementAmount: number = 1): number {
|
|
38
|
+
let value = this.cache.get(key) ?? 0;
|
|
39
|
+
value += incrementAmount;
|
|
40
|
+
this.cache.set(key, value);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
public pop(key: string): void {
|
|
45
|
+
this.cache.delete(key)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
public empty(): void {
|
|
49
|
+
this.cache.clear()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public size(): number {
|
|
53
|
+
return this.cache.size;
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Constants used throughout the ratelimit library
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Suffix for the global dynamic limit key in Redis
|
|
7
|
+
* Full key format: `${prefix}:dynamic:global`
|
|
8
|
+
*/
|
|
9
|
+
export const DYNAMIC_LIMIT_KEY_SUFFIX = ":dynamic:global";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Default prefix for Redis keys
|
|
13
|
+
*/
|
|
14
|
+
export const DEFAULT_PREFIX = "@upstash/ratelimit";
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { DeniedValue, DenyListResponse, LimitPayload} from "../types";
|
|
2
|
+
import { DenyListExtension, IpDenyListStatusKey } from "../types"
|
|
3
|
+
import type { RatelimitResponse, Redis } from "../types"
|
|
4
|
+
import { Cache } from "../cache";
|
|
5
|
+
import { checkDenyListScript } from "./scripts";
|
|
6
|
+
import { updateIpDenyList } from "./ip-deny-list";
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
const denyListCache = new Cache(new Map());
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Checks items in members list and returns the first denied member
|
|
13
|
+
* in denyListCache if there are any.
|
|
14
|
+
*
|
|
15
|
+
* @param members list of values to check against the cache
|
|
16
|
+
* @returns a member from the cache. If there is none, returns undefined
|
|
17
|
+
*/
|
|
18
|
+
export const checkDenyListCache = (members: string[]): DeniedValue => {
|
|
19
|
+
return members.find(
|
|
20
|
+
member => denyListCache.isBlocked(member).blocked
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Blocks a member for 1 minute.
|
|
26
|
+
*
|
|
27
|
+
* If there are more than 1000 elements in the cache, empties
|
|
28
|
+
* it so that the cache doesn't grow in size indefinetely.
|
|
29
|
+
*
|
|
30
|
+
* @param member member to block
|
|
31
|
+
*/
|
|
32
|
+
const blockMember = (member: string) => {
|
|
33
|
+
if (denyListCache.size() > 1000) denyListCache.empty();
|
|
34
|
+
denyListCache.blockUntil(member, Date.now() + 60_000);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Checks if identifier or any of the values are in any of
|
|
39
|
+
* the denied lists in Redis.
|
|
40
|
+
*
|
|
41
|
+
* If some value is in a deny list, we block the identifier for a minute.
|
|
42
|
+
*
|
|
43
|
+
* @param redis redis client
|
|
44
|
+
* @param prefix ratelimit prefix
|
|
45
|
+
* @param members List of values (identifier, ip, user agent, country)
|
|
46
|
+
* @returns true if a member is in deny list at Redis
|
|
47
|
+
*/
|
|
48
|
+
export const checkDenyList = async (
|
|
49
|
+
redis: Redis,
|
|
50
|
+
prefix: string,
|
|
51
|
+
members: string[]
|
|
52
|
+
): Promise<DenyListResponse> => {
|
|
53
|
+
const [ deniedValues, ipDenyListStatus ] = await redis.eval(
|
|
54
|
+
checkDenyListScript,
|
|
55
|
+
[
|
|
56
|
+
[prefix, DenyListExtension, "all"].join(":"),
|
|
57
|
+
[prefix, IpDenyListStatusKey].join(":"),
|
|
58
|
+
],
|
|
59
|
+
members
|
|
60
|
+
) as [boolean[], number];
|
|
61
|
+
|
|
62
|
+
let deniedValue: DeniedValue = undefined;
|
|
63
|
+
deniedValues.map((memberDenied, index) => {
|
|
64
|
+
if (memberDenied) {
|
|
65
|
+
blockMember(members[index])
|
|
66
|
+
deniedValue = members[index]
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
deniedValue,
|
|
72
|
+
invalidIpDenyList: ipDenyListStatus === -2
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Overrides the rate limit response if deny list
|
|
78
|
+
* response indicates that value is in deny list.
|
|
79
|
+
*
|
|
80
|
+
* @param ratelimitResponse
|
|
81
|
+
* @param denyListResponse
|
|
82
|
+
* @returns
|
|
83
|
+
*/
|
|
84
|
+
export const resolveLimitPayload = (
|
|
85
|
+
redis: Redis,
|
|
86
|
+
prefix: string,
|
|
87
|
+
[ratelimitResponse, denyListResponse]: LimitPayload,
|
|
88
|
+
threshold: number
|
|
89
|
+
): RatelimitResponse => {
|
|
90
|
+
|
|
91
|
+
if (denyListResponse.deniedValue) {
|
|
92
|
+
ratelimitResponse.success = false;
|
|
93
|
+
ratelimitResponse.remaining = 0;
|
|
94
|
+
ratelimitResponse.reason = "denyList";
|
|
95
|
+
ratelimitResponse.deniedValue = denyListResponse.deniedValue
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (denyListResponse.invalidIpDenyList) {
|
|
99
|
+
const updatePromise = updateIpDenyList(redis, prefix, threshold)
|
|
100
|
+
ratelimitResponse.pending = Promise.all([
|
|
101
|
+
ratelimitResponse.pending,
|
|
102
|
+
updatePromise
|
|
103
|
+
])
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return ratelimitResponse;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
*
|
|
111
|
+
* @returns Default response to return when some item
|
|
112
|
+
* is in deny list.
|
|
113
|
+
*/
|
|
114
|
+
export const defaultDeniedResponse = (deniedValue: string): RatelimitResponse => {
|
|
115
|
+
return {
|
|
116
|
+
success: false,
|
|
117
|
+
limit: 0,
|
|
118
|
+
remaining: 0,
|
|
119
|
+
reset: 0,
|
|
120
|
+
pending: Promise.resolve(),
|
|
121
|
+
reason: "denyList",
|
|
122
|
+
deniedValue: deniedValue
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./deny-list"
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { Redis } from "../types";
|
|
2
|
+
import { DenyListExtension, IpDenyListKey, IpDenyListStatusKey } from "../types"
|
|
3
|
+
import { getIpListTTL } from "./time"
|
|
4
|
+
|
|
5
|
+
const baseUrl = "https://raw.githubusercontent.com/stamparm/ipsum/master/levels"
|
|
6
|
+
|
|
7
|
+
export class ThresholdError extends Error {
|
|
8
|
+
constructor(threshold: number) {
|
|
9
|
+
super(`Allowed threshold values are from 1 to 8, 1 and 8 included. Received: ${threshold}`);
|
|
10
|
+
this.name = "ThresholdError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Fetches the ips from the ipsum.txt at github
|
|
16
|
+
*
|
|
17
|
+
* In the repo we are using, 30+ ip lists are aggregated. The results are
|
|
18
|
+
* stores in text files from 1 to 8.
|
|
19
|
+
* https://github.com/stamparm/ipsum/tree/master/levels
|
|
20
|
+
*
|
|
21
|
+
* X.txt file holds ips which are in at least X of the lists.
|
|
22
|
+
*
|
|
23
|
+
* @param threshold ips with less than or equal to the threshold are not included
|
|
24
|
+
* @returns list of ips
|
|
25
|
+
*/
|
|
26
|
+
const getIpDenyList = async (threshold: number) => {
|
|
27
|
+
if (typeof threshold !== "number" || threshold < 1 || threshold > 8) {
|
|
28
|
+
throw new ThresholdError(threshold)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
// Fetch data from the URL
|
|
33
|
+
const response = await fetch(`${baseUrl}/${threshold}.txt`)
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
throw new Error(`Error fetching data: ${response.statusText}`)
|
|
36
|
+
}
|
|
37
|
+
const data = await response.text()
|
|
38
|
+
|
|
39
|
+
// Process the data
|
|
40
|
+
const lines = data.split("\n")
|
|
41
|
+
return lines.filter((value) => value.length > 0) // remove empty values
|
|
42
|
+
} catch (error) {
|
|
43
|
+
throw new Error(`Failed to fetch ip deny list: ${error}`)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Gets the list of ips from the github source which are not in the
|
|
49
|
+
* deny list already
|
|
50
|
+
*
|
|
51
|
+
* First, gets the ip list from github using the threshold. Then, calls redis with
|
|
52
|
+
* a transaction which does the following:
|
|
53
|
+
* - subtract the current ip deny list from all
|
|
54
|
+
* - delete current ip deny list
|
|
55
|
+
* - recreate ip deny list with the ips from github. Ips already in the users own lists
|
|
56
|
+
* are excluded.
|
|
57
|
+
* - status key is set to valid with ttl until next 2 AM UTC, which is a bit later than
|
|
58
|
+
* when the list is updated on github.
|
|
59
|
+
*
|
|
60
|
+
* @param redis redis instance
|
|
61
|
+
* @param prefix ratelimit prefix
|
|
62
|
+
* @param threshold ips with less than or equal to the threshold are not included
|
|
63
|
+
* @param ttl time to live in milliseconds for the status flag. Optional. If not
|
|
64
|
+
* passed, ttl is infferred from current time.
|
|
65
|
+
* @returns list of ips which are not in the deny list
|
|
66
|
+
* @see node_modules/@upstash/ratelimit/docs/traffic-protection.mdx
|
|
67
|
+
*/
|
|
68
|
+
export const updateIpDenyList = async (
|
|
69
|
+
redis: Redis,
|
|
70
|
+
prefix: string,
|
|
71
|
+
threshold: number,
|
|
72
|
+
ttl?: number
|
|
73
|
+
) => {
|
|
74
|
+
const allIps = await getIpDenyList(threshold)
|
|
75
|
+
|
|
76
|
+
const allDenyLists = [prefix, DenyListExtension, "all"].join(":")
|
|
77
|
+
const ipDenyList = [prefix, DenyListExtension, IpDenyListKey].join(":")
|
|
78
|
+
const statusKey = [prefix, IpDenyListStatusKey].join(":")
|
|
79
|
+
|
|
80
|
+
const transaction = redis.multi()
|
|
81
|
+
|
|
82
|
+
// remove the old ip deny list from the all set
|
|
83
|
+
transaction.sdiffstore(allDenyLists, allDenyLists, ipDenyList)
|
|
84
|
+
|
|
85
|
+
// delete the old ip deny list and create new one
|
|
86
|
+
transaction.del(ipDenyList)
|
|
87
|
+
|
|
88
|
+
transaction.sadd(ipDenyList, allIps.at(0), ...allIps.slice(1))
|
|
89
|
+
|
|
90
|
+
// make all deny list and ip deny list disjoint by removing duplicate
|
|
91
|
+
// ones from ip deny list
|
|
92
|
+
transaction.sdiffstore(ipDenyList, ipDenyList, allDenyLists)
|
|
93
|
+
|
|
94
|
+
// add remaining ips to all list
|
|
95
|
+
transaction.sunionstore(allDenyLists, allDenyLists, ipDenyList)
|
|
96
|
+
|
|
97
|
+
// set status key with ttl
|
|
98
|
+
transaction.set(statusKey, "valid", {px: ttl ?? getIpListTTL()})
|
|
99
|
+
|
|
100
|
+
return await transaction.exec()
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Disables the ip deny list by removing the ip deny list from the all
|
|
105
|
+
* set and removing the ip deny list. Also sets the status key to disabled
|
|
106
|
+
* with no ttl.
|
|
107
|
+
*
|
|
108
|
+
* @param redis redis instance
|
|
109
|
+
* @param prefix ratelimit prefix
|
|
110
|
+
* @returns
|
|
111
|
+
* @see node_modules/@upstash/ratelimit/docs/traffic-protection.mdx
|
|
112
|
+
*/
|
|
113
|
+
export const disableIpDenyList = async (redis: Redis, prefix: string) => {
|
|
114
|
+
const allDenyListsKey = [prefix, DenyListExtension, "all"].join(":")
|
|
115
|
+
const ipDenyListKey = [prefix, DenyListExtension, IpDenyListKey].join(":")
|
|
116
|
+
const statusKey = [prefix, IpDenyListStatusKey].join(":")
|
|
117
|
+
|
|
118
|
+
const transaction = redis.multi()
|
|
119
|
+
|
|
120
|
+
// remove the old ip deny list from the all set
|
|
121
|
+
transaction.sdiffstore(allDenyListsKey, allDenyListsKey, ipDenyListKey)
|
|
122
|
+
|
|
123
|
+
// delete the old ip deny list
|
|
124
|
+
transaction.del(ipDenyListKey)
|
|
125
|
+
|
|
126
|
+
// set to disabled
|
|
127
|
+
// this way, the TTL command in checkDenyListScript will return -1.
|
|
128
|
+
transaction.set(statusKey, "disabled")
|
|
129
|
+
|
|
130
|
+
return await transaction.exec()
|
|
131
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export const checkDenyListScript = `
|
|
2
|
+
-- Checks if values provideed in ARGV are present in the deny lists.
|
|
3
|
+
-- This is done using the allDenyListsKey below.
|
|
4
|
+
|
|
5
|
+
-- Additionally, checks the status of the ip deny list using the
|
|
6
|
+
-- ipDenyListStatusKey below. Here are the possible states of the
|
|
7
|
+
-- ipDenyListStatusKey key:
|
|
8
|
+
-- * status == -1: set to "disabled" with no TTL
|
|
9
|
+
-- * status == -2: not set, meaning that is was set before but expired
|
|
10
|
+
-- * status > 0: set to "valid", with a TTL
|
|
11
|
+
--
|
|
12
|
+
-- In the case of status == -2, we set the status to "pending" with
|
|
13
|
+
-- 30 second ttl. During this time, the process which got status == -2
|
|
14
|
+
-- will update the ip deny list.
|
|
15
|
+
|
|
16
|
+
local allDenyListsKey = KEYS[1]
|
|
17
|
+
local ipDenyListStatusKey = KEYS[2]
|
|
18
|
+
|
|
19
|
+
local results = redis.call('SMISMEMBER', allDenyListsKey, unpack(ARGV))
|
|
20
|
+
local status = redis.call('TTL', ipDenyListStatusKey)
|
|
21
|
+
if status == -2 then
|
|
22
|
+
redis.call('SETEX', ipDenyListStatusKey, 30, "pending")
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
return { results, status }
|
|
26
|
+
`
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
|
|
2
|
+
// Number of milliseconds in one hour
|
|
3
|
+
const MILLISECONDS_IN_HOUR = 60 * 60 * 1000;
|
|
4
|
+
|
|
5
|
+
// Number of milliseconds in one day
|
|
6
|
+
const MILLISECONDS_IN_DAY = 24 * MILLISECONDS_IN_HOUR;
|
|
7
|
+
|
|
8
|
+
// Number of milliseconds from the current time to 2 AM UTC
|
|
9
|
+
const MILLISECONDS_TO_2AM = 2 * MILLISECONDS_IN_HOUR;
|
|
10
|
+
|
|
11
|
+
export const getIpListTTL = (time?: number) => {
|
|
12
|
+
const now = time || Date.now();
|
|
13
|
+
|
|
14
|
+
// Time since the last 2 AM UTC
|
|
15
|
+
const timeSinceLast2AM = (now - MILLISECONDS_TO_2AM) % MILLISECONDS_IN_DAY;
|
|
16
|
+
|
|
17
|
+
// Remaining time until the next 2 AM UTC
|
|
18
|
+
return MILLISECONDS_IN_DAY - timeSinceLast2AM;
|
|
19
|
+
}
|
|
20
|
+
|
package/src/duration.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
type Unit = "ms" | "s" | "m" | "h" | "d" | "w";
|
|
2
|
+
export type Duration = `${number} ${Unit}` | `${number}${Unit}`;
|
|
3
|
+
|
|
4
|
+
const MULTIPLIERS: Record<Unit, number> = {
|
|
5
|
+
ms: 1,
|
|
6
|
+
s: 1000,
|
|
7
|
+
m: 1000 * 60,
|
|
8
|
+
h: 1000 * 60 * 60,
|
|
9
|
+
d: 1000 * 60 * 60 * 24,
|
|
10
|
+
w: 1000 * 60 * 60 * 24 * 7,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Convert a human readable duration to milliseconds
|
|
15
|
+
*/
|
|
16
|
+
export function ms(d: Duration): number {
|
|
17
|
+
const match = d.match(/^(\d+(?:\.\d+)?)\s?(ms|s|m|h|d|w)$/);
|
|
18
|
+
if (!match) {
|
|
19
|
+
throw new Error(`Unable to parse window size: ${d}`);
|
|
20
|
+
}
|
|
21
|
+
const time = Number.parseFloat(match[1]);
|
|
22
|
+
const unit = match[2] as Unit;
|
|
23
|
+
|
|
24
|
+
const multiplier = MULTIPLIERS[unit];
|
|
25
|
+
if (multiplier === undefined) {
|
|
26
|
+
throw new Error(`Unable to parse window size: ${d}`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Durations are sent to Redis as integer milliseconds (PEXPIRE etc.), so
|
|
30
|
+
// decimals are rounded. A value that rounds to 0 would produce a zero-width
|
|
31
|
+
// window, so reject it here with a clear message.
|
|
32
|
+
const result = Math.round(time * multiplier);
|
|
33
|
+
if (result < 1) {
|
|
34
|
+
throw new Error(`Window size must be at least 1 ms, got: ${d}`);
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
package/src/hash.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ScriptInfo } from "./lua-scripts/hash";
|
|
2
|
+
import type { RegionContext } from "./types";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Runs the specified script with EVALSHA using the scriptHash parameter.
|
|
6
|
+
*
|
|
7
|
+
* If the EVALSHA fails, loads the script to redis and runs again with the
|
|
8
|
+
* hash returned from Redis.
|
|
9
|
+
*
|
|
10
|
+
* @param ctx Regional or multi region context
|
|
11
|
+
* @param script ScriptInfo of script to run. Contains the script and its hash
|
|
12
|
+
* @param keys eval keys
|
|
13
|
+
* @param args eval args
|
|
14
|
+
*/
|
|
15
|
+
export const safeEval = async (
|
|
16
|
+
ctx: RegionContext,
|
|
17
|
+
script: ScriptInfo,
|
|
18
|
+
keys: any[],
|
|
19
|
+
args: any[],
|
|
20
|
+
) => {
|
|
21
|
+
try {
|
|
22
|
+
return await ctx.redis.evalsha(script.hash, keys, args)
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (`${error}`.includes("NOSCRIPT")) {
|
|
25
|
+
return await ctx.redis.eval(script.script, keys, args)
|
|
26
|
+
}
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
export {Analytics, type AnalyticsConfig} from "./analytics";
|
|
14
|
+
export {MultiRegionRatelimit, type MultiRegionRatelimitConfig} from "./multi";
|
|
15
|
+
export {RegionRatelimit as Ratelimit, type RegionRatelimitConfig as RatelimitConfig} from "./single";
|
|
16
|
+
export {type Algorithm} from "./types";
|
|
17
|
+
export * as IpDenyList from "./deny-list/ip-deny-list";
|
|
18
|
+
export {type Duration} from "./duration";
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import * as Single from "./single"
|
|
2
|
+
import * as Multi from "./multi"
|
|
3
|
+
import { resetScript } from "./reset"
|
|
4
|
+
|
|
5
|
+
export type ScriptInfo = {
|
|
6
|
+
script: string,
|
|
7
|
+
hash: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
type Algorithm = {
|
|
11
|
+
limit: ScriptInfo,
|
|
12
|
+
getRemaining: ScriptInfo,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type AlgorithmKind =
|
|
16
|
+
| "fixedWindow"
|
|
17
|
+
| "slidingWindow"
|
|
18
|
+
| "tokenBucket"
|
|
19
|
+
| "cachedFixedWindow"
|
|
20
|
+
|
|
21
|
+
export const SCRIPTS: {
|
|
22
|
+
singleRegion: Record<AlgorithmKind, Algorithm>,
|
|
23
|
+
multiRegion: Record<Exclude<AlgorithmKind, "tokenBucket" | "cachedFixedWindow">, Algorithm>,
|
|
24
|
+
} = {
|
|
25
|
+
singleRegion: {
|
|
26
|
+
fixedWindow: {
|
|
27
|
+
limit: {
|
|
28
|
+
script: Single.fixedWindowLimitScript,
|
|
29
|
+
hash: "b2efc02798c8e9b471a10f9b1d5745db89923ff3"
|
|
30
|
+
},
|
|
31
|
+
getRemaining: {
|
|
32
|
+
script: Single.fixedWindowRemainingTokensScript,
|
|
33
|
+
hash: "823cb2a5a902d69681244f5e28e5ebb8f2a89edd"
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
slidingWindow: {
|
|
37
|
+
limit: {
|
|
38
|
+
script: Single.slidingWindowLimitScript,
|
|
39
|
+
hash: "74740bb3d7792848093cdef586b6b6037c455fd6"
|
|
40
|
+
},
|
|
41
|
+
getRemaining: {
|
|
42
|
+
script: Single.slidingWindowRemainingTokensScript,
|
|
43
|
+
hash: "7ca36169e0fc9caedd81b4eef8e99854c157f9b5"
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
tokenBucket: {
|
|
47
|
+
limit: {
|
|
48
|
+
script: Single.tokenBucketLimitScript,
|
|
49
|
+
hash: "d60be5bd3d83482ae229309f1f7425424f891204"
|
|
50
|
+
},
|
|
51
|
+
getRemaining: {
|
|
52
|
+
script: Single.tokenBucketRemainingTokensScript,
|
|
53
|
+
hash: "40daf4a441df736f5c99f8b77bbe176c909e5de4"
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
cachedFixedWindow: {
|
|
57
|
+
limit: {
|
|
58
|
+
script: Single.cachedFixedWindowLimitScript,
|
|
59
|
+
hash: "1861a700bafe96c833a483af6b1c28a8897cfdb0"
|
|
60
|
+
},
|
|
61
|
+
getRemaining: {
|
|
62
|
+
script: Single.cachedFixedWindowRemainingTokenScript,
|
|
63
|
+
hash: "eb82f0e853d2fc9a236fa9bfbe704fda6ac2fc36"
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
multiRegion: {
|
|
68
|
+
fixedWindow: {
|
|
69
|
+
limit: {
|
|
70
|
+
script: Multi.fixedWindowLimitScript,
|
|
71
|
+
hash: "e04b753a75909b7f99aae4c04cf8869a8de02a9e"
|
|
72
|
+
},
|
|
73
|
+
getRemaining: {
|
|
74
|
+
script: Multi.fixedWindowRemainingTokensScript,
|
|
75
|
+
hash: "e066c8ce3eaca142b0894ad1541e0a58c9924819"
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
slidingWindow: {
|
|
79
|
+
limit: {
|
|
80
|
+
script: Multi.slidingWindowLimitScript,
|
|
81
|
+
hash: "aeb4d8f381e8dafc8e69041baae1324d254ded44"
|
|
82
|
+
},
|
|
83
|
+
getRemaining: {
|
|
84
|
+
script: Multi.slidingWindowRemainingTokensScript,
|
|
85
|
+
hash: "87828c1088f6a8d1f512a434ea330189982a1c0a"
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** COMMON */
|
|
92
|
+
export const RESET_SCRIPT: ScriptInfo = {
|
|
93
|
+
script: resetScript,
|
|
94
|
+
hash: "54bd274ddc59fb3be0f42deee2f64322a10e2b50"
|
|
95
|
+
}
|