@gagandeep023/api-gateway 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gagandeep Bhatia
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,184 @@
1
+ # @gagandeep023/api-gateway
2
+
3
+ Type-safe Express API gateway with IP-based rate limiting, analytics, and a real-time React dashboard.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@gagandeep023/api-gateway.svg)](https://www.npmjs.com/package/@gagandeep023/api-gateway)
6
+ [![license](https://img.shields.io/npm/l/@gagandeep023/api-gateway.svg)](https://github.com/Gagandeep023/api-gateway/blob/main/LICENSE)
7
+
8
+ ## Features
9
+
10
+ - Three rate limiting algorithms: Token Bucket, Sliding Window, Fixed Window
11
+ - IP-based rate limiting and session tracking
12
+ - API key authentication with configurable tiers
13
+ - IP allowlist/blocklist filtering
14
+ - Real-time analytics with circular buffer (10k entries)
15
+ - SSE-powered React dashboard with charts
16
+ - Zero external dependencies beyond Express and React
17
+ - Full TypeScript support
18
+
19
+ ## Installation
20
+
21
+ npm install @gagandeep023/api-gateway
22
+
23
+ ## Quick Start: Backend
24
+
25
+ ```typescript
26
+ import express from 'express';
27
+ import { createGatewayMiddleware, createGatewayRoutes } from '@gagandeep023/api-gateway/backend';
28
+
29
+ const app = express();
30
+ app.use(express.json());
31
+
32
+ // Create gateway with default config
33
+ const gateway = createGatewayMiddleware();
34
+
35
+ // Mount management routes (bypasses rate limiting)
36
+ app.use('/api/gateway', createGatewayRoutes({
37
+ rateLimiterService: gateway.rateLimiterService,
38
+ analyticsService: gateway.analyticsService,
39
+ config: gateway.config,
40
+ }));
41
+
42
+ // Apply rate limiting to all other routes
43
+ app.use('/api', gateway.middleware);
44
+
45
+ // Your routes go after the middleware
46
+ app.get('/api/hello', (req, res) => {
47
+ res.json({ message: 'Hello, world!' });
48
+ });
49
+
50
+ app.listen(3001);
51
+ ```
52
+
53
+ ## Quick Start: Frontend Dashboard
54
+
55
+ ```tsx
56
+ import { GatewayDashboard } from '@gagandeep023/api-gateway/frontend';
57
+ import '@gagandeep023/api-gateway/frontend/styles.css';
58
+
59
+ function App() {
60
+ return <GatewayDashboard apiBaseUrl="http://localhost:3001/api" />;
61
+ }
62
+ ```
63
+
64
+ ## Custom Configuration
65
+
66
+ ```typescript
67
+ import { createGatewayMiddleware } from '@gagandeep023/api-gateway/backend';
68
+
69
+ const gateway = createGatewayMiddleware({
70
+ rateLimits: {
71
+ tiers: {
72
+ free: { algorithm: 'tokenBucket', maxRequests: 100, windowMs: 60000, refillRate: 10 },
73
+ pro: { algorithm: 'slidingWindow', maxRequests: 1000, windowMs: 60000 },
74
+ unlimited: { algorithm: 'none' },
75
+ },
76
+ defaultTier: 'free',
77
+ globalLimit: { maxRequests: 10000, windowMs: 60000 },
78
+ },
79
+ ipRules: {
80
+ allowlist: [],
81
+ blocklist: ['10.0.0.1'],
82
+ mode: 'blocklist',
83
+ },
84
+ apiKeys: {
85
+ keys: [
86
+ {
87
+ id: 'key_001',
88
+ key: 'my_secret_key',
89
+ name: 'My App',
90
+ tier: 'pro',
91
+ createdAt: new Date().toISOString(),
92
+ active: true,
93
+ },
94
+ ],
95
+ },
96
+ });
97
+ ```
98
+
99
+ ## API Reference
100
+
101
+ ### Backend
102
+
103
+ #### `createGatewayMiddleware(config?)`
104
+
105
+ Creates the full middleware chain and returns service instances.
106
+
107
+ **Parameters:**
108
+
109
+ | Parameter | Type | Required | Description |
110
+ |-----------|------|----------|-------------|
111
+ | `config.rateLimits` | `RateLimitConfig` | No | Rate limit tiers and global limit |
112
+ | `config.ipRules` | `IpRules` | No | IP allowlist/blocklist rules |
113
+ | `config.apiKeys` | `ApiKeysConfig` | No | API keys and tiers |
114
+
115
+ **Returns:** `GatewayInstances`
116
+
117
+ | Property | Type | Description |
118
+ |----------|------|-------------|
119
+ | `middleware` | `Router` | Express router with full middleware chain |
120
+ | `rateLimiterService` | `RateLimiterService` | Rate limiter instance |
121
+ | `analyticsService` | `AnalyticsService` | Analytics instance |
122
+ | `config` | `GatewayMiddlewareConfig` | Resolved config |
123
+
124
+ #### `createGatewayRoutes(options)`
125
+
126
+ Creates Express routes for gateway management (analytics, config, key CRUD, logs).
127
+
128
+ #### Individual Middleware
129
+
130
+ - `createApiKeyAuth(getKeys)` - API key authentication
131
+ - `createIpFilter(getRules)` - IP filtering
132
+ - `createRateLimiter(service)` - Rate limiting
133
+ - `createRequestLogger(analytics)` - Request logging
134
+
135
+ ### Frontend
136
+
137
+ #### `<GatewayDashboard apiBaseUrl={string} />`
138
+
139
+ React component displaying real-time gateway analytics.
140
+
141
+ **Props:**
142
+
143
+ | Prop | Type | Description |
144
+ |------|------|-------------|
145
+ | `apiBaseUrl` | `string` | Base URL of the backend API (e.g. `http://localhost:3001/api`) |
146
+
147
+ ### IP-Based Tracking
148
+
149
+ All rate limiting is enforced per IP address. The dashboard shows:
150
+
151
+ - **Active IPs**: Unique IP addresses seen in the last 5 minutes
152
+ - **Active Key Sessions**: Unique (IP + API key) pairs in the last 5 minutes
153
+
154
+ ### Theming the Dashboard
155
+
156
+ Override CSS custom properties to match your theme:
157
+
158
+ ```css
159
+ .gw-dashboard {
160
+ --gw-bg-card: #1a1a2e;
161
+ --gw-accent: #00d4ff;
162
+ --gw-text-primary: #ffffff;
163
+ }
164
+ ```
165
+
166
+ ## TypeScript
167
+
168
+ Full TypeScript support with exported types:
169
+
170
+ ```typescript
171
+ import type {
172
+ RateLimitConfig,
173
+ GatewayAnalytics,
174
+ GatewayConfig,
175
+ RequestLog,
176
+ ApiKey,
177
+ IpRules,
178
+ TierConfig,
179
+ } from '@gagandeep023/api-gateway/types';
180
+ ```
181
+
182
+ ## License
183
+
184
+ MIT
@@ -0,0 +1,55 @@
1
+ import { Router, Request, Response, NextFunction } from 'express';
2
+ import { RateLimitConfig, RequestLog, GatewayAnalytics, GatewayMiddlewareConfig, ApiKeysConfig, IpRules } from '../types/index.mjs';
3
+
4
+ declare class RateLimiterService {
5
+ private tokenBucket;
6
+ private slidingWindow;
7
+ private fixedWindow;
8
+ private globalWindow;
9
+ private config;
10
+ private _rateLimitHits;
11
+ constructor(config: RateLimitConfig);
12
+ get rateLimitHits(): number;
13
+ checkLimit(ip: string, tier: string): {
14
+ allowed: boolean;
15
+ remaining: number;
16
+ resetMs: number;
17
+ limit: number;
18
+ };
19
+ getConfig(): RateLimitConfig;
20
+ }
21
+
22
+ declare class AnalyticsService {
23
+ private logs;
24
+ private head;
25
+ private count;
26
+ addLog(log: RequestLog): void;
27
+ getRecentLogs(limit?: number, offset?: number): RequestLog[];
28
+ getAnalytics(rateLimitHits: number): GatewayAnalytics;
29
+ private getOrderedLogs;
30
+ }
31
+
32
+ interface GatewayInstances {
33
+ rateLimiterService: RateLimiterService;
34
+ analyticsService: AnalyticsService;
35
+ middleware: Router;
36
+ config: Required<GatewayMiddlewareConfig>;
37
+ }
38
+ declare function createGatewayMiddleware(userConfig?: GatewayMiddlewareConfig): GatewayInstances;
39
+
40
+ interface GatewayRoutesOptions {
41
+ rateLimiterService: RateLimiterService;
42
+ analyticsService: AnalyticsService;
43
+ config: Required<GatewayMiddlewareConfig>;
44
+ }
45
+ declare function createGatewayRoutes(options: GatewayRoutesOptions): Router;
46
+
47
+ declare function createApiKeyAuth(getKeys: () => ApiKeysConfig): (req: Request, res: Response, next: NextFunction) => void;
48
+
49
+ declare function createIpFilter(getRules: () => IpRules): (req: Request, res: Response, next: NextFunction) => void;
50
+
51
+ declare function createRateLimiter(service: RateLimiterService): (req: Request, res: Response, next: NextFunction) => void;
52
+
53
+ declare function createRequestLogger(analytics: AnalyticsService): (req: Request, res: Response, next: NextFunction) => void;
54
+
55
+ export { AnalyticsService, type GatewayInstances, type GatewayRoutesOptions, RateLimiterService, createApiKeyAuth, createGatewayMiddleware, createGatewayRoutes, createIpFilter, createRateLimiter, createRequestLogger };
@@ -0,0 +1,55 @@
1
+ import { Router, Request, Response, NextFunction } from 'express';
2
+ import { RateLimitConfig, RequestLog, GatewayAnalytics, GatewayMiddlewareConfig, ApiKeysConfig, IpRules } from '../types/index.js';
3
+
4
+ declare class RateLimiterService {
5
+ private tokenBucket;
6
+ private slidingWindow;
7
+ private fixedWindow;
8
+ private globalWindow;
9
+ private config;
10
+ private _rateLimitHits;
11
+ constructor(config: RateLimitConfig);
12
+ get rateLimitHits(): number;
13
+ checkLimit(ip: string, tier: string): {
14
+ allowed: boolean;
15
+ remaining: number;
16
+ resetMs: number;
17
+ limit: number;
18
+ };
19
+ getConfig(): RateLimitConfig;
20
+ }
21
+
22
+ declare class AnalyticsService {
23
+ private logs;
24
+ private head;
25
+ private count;
26
+ addLog(log: RequestLog): void;
27
+ getRecentLogs(limit?: number, offset?: number): RequestLog[];
28
+ getAnalytics(rateLimitHits: number): GatewayAnalytics;
29
+ private getOrderedLogs;
30
+ }
31
+
32
+ interface GatewayInstances {
33
+ rateLimiterService: RateLimiterService;
34
+ analyticsService: AnalyticsService;
35
+ middleware: Router;
36
+ config: Required<GatewayMiddlewareConfig>;
37
+ }
38
+ declare function createGatewayMiddleware(userConfig?: GatewayMiddlewareConfig): GatewayInstances;
39
+
40
+ interface GatewayRoutesOptions {
41
+ rateLimiterService: RateLimiterService;
42
+ analyticsService: AnalyticsService;
43
+ config: Required<GatewayMiddlewareConfig>;
44
+ }
45
+ declare function createGatewayRoutes(options: GatewayRoutesOptions): Router;
46
+
47
+ declare function createApiKeyAuth(getKeys: () => ApiKeysConfig): (req: Request, res: Response, next: NextFunction) => void;
48
+
49
+ declare function createIpFilter(getRules: () => IpRules): (req: Request, res: Response, next: NextFunction) => void;
50
+
51
+ declare function createRateLimiter(service: RateLimiterService): (req: Request, res: Response, next: NextFunction) => void;
52
+
53
+ declare function createRequestLogger(analytics: AnalyticsService): (req: Request, res: Response, next: NextFunction) => void;
54
+
55
+ export { AnalyticsService, type GatewayInstances, type GatewayRoutesOptions, RateLimiterService, createApiKeyAuth, createGatewayMiddleware, createGatewayRoutes, createIpFilter, createRateLimiter, createRequestLogger };