@aomex/rate-limit 0.0.1 → 0.0.3

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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # @aomex/rate-limit
2
2
 
3
+ ## 0.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [`d8debb9`](https://github.com/aomex/aomex/commit/d8debb9b6319d30e48cb77d97103b5559c57789c) Thanks [@geekact](https://github.com/geekact)! - refactor(web): response 的 header 均使用首字母大写的格式
8
+
9
+ - Updated dependencies [[`d8debb9`](https://github.com/aomex/aomex/commit/d8debb9b6319d30e48cb77d97103b5559c57789c), [`64c10e1`](https://github.com/aomex/aomex/commit/64c10e17ff92251bb2d9f45e0bddde5cba8a3b20), [`6a57463`](https://github.com/aomex/aomex/commit/6a57463c1107c38a8b8cf5fa00ff3289bf629c0a), [`8857115`](https://github.com/aomex/aomex/commit/88571153b7e84ec6d66d37970c3ef7b4e1924a03), [`68b1365`](https://github.com/aomex/aomex/commit/68b13655922a0714bcdd2101ce659da382d44e8b), [`b51a81a`](https://github.com/aomex/aomex/commit/b51a81a65313073dff5307b310b6656da2ad5186), [`ee021e3`](https://github.com/aomex/aomex/commit/ee021e342814f12777e538c06a19971e1020f201), [`b5aaec5`](https://github.com/aomex/aomex/commit/b5aaec540e3d732868a270a969a94ccd6ff9ac6a), [`fd6ae40`](https://github.com/aomex/aomex/commit/fd6ae40577bd9a62c211d4615483fc5dd58f5865)]:
10
+ - @aomex/web@0.0.5
11
+ - @aomex/core@0.0.4
12
+
13
+ ## 0.0.2
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [[`121253a`](https://github.com/aomex/aomex/commit/121253a6fc203e427bfd25e82d713bec6ac13b38), [`59dc183`](https://github.com/aomex/aomex/commit/59dc183bcec9b7221c18865563b38cba5d82869b), [`8cb74fd`](https://github.com/aomex/aomex/commit/8cb74fdd27626037aa9bc80cb2930e4f0d67f8e6), [`d834392`](https://github.com/aomex/aomex/commit/d834392b1e0f6333d66d11378d9f4ceb813a58a9), [`91feda4`](https://github.com/aomex/aomex/commit/91feda457dfa8bd8dd2c8f38bfaaf4f7f2f7702f)]:
18
+ - @aomex/web@0.0.4
19
+ - @aomex/core@0.0.3
20
+
3
21
  ## 0.0.1
4
22
 
5
23
  ### Patch Changes
package/dist/index.js CHANGED
@@ -63,7 +63,7 @@ var rateLimit = (options = {}) => {
63
63
  const after = Math.round(state.reset - now / 1e3);
64
64
  const status = 429;
65
65
  const body = options.errorMessage || `Rate limit exceeded, retry in ${ms(delta, { long: true })}.`;
66
- response.setHeader("retry-after", after);
66
+ response.setHeader("Retry-After", after);
67
67
  response.statusCode = status;
68
68
  if (options.throw) {
69
69
  ctx.throw(status, body, { headers: headers2 });
package/dist/index.js.map CHANGED
@@ -1 +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"]}
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,QAA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headers"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aomex/rate-limit",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "请求访问次数限制",
5
5
  "keywords": [
6
6
  "rate-limit"
@@ -29,22 +29,18 @@
29
29
  "access": "public"
30
30
  },
31
31
  "peerDependencies": {
32
- "@aomex/core": "^0.0.2",
33
- "@aomex/web": "^0.0.3"
32
+ "@aomex/core": "^0.0.4",
33
+ "@aomex/web": "^0.0.5"
34
34
  },
35
35
  "dependencies": {
36
36
  "microtime": "^3.1.1",
37
37
  "ms": "^2.1.3"
38
38
  },
39
39
  "devDependencies": {
40
- "@aomex/core": "^0.0.2",
41
- "@aomex/web": "^0.0.3",
40
+ "@aomex/core": "^0.0.4",
41
+ "@aomex/web": "^0.0.5",
42
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"
43
+ "@types/ms": "^0.7.31"
48
44
  },
49
45
  "scripts": {}
50
46
  }