@robiki/proxy 1.0.2 → 1.0.4

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/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # 🚀 Robiki Proxy
2
2
 
3
- > A high-performance, flexible HTTP/2 reverse proxy with WebSocket support, configurable routing, CORS, and request validation. Use it as an npm package in your Node.js application or as a standalone Docker container. Meant to be used as a domain proxy for local development environments only.
3
+ > A high-performance HTTP/2 reverse proxy with WebSocket support, configurable routing, CORS, and request validation. Use as an npm package or Docker container for local development environments.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@robiki/proxy.svg)](https://www.npmjs.com/package/@robiki/proxy)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
- ## 🌍 Languages / Sprachen / 语言 / 言語 / Języki / Idiomas / Языки
8
+ ## 🌍 Languages
9
9
 
10
10
  [English](README.md) | [Deutsch](README.de.md) | [中文](README.zh.md) | [日本語](README.ja.md) | [Polski](README.pl.md) | [Español](README.es.md) | [Русский](README.ru.md)
11
11
 
@@ -18,54 +18,29 @@
18
18
  - **✅ Request Validation**: Custom validation logic for authentication, rate limiting, etc.
19
19
  - **🔄 URL Remapping**: Transform URLs before forwarding to target services
20
20
  - **📦 Dual Usage**: Use as npm package or Docker container
21
+ - **⚙️ JavaScript & TypeScript Config Support**: Use `.js` or `.ts` config files with functions in Docker
21
22
  - **🎯 Multi-Port Support**: Listen on multiple ports simultaneously
22
23
  - **⚡ High Performance**: Built on Node.js native HTTP/2 implementation
23
24
 
24
25
  ## 📦 Installation
25
26
 
26
- ### As an npm Package
27
+ ### npm Package
27
28
 
28
29
  ```bash
29
30
  npm install @robiki/proxy
30
- ```
31
-
32
- ```bash
31
+ # or
33
32
  yarn add @robiki/proxy
34
33
  ```
35
34
 
36
- ### As a Docker Container
35
+ ### Docker
37
36
 
38
37
  ```bash
39
38
  docker pull robiki/proxy:latest
40
39
  ```
41
40
 
42
- ### As a Docker Compose Service
43
-
44
- ```yaml
45
- services:
46
- proxy:
47
- image: robiki/proxy:latest
48
- container_name: robiki-proxy
49
- restart: unless-stopped
50
- ports:
51
- - '443:443'
52
- - '8080:8080'
53
- - '9229:9229'
54
- volumes:
55
- - ./proxy.config.json:/app/proxy.config.json:ro
56
- - ./certs:/app/certs:ro
57
- networks:
58
- - app-network
59
- ```
60
-
61
- ## Notes
62
-
63
- - Hosts that are configured locally should be added to your local `hosts` file.
64
- - If you are using a custom certificates, you need to add the certificate files to the `certs` directory.
65
-
66
41
  ## 🚀 Quick Start
67
42
 
68
- ### Using as npm Package
43
+ ### npm Package
69
44
 
70
45
  ```javascript
71
46
  import { createProxy } from '@robiki/proxy';
@@ -88,13 +63,11 @@ const proxy = await createProxy({
88
63
  },
89
64
  },
90
65
  });
91
-
92
- console.log('Proxy server is running!');
93
66
  ```
94
67
 
95
- ### Using with Docker
68
+ ### Docker
96
69
 
97
- 1. Create a `proxy.config.json` file:
70
+ Create `proxy.config.json`:
98
71
 
99
72
  ```json
100
73
  {
@@ -108,20 +81,14 @@ console.log('Proxy server is running!');
108
81
  "api.example.com": {
109
82
  "target": "backend-service:3000",
110
83
  "ssl": true
111
- },
112
- "example.com": {
113
- "target": "frontend-service:8080",
114
- "ssl": false
115
84
  }
116
85
  }
117
86
  }
118
87
  ```
119
88
 
120
- 2. Create a `docker-compose.yml`:
89
+ Create `docker-compose.yml`:
121
90
 
122
91
  ```yaml
123
- version: '3.8'
124
-
125
92
  services:
126
93
  proxy:
127
94
  image: robiki/proxy:latest
@@ -133,25 +100,9 @@ services:
133
100
  - ./certs:/app/certs:ro
134
101
  environment:
135
102
  - PROXY_CONFIG=/app/proxy.config.json
136
- networks:
137
- - app-network
138
-
139
- backend-service:
140
- image: your-backend-image
141
- networks:
142
- - app-network
143
-
144
- frontend-service:
145
- image: your-frontend-image
146
- networks:
147
- - app-network
148
-
149
- networks:
150
- app-network:
151
- driver: bridge
152
103
  ```
153
104
 
154
- 3. Start the services:
105
+ Start:
155
106
 
156
107
  ```bash
157
108
  docker-compose up -d
@@ -159,9 +110,9 @@ docker-compose up -d
159
110
 
160
111
  ## 📖 Configuration
161
112
 
162
- ### Configuration File
113
+ ### JSON Configuration
163
114
 
164
- Create a `proxy.config.json` file with the following structure:
115
+ Simple declarative configuration:
165
116
 
166
117
  ```json
167
118
  {
@@ -169,24 +120,17 @@ Create a `proxy.config.json` file with the following structure:
169
120
  "ssl": {
170
121
  "key": "./certs/key.pem",
171
122
  "cert": "./certs/cert.pem",
172
- "ca": "./certs/ca.pem",
173
123
  "allowHTTP1": true
174
124
  },
175
125
  "cors": {
176
126
  "origin": "*",
177
- "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
178
- "allowedHeaders": ["Content-Type", "Authorization"],
179
- "credentials": true,
180
- "maxAge": 86400
127
+ "methods": ["GET", "POST", "PUT", "DELETE"],
128
+ "credentials": true
181
129
  },
182
130
  "routes": {
183
131
  "api.example.com": {
184
- "target": "backend-service:3000",
185
- "ssl": true,
186
- "cors": {
187
- "origin": ["https://example.com"],
188
- "credentials": true
189
- }
132
+ "target": "backend:3000",
133
+ "ssl": true
190
134
  },
191
135
  "*.example.com": {
192
136
  "target": "wildcard-service:4000",
@@ -196,78 +140,32 @@ Create a `proxy.config.json` file with the following structure:
196
140
  }
197
141
  ```
198
142
 
199
- ### Environment Variables
143
+ ### JavaScript Configuration
200
144
 
201
- You can also configure the proxy using environment variables:
202
-
203
- ```bash
204
- # SSL Configuration
205
- SSL_KEY=/app/certs/key.pem
206
- SSL_CERT=/app/certs/cert.pem
207
- SSL_CA=/app/certs/ca.pem
208
- SSL_ALLOW_HTTP1=true
209
-
210
- # CORS Configuration
211
- CORS_ORIGIN=*
212
- CORS_METHODS=GET,POST,PUT,DELETE,OPTIONS
213
- CORS_HEADERS=Content-Type,Authorization
214
- CORS_CREDENTIALS=true
215
-
216
- # Debug Mode
217
- DEBUG=true # Enable detailed logging for proxy connections and errors
218
- ```
219
-
220
- ## 🎯 Advanced Usage
221
-
222
- ### URL Remapping
223
-
224
- Transform URLs before forwarding to target services:
145
+ For advanced features like URL remapping and validation:
225
146
 
226
147
  ```javascript
227
- const config = {
228
- routes: {
229
- 'api.example.com': {
230
- target: 'backend:3000',
231
- ssl: true,
232
- remap: (url) => {
233
- // Remove /api prefix
234
- return url.replace(/^\/api/, '');
235
- },
236
- },
237
- },
238
- };
239
- ```
240
-
241
- ### Request Validation
242
-
243
- Add custom validation logic for authentication, rate limiting, etc.:
244
-
245
- ```javascript
246
- const config = {
247
- // Global validation
248
- validate: async (info) => {
249
- if (!info.headers.authorization) {
250
- return {
251
- status: false,
252
- code: 401,
253
- message: 'Unauthorized',
254
- headers: { 'www-authenticate': 'Bearer' },
255
- };
256
- }
257
- return { status: true };
148
+ // proxy.config.js
149
+ export default {
150
+ ports: [443, 8080],
151
+ ssl: {
152
+ key: './certs/key.pem',
153
+ cert: './certs/cert.pem',
154
+ allowHTTP1: true,
258
155
  },
259
156
  routes: {
260
157
  'api.example.com': {
261
158
  target: 'backend:3000',
262
159
  ssl: true,
263
- // Route-specific validation
160
+ // URL remapping
161
+ remap: (url) => url.replace(/^\/api/, ''),
162
+ // Request validation
264
163
  validate: async (info) => {
265
- const rateLimit = await checkRateLimit(info.remoteAddress);
266
- if (!rateLimit.allowed) {
164
+ if (!info.headers.authorization) {
267
165
  return {
268
166
  status: false,
269
- code: 429,
270
- message: 'Too Many Requests',
167
+ code: 401,
168
+ message: 'Unauthorized',
271
169
  };
272
170
  }
273
171
  return { status: true };
@@ -277,93 +175,80 @@ const config = {
277
175
  };
278
176
  ```
279
177
 
280
- ### Custom CORS Configuration
178
+ ### TypeScript Configuration
281
179
 
282
- Configure CORS globally or per-route:
180
+ Type-safe configuration with full IDE support:
283
181
 
284
- ```javascript
285
- const config = {
286
- // Global CORS
287
- cors: {
288
- origin: ['https://example.com', 'https://www.example.com'],
289
- methods: ['GET', 'POST', 'PUT', 'DELETE'],
290
- allowedHeaders: ['Content-Type', 'Authorization'],
291
- credentials: true,
292
- maxAge: 86400,
182
+ ```typescript
183
+ // proxy.config.ts
184
+ import type { ServerConfig, ConnectionInfo } from '@robiki/proxy';
185
+
186
+ const config: ServerConfig = {
187
+ ports: [443, 8080],
188
+ ssl: {
189
+ key: './certs/key.pem',
190
+ cert: './certs/cert.pem',
191
+ allowHTTP1: true,
293
192
  },
294
193
  routes: {
295
194
  'api.example.com': {
296
195
  target: 'backend:3000',
297
196
  ssl: true,
298
- // Route-specific CORS (overrides global)
299
- cors: {
300
- origin: '*',
301
- credentials: false,
197
+ remap: (url: string) => url.replace(/^\/api/, ''),
198
+ validate: async (info: ConnectionInfo) => {
199
+ if (!info.headers['x-api-key']) {
200
+ return { status: false, code: 401, message: 'API Key Required' };
201
+ }
202
+ return { status: true };
302
203
  },
303
204
  },
304
205
  },
305
206
  };
306
- ```
307
207
 
308
- ### Custom Handlers
208
+ export default config;
209
+ ```
309
210
 
310
- Create custom request handlers for advanced use cases:
211
+ ### Environment Variables
311
212
 
312
- ```javascript
313
- import { createCustomProxy } from '@robiki/proxy';
213
+ ```bash
214
+ # SSL Configuration
215
+ SSL_KEY=/app/certs/key.pem
216
+ SSL_CERT=/app/certs/cert.pem
217
+ SSL_ALLOW_HTTP1=true
314
218
 
315
- const customRestHandler = async (req, res) => {
316
- if (req.url === '/health') {
317
- res.writeHead(200, { 'content-type': 'application/json' });
318
- return res.end(JSON.stringify({ status: 'ok' }));
319
- }
320
- // Fall back to default proxy behavior
321
- const { restAPIProxyHandler } = await import('@robiki/proxy/connections');
322
- return restAPIProxyHandler(req, res);
323
- };
219
+ # CORS Configuration
220
+ CORS_ORIGIN=*
221
+ CORS_METHODS=GET,POST,PUT,DELETE
222
+ CORS_CREDENTIALS=true
324
223
 
325
- const proxy = await createCustomProxy(config, {
326
- rest: customRestHandler,
327
- websocket: customWebSocketHandler,
328
- stream: customStreamHandler,
329
- });
224
+ # Debug Mode
225
+ DEBUG=true
330
226
  ```
331
227
 
332
228
  ## 🔧 API Reference
333
229
 
334
- ### `createProxy(config: ServerConfig): Promise<ProxyServer>`
230
+ ### `createProxy(config: ServerConfig)`
335
231
 
336
- Creates and starts a proxy server with the given configuration.
232
+ Creates and starts a proxy server.
337
233
 
338
- **Parameters:**
339
-
340
- - `config`: Server configuration object
341
-
342
- **Returns:** Promise that resolves to a `ProxyServer` instance
343
-
344
- ### `ProxyServer`
345
-
346
- **Methods:**
347
-
348
- - `start()`: Start the proxy server
349
- - `stop()`: Stop the proxy server
350
- - `getConfig()`: Get the current configuration
351
-
352
- ### Configuration Types
353
-
354
- #### `ServerConfig`
234
+ **ServerConfig:**
355
235
 
356
236
  ```typescript
357
237
  interface ServerConfig {
358
238
  ports?: number[];
359
- ssl?: CertificateConfig;
239
+ ssl?: {
240
+ key: string;
241
+ cert: string;
242
+ ca?: string;
243
+ allowHTTP1?: boolean;
244
+ };
360
245
  routes: Record<string, RouteConfig>;
361
246
  cors?: CorsConfig;
362
247
  validate?: (info: ConnectionInfo) => Promise<ForwardValidationResult>;
363
248
  }
364
249
  ```
365
250
 
366
- #### `RouteConfig`
251
+ **RouteConfig:**
367
252
 
368
253
  ```typescript
369
254
  interface RouteConfig {
@@ -375,265 +260,86 @@ interface RouteConfig {
375
260
  }
376
261
  ```
377
262
 
378
- #### `CorsConfig`
379
-
380
- ```typescript
381
- interface CorsConfig {
382
- origin?: string | string[];
383
- methods?: string[];
384
- allowedHeaders?: string[];
385
- exposedHeaders?: string[];
386
- credentials?: boolean;
387
- maxAge?: number;
388
- }
389
- ```
390
-
391
- #### `ConnectionInfo`
392
-
393
- ```typescript
394
- interface ConnectionInfo {
395
- id: number;
396
- method: string;
397
- path: string;
398
- remoteAddress: string;
399
- scheme: string;
400
- authority: string;
401
- origin: string;
402
- headers: IncomingHttpHeaders;
403
- query: URLSearchParams;
404
- type: RequestType;
405
- }
406
- ```
407
-
408
263
  ## 🐳 Docker Usage
409
264
 
410
- ### Using in Another Project
411
-
412
- 1. Add the proxy to your `docker-compose.yml`:
265
+ Mount your config file (JSON, .js, or .ts):
413
266
 
414
267
  ```yaml
415
268
  services:
416
269
  proxy:
417
270
  image: robiki/proxy:latest
418
- ports:
419
- - '443:443'
420
- - '8080:8080'
421
271
  volumes:
422
- - ./proxy.config.json:/app/proxy.config.json:ro
423
- - ./certs:/app/certs:ro
424
- networks:
425
- - your-network
426
-
427
- your-service:
428
- image: your-service-image
429
- networks:
430
- - your-network
431
- ```
432
-
433
- 2. Configure routes in `proxy.config.json` to point to your services
434
-
435
- 3. Start your stack:
436
-
437
- ```bash
438
- docker-compose up -d
439
- ```
440
-
441
- ### Building Custom Image
442
-
443
- Create a custom Dockerfile:
444
-
445
- ```dockerfile
446
- FROM robiki/proxy:latest
447
-
448
- # Copy your configuration
449
- COPY proxy.config.json /app/proxy.config.json
450
- COPY certs /app/certs
451
-
452
- # Set environment variables
453
- ENV PROXY_CONFIG=/app/proxy.config.json
272
+ - ./proxy.config.js:/usr/src/proxy.config.js:ro
273
+ - ./certs:/usr/src/certs:ro
274
+ environment:
275
+ - PROXY_CONFIG=/usr/src/proxy.config.js
454
276
  ```
455
277
 
456
- ## 📚 Examples
457
-
458
- Check the `examples/` directory for more usage examples:
459
-
460
- - `basic-usage.js` - Simple proxy setup
461
- - `advanced-usage.js` - Advanced features (validation, CORS, remapping)
462
- - `custom-handlers.js` - Custom request handlers
463
- - `docker-compose.example.yml` - Complete Docker setup
464
-
465
- ## 🔐 SSL/TLS Certificates
466
-
467
- ### Generating Self-Signed Certificates
278
+ ## 🔐 SSL Certificates
468
279
 
469
- For development:
280
+ ### Development (Self-Signed)
470
281
 
471
282
  ```bash
472
283
  mkdir -p certs
473
284
  openssl req -x509 -newkey rsa:4096 -keyout certs/key.pem -out certs/cert.pem -days 365 -nodes
474
285
  ```
475
286
 
476
- ### Using Let's Encrypt
477
-
478
- For production, use Let's Encrypt certificates:
287
+ ### Production (Let's Encrypt)
479
288
 
480
289
  ```bash
481
290
  certbot certonly --standalone -d example.com
482
291
  ```
483
292
 
484
- Then reference them in your config:
485
-
486
- ```json
487
- {
488
- "ssl": {
489
- "key": "/etc/letsencrypt/live/example.com/privkey.pem",
490
- "cert": "/etc/letsencrypt/live/example.com/fullchain.pem"
491
- }
492
- }
493
- ```
494
-
495
- ## 🤝 Contributing
496
-
497
- Contributions are welcome! Please feel free to submit a Pull Request.
498
-
499
- ## 📄 License
500
-
501
- MIT © Robiki sp. z o.o.
502
-
503
- ## 🔗 Links
504
-
505
- - [GitHub Repository](https://github.com/robiki-ai/robiki-proxy)
506
- - [npm Package](https://www.npmjs.com/package/@robiki/proxy)
507
- - [Issue Tracker](https://github.com/robiki-ai/robiki-proxy/issues)
508
-
509
- ## 💡 Use Cases
510
-
511
- - **Microservices Architecture**: Route requests to different services based on domain/path
512
- - **Development Environment**: Local proxy for testing multiple services
513
- - **API Gateway**: Centralized entry point with authentication and rate limiting
514
- - **SSL Termination**: Handle SSL/TLS at the proxy level
515
- - **CORS Management**: Centralized CORS configuration
516
- - **Load Balancing**: Distribute traffic across multiple instances (with custom handlers)
517
-
518
293
  ## 🛠️ Troubleshooting
519
294
 
520
295
  ### Debug Mode
521
296
 
522
- Enable detailed logging to troubleshoot connection issues:
297
+ Enable detailed logging:
523
298
 
524
299
  ```bash
525
- # Enable debug mode
526
- DEBUG=true node your-proxy-script.js
527
-
528
- # Or with Docker
300
+ DEBUG=true node your-script.js
301
+ # or
529
302
  docker run -e DEBUG=true robiki/proxy:latest
530
-
531
- # Or in docker-compose.yml
532
- services:
533
- proxy:
534
- image: robiki/proxy:latest
535
- environment:
536
- - DEBUG=true
537
303
  ```
538
304
 
539
- When `DEBUG=true`, the proxy will log:
540
-
541
- - All proxy connection attempts (REST, WebSocket, HTTP/2 streams)
542
- - Request and response details
543
- - Connection errors and timeouts
544
- - Proxy errors and client errors
545
-
546
305
  ### Port Already in Use
547
306
 
548
- The proxy will automatically attempt to kill processes on the configured ports. If this fails, manually free the ports:
549
-
550
307
  ```bash
551
308
  lsof -ti:443 | xargs kill -9
552
- lsof -ti:8080 | xargs kill -9
553
309
  ```
554
310
 
555
- ### SSL Certificate Errors
556
-
557
- Ensure your certificate files are readable and in the correct format (PEM). For development, use self-signed certificates.
558
-
559
- ### WebSocket Connection Issues
560
-
561
- Make sure your WebSocket routes are configured with the correct protocol (ws/wss) and that the target service supports WebSocket connections.
562
-
563
311
  ## 🧪 Testing
564
312
 
565
- Robiki Proxy includes a comprehensive test suite covering unit tests, integration tests, and advanced scenarios.
566
-
567
- ### Running Tests
568
-
569
313
  ```bash
570
314
  # Run all tests
571
315
  yarn test
572
316
 
573
- # Run tests in watch mode
574
- yarn test:watch
575
-
576
- # Run tests with coverage
317
+ # Run with coverage
577
318
  yarn test:coverage
578
319
 
579
- # Run tests with UI
580
- yarn test:ui
581
- ```
582
-
583
- ### Test Coverage
584
-
585
- The test suite includes:
586
-
587
- - **Unit Tests**: Configuration, utilities, header conversion, CORS handling
588
- - **Integration Tests**: HTTP proxying, route resolution, validation, config loading
589
- - **Advanced Tests**: WebSocket proxying, HTTP/2 streams, concurrent connections
590
- - **Docker Tests**: Container builds, config loading, runtime behavior
591
-
592
- ### Docker Tests
593
-
594
- Run Docker integration tests:
595
-
596
- ```bash
597
- # Full Docker integration test
320
+ # Docker tests
598
321
  yarn test:docker
599
-
600
- # Test config loading specifically
601
- yarn test:docker:config
602
-
603
- # Run all tests (unit + integration + Docker)
604
- yarn test:all
605
322
  ```
606
323
 
607
- Or using Make:
608
-
609
- ```bash
610
- # Quick Docker build test
611
- make test-docker
612
-
613
- # Full integration test suite
614
- make test-docker-full
324
+ ## 📚 Examples
615
325
 
616
- # Config loading test
617
- make test-docker-config
326
+ Check the `examples/` directory:
618
327
 
619
- # Docker Compose test
620
- make test-docker-compose
621
- ```
328
+ - `basic-usage.js` - Simple proxy setup
329
+ - `advanced-usage.js` - Validation, CORS, remapping
330
+ - `custom-handlers.js` - Custom request handlers
331
+ - `docker-compose.example.yml` - Docker setup
622
332
 
623
- See the [Docker Tests README](tests/docker/README.md) for more details.
333
+ ## 🤝 Contributing
624
334
 
625
- ## 📊 Performance
335
+ Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
626
336
 
627
- The proxy is built on Node.js native HTTP/2 implementation and is designed for high performance:
337
+ ## 📄 License
628
338
 
629
- - Efficient stream handling
630
- - Minimal overhead
631
- - Connection pooling
632
- - Automatic HTTP/1.1 fallback
339
+ MIT © Robiki sp. z o.o.
633
340
 
634
- For production deployments, consider:
341
+ ## 🔗 Links
635
342
 
636
- - Using a process manager (PM2, systemd)
637
- - Enabling clustering for multi-core systems
638
- - Monitoring with health checks
639
- - Setting up proper logging
343
+ - [GitHub Repository](https://github.com/robiki-ai/robiki-proxy)
344
+ - [npm Package](https://www.npmjs.com/package/@robiki/proxy)
345
+ - [Issue Tracker](https://github.com/robiki-ai/robiki-proxy/issues)