@teikyo/rate-limit 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +32 -2
- package/lib/index.d.ts +19 -0
- package/lib/index.js +34 -0
- package/lib/key.d.ts +7 -0
- package/lib/key.js +47 -0
- package/package.json +47 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Paul Le Cam
|
|
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
CHANGED
|
@@ -1,3 +1,33 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @teikyo/rate-limit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Rate limiting plugin for `@sozai/http-server`. It limits every request per resolved client IP, answering `429` with a `Retry-After` header past the limit. Routes registered by plugins listed before it are limited too; health routes never are.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @teikyo/rate-limit @sozai/http-server hono
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Plugin name: `http:rate-limit` (exported as `RATE_LIMIT`).
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createServer } from '@sozai/http-server'
|
|
17
|
+
import { rateLimitPlugin } from '@teikyo/rate-limit'
|
|
18
|
+
|
|
19
|
+
const server = await createServer({
|
|
20
|
+
trustProxy: 1,
|
|
21
|
+
plugins: [rateLimitPlugin({ windowMs: 60_000, limit: 100 })],
|
|
22
|
+
})
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Clients are keyed on the IP resolved by the server, so set `trustProxy` when running behind a reverse proxy. An IPv4 address is keyed whole; an IPv6 address is keyed by its /64 prefix, the usual allocation to one subscriber, so a client cannot multiply its budget by rotating addresses within its prefix. IPv4-mapped IPv6 (`::ffff:a.b.c.d`) is keyed as IPv4. Responses carry the IETF `RateLimit` draft-7 headers.
|
|
26
|
+
|
|
27
|
+
## Options
|
|
28
|
+
|
|
29
|
+
| Option | Type | Description |
|
|
30
|
+
| --- | --- | --- |
|
|
31
|
+
| `windowMs` | `number` | Length of the window in milliseconds. Must be a positive safe integer. |
|
|
32
|
+
| `limit` | `number` | Maximum requests per client within a window. Must be a positive safe integer. |
|
|
33
|
+
| `store` | `Store` (optional) | A `hono-rate-limiter` store, in-memory by default. The plugin calls its `shutdown()` when the server closes, so do not pass a store shared with or owned by something else. |
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type HTTPPlugin } from '@sozai/http-server';
|
|
2
|
+
import { type Store } from 'hono-rate-limiter';
|
|
3
|
+
export declare const RATE_LIMIT: import("@sozai/http-server").PluginName<"http:rate-limit", void>;
|
|
4
|
+
export type RateLimitPluginParams = {
|
|
5
|
+
/** Length of the rate limiting window, in milliseconds. */
|
|
6
|
+
windowMs: number;
|
|
7
|
+
/** Maximum number of requests per client within a window. */
|
|
8
|
+
limit: number;
|
|
9
|
+
/**
|
|
10
|
+
* Custom store, defaults to an in-memory store. The plugin calls `shutdown()` on it when
|
|
11
|
+
* the server closes, so do not pass a store shared with or owned by something else.
|
|
12
|
+
*/
|
|
13
|
+
store?: Store;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Rate limit every request by resolved client IP (IPv6 grouped by /64), answering `429` with a
|
|
17
|
+
* `Retry-After` header past the limit. Health routes are never limited.
|
|
18
|
+
*/
|
|
19
|
+
export declare function rateLimitPlugin(params: RateLimitPluginParams): HTTPPlugin<'http:rate-limit', void, []>;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { pluginName } from '@sozai/http-server';
|
|
2
|
+
import { MemoryStore, rateLimiter } from 'hono-rate-limiter';
|
|
3
|
+
import { clientKey } from './key.js';
|
|
4
|
+
export const RATE_LIMIT = pluginName()('http:rate-limit');
|
|
5
|
+
function assertPositiveInteger(name, value) {
|
|
6
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
7
|
+
throw new Error(`${name} must be a positive safe integer, received ${String(value)}`);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Rate limit every request by resolved client IP (IPv6 grouped by /64), answering `429` with a
|
|
12
|
+
* `Retry-After` header past the limit. Health routes are never limited.
|
|
13
|
+
*/ export function rateLimitPlugin(params) {
|
|
14
|
+
assertPositiveInteger('windowMs', params.windowMs);
|
|
15
|
+
assertPositiveInteger('limit', params.limit);
|
|
16
|
+
const { windowMs, limit } = params;
|
|
17
|
+
return {
|
|
18
|
+
name: RATE_LIMIT,
|
|
19
|
+
dependsOn: [],
|
|
20
|
+
setup (ctx) {
|
|
21
|
+
const store = params.store ?? new MemoryStore();
|
|
22
|
+
ctx.middleware(rateLimiter({
|
|
23
|
+
windowMs,
|
|
24
|
+
limit,
|
|
25
|
+
standardHeaders: 'draft-7',
|
|
26
|
+
// IPv6 clients share one bucket per /64. A request with no resolvable client IP falls
|
|
27
|
+
// into one shared bucket.
|
|
28
|
+
keyGenerator: (c)=>clientKey(ctx.clientIP(c)),
|
|
29
|
+
store
|
|
30
|
+
}));
|
|
31
|
+
ctx.onClose(()=>store.shutdown?.());
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
package/lib/key.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate-limit key for a client address. IPv4 is kept whole and IPv6 is grouped by its /64, the
|
|
3
|
+
* usual allocation to one subscriber, so a client cannot multiply its budget by rotating through
|
|
4
|
+
* addresses in its own prefix. IPv4-mapped IPv6 (`::ffff:a.b.c.d`) is keyed as IPv4. Anything else
|
|
5
|
+
* (no resolvable address) is returned unchanged.
|
|
6
|
+
*/
|
|
7
|
+
export declare function clientKey(ip: string): string;
|
package/lib/key.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
function parseGroups(part) {
|
|
2
|
+
return part === '' ? [] : part.split(':').map((group)=>Number.parseInt(group, 16));
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Expand an IPv6 address into its eight 16-bit groups, or return `undefined` when it is not one.
|
|
6
|
+
* The WHATWG URL parser validates it and rewrites any dotted IPv4 tail as two hex groups.
|
|
7
|
+
*/ function ipv6Groups(address) {
|
|
8
|
+
const zoneIndex = address.indexOf('%');
|
|
9
|
+
let canonical;
|
|
10
|
+
try {
|
|
11
|
+
const host = zoneIndex === -1 ? address : address.slice(0, zoneIndex);
|
|
12
|
+
canonical = new URL(`http://[${host}]`).hostname.slice(1, -1);
|
|
13
|
+
} catch {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
const [head = '', tail] = canonical.split('::');
|
|
17
|
+
if (tail == null) return parseGroups(head);
|
|
18
|
+
const headGroups = parseGroups(head);
|
|
19
|
+
const tailGroups = parseGroups(tail);
|
|
20
|
+
const zeros = new Array(8 - headGroups.length - tailGroups.length).fill(0);
|
|
21
|
+
return [
|
|
22
|
+
...headGroups,
|
|
23
|
+
...zeros,
|
|
24
|
+
...tailGroups
|
|
25
|
+
];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Rate-limit key for a client address. IPv4 is kept whole and IPv6 is grouped by its /64, the
|
|
29
|
+
* usual allocation to one subscriber, so a client cannot multiply its budget by rotating through
|
|
30
|
+
* addresses in its own prefix. IPv4-mapped IPv6 (`::ffff:a.b.c.d`) is keyed as IPv4. Anything else
|
|
31
|
+
* (no resolvable address) is returned unchanged.
|
|
32
|
+
*/ export function clientKey(ip) {
|
|
33
|
+
if (!ip.includes(':')) return ip;
|
|
34
|
+
const groups = ipv6Groups(ip);
|
|
35
|
+
if (groups == null) return ip;
|
|
36
|
+
if (groups.slice(0, 5).every((group)=>group === 0) && groups[5] === 0xffff) {
|
|
37
|
+
const high = groups[6] ?? 0;
|
|
38
|
+
const low = groups[7] ?? 0;
|
|
39
|
+
return [
|
|
40
|
+
high >> 8,
|
|
41
|
+
high & 0xff,
|
|
42
|
+
low >> 8,
|
|
43
|
+
low & 0xff
|
|
44
|
+
].join('.');
|
|
45
|
+
}
|
|
46
|
+
return `${groups.slice(0, 4).map((group)=>group.toString(16)).join(':')}::/64`;
|
|
47
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teikyo/rate-limit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Rate limiting plugin for Sozai HTTP servers",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/TairuFramework/teikyo.git",
|
|
8
|
+
"directory": "packages/rate-limit"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"type": "module",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": "./lib/index.js"
|
|
15
|
+
},
|
|
16
|
+
"main": "lib/index.js",
|
|
17
|
+
"types": "lib/index.d.ts",
|
|
18
|
+
"files": [
|
|
19
|
+
"lib/*"
|
|
20
|
+
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@sozai/http-server": "^0.1.0",
|
|
23
|
+
"hono-rate-limiter": "^0.5.4"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^26.6.4",
|
|
27
|
+
"del-cli": "^7.0.0",
|
|
28
|
+
"hono": "^4.13.13",
|
|
29
|
+
"vitest": "5.0.3"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"hono": "^4.13.13"
|
|
33
|
+
},
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=24"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
|
|
42
|
+
"build:clean": "del-cli lib",
|
|
43
|
+
"build:js": "del-cli \"lib/**/*.js\" && swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
|
|
44
|
+
"build:types": "del-cli \"lib/**/*.d.ts\" \"lib/**/*.d.ts.map\" && tsc --emitDeclarationOnly --skipLibCheck",
|
|
45
|
+
"build:types:ci": "tsc --emitDeclarationOnly --skipLibCheck --declarationMap false",
|
|
46
|
+
"test": "pnpm run test:types && pnpm run test:unit",
|
|
47
|
+
"test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
|
|
48
|
+
"test:unit": "vitest run"
|
|
49
|
+
}
|
|
6
50
|
}
|