@aomex/rate-limit 0.0.1
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 +11 -0
- package/LICENSE +21 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +78 -0
- package/dist/index.js.map +1 -0
- package/package.json +50 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @aomex/rate-limit
|
|
2
|
+
|
|
3
|
+
## 0.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [`7bcb2fc`](https://github.com/aomex/aomex/commit/7bcb2fccbe99675b0edca32ff3af9599113e754b) Thanks [@geekact](https://github.com/geekact)! - 增加 web 插件 rate-limit
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [[`4735157`](https://github.com/aomex/aomex/commit/4735157c52d0abecc41d6c7f416280ebfd6ee696), [`d6ac7b5`](https://github.com/aomex/aomex/commit/d6ac7b5403334b51fa15dbe82dd6b5b6d048f661), [`9254754`](https://github.com/aomex/aomex/commit/9254754d234fc0062eb5d600284ee8453825306c), [`d1ce4e2`](https://github.com/aomex/aomex/commit/d1ce4e2276f93c44e67ea06666d048917fa94e53), [`6056f55`](https://github.com/aomex/aomex/commit/6056f556577865220d6b5be2a4eafad9e4dbf8d4), [`1c67399`](https://github.com/aomex/aomex/commit/1c673992c4b313c2accb4cbc1fc66537a9886c29), [`352642a`](https://github.com/aomex/aomex/commit/352642abf2ccb3fe97e2d83a691d8428ccfc9758)]:
|
|
10
|
+
- @aomex/web@0.0.3
|
|
11
|
+
- @aomex/core@0.0.2
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 geekact
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Storage } from '@aomex/core';
|
|
2
|
+
import { WebContext, WebMiddleware } from '@aomex/web';
|
|
3
|
+
|
|
4
|
+
interface RateLimitOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The database powering the backing rate-limiter package.
|
|
7
|
+
*/
|
|
8
|
+
storage?: Storage;
|
|
9
|
+
/**
|
|
10
|
+
* The length of a single limiting period. This value is expressed
|
|
11
|
+
* in milliseconds, defaulting to one hour.
|
|
12
|
+
*/
|
|
13
|
+
duration?: number;
|
|
14
|
+
/**
|
|
15
|
+
* The maximum amount of requests a client (see the `id` field) may
|
|
16
|
+
* make during a limiting period. (see `duration`)
|
|
17
|
+
*/
|
|
18
|
+
max?: number;
|
|
19
|
+
/**
|
|
20
|
+
* Get the unique-identifier for a request. This defaults to the
|
|
21
|
+
* client's IP address. Returning "false" will skip rate-limiting.
|
|
22
|
+
*/
|
|
23
|
+
id?: (ctx: WebContext) => string | false;
|
|
24
|
+
/**
|
|
25
|
+
* Whether or not to disable the usage of rate limit headers. This defaults
|
|
26
|
+
* to **false**.
|
|
27
|
+
*/
|
|
28
|
+
disableHeader?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* The message used on the response body if a client is rate-limited. There is
|
|
31
|
+
* a default message; which includes when they should try again.
|
|
32
|
+
*/
|
|
33
|
+
errorMessage?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Whether or not to throw an error upon being rate-limited. This uses
|
|
36
|
+
* the Koa context function "throw".
|
|
37
|
+
*/
|
|
38
|
+
throw?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* A relation of header to the header's display name.
|
|
41
|
+
*/
|
|
42
|
+
headers?: {
|
|
43
|
+
/**
|
|
44
|
+
* The amount of requests remaining in the current limiting period.
|
|
45
|
+
*/
|
|
46
|
+
remaining?: string;
|
|
47
|
+
/**
|
|
48
|
+
* The time, expressed as a UNIX epoch timestamp, at which your rate-limit expires.
|
|
49
|
+
*/
|
|
50
|
+
reset?: string;
|
|
51
|
+
/**
|
|
52
|
+
* The total amount of requests a client may make during a limiting period.
|
|
53
|
+
*/
|
|
54
|
+
total?: string;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* If function returns true, middleware exits before limiting
|
|
58
|
+
*/
|
|
59
|
+
allowList?: (ctx: WebContext) => boolean | Promise<boolean>;
|
|
60
|
+
/**
|
|
61
|
+
* If function returns true, 403 error is thrown
|
|
62
|
+
*/
|
|
63
|
+
denyList?: (ctx: WebContext) => boolean | Promise<boolean>;
|
|
64
|
+
}
|
|
65
|
+
declare const rateLimit: (options?: RateLimitOptions) => WebMiddleware;
|
|
66
|
+
|
|
67
|
+
export { RateLimitOptions, rateLimit };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { middleware, MemoryStorage } from "@aomex/core";
|
|
3
|
+
import microtime from "microtime";
|
|
4
|
+
import ms from "ms";
|
|
5
|
+
var getState = async (storage, id, max, duration) => {
|
|
6
|
+
const key = `ratelimit:${id}`;
|
|
7
|
+
let state = await storage.get(key);
|
|
8
|
+
const now = microtime.now();
|
|
9
|
+
const expired = state && state.reset * 1e6 < now;
|
|
10
|
+
if (!state || expired) {
|
|
11
|
+
state = {
|
|
12
|
+
id,
|
|
13
|
+
reset: (now + duration * 1e3) / 1e6,
|
|
14
|
+
current: max,
|
|
15
|
+
total: max
|
|
16
|
+
};
|
|
17
|
+
} else {
|
|
18
|
+
state.current = state.current > 0 ? state.current - 1 : 0;
|
|
19
|
+
}
|
|
20
|
+
await storage.set(key, state);
|
|
21
|
+
return state;
|
|
22
|
+
};
|
|
23
|
+
var rateLimit = (options = {}) => {
|
|
24
|
+
const {
|
|
25
|
+
storage = new MemoryStorage(),
|
|
26
|
+
duration = 3600 * 1e3,
|
|
27
|
+
// 1 hour
|
|
28
|
+
max = 2500,
|
|
29
|
+
id: getId = (ctx) => ctx.request.ip,
|
|
30
|
+
headers = {},
|
|
31
|
+
disableHeader = false,
|
|
32
|
+
denyList,
|
|
33
|
+
allowList
|
|
34
|
+
} = options;
|
|
35
|
+
const {
|
|
36
|
+
remaining = "X-RateLimit-Remaining",
|
|
37
|
+
reset = "X-RateLimit-Reset",
|
|
38
|
+
total = "X-RateLimit-Limit"
|
|
39
|
+
} = headers;
|
|
40
|
+
return middleware.web(async (ctx, next) => {
|
|
41
|
+
if (denyList && await denyList(ctx)) {
|
|
42
|
+
ctx.throw(403);
|
|
43
|
+
}
|
|
44
|
+
const id = getId(ctx);
|
|
45
|
+
if (id === false || allowList && await allowList(ctx)) {
|
|
46
|
+
return next();
|
|
47
|
+
}
|
|
48
|
+
const { response } = ctx;
|
|
49
|
+
const state = await getState(storage, id, max, duration);
|
|
50
|
+
let headers2 = {};
|
|
51
|
+
if (!disableHeader) {
|
|
52
|
+
headers2 = {
|
|
53
|
+
[remaining]: state.current > 0 ? state.current - 1 : 0,
|
|
54
|
+
[reset]: state.reset,
|
|
55
|
+
[total]: state.total
|
|
56
|
+
};
|
|
57
|
+
response.setHeaders(headers2);
|
|
58
|
+
}
|
|
59
|
+
if (state.current)
|
|
60
|
+
return next();
|
|
61
|
+
const now = Date.now();
|
|
62
|
+
const delta = Math.round(state.reset * 1e3 - now);
|
|
63
|
+
const after = Math.round(state.reset - now / 1e3);
|
|
64
|
+
const status = 429;
|
|
65
|
+
const body = options.errorMessage || `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;
|
|
66
|
+
response.setHeader("retry-after", after);
|
|
67
|
+
response.statusCode = status;
|
|
68
|
+
if (options.throw) {
|
|
69
|
+
ctx.throw(status, body, { headers: headers2 });
|
|
70
|
+
} else {
|
|
71
|
+
ctx.send(body);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
};
|
|
75
|
+
export {
|
|
76
|
+
rateLimit
|
|
77
|
+
};
|
|
78
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { middleware, Storage, MemoryStorage } from '@aomex/core';\nimport type { WebContext, WebMiddleware } from '@aomex/web';\nimport microtime from 'microtime';\nimport ms from 'ms';\n\nexport interface RateLimitOptions {\n /**\n * The database powering the backing rate-limiter package.\n */\n storage?: Storage;\n\n /**\n * The length of a single limiting period. This value is expressed\n * in milliseconds, defaulting to one hour.\n */\n duration?: number;\n\n /**\n * The maximum amount of requests a client (see the `id` field) may\n * make during a limiting period. (see `duration`)\n */\n max?: number;\n\n /**\n * Get the unique-identifier for a request. This defaults to the\n * client's IP address. Returning \"false\" will skip rate-limiting.\n */\n id?: (ctx: WebContext) => string | false;\n\n /**\n * Whether or not to disable the usage of rate limit headers. This defaults\n * to **false**.\n */\n disableHeader?: boolean;\n\n /**\n * The message used on the response body if a client is rate-limited. There is\n * a default message; which includes when they should try again.\n */\n errorMessage?: string;\n\n /**\n * Whether or not to throw an error upon being rate-limited. This uses\n * the Koa context function \"throw\".\n */\n throw?: boolean;\n\n /**\n * A relation of header to the header's display name.\n */\n headers?: {\n /**\n * The amount of requests remaining in the current limiting period.\n */\n remaining?: string;\n\n /**\n * The time, expressed as a UNIX epoch timestamp, at which your rate-limit expires.\n */\n reset?: string;\n\n /**\n * The total amount of requests a client may make during a limiting period.\n */\n total?: string;\n };\n\n /**\n * If function returns true, middleware exits before limiting\n */\n allowList?: (ctx: WebContext) => boolean | Promise<boolean>;\n\n /**\n * If function returns true, 403 error is thrown\n */\n denyList?: (ctx: WebContext) => boolean | Promise<boolean>;\n}\n\ninterface LimitState {\n id: string;\n reset: number;\n current: number;\n total: number;\n}\n\nconst getState = async (\n storage: Storage,\n id: string,\n max: number,\n duration: number,\n) => {\n const key = `ratelimit:${id}`;\n let state = await storage.get<LimitState>(key);\n const now = microtime.now();\n const expired = state && state.reset * 1e6 < now;\n\n if (!state || expired) {\n state = {\n id,\n reset: (now + duration * 1e3) / 1e6,\n current: max,\n total: max,\n };\n } else {\n state.current = state.current > 0 ? state.current - 1 : 0;\n }\n\n await storage.set(key, state);\n return state!;\n};\n\nexport const rateLimit = (options: RateLimitOptions = {}): WebMiddleware => {\n const {\n storage = new MemoryStorage(),\n duration = 3600 * 1000, // 1 hour\n max = 2500,\n id: getId = (ctx) => ctx.request.ip,\n headers = {},\n disableHeader = false,\n denyList,\n allowList,\n } = options;\n\n const {\n remaining = 'X-RateLimit-Remaining',\n reset = 'X-RateLimit-Reset',\n total = 'X-RateLimit-Limit',\n } = headers;\n\n return middleware.web(async (ctx, next) => {\n if (denyList && (await denyList(ctx))) {\n ctx.throw(403);\n }\n\n const id = getId(ctx);\n if (id === false || (allowList && (await allowList(ctx)))) {\n return next();\n }\n\n const { response } = ctx;\n const state = await getState(storage, id, max, duration);\n let headers: Record<string, number> = {};\n if (!disableHeader) {\n headers = {\n [remaining]: state.current > 0 ? state.current - 1 : 0,\n [reset]: state.reset,\n [total]: state.total,\n };\n response.setHeaders(headers);\n }\n\n if (state.current) return next();\n\n const now = Date.now();\n const delta = Math.round(state.reset * 1e3 - now);\n const after = Math.round(state.reset - now / 1e3);\n const status = 429;\n const body =\n options.errorMessage ||\n `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;\n\n response.setHeader('retry-after', after);\n response.statusCode = status;\n\n if (options.throw) {\n ctx.throw(status, body, { headers });\n } else {\n ctx.send(body);\n }\n });\n};\n"],"mappings":";AAAA,SAAS,YAAqB,qBAAqB;AAEnD,OAAO,eAAe;AACtB,OAAO,QAAQ;AAkFf,IAAM,WAAW,OACf,SACA,IACA,KACA,aACG;AACH,QAAM,MAAM,aAAa;AACzB,MAAI,QAAQ,MAAM,QAAQ,IAAgB,GAAG;AAC7C,QAAM,MAAM,UAAU,IAAI;AAC1B,QAAM,UAAU,SAAS,MAAM,QAAQ,MAAM;AAE7C,MAAI,CAAC,SAAS,SAAS;AACrB,YAAQ;AAAA,MACN;AAAA,MACA,QAAQ,MAAM,WAAW,OAAO;AAAA,MAChC,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,UAAM,UAAU,MAAM,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EAC1D;AAEA,QAAM,QAAQ,IAAI,KAAK,KAAK;AAC5B,SAAO;AACT;AAEO,IAAM,YAAY,CAAC,UAA4B,CAAC,MAAqB;AAC1E,QAAM;AAAA,IACJ,UAAU,IAAI,cAAc;AAAA,IAC5B,WAAW,OAAO;AAAA;AAAA,IAClB,MAAM;AAAA,IACN,IAAI,QAAQ,CAAC,QAAQ,IAAI,QAAQ;AAAA,IACjC,UAAU,CAAC;AAAA,IACX,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM;AAAA,IACJ,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,IAAI;AAEJ,SAAO,WAAW,IAAI,OAAO,KAAK,SAAS;AACzC,QAAI,YAAa,MAAM,SAAS,GAAG,GAAI;AACrC,UAAI,MAAM,GAAG;AAAA,IACf;AAEA,UAAM,KAAK,MAAM,GAAG;AACpB,QAAI,OAAO,SAAU,aAAc,MAAM,UAAU,GAAG,GAAK;AACzD,aAAO,KAAK;AAAA,IACd;AAEA,UAAM,EAAE,SAAS,IAAI;AACrB,UAAM,QAAQ,MAAM,SAAS,SAAS,IAAI,KAAK,QAAQ;AACvD,QAAIA,WAAkC,CAAC;AACvC,QAAI,CAAC,eAAe;AAClB,MAAAA,WAAU;AAAA,QACR,CAAC,SAAS,GAAG,MAAM,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,QACrD,CAAC,KAAK,GAAG,MAAM;AAAA,QACf,CAAC,KAAK,GAAG,MAAM;AAAA,MACjB;AACA,eAAS,WAAWA,QAAO;AAAA,IAC7B;AAEA,QAAI,MAAM;AAAS,aAAO,KAAK;AAE/B,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,MAAM,GAAG;AAChD,UAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,MAAM,GAAG;AAChD,UAAM,SAAS;AACf,UAAM,OACJ,QAAQ,gBACR,iCAAiC,GAAG,OAAO,EAAE,MAAM,KAAK,CAAC;AAE3D,aAAS,UAAU,eAAe,KAAK;AACvC,aAAS,aAAa;AAEtB,QAAI,QAAQ,OAAO;AACjB,UAAI,MAAM,QAAQ,MAAM,EAAE,SAAAA,SAAQ,CAAC;AAAA,IACrC,OAAO;AACL,UAAI,KAAK,IAAI;AAAA,IACf;AAAA,EACF,CAAC;AACH;","names":["headers"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@aomex/rate-limit",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "请求访问次数限制",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"rate-limit"
|
|
7
|
+
],
|
|
8
|
+
"repository": "git@github.com:aomex/aomex.git",
|
|
9
|
+
"homepage": "https://aomex.js.org",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"type": "module",
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"types": "dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"package.json",
|
|
25
|
+
"README.md",
|
|
26
|
+
"CHANGELOG.md"
|
|
27
|
+
],
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@aomex/core": "^0.0.2",
|
|
33
|
+
"@aomex/web": "^0.0.3"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"microtime": "^3.1.1",
|
|
37
|
+
"ms": "^2.1.3"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@aomex/core": "^0.0.2",
|
|
41
|
+
"@aomex/web": "^0.0.3",
|
|
42
|
+
"@types/microtime": "^2.1.0",
|
|
43
|
+
"@types/ms": "^0.7.31",
|
|
44
|
+
"@types/supertest": "^2.0.12",
|
|
45
|
+
"sleep-promise": "^9.1.0",
|
|
46
|
+
"supertest": "^6.2.4",
|
|
47
|
+
"vitest": "^0.28.4"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {}
|
|
50
|
+
}
|