@davaux/rate-limit 0.8.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/CLAUDE.md ADDED
@@ -0,0 +1,95 @@
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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David L Dyess II
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/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @davaux/rate-limit
2
+
3
+ Rate limiting middleware for Davaux.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @davaux/rate-limit
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ ```ts
14
+ // davaux.config.ts
15
+ import { defineConfig } from 'davaux/config'
16
+ import { rateLimit } from '@davaux/rate-limit'
17
+
18
+ export default defineConfig({
19
+ middleware: [
20
+ rateLimit({ windowMs: 60_000, max: 100 }),
21
+ ],
22
+ })
23
+ ```
24
+
25
+ Or scope it to specific routes via `_middleware.ts`:
26
+
27
+ ```ts
28
+ // src/routes/api/_middleware.ts
29
+ import { rateLimit } from '@davaux/rate-limit'
30
+ export default rateLimit({ windowMs: 60_000, max: 20 })
31
+ ```
32
+
33
+ ## Options
34
+
35
+ | Option | Type | Default | Description |
36
+ |---|---|---|---|
37
+ | `windowMs` | `number` | — | Time window in milliseconds (required) |
38
+ | `max` | `number` | — | Maximum requests per window per key (required) |
39
+ | `keyFn` | `(ctx) => string` | Client IP | Function to derive the rate-limit key |
40
+ | `message` | `string` | `'Too Many Requests'` | Body of the 429 response |
41
+ | `store` | `RateLimitStore` | `MemoryStore` | Backing store for counters |
42
+ | `headers` | `boolean` | `true` | Send `RateLimit-*` headers on every response |
43
+ | `trustProxy` | `boolean` | `false` | Use `X-Forwarded-For` as the key. Only enable behind a trusted reverse proxy |
44
+
45
+ ## Custom store
46
+
47
+ Implement `RateLimitStore` to use Redis, Valkey, or any other distributed backend:
48
+
49
+ ```ts
50
+ import type { RateLimitStore, RateLimitResult } from '@davaux/rate-limit'
51
+
52
+ class RedisStore implements RateLimitStore {
53
+ async increment(key: string, windowMs: number): Promise<RateLimitResult> {
54
+ // ...
55
+ }
56
+ }
57
+
58
+ rateLimit({ windowMs: 60_000, max: 100, store: new RedisStore() })
59
+ ```
60
+
61
+ ## Documentation
62
+
63
+ [davaux.codeberg.page/docs/rate-limit](https://davaux.codeberg.page/docs/rate-limit)
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@davaux/rate-limit",
3
+ "version": "0.8.0",
4
+ "description": "Rate limiting middleware for Davaux",
5
+ "type": "module",
6
+ "author": "David L Dyess II",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://codeberg.org/davaux/davaux"
11
+ },
12
+ "bugs": {
13
+ "url": "https://codeberg.org/davaux/davaux/issues"
14
+ },
15
+ "homepage": "https://codeberg.org/davaux/davaux#readme",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.js",
19
+ "types": "./dist/index.d.ts"
20
+ }
21
+ },
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "peerDependencies": {
27
+ "davaux": ">=0.8.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^25.0.0",
31
+ "davaux": "*",
32
+ "typescript": "^6.0.3"
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,124 @@
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 ADDED
@@ -0,0 +1,17 @@
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
+ }