@davaux/rate-limit 0.8.0 → 0.8.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/dist/index.d.ts +64 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/package.json +6 -3
- package/CLAUDE.md +0 -95
- package/src/index.ts +0 -124
- package/tsconfig.json +0 -17
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { MiddlewareFn, RequestContext } from 'davaux';
|
|
2
|
+
export interface RateLimitResult {
|
|
3
|
+
/** Total hits in the current window. */
|
|
4
|
+
count: number;
|
|
5
|
+
/** Unix timestamp (ms) when the current window resets. */
|
|
6
|
+
resetAt: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Backing store for rate limit counters. The default `MemoryStore` works for
|
|
10
|
+
* single-process deployments. Implement this interface and pass it via
|
|
11
|
+
* `options.store` to use Redis, Valkey, or any other backend.
|
|
12
|
+
*/
|
|
13
|
+
export interface RateLimitStore {
|
|
14
|
+
increment(key: string, windowMs: number): Promise<RateLimitResult>;
|
|
15
|
+
}
|
|
16
|
+
/** In-memory rate-limit counter store. Suitable for single-process deployments. */
|
|
17
|
+
export declare class MemoryStore implements RateLimitStore {
|
|
18
|
+
private readonly hits;
|
|
19
|
+
increment(key: string, windowMs: number): Promise<RateLimitResult>;
|
|
20
|
+
}
|
|
21
|
+
export interface RateLimitOptions {
|
|
22
|
+
/** Time window in milliseconds. */
|
|
23
|
+
windowMs: number;
|
|
24
|
+
/** Maximum number of requests allowed per window per key. */
|
|
25
|
+
max: number;
|
|
26
|
+
/**
|
|
27
|
+
* Function that derives the rate-limit key from the request context.
|
|
28
|
+
* Default: the client's IP address (`req.socket.remoteAddress`).
|
|
29
|
+
*/
|
|
30
|
+
keyFn?: (ctx: RequestContext) => string;
|
|
31
|
+
/**
|
|
32
|
+
* Body of the 429 response.
|
|
33
|
+
* Default: `'Too Many Requests'`
|
|
34
|
+
*/
|
|
35
|
+
message?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Backing store. Default: `MemoryStore` (suitable for single-process apps).
|
|
38
|
+
* Pass a custom implementation for Redis or other distributed stores.
|
|
39
|
+
*/
|
|
40
|
+
store?: RateLimitStore;
|
|
41
|
+
/**
|
|
42
|
+
* When `true`, rate-limit headers are sent on every response, not just 429s.
|
|
43
|
+
* Default: `true`
|
|
44
|
+
*/
|
|
45
|
+
headers?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* When `true`, the leftmost IP in `X-Forwarded-For` is used as the rate-limit
|
|
48
|
+
* key instead of `req.socket.remoteAddress`. Only enable when the app runs
|
|
49
|
+
* behind a trusted reverse proxy — clients can spoof this header otherwise.
|
|
50
|
+
* Default: `false`
|
|
51
|
+
*/
|
|
52
|
+
trustProxy?: boolean;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Rate-limiting middleware. Counts requests per key within a rolling time
|
|
56
|
+
* window and returns `429 Too Many Requests` when the limit is exceeded.
|
|
57
|
+
* Standard `RateLimit-*` headers are sent on every response by default.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* import { rateLimit } from '@davaux/rate-limit'
|
|
61
|
+
* export default rateLimit({ windowMs: 60_000, max: 100 })
|
|
62
|
+
*/
|
|
63
|
+
export declare function rateLimit(options: RateLimitOptions): MiddlewareFn;
|
|
64
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAA;AAI1D,MAAM,WAAW,eAAe;IAC9B,wCAAwC;IACxC,KAAK,EAAE,MAAM,CAAA;IACb,0DAA0D;IAC1D,OAAO,EAAE,MAAM,CAAA;CAChB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAAA;CACnE;AAID,mFAAmF;AACnF,qBAAa,WAAY,YAAW,cAAc;IAChD,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAqC;IAEpD,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;CAazE;AAID,MAAM,WAAW,gBAAgB;IAC/B,mCAAmC;IACnC,QAAQ,EAAE,MAAM,CAAA;IAChB,6DAA6D;IAC7D,GAAG,EAAE,MAAM,CAAA;IACX;;;OAGG;IACH,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,MAAM,CAAA;IACvC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,KAAK,CAAC,EAAE,cAAc,CAAA;IACtB;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAID;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,YAAY,CA2BjE"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// ─── In-memory store ──────────────────────────────────────────────────────────
|
|
2
|
+
/** In-memory rate-limit counter store. Suitable for single-process deployments. */
|
|
3
|
+
export class MemoryStore {
|
|
4
|
+
hits = new Map();
|
|
5
|
+
async increment(key, windowMs) {
|
|
6
|
+
const now = Date.now();
|
|
7
|
+
const entry = this.hits.get(key);
|
|
8
|
+
if (!entry || now >= entry.resetAt) {
|
|
9
|
+
const result = { count: 1, resetAt: now + windowMs };
|
|
10
|
+
this.hits.set(key, result);
|
|
11
|
+
return result;
|
|
12
|
+
}
|
|
13
|
+
entry.count++;
|
|
14
|
+
return { count: entry.count, resetAt: entry.resetAt };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
// ─── Middleware ───────────────────────────────────────────────────────────────
|
|
18
|
+
/**
|
|
19
|
+
* Rate-limiting middleware. Counts requests per key within a rolling time
|
|
20
|
+
* window and returns `429 Too Many Requests` when the limit is exceeded.
|
|
21
|
+
* Standard `RateLimit-*` headers are sent on every response by default.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* import { rateLimit } from '@davaux/rate-limit'
|
|
25
|
+
* export default rateLimit({ windowMs: 60_000, max: 100 })
|
|
26
|
+
*/
|
|
27
|
+
export function rateLimit(options) {
|
|
28
|
+
const store = options.store ?? new MemoryStore();
|
|
29
|
+
const keyFn = options.keyFn ?? ((ctx) => defaultKey(ctx, options.trustProxy));
|
|
30
|
+
const message = options.message ?? 'Too Many Requests';
|
|
31
|
+
const sendHeaders = options.headers !== false;
|
|
32
|
+
return async (ctx, next) => {
|
|
33
|
+
const key = keyFn(ctx);
|
|
34
|
+
const { count, resetAt } = await store.increment(key, options.windowMs);
|
|
35
|
+
const remaining = Math.max(0, options.max - count);
|
|
36
|
+
const resetSecs = Math.ceil((resetAt - Date.now()) / 1000);
|
|
37
|
+
if (sendHeaders) {
|
|
38
|
+
ctx.res.setHeader('RateLimit-Limit', String(options.max));
|
|
39
|
+
ctx.res.setHeader('RateLimit-Remaining', String(remaining));
|
|
40
|
+
ctx.res.setHeader('RateLimit-Reset', String(resetSecs));
|
|
41
|
+
}
|
|
42
|
+
if (count > options.max) {
|
|
43
|
+
ctx.res.setHeader('Retry-After', String(resetSecs));
|
|
44
|
+
ctx.res.writeHead(429, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
45
|
+
ctx.res.end(message);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
await next();
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function defaultKey(ctx, trustProxy) {
|
|
52
|
+
if (trustProxy) {
|
|
53
|
+
const xff = ctx.req.headers['x-forwarded-for'];
|
|
54
|
+
if (xff)
|
|
55
|
+
return xff.split(',')[0].trim();
|
|
56
|
+
}
|
|
57
|
+
return ctx.req.socket.remoteAddress ?? 'unknown';
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoBA,iFAAiF;AAEjF,mFAAmF;AACnF,MAAM,OAAO,WAAW;IACL,IAAI,GAAG,IAAI,GAAG,EAA2B,CAAA;IAE1D,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,QAAgB;QAC3C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QACtB,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAEhC,IAAI,CAAC,KAAK,IAAI,GAAG,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;YACnC,MAAM,MAAM,GAAoB,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,GAAG,GAAG,QAAQ,EAAE,CAAA;YACrE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;YAC1B,OAAO,MAAM,CAAA;QACf,CAAC;QAED,KAAK,CAAC,KAAK,EAAE,CAAA;QACb,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAA;IACvD,CAAC;CACF;AAsCD,iFAAiF;AAEjF;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,OAAyB;IACjD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,IAAI,WAAW,EAAE,CAAA;IAChD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;IAC7E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,mBAAmB,CAAA;IACtD,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,KAAK,KAAK,CAAA;IAE7C,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,CAAA;QACtB,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAA;QACvE,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,GAAG,KAAK,CAAC,CAAA;QAClD,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,CAAA;QAE1D,IAAI,WAAW,EAAE,CAAC;YAChB,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,iBAAiB,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;YACzD,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,qBAAqB,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC,CAAA;YAC3D,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,iBAAiB,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC,CAAA;QACzD,CAAC;QAED,IAAI,KAAK,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;YACxB,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,aAAa,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC,CAAA;YACnD,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,cAAc,EAAE,2BAA2B,EAAE,CAAC,CAAA;YACvE,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;YACpB,OAAM;QACR,CAAC;QAED,MAAM,IAAI,EAAE,CAAA;IACd,CAAC,CAAA;AACH,CAAC;AAED,SAAS,UAAU,CAAC,GAAmB,EAAE,UAAoB;IAC3D,IAAI,UAAU,EAAE,CAAC;QACf,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAuB,CAAA;QACpE,IAAI,GAAG;YAAE,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;IAC1C,CAAC;IACD,OAAO,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAA;AAClD,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@davaux/rate-limit",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "Rate limiting middleware for Davaux",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"author": "David L Dyess II",
|
|
@@ -13,6 +13,9 @@
|
|
|
13
13
|
"url": "https://codeberg.org/davaux/davaux/issues"
|
|
14
14
|
},
|
|
15
15
|
"homepage": "https://codeberg.org/davaux/davaux#readme",
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
16
19
|
"exports": {
|
|
17
20
|
".": {
|
|
18
21
|
"import": "./dist/index.js",
|
|
@@ -24,11 +27,11 @@
|
|
|
24
27
|
"typecheck": "tsc --noEmit"
|
|
25
28
|
},
|
|
26
29
|
"peerDependencies": {
|
|
27
|
-
"davaux": ">=0.8.
|
|
30
|
+
"davaux": ">=0.8.1"
|
|
28
31
|
},
|
|
29
32
|
"devDependencies": {
|
|
30
33
|
"@types/node": "^25.0.0",
|
|
31
34
|
"davaux": "*",
|
|
32
35
|
"typescript": "^6.0.3"
|
|
33
36
|
}
|
|
34
|
-
}
|
|
37
|
+
}
|
package/CLAUDE.md
DELETED
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
<!-- pka-generated -->
|
|
2
|
-
# @davaux/rate-limit
|
|
3
|
-
|
|
4
|
-
> Generated by Project Knowledge Analyzer on 2026-06-06T21:53:10.395Z
|
|
5
|
-
|
|
6
|
-
## Overview
|
|
7
|
-
|
|
8
|
-
Rate limiting middleware for Davaux
|
|
9
|
-
|
|
10
|
-
**Version**: 0.8.0
|
|
11
|
-
**Author**: David L Dyess II
|
|
12
|
-
**License**: MIT
|
|
13
|
-
**Repository**: https://codeberg.org/davaux/davaux#readme
|
|
14
|
-
|
|
15
|
-
## Tech Stack
|
|
16
|
-
|
|
17
|
-
- **Language**: TypeScript
|
|
18
|
-
- **Module System**: ESM (`type: module`)
|
|
19
|
-
|
|
20
|
-
## Commands
|
|
21
|
-
|
|
22
|
-
- `npm run build` — tsc
|
|
23
|
-
- `npm run typecheck` — tsc --noEmit
|
|
24
|
-
|
|
25
|
-
## Project Structure
|
|
26
|
-
|
|
27
|
-
```
|
|
28
|
-
├── CLAUDE.md
|
|
29
|
-
├── README.md
|
|
30
|
-
├── package.json
|
|
31
|
-
├── tsconfig.json
|
|
32
|
-
└── src/
|
|
33
|
-
└── index.ts
|
|
34
|
-
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
## Entry Points
|
|
38
|
-
|
|
39
|
-
- `src/index.ts`
|
|
40
|
-
|
|
41
|
-
## Files by Type
|
|
42
|
-
|
|
43
|
-
### Documentation (2)
|
|
44
|
-
- `CLAUDE.md`
|
|
45
|
-
- `README.md`
|
|
46
|
-
|
|
47
|
-
### Config (2)
|
|
48
|
-
- `package.json`
|
|
49
|
-
- `tsconfig.json`
|
|
50
|
-
|
|
51
|
-
### Module (1)
|
|
52
|
-
- `src/index.ts`
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
## Git
|
|
56
|
-
- **Branch**: main
|
|
57
|
-
- **Last Commit**: chore: Add alpha status note to README
|
|
58
|
-
- **Author**: David Dyess II
|
|
59
|
-
- **Date**: 2026-06-06 15:52:27 -0600
|
|
60
|
-
- **Remote**: https://codeberg.org/davaux/davaux.git
|
|
61
|
-
|
|
62
|
-
### Recent Commits
|
|
63
|
-
```
|
|
64
|
-
f527031 chore: Add alpha status note to README
|
|
65
|
-
90c819e chore: Add repo info to package.json files
|
|
66
|
-
b200d9d feat(davaux)!: Add OmlCacheConfig - opt-in with includes option or opt-out with excludes option; Fix OML implementation to follow OML spec - use output instead of return
|
|
67
|
-
3bce0c2 chore: Update and add READMEs to packages; update ROADMAP
|
|
68
|
-
fc27c20 fix(davaux): Remove old dist folder on new builds; fix server port per DavauxConfig
|
|
69
|
-
c760659 feat(davaux): Add minify CSS in production builds
|
|
70
|
-
c899ab8 fix(davaux): Added method JS and JSX extenstion to scanner
|
|
71
|
-
7d99f04 feat(davaux): Add support for declarative partial updates
|
|
72
|
-
3b47f37 chore: Bump package versions to 0.8.0
|
|
73
|
-
aa0460f chore: Add CHANGELOG.md
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
## Dependencies
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
### Development
|
|
80
|
-
@types/node, davaux, typescript
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
## Exported Symbols
|
|
91
|
-
|
|
92
|
-
**`src/index.ts`**
|
|
93
|
-
`MemoryStore`, `rateLimit`, `RateLimitResult`, `RateLimitStore`, `RateLimitOptions`
|
|
94
|
-
|
|
95
|
-
|
package/src/index.ts
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
import type { MiddlewareFn, RequestContext } from 'davaux'
|
|
2
|
-
|
|
3
|
-
// ─── Store interface ───────────────────────────────────────────────────────────
|
|
4
|
-
|
|
5
|
-
export interface RateLimitResult {
|
|
6
|
-
/** Total hits in the current window. */
|
|
7
|
-
count: number
|
|
8
|
-
/** Unix timestamp (ms) when the current window resets. */
|
|
9
|
-
resetAt: number
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Backing store for rate limit counters. The default `MemoryStore` works for
|
|
14
|
-
* single-process deployments. Implement this interface and pass it via
|
|
15
|
-
* `options.store` to use Redis, Valkey, or any other backend.
|
|
16
|
-
*/
|
|
17
|
-
export interface RateLimitStore {
|
|
18
|
-
increment(key: string, windowMs: number): Promise<RateLimitResult>
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// ─── In-memory store ──────────────────────────────────────────────────────────
|
|
22
|
-
|
|
23
|
-
/** In-memory rate-limit counter store. Suitable for single-process deployments. */
|
|
24
|
-
export class MemoryStore implements RateLimitStore {
|
|
25
|
-
private readonly hits = new Map<string, RateLimitResult>()
|
|
26
|
-
|
|
27
|
-
async increment(key: string, windowMs: number): Promise<RateLimitResult> {
|
|
28
|
-
const now = Date.now()
|
|
29
|
-
const entry = this.hits.get(key)
|
|
30
|
-
|
|
31
|
-
if (!entry || now >= entry.resetAt) {
|
|
32
|
-
const result: RateLimitResult = { count: 1, resetAt: now + windowMs }
|
|
33
|
-
this.hits.set(key, result)
|
|
34
|
-
return result
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
entry.count++
|
|
38
|
-
return { count: entry.count, resetAt: entry.resetAt }
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// ─── Options ──────────────────────────────────────────────────────────────────
|
|
43
|
-
|
|
44
|
-
export interface RateLimitOptions {
|
|
45
|
-
/** Time window in milliseconds. */
|
|
46
|
-
windowMs: number
|
|
47
|
-
/** Maximum number of requests allowed per window per key. */
|
|
48
|
-
max: number
|
|
49
|
-
/**
|
|
50
|
-
* Function that derives the rate-limit key from the request context.
|
|
51
|
-
* Default: the client's IP address (`req.socket.remoteAddress`).
|
|
52
|
-
*/
|
|
53
|
-
keyFn?: (ctx: RequestContext) => string
|
|
54
|
-
/**
|
|
55
|
-
* Body of the 429 response.
|
|
56
|
-
* Default: `'Too Many Requests'`
|
|
57
|
-
*/
|
|
58
|
-
message?: string
|
|
59
|
-
/**
|
|
60
|
-
* Backing store. Default: `MemoryStore` (suitable for single-process apps).
|
|
61
|
-
* Pass a custom implementation for Redis or other distributed stores.
|
|
62
|
-
*/
|
|
63
|
-
store?: RateLimitStore
|
|
64
|
-
/**
|
|
65
|
-
* When `true`, rate-limit headers are sent on every response, not just 429s.
|
|
66
|
-
* Default: `true`
|
|
67
|
-
*/
|
|
68
|
-
headers?: boolean
|
|
69
|
-
/**
|
|
70
|
-
* When `true`, the leftmost IP in `X-Forwarded-For` is used as the rate-limit
|
|
71
|
-
* key instead of `req.socket.remoteAddress`. Only enable when the app runs
|
|
72
|
-
* behind a trusted reverse proxy — clients can spoof this header otherwise.
|
|
73
|
-
* Default: `false`
|
|
74
|
-
*/
|
|
75
|
-
trustProxy?: boolean
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// ─── Middleware ───────────────────────────────────────────────────────────────
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Rate-limiting middleware. Counts requests per key within a rolling time
|
|
82
|
-
* window and returns `429 Too Many Requests` when the limit is exceeded.
|
|
83
|
-
* Standard `RateLimit-*` headers are sent on every response by default.
|
|
84
|
-
*
|
|
85
|
-
* @example
|
|
86
|
-
* import { rateLimit } from '@davaux/rate-limit'
|
|
87
|
-
* export default rateLimit({ windowMs: 60_000, max: 100 })
|
|
88
|
-
*/
|
|
89
|
-
export function rateLimit(options: RateLimitOptions): MiddlewareFn {
|
|
90
|
-
const store = options.store ?? new MemoryStore()
|
|
91
|
-
const keyFn = options.keyFn ?? ((ctx) => defaultKey(ctx, options.trustProxy))
|
|
92
|
-
const message = options.message ?? 'Too Many Requests'
|
|
93
|
-
const sendHeaders = options.headers !== false
|
|
94
|
-
|
|
95
|
-
return async (ctx, next) => {
|
|
96
|
-
const key = keyFn(ctx)
|
|
97
|
-
const { count, resetAt } = await store.increment(key, options.windowMs)
|
|
98
|
-
const remaining = Math.max(0, options.max - count)
|
|
99
|
-
const resetSecs = Math.ceil((resetAt - Date.now()) / 1000)
|
|
100
|
-
|
|
101
|
-
if (sendHeaders) {
|
|
102
|
-
ctx.res.setHeader('RateLimit-Limit', String(options.max))
|
|
103
|
-
ctx.res.setHeader('RateLimit-Remaining', String(remaining))
|
|
104
|
-
ctx.res.setHeader('RateLimit-Reset', String(resetSecs))
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
if (count > options.max) {
|
|
108
|
-
ctx.res.setHeader('Retry-After', String(resetSecs))
|
|
109
|
-
ctx.res.writeHead(429, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
110
|
-
ctx.res.end(message)
|
|
111
|
-
return
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
await next()
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function defaultKey(ctx: RequestContext, trustProxy?: boolean): string {
|
|
119
|
-
if (trustProxy) {
|
|
120
|
-
const xff = ctx.req.headers['x-forwarded-for'] as string | undefined
|
|
121
|
-
if (xff) return xff.split(',')[0].trim()
|
|
122
|
-
}
|
|
123
|
-
return ctx.req.socket.remoteAddress ?? 'unknown'
|
|
124
|
-
}
|
package/tsconfig.json
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "ESNext",
|
|
4
|
-
"module": "NodeNext",
|
|
5
|
-
"moduleResolution": "NodeNext",
|
|
6
|
-
"strict": true,
|
|
7
|
-
"declaration": true,
|
|
8
|
-
"declarationMap": true,
|
|
9
|
-
"sourceMap": true,
|
|
10
|
-
"outDir": "./dist",
|
|
11
|
-
"rootDir": "./src",
|
|
12
|
-
"skipLibCheck": true,
|
|
13
|
-
"lib": ["ESNext"],
|
|
14
|
-
"types": ["node"]
|
|
15
|
-
},
|
|
16
|
-
"include": ["src/**/*"]
|
|
17
|
-
}
|