throttl-express 1.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Throttl
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,101 @@
1
+ # @throttl/express
2
+
3
+ Express middleware for [Throttl](https://throttl.xyz) API rate limiting.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @throttl/express
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```javascript
14
+ import express from 'express';
15
+ import { throttl } from '@throttl/express';
16
+
17
+ const app = express();
18
+
19
+ // Add Throttl middleware
20
+ app.use(throttl({
21
+ serverUrl: 'https://api.throttl.xyz'
22
+ }));
23
+
24
+ // Your routes are now protected
25
+ app.get('/api/data', (req, res) => {
26
+ // Access rate limit info via req.throttl
27
+ console.log(`Remaining requests: ${req.throttl?.remaining}`);
28
+ res.json({ data: 'protected!' });
29
+ });
30
+
31
+ app.listen(3000);
32
+ ```
33
+
34
+ ## Options
35
+
36
+ | Option | Type | Required | Description |
37
+ |--------|------|----------|-------------|
38
+ | `serverUrl` | `string` | Yes | Throttl API server URL |
39
+ | `extractKey` | `function` | No | Custom function to extract API key from request |
40
+ | `onError` | `function` | No | Custom error handler |
41
+
42
+ ### Default Key Extraction
43
+
44
+ By default, the middleware looks for the API key in:
45
+ 1. `x-api-key` header
46
+ 2. `Authorization: Bearer <key>` header
47
+ 3. `api_key` query parameter
48
+
49
+ ### Custom Key Extraction
50
+
51
+ ```javascript
52
+ app.use(throttl({
53
+ serverUrl: 'https://api.throttl.xyz',
54
+ extractKey: (req) => req.headers['x-custom-key']
55
+ }));
56
+ ```
57
+
58
+ ### Custom Error Handling
59
+
60
+ ```javascript
61
+ app.use(throttl({
62
+ serverUrl: 'https://api.throttl.xyz',
63
+ onError: (error, req, res) => {
64
+ console.error('Rate limit error:', error);
65
+ res.status(500).json({ error: 'Service unavailable' });
66
+ }
67
+ }));
68
+ ```
69
+
70
+ ## Response
71
+
72
+ The middleware adds a `throttl` object to the request:
73
+
74
+ ```typescript
75
+ interface ThrottlInfo {
76
+ valid: boolean;
77
+ remaining?: number;
78
+ error?: string;
79
+ }
80
+
81
+ // Access in your route handlers
82
+ app.get('/api/data', (req, res) => {
83
+ if (req.throttl?.remaining < 100) {
84
+ res.set('X-RateLimit-Warning', 'Approaching limit');
85
+ }
86
+ res.json({ data: '...' });
87
+ });
88
+ ```
89
+
90
+ ## Error Responses
91
+
92
+ | Status | Error | Description |
93
+ |--------|-------|-------------|
94
+ | 401 | `API key required` | No API key provided |
95
+ | 401 | `invalid_key` | API key not found or inactive |
96
+ | 429 | `quota_exceeded` | Monthly quota exhausted |
97
+ | 503 | `Rate limit service unavailable` | Throttl API unreachable |
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1 @@
1
+ export { throttl, type ThrottlOptions, type ThrottlInfo } from './middleware';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.throttl = void 0;
4
+ var middleware_1 = require("./middleware");
5
+ Object.defineProperty(exports, "throttl", { enumerable: true, get: function () { return middleware_1.throttl; } });
@@ -0,0 +1,19 @@
1
+ import type { Request, Response, NextFunction } from 'express';
2
+ export interface ThrottlOptions {
3
+ serverUrl: string;
4
+ extractKey?: (req: Request) => string | undefined;
5
+ onError?: (error: Error, req: Request, res: Response) => void;
6
+ }
7
+ export interface ThrottlInfo {
8
+ valid: boolean;
9
+ remaining?: number;
10
+ error?: string;
11
+ }
12
+ declare global {
13
+ namespace Express {
14
+ interface Request {
15
+ throttl?: ThrottlInfo;
16
+ }
17
+ }
18
+ }
19
+ export declare function throttl(options: ThrottlOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.throttl = throttl;
4
+ const defaultExtractKey = (req) => {
5
+ return (req.headers['x-api-key'] ||
6
+ (req.headers['authorization']?.replace('Bearer ', '')) ||
7
+ req.query.api_key);
8
+ };
9
+ function throttl(options) {
10
+ const { serverUrl, extractKey = defaultExtractKey, onError } = options;
11
+ const validateUrl = `${serverUrl.replace(/\/$/, '')}/api/validate`;
12
+ return async (req, res, next) => {
13
+ const key = extractKey(req);
14
+ if (!key) {
15
+ return res.status(401).json({
16
+ error: 'API key required',
17
+ message: 'Provide key via x-api-key header, Authorization Bearer, or api_key query param',
18
+ });
19
+ }
20
+ try {
21
+ const response = await fetch(validateUrl, {
22
+ method: 'POST',
23
+ headers: { 'Content-Type': 'application/json' },
24
+ body: JSON.stringify({ key }),
25
+ });
26
+ const result = await response.json();
27
+ req.throttl = result;
28
+ if (!result.valid) {
29
+ const status = result.error === 'quota_exceeded' ? 429 : 401;
30
+ return res.status(status).json({
31
+ error: result.error,
32
+ remaining: result.remaining,
33
+ });
34
+ }
35
+ next();
36
+ }
37
+ catch (error) {
38
+ if (onError) {
39
+ onError(error, req, res);
40
+ }
41
+ else {
42
+ console.error('Throttl validation error:', error);
43
+ res.status(503).json({ error: 'Rate limit service unavailable' });
44
+ }
45
+ }
46
+ };
47
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "throttl-express",
3
+ "version": "1.0.0",
4
+ "description": "Express middleware for Throttl API rate limiting",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "prepublishOnly": "npm run build"
13
+ },
14
+ "keywords": [
15
+ "throttl",
16
+ "rate-limit",
17
+ "api-key",
18
+ "express",
19
+ "middleware",
20
+ "quota",
21
+ "usage-tracking"
22
+ ],
23
+ "author": "Throttl",
24
+ "license": "MIT",
25
+ "homepage": "https://throttl.xyz",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/wahans/throttl.git",
29
+ "directory": "sdk"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/wahans/throttl/issues"
33
+ },
34
+ "peerDependencies": {
35
+ "express": "^4.18.0 || ^5.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/express": "^4.17.21",
39
+ "@types/node": "^20.10.0",
40
+ "typescript": "^5.3.2"
41
+ }
42
+ }