2022-07-29 01:52:34 +02:00
2019-08-20 17:50:17 +02:00
2025-05-10 00:26:04 +00:00
2025-05-10 00:01:02 +00:00

@push.rocks/smartproxy

A unified high-performance proxy toolkit for Node.js, with SmartProxy as the central API to handle all your proxy needs:

  • Unified Route-Based Configuration: Match/action pattern for clean, consistent traffic routing
  • SSL/TLS Support: Automatic HTTPS with Let's Encrypt certificate provisioning
  • Flexible Matching Patterns: Route by port, domain, path, client IP, and TLS version
  • Advanced SNI Handling: Smart TCP/SNI-based forwarding with IP filtering
  • Multiple Action Types: Forward (with TLS modes), redirect, or block traffic
  • Security Features: IP allowlists, connection limits, timeouts, and more

Project Architecture Overview

SmartProxy has been restructured using a modern, modular architecture with a unified route-based configuration system in v14.0.0:

/ts
├── /core                     # Core functionality
│   ├── /models               # Data models and interfaces
│   ├── /utils                # Shared utilities (IP validation, logging, etc.)
│   └── /events               # Common event definitions
├── /certificate              # Certificate management
│   ├── /acme                 # ACME-specific functionality
│   ├── /providers            # Certificate providers (static, ACME)
│   └── /storage              # Certificate storage mechanisms
├── /forwarding               # Forwarding system
│   ├── /handlers             # Various forwarding handlers
│   │   ├── base-handler.ts   # Abstract base handler
│   │   ├── http-handler.ts   # HTTP-only handler
│   │   └── ...               # Other handlers
│   ├── /config               # Configuration models
│   └── /factory              # Factory for creating handlers
├── /proxies                  # Different proxy implementations
│   ├── /smart-proxy          # SmartProxy implementation
│   │   ├── /models           # SmartProxy-specific interfaces
│   │   │   ├── route-types.ts # Route-based configuration types
│   │   │   └── interfaces.ts  # SmartProxy interfaces
│   │   ├── route-helpers.ts  # Helper functions for creating routes
│   │   ├── route-manager.ts  # Route management system
│   │   ├── smart-proxy.ts    # Main SmartProxy class
│   │   └── ...               # Supporting classes
│   ├── /network-proxy        # NetworkProxy implementation
│   └── /nftables-proxy       # NfTablesProxy implementation
├── /tls                      # TLS-specific functionality
│   ├── /sni                  # SNI handling components
│   └── /alerts               # TLS alerts system
└── /http                     # HTTP-specific functionality
    ├── /port80               # Port80Handler components
    ├── /router               # HTTP routing system
    └── /redirects            # Redirect handlers

Main Components

  • SmartProxy (ts/proxies/smart-proxy/smart-proxy.ts) The central unified API for all proxy needs, featuring:
    • Route-based configuration with match/action pattern
    • Flexible matching criteria (ports, domains, paths, client IPs)
    • Multiple action types (forward, redirect, block)
    • Automatic certificate management
    • Advanced security controls

Helper Functions

  • createRoute, createHttpRoute, createHttpsRoute, createPassthroughRoute Helper functions to create different route configurations with clean syntax
  • createRedirectRoute, createHttpToHttpsRedirect, createBlockRoute Helper functions for common redirect and security configurations
  • createLoadBalancerRoute, createHttpsServer Helper functions for complex configurations

Specialized Components

  • NetworkProxy (ts/proxies/network-proxy/network-proxy.ts) HTTP/HTTPS reverse proxy with TLS termination and WebSocket support
  • Port80Handler (ts/http/port80/port80-handler.ts) ACME HTTP-01 challenge handler for Let's Encrypt certificates
  • NfTablesProxy (ts/proxies/nftables-proxy/nftables-proxy.ts) Low-level port forwarding using nftables NAT rules
  • Redirect, SslRedirect (ts/http/redirects/redirect-handler.ts) HTTP-to-HTTPS redirects with customizable rules
  • SniHandler (ts/tls/sni/sni-handler.ts) Utilities for SNI extraction from TLS handshakes

Core Utilities

  • ValidationUtils (ts/core/utils/validation-utils.ts) Domain, port, and configuration validation
  • IpUtils (ts/core/utils/ip-utils.ts) IP address validation and filtering with glob patterns

Interfaces and Types

  • IRouteConfig, IRouteMatch, IRouteAction (ts/proxies/smart-proxy/models/route-types.ts)
  • IRoutedSmartProxyOptions (ts/proxies/smart-proxy/models/route-types.ts)
  • INetworkProxyOptions (ts/proxies/network-proxy/models/types.ts)
  • IAcmeOptions, IDomainOptions (ts/certificate/models/certificate-types.ts)
  • INfTableProxySettings (ts/proxies/nftables-proxy/models/interfaces.ts)

Installation

Install via npm:

npm install @push.rocks/smartproxy

Quick Start with SmartProxy v14.0.0

SmartProxy v14.0.0 introduces a new unified route-based configuration system that makes configuring proxies more flexible and intuitive.

import { 
  SmartProxy, 
  createHttpRoute, 
  createHttpsRoute, 
  createPassthroughRoute, 
  createHttpToHttpsRedirect
} from '@push.rocks/smartproxy';

// Create a new SmartProxy instance with route-based configuration
const proxy = new SmartProxy({
  // Define all your routing rules in one array
  routes: [
    // Basic HTTP route - forward traffic from port 80 to internal service
    createHttpRoute({
      ports: 80,
      domains: 'api.example.com',
      target: { host: 'localhost', port: 3000 }
    }),

    // HTTPS route with TLS termination and automatic certificates
    createHttpsRoute({
      ports: 443,
      domains: 'secure.example.com',
      target: { host: 'localhost', port: 8080 },
      certificate: 'auto'  // Use Let's Encrypt
    }),

    // HTTPS passthrough for legacy systems
    createPassthroughRoute({
      ports: 443,
      domains: 'legacy.example.com',
      target: { host: '192.168.1.10', port: 443 }
    }),

    // Redirect HTTP to HTTPS
    createHttpToHttpsRedirect({
      domains: ['example.com', '*.example.com']
    }),

    // Complex load balancer setup with security controls
    createLoadBalancerRoute({
      domains: ['app.example.com'],
      targets: ['192.168.1.10', '192.168.1.11', '192.168.1.12'],
      targetPort: 8080,
      tlsMode: 'terminate',
      certificate: 'auto',
      security: {
        allowedIps: ['10.0.0.*', '192.168.1.*'],
        blockedIps: ['1.2.3.4'],
        maxConnections: 1000
      }
    })
  ],

  // Global settings that apply to all routes
  defaults: {
    security: {
      maxConnections: 500
    }
  },

  // Automatic Let's Encrypt integration
  acme: {
    enabled: true,
    contactEmail: 'admin@example.com',
    useProduction: true
  }
});

// Listen for certificate events
proxy.on('certificate', evt => {
  console.log(`Certificate for ${evt.domain} ready, expires: ${evt.expiryDate}`);
});

// Start the proxy
await proxy.start();

// Dynamically add new routes later
await proxy.addRoutes([
  createHttpsRoute({
    domains: 'new-domain.com',
    target: { host: 'localhost', port: 9000 },
    certificate: 'auto'
  })
]);

// Later, gracefully shut down
await proxy.stop();

Route-Based Configuration System

SmartProxy v14.0.0 introduces a new unified route configuration system based on the IRouteConfig interface. This system follows a match/action pattern that makes routing more powerful, flexible, and declarative.

IRouteConfig Interface

The IRouteConfig interface is the core building block of SmartProxy's configuration system. Each route definition consists of match criteria and an action to perform on matched traffic:

interface IRouteConfig {
  // What traffic to match (required)
  match: IRouteMatch;

  // What to do with matched traffic (required)
  action: IRouteAction;

  // Metadata (all optional)
  name?: string;             // Human-readable name for this route
  description?: string;      // Description of the route's purpose
  priority?: number;         // Controls matching order (higher = matched first)
  tags?: string[];           // Arbitrary tags for categorization
}

Match Criteria (IRouteMatch)

The match property defines criteria for identifying which incoming traffic should be handled by this route:

interface IRouteMatch {
  // Listen on these ports (required)
  ports: TPortRange;  // number | number[] | Array<{ from: number; to: number }>

  // Optional domain patterns to match (default: all domains)
  domains?: string | string[];  // Supports wildcards like '*.example.com'

  // Advanced matching criteria (all optional)
  path?: string;           // Match specific URL paths, supports glob patterns
  clientIp?: string[];     // Match specific client IPs, supports glob patterns
  tlsVersion?: string[];   // Match specific TLS versions e.g. ['TLSv1.2', 'TLSv1.3']
}

Port Specification:

  • Single port: ports: 80
  • Multiple ports: ports: [80, 443]
  • Port ranges: ports: [{ from: 8000, to: 8100 }]
  • Mixed format: ports: [80, 443, { from: 8000, to: 8100 }]

Domain Matching:

  • Single domain: domains: 'example.com'
  • Multiple domains: domains: ['example.com', 'api.example.com']
  • Wildcard domains: domains: '*.example.com' (matches any subdomain)
  • Root domain + subdomains: domains: ['example.com', '*.example.com']

Path Matching:

  • Exact path: path: '/api' (matches only /api exactly)
  • Prefix match: path: '/api/*' (matches /api and any paths under it)
  • Multiple patterns: Use multiple routes with different priorities

Client IP Matching:

  • Exact IP: clientIp: ['192.168.1.1']
  • Subnet wildcards: clientIp: ['10.0.0.*', '192.168.1.*']
  • CIDR notation: clientIp: ['10.0.0.0/24']

TLS Version Matching:

  • tlsVersion: ['TLSv1.2', 'TLSv1.3'] (only match these TLS versions)

Action Configuration (IRouteAction)

The action property defines what to do with traffic that matches the criteria:

interface IRouteAction {
  // Action type (required)
  type: 'forward' | 'redirect' | 'block';

  // For 'forward' actions
  target?: IRouteTarget;

  // TLS handling for 'forward' actions
  tls?: IRouteTls;

  // For 'redirect' actions
  redirect?: IRouteRedirect;

  // Security options for any action
  security?: IRouteSecurity;

  // Advanced options
  advanced?: IRouteAdvanced;
}

Forward Action: When type: 'forward', the traffic is forwarded to the specified target:

interface IRouteTarget {
  host: string | string[];  // Target host(s) - string array enables round-robin
  port: number;             // Target port
  preservePort?: boolean;   // Use incoming port as target port (default: false)
}

TLS Configuration: When forwarding with TLS, you can configure how TLS is handled:

interface IRouteTls {
  mode: 'passthrough' | 'terminate' | 'terminate-and-reencrypt';
  certificate?: 'auto' | {   // 'auto' = use ACME (Let's Encrypt)
    key: string;            // TLS private key content
    cert: string;           // TLS certificate content
  };
}

TLS Modes:

  • passthrough: Forward raw encrypted TLS traffic without decryption
  • terminate: Terminate TLS and forward as HTTP
  • terminate-and-reencrypt: Terminate TLS and create a new TLS connection to the backend

Redirect Action: When type: 'redirect', the client is redirected:

interface IRouteRedirect {
  to: string;                   // URL or template with variables
  status: 301 | 302 | 307 | 308;  // HTTP status code
}

Block Action: When type: 'block', the connection is immediately closed.

Security Options: For any action type, you can add security controls:

interface IRouteSecurity {
  allowedIps?: string[];     // IP allowlist with glob pattern support
  blockedIps?: string[];     // IP blocklist with glob pattern support
  maxConnections?: number;   // Maximum concurrent connections
  authentication?: {         // Optional authentication (future support)
    type: 'basic' | 'digest' | 'oauth';
    // Auth-specific options
  };
}

Advanced Options: Additional advanced configurations:

interface IRouteAdvanced {
  timeout?: number;                 // Connection timeout in milliseconds
  headers?: Record<string, string>; // Custom HTTP headers
  keepAlive?: boolean;              // Enable connection pooling
  // Additional advanced options
}

Template Variables

String values in redirect URLs and headers can include variables:

  • {domain}: The requested domain name
  • {port}: The incoming port number
  • {path}: The requested URL path
  • {query}: The query string
  • {clientIp}: The client's IP address
  • {sni}: The SNI hostname

Example with template variables:

redirect: {
  to: 'https://{domain}{path}?source=redirect',
  status: 301
}

Route Metadata and Prioritization

You can add metadata to routes to help with organization and control matching priority:

{
  name: 'API Server',                 // Human-readable name
  description: 'Main API endpoints',  // Description
  priority: 100,                      // Matching priority (higher = matched first)
  tags: ['api', 'internal']           // Arbitrary tags
}

Routes with higher priority values are matched first, allowing you to create specialized routes that take precedence over more general ones.

Complete Route Configuration Example

// Example of a complete route configuration
{
  match: {
    ports: 443,
    domains: ['api.example.com', 'api-v2.example.com'],
    path: '/secure/*',
    clientIp: ['10.0.0.*', '192.168.1.*']
  },
  action: {
    type: 'forward',
    target: {
      host: ['10.0.0.1', '10.0.0.2'],  // Round-robin between these hosts
      port: 8080
    },
    tls: {
      mode: 'terminate',
      certificate: 'auto'  // Use Let's Encrypt
    },
    security: {
      allowedIps: ['10.0.0.*'],
      maxConnections: 100
    },
    advanced: {
      timeout: 30000,
      headers: {
        'X-Original-Host': '{domain}',
        'X-Client-IP': '{clientIp}'
      },
      keepAlive: true
    }
  },
  name: 'Secure API Route',
  description: 'Route for secure API endpoints with authentication',
  priority: 100,
  tags: ['api', 'secure', 'internal']
}

Using Helper Functions

While you can create route configurations manually, SmartProxy provides helper functions to make it easier:

// Instead of building the full object:
const route = {
  match: { ports: 80, domains: 'example.com' },
  action: { type: 'forward', target: { host: 'localhost', port: 8080 } },
  name: 'Web Server'
};

// Use the helper function:
const route = createHttpRoute({
  domains: 'example.com',
  target: { host: 'localhost', port: 8080 },
  name: 'Web Server'
});

Available helper functions:

  • createRoute() - Basic function to create any route configuration
  • createHttpRoute() - Create an HTTP forwarding route
  • createHttpsRoute() - Create an HTTPS route with TLS termination
  • createPassthroughRoute() - Create an HTTPS passthrough route
  • createRedirectRoute() - Create a generic redirect route
  • createHttpToHttpsRedirect() - Create an HTTP to HTTPS redirect
  • createBlockRoute() - Create a route to block specific traffic
  • createLoadBalancerRoute() - Create a route for load balancing
  • createHttpsServer() - Create a complete HTTPS server setup with HTTP redirect

What You Can Do with SmartProxy

  1. Route-Based Traffic Management

    // Route requests for different domains to different backend servers
    createHttpsRoute({
      domains: 'api.example.com',
      target: { host: 'api-server', port: 3000 },
      certificate: 'auto'
    })
    
  2. Automatic SSL with Let's Encrypt

    // Get and automatically renew certificates
    createHttpsRoute({
      domains: 'secure.example.com',
      target: { host: 'localhost', port: 8080 },
      certificate: 'auto'
    })
    
  3. Load Balancing

    // Distribute traffic across multiple backend servers
    createLoadBalancerRoute({
      domains: 'app.example.com',
      targets: ['10.0.0.1', '10.0.0.2', '10.0.0.3'],
      targetPort: 8080,
      tlsMode: 'terminate',
      certificate: 'auto'
    })
    
  4. Security Controls

    // Restrict access based on IP addresses
    createHttpsRoute({
      domains: 'admin.example.com',
      target: { host: 'localhost', port: 8080 },
      certificate: 'auto',
      security: {
        allowedIps: ['10.0.0.*', '192.168.1.*'],
        maxConnections: 100
      }
    })
    
  5. Wildcard Domains

    // Handle all subdomains with one config
    createPassthroughRoute({
      domains: ['example.com', '*.example.com'],
      target: { host: 'backend-server', port: 443 }
    })
    
  6. Path-Based Routing

    // Route based on URL path
    createHttpsRoute({
      domains: 'example.com',
      path: '/api/*',
      target: { host: 'api-server', port: 3000 },
      certificate: 'auto'
    })
    
  7. Block Malicious Traffic

    // Block traffic from specific IPs
    createBlockRoute({
      ports: [80, 443],
      clientIp: ['1.2.3.*', '5.6.7.*'],
      priority: 1000  // High priority to ensure blocking
    })
    

Other Components

While SmartProxy provides a unified API for most needs, you can also use individual components:

NetworkProxy

For HTTP/HTTPS reverse proxy with TLS termination and WebSocket support:

import { NetworkProxy } from '@push.rocks/smartproxy';
import * as fs from 'fs';

const proxy = new NetworkProxy({ port: 443 });
await proxy.start();
await proxy.updateProxyConfigs([
  {
    hostName: 'example.com',
    destinationIps: ['127.0.0.1'],
    destinationPorts: [3000],
    publicKey: fs.readFileSync('cert.pem', 'utf8'),
    privateKey: fs.readFileSync('key.pem', 'utf8'),
  }
]);

Port80Handler

For standalone ACME certificate management:

import { Port80Handler } from '@push.rocks/smartproxy';

const acme = new Port80Handler({
  port: 80,
  contactEmail: 'admin@example.com',
  useProduction: true
});
acme.on('certificate-issued', evt => console.log(`Certificate ready: ${evt.domain}`));
await acme.start();

NfTablesProxy

For low-level port forwarding using nftables:

import { NfTablesProxy } from '@push.rocks/smartproxy';

const nft = new NfTablesProxy({
  fromPort: 80,
  toPort: 8080,
  toHost: 'localhost',
  preserveSourceIP: true
});
await nft.start();

Redirect / SslRedirect

For HTTP-to-HTTPS redirects:

import { SslRedirect } from '@push.rocks/smartproxy';

// Quick HTTP→HTTPS helper on port 80
const redirect = new SslRedirect(80);
await redirect.start();

Migration from v13.x to v14.0.0

Version 14.0.0 introduces a breaking change with the new route-based configuration system:

Key Changes

  1. Configuration Structure: The configuration now uses the match/action pattern instead of the old domain-based and port-based approach
  2. SmartProxy Options: Now takes an array of route configurations instead of domainConfigs and port ranges
  3. Helper Functions: New helper functions have been introduced to simplify configuration

Migration Example

v13.x Configuration:

import { SmartProxy, createDomainConfig, httpOnly, tlsTerminateToHttp } from '@push.rocks/smartproxy';

const proxy = new SmartProxy({
  fromPort: 443,
  domainConfigs: [
    createDomainConfig('example.com', tlsTerminateToHttp({
      target: { host: 'localhost', port: 8080 },
      acme: { enabled: true, production: true }
    }))
  ],
  sniEnabled: true
});

v14.0.0 Configuration:

import { SmartProxy, createHttpsRoute } from '@push.rocks/smartproxy';

const proxy = new SmartProxy({
  routes: [
    createHttpsRoute({
      ports: 443,
      domains: 'example.com',
      target: { host: 'localhost', port: 8080 },
      certificate: 'auto'
    })
  ]
});

Migration Steps

  1. Replace domainConfigs with an array of route configurations using routes
  2. Convert each domain configuration to use the new helper functions
  3. Update any code that uses updateDomainConfigs() to use addRoutes() or updateRoutes()
  4. For port-only configurations, create route configurations with port matching only
  5. For SNI-based routing, SNI is now automatically enabled when needed

Architecture & Flow Diagrams

flowchart TB
    Client([Client])
    
    subgraph "SmartProxy Components"
        direction TB
        RouteConfig["Route Configuration<br>(Match/Action)"]
        RouteManager["Route Manager"]
        HTTPS443["HTTPS Port 443<br>NetworkProxy"]
        SmartProxy["SmartProxy<br>(TCP/SNI Proxy)"]
        ACME["Port80Handler<br>(ACME HTTP-01)"]
        Certs[(SSL Certificates)]
    end
    
    subgraph "Backend Services"
        Service1[Service 1]
        Service2[Service 2]
        Service3[Service 3]
    end
    
    Client -->|HTTP/HTTPS Request| SmartProxy
    
    SmartProxy -->|Route Matching| RouteManager
    RouteManager -->|Use| RouteConfig
    RouteManager -->|Execute Action| SmartProxy
    
    SmartProxy -->|Forward| Service1
    SmartProxy -->|Redirect| Client
    SmartProxy -->|Forward| Service2
    SmartProxy -->|Forward| Service3
    
    ACME -.->|Generate/Manage| Certs
    Certs -.->|Provide TLS Certs| SmartProxy
    
    classDef component fill:#f9f,stroke:#333,stroke-width:2px;
    classDef backend fill:#bbf,stroke:#333,stroke-width:1px;
    classDef client fill:#dfd,stroke:#333,stroke-width:2px;
    
    class Client client;
    class RouteConfig,RouteManager,HTTPS443,SmartProxy,ACME component;
    class Service1,Service2,Service3 backend;

Route-Based Connection Handling

This diagram illustrates how requests are matched and processed using the route-based configuration:

sequenceDiagram
    participant Client
    participant SmartProxy
    participant RouteManager
    participant Backend
    
    Client->>SmartProxy: Connection (TCP/HTTP/HTTPS)
    
    SmartProxy->>RouteManager: Match connection against routes
    
    RouteManager->>RouteManager: Check port match
    RouteManager->>RouteManager: Check domain match (if SNI)
    RouteManager->>RouteManager: Check path match (if HTTP)
    RouteManager->>RouteManager: Check client IP match
    RouteManager->>RouteManager: Check TLS version match
    
    RouteManager->>RouteManager: Determine highest priority matching route
    
    alt Forward Action
        RouteManager->>SmartProxy: Use forward action
        
        alt TLS Termination
            SmartProxy->>SmartProxy: Terminate TLS
            SmartProxy->>Backend: Forward as HTTP/HTTPS
        else TLS Passthrough
            SmartProxy->>Backend: Forward raw TCP
        end
        
    else Redirect Action
        RouteManager->>SmartProxy: Use redirect action
        SmartProxy->>Client: Send redirect response
        
    else Block Action
        RouteManager->>SmartProxy: Use block action
        SmartProxy->>Client: Close connection
    end
    
    loop Connection Active
        SmartProxy-->>SmartProxy: Monitor Activity
        SmartProxy-->>SmartProxy: Check Security Rules
        alt Security Violation or Timeout
            SmartProxy->>Client: Close Connection
            SmartProxy->>Backend: Close Connection
        end
    end

Features

  • Route-Based Traffic Management • Match/action pattern for flexible routing • Port, domain, path, client IP, and TLS version matching • Multiple action types (forward, redirect, block)

  • TLS Handling Options • TLS passthrough for end-to-end encryption • TLS termination for content inspection • TLS termination with re-encryption for gateway scenarios

  • Automatic ACME Certificates • HTTP-01 challenge handling • Certificate issuance/renewal • Pluggable storage

  • Security Controls • IP allow/block lists with glob pattern support • Connection limits and rate limiting • Timeout controls and connection monitoring

  • Load Balancing • Round-robin distribution across multiple backends • Health checks and failure handling

  • Advanced Features • Custom header manipulation • Template variables for dynamic values • Priority-based route matching

Certificate Hooks & Events

Listen for certificate events via EventEmitter:

  • Port80Handler:
    • certificate-issued, certificate-renewed, certificate-failed
    • manager-started, manager-stopped, request-forwarded
  • SmartProxy:
    • certificate (domain, publicKey, privateKey, expiryDate, source, isRenewal)

Provide a certProvisionFunction(domain) in SmartProxy settings to supply static certs or return 'http01'.

SmartProxy: Common Use Cases

The SmartProxy component with route-based configuration offers a clean, unified approach to handle virtually any proxy scenario.

1. API Gateway / Backend Routing

Create a flexible API gateway to route traffic to different microservices based on domain and path:

import { SmartProxy, createHttpsRoute } from '@push.rocks/smartproxy';

const apiGateway = new SmartProxy({
  routes: [
    // Users API
    createHttpsRoute({
      ports: 443,
      domains: 'api.example.com',
      path: '/users/*',
      target: { host: 'users-service', port: 3000 },
      certificate: 'auto'
    }),

    // Products API
    createHttpsRoute({
      ports: 443,
      domains: 'api.example.com',
      path: '/products/*',
      target: { host: 'products-service', port: 3001 },
      certificate: 'auto'
    }),

    // Admin dashboard with extra security
    createHttpsRoute({
      ports: 443,
      domains: 'admin.example.com',
      target: { host: 'admin-dashboard', port: 8080 },
      certificate: 'auto',
      security: {
        allowedIps: ['10.0.0.*', '192.168.1.*'] // Only allow internal network
      }
    })
  ]
});

await apiGateway.start();

2. Complete HTTPS Server with HTTP Redirect

Easily set up a secure HTTPS server with automatic redirection from HTTP:

import { SmartProxy, createHttpsServer } from '@push.rocks/smartproxy';

const webServer = new SmartProxy({
  routes: [
    // createHttpsServer creates both the HTTPS route and HTTP redirect
    ...createHttpsServer({
      domains: 'example.com',
      target: { host: 'localhost', port: 8080 },
      certificate: 'auto',
      addHttpRedirect: true
    })
  ]
});

await webServer.start();

3. Multi-Tenant Application with Wildcard Domains

Support dynamically created tenants with wildcard domain matching:

import { SmartProxy, createHttpsRoute, createHttpToHttpsRedirect } from '@push.rocks/smartproxy';

const multiTenantApp = new SmartProxy({
  routes: [
    // Handle all tenant subdomains with one route
    createHttpsRoute({
      ports: 443,
      domains: '*.example.com',
      target: { host: 'tenant-router', port: 8080 },
      certificate: 'auto',
      // Pass original hostname to backend for tenant identification
      advanced: {
        headers: {
          'X-Original-Host': '{sni}'
        }
      }
    }),
    
    // Redirect HTTP to HTTPS for all subdomains
    createHttpToHttpsRedirect({
      domains: ['*.example.com']
    })
  ]
});

await multiTenantApp.start();

4. Complex Multi-Service Infrastructure

Create a comprehensive proxy solution with multiple services and security controls:

import { 
  SmartProxy,
  createHttpsRoute,
  createPassthroughRoute,
  createBlockRoute,
  createHttpToHttpsRedirect
} from '@push.rocks/smartproxy';

const enterpriseProxy = new SmartProxy({
  routes: [
    // Web application with automatic HTTPS
    createHttpsRoute({
      ports: 443,
      domains: 'app.example.com',
      target: { host: 'web-app', port: 8080 },
      certificate: 'auto'
    }),

    // Legacy system that needs HTTPS passthrough
    createPassthroughRoute({
      ports: 443,
      domains: 'legacy.example.com',
      target: { host: 'legacy-server', port: 443 }
    }),

    // Internal APIs with IP restrictions
    createHttpsRoute({
      ports: 443,
      domains: 'api.internal.example.com',
      target: { host: 'api-gateway', port: 3000 },
      certificate: 'auto',
      security: {
        allowedIps: ['10.0.0.0/16', '192.168.0.0/16'],
        maxConnections: 500
      }
    }),

    // Block known malicious IPs
    createBlockRoute({
      ports: [80, 443],
      clientIp: ['1.2.3.*', '5.6.7.*'],
      priority: 1000
    }),

    // Redirect all HTTP to HTTPS
    createHttpToHttpsRedirect({
      domains: ['*.example.com', 'example.com']
    })
  ],

  // Global settings that apply to all routes
  defaults: {
    security: {
      maxConnections: 1000
    }
  },

  // Enable connection timeouts for security
  inactivityTimeout: 30000,
  
  // Using global certificate management
  acme: {
    enabled: true,
    contactEmail: 'admin@example.com',
    useProduction: true,
    renewThresholdDays: 30
  }
});

await enterpriseProxy.start();

Route-Based Configuration Details

Match Criteria Options

  • ports: number | number[] | Array<{ from: number; to: number }> (required) Listen on specific ports or port ranges

  • domains: string | string[] (optional) Match specific domain names, supports wildcards (e.g., *.example.com)

  • path: string (optional) Match specific URL paths, supports glob patterns

  • clientIp: string[] (optional) Match client IP addresses, supports glob patterns

  • tlsVersion: string[] (optional) Match specific TLS versions (e.g., TLSv1.2, TLSv1.3)

Action Types

  1. Forward:

    {
      type: 'forward',
      target: { host: 'localhost', port: 8080 },
      tls: { mode: 'terminate', certificate: 'auto' }
    }
    
  2. Redirect:

    {
      type: 'redirect',
      redirect: { to: 'https://{domain}{path}', status: 301 }
    }
    
  3. Block:

    {
      type: 'block'
    }
    

TLS Modes

  • passthrough: Forward raw TLS traffic without decryption
  • terminate: Terminate TLS and forward as HTTP
  • terminate-and-reencrypt: Terminate TLS and create a new TLS connection to the backend

Template Variables

Template variables can be used in string values:

  • {domain}: The requested domain name
  • {port}: The incoming port number
  • {path}: The requested URL path
  • {query}: The query string
  • {clientIp}: The client's IP address
  • {sni}: The SNI hostname

Example:

createRedirectRoute({
  domains: 'old.example.com',
  redirectTo: 'https://new.example.com{path}?source=redirect'
})

Configuration Options

SmartProxy (IRoutedSmartProxyOptions)

  • routes (IRouteConfig[], required) - Array of route configurations
  • defaults (object) - Default settings for all routes
  • acme (IAcmeOptions) - ACME certificate options
  • Connection timeouts: initialDataTimeout, socketTimeout, inactivityTimeout, etc.
  • Socket opts: noDelay, keepAlive, enableKeepAliveProbes
  • certProvisionFunction (callback) - Custom certificate provisioning

NetworkProxy (INetworkProxyOptions)

  • port (number, required)
  • backendProtocol ('http1'|'http2', default 'http1')
  • maxConnections (number, default 10000)
  • keepAliveTimeout (ms, default 120000)
  • headersTimeout (ms, default 60000)
  • cors (object)
  • connectionPoolSize (number, default 50)
  • logLevel ('error'|'warn'|'info'|'debug')
  • acme (IAcmeOptions)
  • useExternalPort80Handler (boolean)
  • portProxyIntegration (boolean)

Port80Handler (IAcmeOptions)

  • enabled (boolean, default true)
  • port (number, default 80)
  • contactEmail (string)
  • useProduction (boolean, default false)
  • renewThresholdDays (number, default 30)
  • autoRenew (boolean, default true)
  • certificateStore (string)
  • skipConfiguredCerts (boolean)
  • domainForwards (IDomainForwardConfig[])

NfTablesProxy (INfTableProxySettings)

  • fromPort / toPort (number|range|array)
  • toHost (string, default 'localhost')
  • preserveSourceIP, deleteOnExit, protocol, enableLogging, ipv6Support (booleans)
  • allowedSourceIPs, bannedSourceIPs (string[])
  • useIPSets (boolean, default true)
  • qos, netProxyIntegration (objects)

Troubleshooting

SmartProxy

  • If routes aren't matching as expected, check their priorities
  • For domain matching issues, verify SNI extraction is working
  • Use higher priority for block routes to ensure they take precedence
  • Enable enableDetailedLogging or enableTlsDebugLogging for debugging

TLS/Certificates

  • For certificate issues, check the ACME settings and domain validation
  • Ensure domains are publicly accessible for Let's Encrypt validation
  • For TLS handshake issues, increase initialDataTimeout and maxPendingDataSize

NetworkProxy

  • Verify ports, certificates and rejectUnauthorized for TLS errors
  • Configure CORS for preflight issues
  • Increase maxConnections or connectionPoolSize under load

Port80Handler

  • Run as root or grant CAP_NET_BIND_SERVICE for port 80
  • Inspect certificate-failed events and switch staging/production

NfTablesProxy

  • Ensure nft is installed and run with sufficient privileges
  • Use forceCleanSlate:true to clear conflicting rules

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

Company Information

Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

Description
a proxy for handling high workloads of proxying
Readme 8.5 MiB
Languages
TypeScript 100%