@remotelinker/reverse-ws-tunnel 1.0.5 → 1.0.7

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
@@ -38,7 +38,7 @@ npm install @remotelinker/reverse-ws-tunnel
38
38
 
39
39
  ## 📦 Module Compatibility
40
40
 
41
- This library supports both **CommonJS** (`require()`) and **ES Modules** (`import`) for maximum compatibility:
41
+ This library supports both **CommonJS** (`require()`) and **ES Modules** (`import`) for maximum compatibility, and includes **full TypeScript support**:
42
42
 
43
43
  ### CommonJS (Traditional)
44
44
  ```javascript
@@ -54,6 +54,22 @@ import { startWebSocketServer } from '@remotelinker/reverse-ws-tunnel/server';
54
54
  import { loadConfig } from '@remotelinker/reverse-ws-tunnel/utils';
55
55
  ```
56
56
 
57
+ ### TypeScript
58
+ ```typescript
59
+ import { startClient } from '@remotelinker/reverse-ws-tunnel/client';
60
+
61
+ // Full type safety with IntelliSense
62
+ const client = startClient({
63
+ tunnelId: 'uuid',
64
+ wsUrl: 'wss://example.com/tunnel',
65
+ targetUrl: 'http://localhost:3000',
66
+ tunnelEntryPort: 4443
67
+ });
68
+
69
+ // Typed event handlers
70
+ client.on('connected', () => console.log('Connected!'));
71
+ ```
72
+
57
73
  ## 🚀 Quick Start
58
74
 
59
75
  ### Server Setup
package/package.json CHANGED
@@ -1,8 +1,26 @@
1
1
  {
2
2
  "name": "@remotelinker/reverse-ws-tunnel",
3
- "version": "1.0.5",
4
- "description": "",
3
+ "version": "1.0.7",
4
+ "description": "A Node.js library for creating secure reverse tunnels over WebSocket connections",
5
5
  "main": "index.cjs",
6
+ "types": "types/index.d.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/remoteLinker/reverse-ws-tunnel.git"
10
+ },
11
+ "homepage": "https://github.com/remoteLinker/reverse-ws-tunnel#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/remoteLinker/reverse-ws-tunnel/issues"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "index.mjs",
18
+ "index.cjs",
19
+ "client/",
20
+ "server/",
21
+ "utils/",
22
+ "types/"
23
+ ],
6
24
  "config": {
7
25
  "dockerRegistry": {
8
26
  "prod": "",
@@ -14,6 +32,8 @@
14
32
  "test:safe": "node run-tests.js",
15
33
  "test:coverage": "jest --coverage",
16
34
  "test:watch": "jest --watch",
35
+ "type-check": "tsc --noEmit examples/typescript/*.ts",
36
+ "build:types": "tsc",
17
37
  "pack": "npm pack && mv *.tgz dist/",
18
38
  "docker:build": "cross-conf-env docker image build -f Dockerfile . -t $npm_package_config_dockerRegistry_prodremotelinker/reverse-ws-tunnel:$npm_package_version",
19
39
  "docker:deploy": "docker-compose up -d",
@@ -57,6 +77,7 @@
57
77
  "ws": "^8.18.0"
58
78
  },
59
79
  "devDependencies": {
60
- "jest": "^29.7.0"
80
+ "jest": "^29.7.0",
81
+ "typescript": "^5.9.3"
61
82
  }
62
83
  }
@@ -0,0 +1,12 @@
1
+ // types/client.d.ts
2
+ import { EventEmitter } from 'events';
3
+ import { ClientConfig } from './common';
4
+
5
+ export interface TunnelClient extends EventEmitter {
6
+ close(): void;
7
+ on(event: 'connected', listener: () => void): this;
8
+ on(event: 'disconnected', listener: () => void): this;
9
+ on(event: 'error', listener: (error: Error) => void): this;
10
+ }
11
+
12
+ export function startClient(config: ClientConfig): TunnelClient;
@@ -0,0 +1,36 @@
1
+ // types/common.d.ts
2
+ export type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
3
+
4
+ export interface Headers {
5
+ [key: string]: string;
6
+ }
7
+
8
+ export interface ClientConfig {
9
+ targetUrl: string;
10
+ allowInsicureCerts?: boolean;
11
+ wsUrl: string;
12
+ tunnelId: string;
13
+ tunnelEntryUrl?: string;
14
+ tunnelEntryPort: number;
15
+ headers?: Headers;
16
+ environment?: 'development' | 'production';
17
+ autoReconnect?: boolean;
18
+ }
19
+
20
+ export interface ServerConfig {
21
+ port: number;
22
+ host?: string;
23
+ path?: string;
24
+ tunnelIdHeaderName?: string;
25
+ }
26
+
27
+ export interface ConfigResult {
28
+ targetUrl?: string;
29
+ allowInsicureCerts?: boolean;
30
+ wsUrl?: string;
31
+ tunnelId?: string;
32
+ tunnelEntryUrl?: string;
33
+ tunnelEntryPort?: string;
34
+ headers?: Headers;
35
+ environment?: string;
36
+ }
@@ -0,0 +1,4 @@
1
+ // types/index.d.ts
2
+ export * from './client';
3
+ export * from './server';
4
+ export * from './utils';
@@ -0,0 +1,5 @@
1
+ // types/server.d.ts
2
+ import { ServerConfig } from './common';
3
+
4
+ export function startWebSocketServer(config: ServerConfig): void;
5
+ export function setLogContext(context: string): void;
@@ -0,0 +1,6 @@
1
+ // types/utils.d.ts
2
+ import { LogLevel, ConfigResult } from './common';
3
+
4
+ export function setLogLevel(level: LogLevel): void;
5
+ export function getLogLevel(): LogLevel;
6
+ export function loadConfig(customPath?: string): ConfigResult;
package/CHANGELOG.md DELETED
@@ -1,54 +0,0 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- ## [1.0.3] - 2025-11-29
6
-
7
- ### Features
8
- - Updated `startClient` to return a client instance.
9
- - Added `connected` and `disconnected` events to the client instance.
10
- - Added `close()` method to the client instance to terminate the connection and stop reconnection.
11
-
12
- ## [1.0.2] - 2025-10-05
13
-
14
- ### Fixes
15
- - Corrected a typo in the environment variable name for `allowInsicureCerts` in the client configuration loader.
16
-
17
- ## [1.0.1] - 2025-09-16
18
-
19
- ### Features
20
- - Added a comprehensive example of a reverse tunnel to README.md.
21
- - Included a minimal web server to act as the tunnel's target.
22
- - Updated the client configuration to align with the new example.
23
- - Generated a CHANGELOG.md file from the project's git history.
24
-
25
- ### Refactoring
26
- - Refactored WebSocket connection state management.
27
-
28
- ## [1.0.0] - 2025-09-16
29
-
30
- ### Features
31
- - Added dynamic environment configuration.
32
- - Added client IP to server connection function.
33
- - Added support for custom config path.
34
- - Added unit tests with Jest.
35
- - Added `config.toml` for configuration.
36
- - Added logger.
37
- - Added examples.
38
- - Added dynamic allowance of insecure HTTPS certificates.
39
- - Added support for multiple servers on different ports.
40
- - Added return of the WebSocket server instance.
41
- - Added dynamic TCP server.
42
- - Initial working version.
43
-
44
- ### Fixes
45
- - Fixed WebSocket server heartbeat.
46
- - Fixed `allowInsicureCerts` option.
47
- - Fixed logger path.
48
- - Fixed heartbeat issue.
49
- - Disabled secure proxy when set to false.
50
-
51
- ### Refactoring
52
- - Refactored dist directory structure.
53
- - Changed `tunnelIdHeaderName`.
54
- - Refactored with ChatGPT suggestions.
package/cookbook.md DELETED
@@ -1,608 +0,0 @@
1
- # WebSocket Tunneling Cookbook: Building Reverse Tunnels in Node.js
2
-
3
- ## Overview
4
-
5
- This cookbook provides comprehensive examples and technical deep-dives into reverse WebSocket tunneling using the Node.js library. Whether you're a developer exposing local services, a DevOps engineer deploying production tunnels, or an IoT developer connecting edge devices, this guide offers practical implementations and detailed explanations.
6
-
7
- ## Table of Contents
8
-
9
- 1. [Quick Start Examples](#quick-start-examples)
10
- 2. [Architecture Deep Dive](#architecture-deep-dive)
11
- 3. [Communication Protocol](#communication-protocol)
12
- 4. [Security Best Practices](#security-best-practices)
13
- 5. [Production Deployment](#production-deployment)
14
- 6. [Troubleshooting Guide](#troubleshooting-guide)
15
- 7. [Advanced Use Cases](#advanced-use-cases)
16
-
17
- ## Quick Start Examples
18
-
19
- ### Example 1: Local Development Server Exposure
20
-
21
- **Scenario**: You're developing a web app on `localhost:3000` and need to share it with a client for feedback.
22
-
23
- **Step 1: Set up your local service**
24
- ```bash
25
- # Create a simple Express server
26
- npm init -y
27
- npm install express
28
- ```
29
-
30
- ```javascript
31
- // server.js
32
- const express = require('express');
33
- const app = express();
34
-
35
- app.get('/', (req, res) => {
36
- res.send('Hello from my development server!');
37
- });
38
-
39
- app.listen(3000, () => {
40
- console.log('Dev server running on http://localhost:3000');
41
- });
42
- ```
43
-
44
- **Step 2: Install the tunneling library**
45
- ```bash
46
- npm install @remotelinker/reverse-ws-tunnel
47
- ```
48
-
49
- **Step 3: Create tunnel configuration**
50
- ```javascript
51
- // tunnel-config.js (CommonJS)
52
- // const { startClient } = require('@remotelinker/reverse-ws-tunnel/client');
53
-
54
- // tunnel-config.mjs (ES Modules)
55
- // import { startClient } from '@remotelinker/reverse-ws-tunnel/client';
56
-
57
- const { startClient } = require('@remotelinker/reverse-ws-tunnel/client');
58
-
59
- const client = startClient({
60
- tunnelId: '550e8400-e29b-41d4-a716-446655440000', // Generate a UUID
61
- wsUrl: 'wss://your-tunnel-server.com/tunnel',
62
- targetUrl: 'http://localhost:3000',
63
- tunnelEntryPort: 4443
64
- });
65
-
66
- client.on('connected', () => {
67
- console.log('🎉 Tunnel active! Access at: https://your-tunnel-server.com?tunnelId=550e8400-e29b-41d4-a716-446655440000');
68
- });
69
- ```
70
-
71
- ### Example 2: IoT Device Connectivity
72
-
73
- **Scenario**: Connect a Raspberry Pi running a sensor service behind NAT to the cloud.
74
-
75
- ```javascript
76
- // iot-tunnel.js
77
- const { startClient } = require('@remotelinker/reverse-ws-tunnel/client');
78
-
79
- const client = startClient({
80
- tunnelId: 'device-001-sensor-data',
81
- wsUrl: 'wss://iot-gateway.yourcompany.com/tunnel',
82
- targetUrl: 'http://localhost:8080',
83
- headers: {
84
- 'Authorization': 'Bearer device-token-123',
85
- 'Device-Type': 'raspberry-pi-4',
86
- 'Sensor-Capabilities': 'temperature,humidity'
87
- },
88
- autoReconnect: true
89
- });
90
-
91
- client.on('connected', () => {
92
- console.log('IoT device connected to cloud');
93
- });
94
-
95
- client.on('disconnected', () => {
96
- console.log('Connection lost, auto-reconnecting...');
97
- });
98
- ```
99
-
100
- ### Example 3: API Development with Webhook Testing
101
-
102
- **Scenario**: Develop and test webhooks for payment processing.
103
-
104
- ```javascript
105
- // webhook-tester.js
106
- const { startClient } = require('@remotelinker/reverse-ws-tunnel/client');
107
- const express = require('express');
108
-
109
- const app = express();
110
- app.use(express.json());
111
-
112
- // Webhook endpoint for payment provider
113
- app.post('/webhooks/payments', (req, res) => {
114
- console.log('Received payment webhook:', req.body);
115
- res.json({ status: 'processed' });
116
- });
117
-
118
- const server = app.listen(3001, () => {
119
- console.log('Webhook server ready on port 3001');
120
- });
121
-
122
- // Create tunnel for webhook testing
123
- const client = startClient({
124
- tunnelId: 'webhook-test-session-123',
125
- wsUrl: 'wss://tunnel.stripe-test.com/tunnel',
126
- targetUrl: 'http://localhost:3001',
127
- headers: {
128
- 'X-Webhook-Secret': 'whsec_test_secret'
129
- }
130
- });
131
-
132
- client.on('connected', () => {
133
- console.log('Webhook tunnel active - configure your Stripe dashboard with:');
134
- console.log('https://tunnel.stripe-test.com/webhooks?tunnelId=webhook-test-session-123');
135
- });
136
- ```
137
-
138
- ## Architecture Deep Dive
139
-
140
- ### Core Components
141
-
142
- The library consists of three main architectural components:
143
-
144
- **1. WebSocket Server Component**
145
- - Handles persistent WebSocket connections from clients
146
- - Manages tunnel registration and state
147
- - Routes incoming HTTP requests based on tunnel IDs
148
-
149
- **2. Client Component**
150
- - Establishes outbound WebSocket connection
151
- - Proxies local service requests
152
- - Handles connection lifecycle and reconnection
153
-
154
- **3. TCP Proxy Layer**
155
- - Receives external HTTP requests
156
- - Forwards requests through WebSocket tunnels
157
- - Manages connection multiplexing
158
-
159
- ### System Architecture Diagram
160
-
161
- ```mermaid
162
- architecture-beta
163
- group internet[Internet]
164
-
165
- service ext[External Client] in internet
166
- service tcp[TCP Server] in internet
167
-
168
- end
169
-
170
- service ws[WebSocket Server] in internet
171
-
172
- group local[Local Network]
173
-
174
- service proxy[HTTP Proxy] in local
175
- service target[Target Service] in local
176
- service client[WebSocket Client] in local
177
-
178
- end
179
-
180
- ext:R -- L:HTTP Request
181
- tcp:L -- R:Route by tunnel-id
182
- tcp:R -- L:WS DATA message
183
- ws:L -- R:Forward to tunnel
184
- client:R -- L:Receive WS message
185
- client:R -- L:Forward to proxy
186
- proxy:L -- R:HTTP to target
187
- target:R -- L:Response
188
- proxy:R -- L:TCP data back
189
- client:R -- L:WS DATA response
190
- ws:R -- L:Forward to TCP
191
- tcp:R -- L:HTTP response
192
- ext:L -- R:Receive response
193
- ```
194
-
195
- *Reverse tunneling architecture showing request flow from external clients to local services*
196
-
197
- ## Communication Protocol
198
-
199
- ### Message Format
200
-
201
- The tunneling protocol uses a custom binary message format optimized for efficiency:
202
-
203
- ```
204
- [4 bytes: length] [36 bytes: tunnel_id] [36 bytes: connection_uuid] [1 byte: type] [payload]
205
- ```
206
-
207
- **Message Types:**
208
- - **CONFIG (0x01)**: Initial tunnel setup with target URL, ports, and metadata
209
- - **DATA (0x02)**: Bidirectional data transfer for HTTP requests/responses
210
-
211
- ### Connection Lifecycle
212
-
213
- ```mermaid
214
- sequenceDiagram
215
- participant Local as Local Service
216
- participant Proxy as Client Proxy
217
- participant WSClient as Client WS
218
- participant WSServer as Server WS
219
- participant TCPServer as Server TCP
220
- participant Ext as External Client
221
-
222
- Note over WSClient,WSServer: 1. Tunnel Establishment
223
- WSClient->>WSServer: WS Connect + CONFIG message
224
- WSServer->>WSClient: Acknowledgment
225
-
226
- Note over TCPServer,Ext: 2. External Request
227
- Ext->>TCPServer: HTTP Request + x-tunnel-id header
228
- TCPServer->>WSServer: Parse HTTP → WS DATA message
229
-
230
- Note over WSClient,Proxy: 3. Request Forwarding
231
- WSServer->>WSClient: WS DATA message
232
- WSClient->>Proxy: TCP data to local proxy
233
- Proxy->>Local: HTTP request to target service
234
-
235
- Note over Local,WSClient: 4. Response Flow
236
- Local-->>Proxy: HTTP response
237
- Proxy-->>WSClient: TCP data
238
- WSClient-->>WSServer: WS DATA message
239
- WSServer-->>TCPServer: Forward to TCP socket
240
- TCPServer-->>Ext: HTTP response
241
- ```
242
-
243
- *Complete request-response cycle through the tunnel*
244
-
245
- ## Security Best Practices
246
-
247
- ### Authentication & Authorization
248
-
249
- ```javascript
250
- // Secure tunnel with multiple auth methods
251
- const secureClient = startClient({
252
- tunnelId: 'prod-api-gateway',
253
- wsUrl: 'wss://secure-tunnel.yourcompany.com/tunnel',
254
- targetUrl: 'http://localhost:8080',
255
- headers: {
256
- 'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIs...',
257
- 'X-API-Key': 'sk_prod_1234567890',
258
- 'X-Client-Cert': 'certificate_fingerprint'
259
- },
260
- allowInsicureCerts: false // Always false in production
261
- });
262
- ```
263
-
264
- ### SSL/TLS Configuration
265
-
266
- **Server-side SSL termination:**
267
- ```javascript
268
- const https = require('https');
269
- // const { startWebSocketServer } = require('@remotelinker/reverse-ws-tunnel/server'); // CommonJS
270
- // import { startWebSocketServer } from '@remotelinker/reverse-ws-tunnel/server'; // ES Modules
271
- const { startWebSocketServer } = require('@remotelinker/reverse-ws-tunnel/server');
272
-
273
- const sslOptions = {
274
- key: fs.readFileSync('server.key'),
275
- cert: fs.readFileSync('server.crt'),
276
- ca: fs.readFileSync('ca.crt')
277
- };
278
-
279
- const server = https.createServer(sslOptions);
280
- startWebSocketServer({
281
- server, // Use existing HTTPS server
282
- path: '/secure-tunnel'
283
- });
284
- ```
285
-
286
- ### Network Security
287
-
288
- - **Firewall Rules**: Restrict WebSocket server access to known client IPs
289
- - **Rate Limiting**: Implement request throttling to prevent abuse
290
- - **Connection Monitoring**: Log and monitor tunnel usage patterns
291
- - **Certificate Pinning**: Pin SSL certificates to prevent MITM attacks
292
-
293
- ## Production Deployment
294
-
295
- ### Docker Compose Setup
296
-
297
- ```yaml
298
- # docker-compose.yml
299
- version: '3.8'
300
- services:
301
- tunnel-server:
302
- image: remotelinker/reverse-ws-tunnel:latest
303
- ports:
304
- - "443:443"
305
- - "80:80"
306
- environment:
307
- - WS_PORT=443
308
- - HOST=0.0.0.0
309
- - TUNNEL_ID_HEADER_NAME=x-tunnel-id
310
- - LOG_LEVEL=info
311
- volumes:
312
- - ./ssl:/app/ssl:ro
313
- - ./config:/app/config:ro
314
- restart: unless-stopped
315
-
316
- tunnel-client:
317
- image: remotelinker/reverse-ws-tunnel:latest
318
- environment:
319
- - TUNNEL_ID=prod-service-001
320
- - WS_URL=wss://tunnel.yourdomain.com/tunnel
321
- - TARGET_URL=http://host.docker.internal:3000
322
- - LOG_LEVEL=debug
323
- depends_on:
324
- - tunnel-server
325
- restart: unless-stopped
326
- ```
327
-
328
- ### Kubernetes Deployment
329
-
330
- ```yaml
331
- # tunnel-server-deployment.yaml
332
- apiVersion: apps/v1
333
- kind: Deployment
334
- metadata:
335
- name: tunnel-server
336
- spec:
337
- replicas: 3
338
- selector:
339
- matchLabels:
340
- app: tunnel-server
341
- template:
342
- metadata:
343
- labels:
344
- app: tunnel-server
345
- spec:
346
- containers:
347
- - name: tunnel-server
348
- image: remotelinker/reverse-ws-tunnel:latest
349
- ports:
350
- - containerPort: 443
351
- env:
352
- - name: WS_PORT
353
- value: "443"
354
- - name: LOG_LEVEL
355
- value: "info"
356
- resources:
357
- requests:
358
- memory: "128Mi"
359
- cpu: "100m"
360
- limits:
361
- memory: "512Mi"
362
- cpu: "500m"
363
- livenessProbe:
364
- httpGet:
365
- path: /health
366
- port: 443
367
- scheme: HTTPS
368
- initialDelaySeconds: 30
369
- periodSeconds: 10
370
- ```
371
-
372
- ### Monitoring & Observability
373
-
374
- ```javascript
375
- // Monitoring integration
376
- const client = startClient({
377
- // ... config
378
- });
379
-
380
- client.on('connected', () => {
381
- // Send metrics to monitoring system
382
- prometheusGauge.set({ tunnel_id: config.tunnelId }, 1);
383
- });
384
-
385
- client.on('disconnected', () => {
386
- prometheusGauge.set({ tunnel_id: config.tunnelId }, 0);
387
- });
388
-
389
- // Custom metrics collection
390
- setInterval(() => {
391
- const metrics = {
392
- tunnelId: config.tunnelId,
393
- uptime: process.uptime(),
394
- memoryUsage: process.memoryUsage(),
395
- activeConnections: getActiveConnectionCount()
396
- };
397
-
398
- sendToMonitoring(metrics);
399
- }, 30000);
400
- ```
401
-
402
- ## Troubleshooting Guide
403
-
404
- ### Common Issues
405
-
406
- **Connection Refused**
407
- ```bash
408
- # Check if server is running
409
- curl -I https://your-tunnel-server.com/tunnel
410
-
411
- # Verify WebSocket connectivity
412
- wscat -c wss://your-tunnel-server.com/tunnel
413
- ```
414
-
415
- **SSL Certificate Errors**
416
- ```javascript
417
- // For development only
418
- const client = startClient({
419
- // ... config
420
- allowInsicureCerts: true, // Remove in production
421
- rejectUnauthorized: false
422
- });
423
- ```
424
-
425
- **Tunnel Not Receiving Traffic**
426
- ```bash
427
- # Test with curl
428
- curl -H "x-tunnel-id: your-tunnel-id" \
429
- https://your-tunnel-server.com/
430
-
431
- # Check server logs for routing errors
432
- docker logs tunnel-server
433
- ```
434
-
435
- **Connection Drops**
436
- ```javascript
437
- // Implement reconnection logic
438
- const client = startClient({
439
- // ... config
440
- autoReconnect: true,
441
- reconnectInterval: 5000,
442
- maxReconnectAttempts: 10
443
- });
444
-
445
- client.on('disconnected', (reason) => {
446
- console.log('Disconnected:', reason);
447
- // Implement exponential backoff
448
- });
449
- ```
450
-
451
- ### Debug Logging
452
-
453
- ```javascript
454
- // Enable detailed logging
455
- process.env.LOG_LEVEL = 'debug';
456
-
457
- // Or programmatically
458
- // const { setLogLevel } = require('@remotelinker/reverse-ws-tunnel/utils'); // CommonJS
459
- // import { setLogLevel } from '@remotelinker/reverse-ws-tunnel/utils'; // ES Modules
460
- const { setLogLevel } = require('@remotelinker/reverse-ws-tunnel/utils');
461
- setLogLevel('trace');
462
- ```
463
-
464
- ## Advanced Use Cases
465
-
466
- ### Load Balancing Multiple Instances
467
-
468
- ```javascript
469
- // Load balancer configuration
470
- const clients = [];
471
-
472
- for (let i = 0; i < 3; i++) {
473
- const client = startClient({
474
- tunnelId: `api-server-${i}`,
475
- wsUrl: 'wss://load-balancer.com/tunnel',
476
- targetUrl: `http://api-server-${i}:3000`,
477
- headers: {
478
- 'X-Instance-ID': i,
479
- 'X-Load-Balancer': 'round-robin'
480
- }
481
- });
482
-
483
- clients.push(client);
484
- }
485
-
486
- // Health check monitoring
487
- clients.forEach((client, index) => {
488
- client.on('connected', () => {
489
- console.log(`Instance ${index} connected`);
490
- });
491
- });
492
- ```
493
-
494
- ### Custom Authentication Middleware
495
-
496
- ```javascript
497
- // Server-side auth validation
498
- // const { startWebSocketServer } = require('@remotelinker/reverse-ws-tunnel/server'); // CommonJS
499
- // import { startWebSocketServer } from '@remotelinker/reverse-ws-tunnel/server'; // ES Modules
500
- const { startWebSocketServer } = require('@remotelinker/reverse-ws-tunnel/server');
501
-
502
- const authenticateTunnel = (headers) => {
503
- const token = headers['authorization'];
504
- if (!token) return false;
505
-
506
- // Validate JWT token
507
- try {
508
- const decoded = jwt.verify(token, process.env.JWT_SECRET);
509
- return decoded.role === 'tunnel-client';
510
- } catch (err) {
511
- return false;
512
- }
513
- };
514
-
515
- startWebSocketServer({
516
- port: 443,
517
- authenticate: authenticateTunnel
518
- });
519
- ```
520
-
521
- ### WebSocket Upgrade Handling
522
-
523
- ```javascript
524
- // Handle WebSocket connections through tunnel
525
- const WebSocket = require('ws');
526
- // const { startClient } = require('@remotelinker/reverse-ws-tunnel/client'); // CommonJS
527
- // import { startClient } from '@remotelinker/reverse-ws-tunnel/client'; // ES Modules
528
- const { startClient } = require('@remotelinker/reverse-ws-tunnel/client');
529
-
530
- const client = startClient({
531
- tunnelId: 'websocket-service',
532
- wsUrl: 'wss://tunnel.com/tunnel',
533
- targetUrl: 'http://localhost:8080'
534
- });
535
-
536
- // The tunnel automatically handles WebSocket upgrades
537
- // No additional configuration needed for WS connections
538
- ```
539
-
540
- ### File Upload/Download Tunneling
541
-
542
- ```javascript
543
- // Large file transfer configuration
544
- const client = startClient({
545
- tunnelId: 'file-transfer-service',
546
- wsUrl: 'wss://tunnel.com/tunnel',
547
- targetUrl: 'http://localhost:3000',
548
- // Increase buffer sizes for large files
549
- maxPayloadSize: '100MB',
550
- timeout: 300000 // 5 minutes
551
- });
552
-
553
- // Server-side file handling
554
- const express = require('express');
555
- const multer = require('multer');
556
- const app = express();
557
-
558
- const upload = multer({
559
- dest: 'uploads/',
560
- limits: { fileSize: 100 * 1024 * 1024 } // 100MB
561
- });
562
-
563
- app.post('/upload', upload.single('file'), (req, res) => {
564
- res.json({ message: 'File uploaded successfully' });
565
- });
566
- ```
567
-
568
- ## Performance Optimization
569
-
570
- ### Connection Pooling
571
-
572
- ```javascript
573
- // Optimize for high-throughput scenarios
574
- const client = startClient({
575
- tunnelId: 'high-throughput-api',
576
- wsUrl: 'wss://tunnel.com/tunnel',
577
- targetUrl: 'http://localhost:3000',
578
- // Connection pooling settings
579
- maxConnections: 100,
580
- keepAlive: true,
581
- keepAliveTimeout: 60000
582
- });
583
- ```
584
-
585
- ### Compression
586
-
587
- ```javascript
588
- // Enable compression for text-based content
589
- const compression = require('compression');
590
-
591
- app.use(compression({
592
- level: 6, // Balance between speed and compression
593
- threshold: 1024 // Only compress responses > 1KB
594
- }));
595
- ```
596
-
597
- ## Conclusion
598
-
599
- This WebSocket tunneling library provides a robust, flexible solution for exposing local services to the internet. From simple development workflows to complex production deployments, the examples in this cookbook demonstrate the library's versatility across different use cases.
600
-
601
- Key takeaways:
602
- - **Security First**: Always use SSL/TLS and implement proper authentication
603
- - **Monitoring**: Implement comprehensive logging and metrics collection
604
- - **Scalability**: Design for horizontal scaling with load balancing
605
- - **Reliability**: Use auto-reconnection and proper error handling
606
-
607
- For more advanced implementations and custom integrations, refer to the library's source code and API documentation.</content>
608
- <parameter name="filePath">cookbook.md
package/jest.config.cjs DELETED
@@ -1,5 +0,0 @@
1
- module.exports = {
2
- testEnvironment: 'node',
3
- testTimeout: 30000,
4
- verbose: true,
5
- };