JSPM

simple-proxy-id

1.1.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q30168F
  • License MIT

A secure HTTP/HTTPS proxy library for Node.js with zero dependencies - target proxy can only be set by developers in code

Package Exports

  • simple-proxy-id
  • simple-proxy-id/src/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (simple-proxy-id) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

simple-proxy-id

npm version npm downloads license CI

πŸ”’ A secure HTTP/HTTPS proxy for Node.js with zero dependencies and fixed target. Think of it as a safe reverse proxy that prevents open proxy abuse.

⚑ High Performance: Optimized with connection pooling and keep-alive, achieving ~1,660 req/s with 60ms average latency.


✨ Features

  • Standalone HTTP/HTTPS proxy server
  • Express middleware support
  • Fixed target (secure by default, cannot be changed from requests)
  • Optional changeOrigin to set Host header
  • Automatic error handling
  • Logger plugin with daily rotating logs
  • Attack detector plugin for brute force protection
  • IP detection (Cloudflare Tunnel compatible)
  • High performance with HTTP Agent connection pooling
  • TypeScript definitions included
  • Zero dependencies

πŸ“¦ Installation

npm install simple-proxy-id

πŸš€ Usage

Basic Usage (Standalone)

const { createProxy } = require('simple-proxy-id');

// Create proxy server
const server = createProxy({
  target: 'https://jsonplaceholder.typicode.com',
  changeOrigin: true,
  port: 3000
});

// Access: http://localhost:3000/posts

Express Middleware

const express = require('express');
const { createProxyMiddleware } = require('simple-proxy-id');

const app = express();

// Proxy for path /api/*
app.use('/api', createProxyMiddleware({
  target: 'https://jsonplaceholder.typicode.com',
  changeOrigin: true
}));

app.listen(3000);

// Access: http://localhost:3000/api/posts

With Logger Plugin

const { createProxy } = require('simple-proxy-id');

// Enable request logging
const server = createProxy({
  target: 'https://jsonplaceholder.typicode.com',
  changeOrigin: true,
  port: 3000,
  logger: {
    logDir: './logs',
    maxDays: 7
  }
});

// Or with Express
const express = require('express');
const { createProxyMiddleware } = require('simple-proxy-id');
const createLogger = require('simple-proxy-id/logger');

const app = express();

app.use(createLogger({
  logDir: './logs',
  maxDays: 7
}));

app.use('/api', createProxyMiddleware({
  target: 'https://jsonplaceholder.typicode.com',
  changeOrigin: true
}));

app.listen(3000);

With Attack Detector Plugin

const { createProxy } = require('simple-proxy-id');

// Standalone with attack detector
const server = createProxy({
  target: 'https://jsonplaceholder.typicode.com',
  changeOrigin: true,
  port: 3000,
  attackDetector: {
    path: '/api/login',
    statusCode: 401,
    threshold: 5,
    timeWindow: 1000,
    onTrigger: (data) => {
      console.log('Attack detected from IP:', data.ip);
      // Block IP via your firewall API
    }
  }
});

// Or with Express
const express = require('express');
const { createProxyMiddleware } = require('simple-proxy-id');
const createAttackDetector = require('simple-proxy-id/attack-detector');

const app = express();

app.use(createAttackDetector({
  path: '/api/login',
  statusCode: 401,
  threshold: 5,
  timeWindow: 1000,
  onTrigger: (data) => {
    console.log('Attack detected from IP:', data.ip);
    // Block IP via Cloudflare API, Mikrotik, iptables, etc.
  }
}));

app.use('/api', createProxyMiddleware({
  target: 'https://api.example.com',
  changeOrigin: true
}));

app.listen(3000);

πŸ§ͺ Testing

npm test

Jest is used for testing. All tests must pass before publishing.


⚑ Performance

Benchmarked with autocannon on localhost (100 concurrent connections):

npm run benchmark

Results:

  • Throughput: ~1,660 requests/second
  • Latency (avg): 60ms
  • Latency (p50): 52ms
  • Latency (p99): 138ms
  • Errors: 0

Optimizations:

  • HTTP Agent with keepAlive: true for connection pooling
  • Cached target URL parsing (no re-parsing per request)
  • Pre-computed error responses
  • TCP_NODELAY enabled for lower latency
  • Connection reuse across requests

πŸ“‚ Project Structure

src/       β†’ main source code
  plugins/ β†’ logger and attack-detector plugins
test/      β†’ jest test suite
example/   β†’ usage examples
benchmark/ β†’ performance benchmarks
.github/   β†’ CI workflows

πŸ“œ API

createProxy(options)

Create a standalone HTTP/HTTPS proxy server.

Parameters:

  • target (string, required): Target URL to proxy
  • changeOrigin (boolean, optional): Set Host header to target (default: false)
  • port (number, optional): Port for proxy server (default: 3000)
  • logger (object, optional): Logger configuration
    • logDir (string): Directory to store log files (default: './logs')
    • maxDays (number): Maximum days to keep logs (default: 7)
  • attackDetector (object|array, optional): Attack detector configuration (single or array)
    • path (string|RegExp): Path to monitor
    • statusCode (number): Status code to monitor
    • threshold (number): Max hits before trigger
    • timeWindow (number): Time window in ms (default: 1000)
    • onTrigger (function): Callback function

Returns: http.Server instance

Example:

const server = createProxy({
  target: 'https://api.example.com',
  changeOrigin: true,
  port: 8080,
  logger: {
    logDir: './logs',
    maxDays: 14
  },
  attackDetector: [
    {
      path: '/api/login',
      statusCode: 401,
      threshold: 5,
      timeWindow: 1000,
      onTrigger: (data) => console.log('Login attack:', data.ip)
    },
    {
      path: /^\/api\/.*/,
      statusCode: 404,
      threshold: 10,
      timeWindow: 2000,
      onTrigger: (data) => console.log('Scan attack:', data.ip)
    }
  ]
});

createProxyMiddleware(options)

Create Express middleware for proxy.

Parameters:

  • target (string, required): Target URL to proxy
  • changeOrigin (boolean, optional): Set Host header to target (default: false)

Returns: Express middleware function

Example:

app.use('/api', createProxyMiddleware({
  target: 'https://api.github.com',
  changeOrigin: true
}));

createLogger(options)

Create logger middleware for tracking requests.

Parameters:

  • logDir (string, optional): Directory to store log files (default: './logs')
  • maxDays (number, optional): Days to keep logs before auto-cleanup (default: 7)

Returns: Express/Connect middleware function

Example:

const createLogger = require('simple-proxy-id/logger');

app.use(createLogger({
  logDir: './logs',
  maxDays: 14
}));

Log Format:

[2025-10-03 14:30:45] 192.168.1.100 GET /api/users 200 125ms

Features:

  • Daily rotating log files (YYYY-MM-DD.log)
  • Captures real IP (supports Cloudflare Tunnel)
  • Automatic cleanup of old logs
  • Zero dependencies

createAttackDetector(options)

Create attack detector middleware for brute force protection.

Parameters:

  • path (string|RegExp, required): Path to monitor (string for exact match, RegExp for pattern)
  • statusCode (number, required): HTTP status code to monitor (e.g., 401, 403, 404)
  • threshold (number, required): Maximum allowed hits within time window
  • timeWindow (number, optional): Time window in milliseconds (default: 1000)
  • onTrigger (function, required): Callback function triggered when threshold exceeded

Callback receives:

{
  ip: '192.168.1.100',
  hits: 5,
  path: '/api/login',
  timestamp: 1696234567890,
  userAgent: 'Mozilla/5.0...'
}

Returns: Express/Connect middleware function

Example:

const createAttackDetector = require('simple-proxy-id/attack-detector');

app.use(createAttackDetector({
  path: /^\/api\/.*/,          // Monitor all API paths with RegExp
  statusCode: 404,              // Monitor not found responses
  threshold: 10,                // Trigger after 10 hits
  timeWindow: 2000,             // Within 2 seconds
  onTrigger: (data) => {
    // Block IP via your firewall API
    console.log(`Blocking IP: ${data.ip}`);
  }
}));

Features:

  • Per-IP tracking and rate limiting
  • Support exact path or RegExp pattern matching
  • Automatic cleanup of old tracking data
  • Custom callback for any blocking mechanism (Cloudflare, Mikrotik, iptables, etc.)
  • Zero dependencies

πŸ”’ Security

This library is designed with security-first principles:

The proxy target is fixed in code and cannot be changed by external requests.

Attack Vector Protected
Request headers manipulation βœ…
Query string injection βœ…
Request body tampering βœ…
Open proxy abuse βœ…

IP Detection Priority:

When logging requests or detecting attacks, the library detects the real client IP in this order:

  1. CF-Connecting-IP header (Cloudflare Tunnel)
  2. X-Forwarded-For header (Proxy/Load Balancer)
  3. X-Real-IP header (Nginx proxy)
  4. socket.remoteAddress (Direct connection)

🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Ways to contribute:

  • Report bugs and suggest features
  • Submit pull requests
  • Improve documentation
  • Develop plugins

πŸ—ΊοΈ Roadmap

See ROADMAP.md for planned features and future development.

Upcoming:

  • v1.2.0 - Circuit breaker, Health check, Response caching, Request size limiting, Retry logic
  • v1.3.0 - IP whitelist/blacklist, Rate limiting, CORS plugin, SSL/TLS termination
  • v1.4.0 - Compression, HTTP/2 support, Clustering
  • v1.5.0 - Load balancing, WebSocket support, Request/Response transformation

πŸ“„ License

MIT Β© 2025