Files
remoteingress/readme.md

216 lines
10 KiB
Markdown

# @serve.zone/remoteingress
Edge ingress tunnel for DcRouter — accepts incoming TCP connections at the network edge and tunnels them to a DcRouter SmartProxy instance, preserving the original client IP via PROXY protocol v1.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
```sh
pnpm install @serve.zone/remoteingress
```
## 🏗️ Architecture
`@serve.zone/remoteingress` uses a **Hub ↔ Edge** topology with a high-performance Rust core and a TypeScript API surface:
```
┌─────────────────────┐ TLS Tunnel ┌─────────────────────┐
│ Network Edge │ ◄══════════════════════════► │ Private Cluster │
│ │ (multiplexed frames + │ │
│ RemoteIngressEdge │ shared-secret auth) │ RemoteIngressHub │
│ Listens on :80,:443│ │ Forwards to │
│ Accepts client TCP │ │ SmartProxy on │
│ │ │ local ports │
└─────────────────────┘ └─────────────────────┘
▲ │
│ TCP from end users ▼
Internet DcRouter / SmartProxy
```
| Component | Role |
|-----------|------|
| **RemoteIngressEdge** | Deployed at the network edge (e.g. a VPS or cloud instance). Listens on public ports, accepts raw TCP connections, and multiplexes them over a single TLS tunnel to the hub. |
| **RemoteIngressHub** | Deployed alongside DcRouter/SmartProxy in a private cluster. Accepts edge connections, demuxes streams, and forwards each to SmartProxy with a PROXY protocol v1 header so the real client IP is preserved. |
| **Rust Binary** (`remoteingress-bin`) | The performance-critical networking core. Managed via `@push.rocks/smartrust` RustBridge IPC — you never interact with it directly. Cross-compiled for `linux/amd64` and `linux/arm64`. |
### 🔑 Key Features
- 🔒 **TLS-encrypted tunnel** between edge and hub (auto-generated self-signed cert or bring your own)
- 🔀 **Multiplexed streams** — thousands of client connections flow over a single tunnel
- 🌐 **PROXY protocol v1** — SmartProxy sees the real client IP, not the tunnel IP
- 🔐 **Shared-secret authentication** — edges must present valid credentials to connect
- 📡 **STUN-based public IP discovery** — the edge automatically discovers its public IP via Cloudflare STUN
- 🔄 **Auto-reconnect** with exponential backoff if the tunnel drops
- 📢 **Event-driven** — both Hub and Edge extend `EventEmitter` for real-time monitoring
-**Rust core** — all frame encoding, TLS, and TCP proxying happen in native code for maximum throughput
## Usage
Both classes are imported from the package and communicate with the Rust binary under the hood. All you need to do is configure and start them.
### Setting up the Hub (private cluster side)
```typescript
import { RemoteIngressHub } from '@serve.zone/remoteingress';
const hub = new RemoteIngressHub();
// Listen for events
hub.on('edgeConnected', ({ edgeId }) => {
console.log(`✅ Edge ${edgeId} connected`);
});
hub.on('edgeDisconnected', ({ edgeId }) => {
console.log(`❌ Edge ${edgeId} disconnected`);
});
hub.on('streamOpened', ({ edgeId, streamId }) => {
console.log(`🔗 Stream ${streamId} opened from edge ${edgeId}`);
});
hub.on('streamClosed', ({ edgeId, streamId }) => {
console.log(`🔗 Stream ${streamId} closed from edge ${edgeId}`);
});
// Start the hub — it will listen for incoming edge TLS connections
await hub.start({
tunnelPort: 8443, // port edges connect to (default: 8443)
targetHost: '127.0.0.1', // SmartProxy host to forward streams to (default: 127.0.0.1)
});
// Register which edges are allowed to connect
await hub.updateAllowedEdges([
{ id: 'edge-nyc-01', secret: 'supersecrettoken1' },
{ id: 'edge-fra-02', secret: 'supersecrettoken2' },
]);
// Check status at any time
const status = await hub.getStatus();
console.log(status);
// {
// running: true,
// tunnelPort: 8443,
// connectedEdges: [
// { edgeId: 'edge-nyc-01', connectedAt: 1700000000, activeStreams: 12 }
// ]
// }
// Graceful shutdown
await hub.stop();
```
### Setting up the Edge (network edge side)
```typescript
import { RemoteIngressEdge } from '@serve.zone/remoteingress';
const edge = new RemoteIngressEdge();
// Listen for events
edge.on('tunnelConnected', () => {
console.log('🟢 Tunnel to hub established');
});
edge.on('tunnelDisconnected', () => {
console.log('🔴 Tunnel to hub lost — will auto-reconnect');
});
edge.on('publicIpDiscovered', ({ ip }) => {
console.log(`🌐 Public IP: ${ip}`);
});
// Start the edge — it connects to the hub and starts listening for clients
await edge.start({
hubHost: 'hub.example.com', // hostname or IP of the hub
hubPort: 8443, // must match hub's tunnelPort (default: 8443)
edgeId: 'edge-nyc-01', // unique edge identifier
secret: 'supersecrettoken1', // must match the hub's allowed edge secret
listenPorts: [80, 443], // public ports to accept TCP connections on
stunIntervalSecs: 300, // STUN refresh interval in seconds (default: 300)
});
// Check status at any time
const status = await edge.getStatus();
console.log(status);
// {
// running: true,
// connected: true,
// publicIp: '203.0.113.42',
// activeStreams: 5,
// listenPorts: [80, 443]
// }
// Graceful shutdown
await edge.stop();
```
### API Reference
#### `RemoteIngressHub`
| Method / Property | Description |
|-------------------|-------------|
| `start(config?)` | Spawns the Rust binary and starts the tunnel listener. Config: `{ tunnelPort?: number, targetHost?: string }` |
| `stop()` | Gracefully shuts down the hub and kills the Rust process. |
| `updateAllowedEdges(edges)` | Dynamically update which edges are authorized. Each edge: `{ id: string, secret: string }` |
| `getStatus()` | Returns current hub status including connected edges and active stream counts. |
| `running` | `boolean` — whether the Rust binary is alive. |
**Events:** `edgeConnected`, `edgeDisconnected`, `streamOpened`, `streamClosed`
#### `RemoteIngressEdge`
| Method / Property | Description |
|-------------------|-------------|
| `start(config)` | Spawns the Rust binary, connects to the hub, and starts listening on the specified ports. |
| `stop()` | Gracefully shuts down the edge and kills the Rust process. |
| `getStatus()` | Returns current edge status including connection state, public IP, and active streams. |
| `running` | `boolean` — whether the Rust binary is alive. |
**Events:** `tunnelConnected`, `tunnelDisconnected`, `publicIpDiscovered`
### 🔌 Wire Protocol
The tunnel uses a custom binary frame protocol over TLS:
```
[stream_id: 4 bytes][type: 1 byte][length: 4 bytes][payload: N bytes]
```
| Frame Type | Value | Direction | Purpose |
|------------|-------|-----------|---------|
| `OPEN` | `0x01` | Edge → Hub | Open a new stream; payload is PROXY v1 header |
| `DATA` | `0x02` | Edge → Hub | Client data flowing upstream |
| `CLOSE` | `0x03` | Edge → Hub | Client closed the connection |
| `DATA_BACK` | `0x04` | Hub → Edge | Response data flowing downstream |
| `CLOSE_BACK` | `0x05` | Hub → Edge | Upstream (SmartProxy) closed the connection |
Max payload size per frame: **16 MB**.
### Example Scenarios
1. **Expose a private Kubernetes cluster to the internet** — Deploy an Edge on a public VPS, configure your DNS to point to the VPS IP. The Edge tunnels all traffic to the Hub running inside the cluster, which hands it off to SmartProxy/DcRouter. Your cluster stays fully private — no public-facing ports needed.
2. **Multi-region edge ingress** — Run multiple Edges in different geographic regions (NYC, Frankfurt, Tokyo) all connecting to a single Hub. Use GeoDNS to route users to their nearest Edge. The Hub sees the real client IPs via PROXY protocol regardless of which edge they connected through.
3. **Secure API exposure** — Your backend runs on a private network with no direct internet access. An Edge on a minimal cloud instance acts as the only public entry point. TLS tunnel + shared-secret auth ensure only your authorized Edge can forward traffic.
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or 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.