traforo 0.1.0 → 0.2.0

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/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ cli
11
11
  .option('-s, --server [url]', 'Tunnel server URL')
12
12
  .option('-c, --cache [key]', 'Enable edge caching for static assets (optional key for cache partitioning, default: "default")')
13
13
  .option('--password <password>', 'Protect the tunnel with a password (visitors must enter it to access)')
14
+ .option('-k, --kill', 'Kill any existing process on the port before starting')
14
15
  .example(`${CLI_NAME} -p 3000`)
15
16
  .example(`${CLI_NAME} -p 3000 -- next start`)
16
17
  .example(`${CLI_NAME} -p 3000 -- pnpm dev`)
@@ -42,6 +43,7 @@ cli
42
43
  command: command.length > 0 ? command : undefined,
43
44
  cacheKey,
44
45
  password: options.password,
46
+ kill: options.kill,
45
47
  });
46
48
  });
47
49
  cli.help();
package/dist/client.d.ts CHANGED
@@ -28,10 +28,13 @@ export declare class TunnelClient {
28
28
  private ws;
29
29
  private localWsConnections;
30
30
  private closed;
31
+ private pingInterval;
31
32
  constructor(options: TunnelClientOptions);
32
33
  get url(): string;
33
34
  connect(): Promise<void>;
34
35
  close(): void;
36
+ private startPingInterval;
37
+ private stopPingInterval;
35
38
  private handleMessage;
36
39
  private handleHttpRequest;
37
40
  private handleWsOpen;
package/dist/client.js CHANGED
@@ -2,11 +2,19 @@
2
2
  * Local tunnel client - runs on user's machine to expose a local server.
3
3
  */
4
4
  import WebSocket from 'ws';
5
+ /**
6
+ * Interval (ms) between keepalive pings sent to the DO.
7
+ * Cloudflare's CDN has a ~100s inactivity timeout on WebSockets.
8
+ * The DO's setWebSocketAutoResponse handles these at the edge without
9
+ * waking the DO from hibernation, so this is zero-cost.
10
+ */
11
+ const PING_INTERVAL_MS = 30_000;
5
12
  export class TunnelClient {
6
13
  options;
7
14
  ws = null;
8
15
  localWsConnections = new Map();
9
16
  closed = false;
17
+ pingInterval = null;
10
18
  constructor(options) {
11
19
  const baseDomain = options.baseDomain || 'traforo.dev';
12
20
  this.options = {
@@ -39,6 +47,7 @@ export class TunnelClient {
39
47
  this.ws = new WebSocket(wsUrl);
40
48
  this.ws.on('open', () => {
41
49
  console.log(`Connected with Traforo! Tunnel URL: ${this.url}`);
50
+ this.startPingInterval();
42
51
  resolve();
43
52
  });
44
53
  this.ws.on('error', (err) => {
@@ -47,6 +56,7 @@ export class TunnelClient {
47
56
  });
48
57
  this.ws.on('close', (code, reason) => {
49
58
  console.log(`Disconnected: ${code} ${reason.toString()}`);
59
+ this.stopPingInterval();
50
60
  this.ws = null;
51
61
  // Close all local WS connections
52
62
  for (const [, localWs] of this.localWsConnections) {
@@ -71,6 +81,7 @@ export class TunnelClient {
71
81
  }
72
82
  close() {
73
83
  this.closed = true;
84
+ this.stopPingInterval();
74
85
  if (this.ws) {
75
86
  this.ws.close();
76
87
  this.ws = null;
@@ -83,6 +94,27 @@ export class TunnelClient {
83
94
  }
84
95
  this.localWsConnections.clear();
85
96
  }
97
+ startPingInterval() {
98
+ this.stopPingInterval();
99
+ this.pingInterval = setInterval(() => {
100
+ const ws = this.ws;
101
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
102
+ return;
103
+ }
104
+ try {
105
+ ws.send('{"type":"ping"}');
106
+ }
107
+ catch {
108
+ // readyState can flip between check and send(); safe to ignore
109
+ }
110
+ }, PING_INTERVAL_MS);
111
+ }
112
+ stopPingInterval() {
113
+ if (this.pingInterval) {
114
+ clearInterval(this.pingInterval);
115
+ this.pingInterval = null;
116
+ }
117
+ }
86
118
  handleMessage(rawMessage) {
87
119
  let msg;
88
120
  try {
@@ -10,6 +10,8 @@ export type RunTunnelOptions = {
10
10
  cacheKey?: string;
11
11
  /** Password to protect the tunnel */
12
12
  password?: string;
13
+ /** Kill any existing process on the port before starting */
14
+ kill?: boolean;
13
15
  };
14
16
  /**
15
17
  * Parse argv to extract command after `--` separator.
@@ -1,6 +1,8 @@
1
- import { spawn } from 'node:child_process';
1
+ import { exec, spawn } from 'node:child_process';
2
2
  import net from 'node:net';
3
+ import { promisify } from 'node:util';
3
4
  import { TunnelClient } from './client.js';
5
+ const execPromise = promisify(exec);
4
6
  export const CLI_NAME = 'traforo';
5
7
  const DEFAULT_TUNNEL_ID_LENGTH = 16;
6
8
  /**
@@ -30,6 +32,113 @@ async function waitForPort(port, host = 'localhost', timeoutMs = 60_000) {
30
32
  check();
31
33
  });
32
34
  }
35
+ /**
36
+ * Check if a port is currently in use (something is listening).
37
+ */
38
+ async function isPortInUse(port, host = 'localhost') {
39
+ return new Promise((resolve) => {
40
+ const socket = new net.Socket();
41
+ socket.once('connect', () => {
42
+ socket.destroy();
43
+ resolve(true);
44
+ });
45
+ socket.once('error', () => {
46
+ socket.destroy();
47
+ resolve(false);
48
+ });
49
+ socket.connect(port, host);
50
+ });
51
+ }
52
+ /**
53
+ * Kill any process listening on the given port.
54
+ * Cross-platform: uses lsof on macOS/Linux, netstat+taskkill on Windows.
55
+ * Never throws — silently succeeds if no process is found or kill fails.
56
+ */
57
+ async function killProcessOnPort(port) {
58
+ try {
59
+ const inUse = await isPortInUse(port);
60
+ if (!inUse) {
61
+ return;
62
+ }
63
+ console.log(`Killing process on port ${port}...`);
64
+ if (process.platform === 'win32') {
65
+ // Windows: parse netstat output to find PIDs listening on the port
66
+ const { stdout } = await execPromise(`netstat -ano | findstr :${port} | findstr LISTENING`);
67
+ const pids = new Set();
68
+ for (const line of stdout.trim().split('\n')) {
69
+ const parts = line.trim().split(/\s+/);
70
+ const pid = parseInt(parts[parts.length - 1], 10);
71
+ if (!isNaN(pid) && pid > 0) {
72
+ pids.add(pid);
73
+ }
74
+ }
75
+ for (const pid of pids) {
76
+ try {
77
+ await execPromise(`taskkill /PID ${pid} /F`);
78
+ }
79
+ catch { }
80
+ }
81
+ }
82
+ else {
83
+ // macOS / Linux: lsof returns PIDs listening on tcp port
84
+ const { stdout } = await execPromise(`lsof -ti tcp:${port}`);
85
+ const pids = stdout
86
+ .trim()
87
+ .split('\n')
88
+ .map((s) => {
89
+ return parseInt(s, 10);
90
+ })
91
+ .filter((n) => {
92
+ return !isNaN(n) && n > 0;
93
+ });
94
+ for (const pid of pids) {
95
+ try {
96
+ process.kill(pid, 'SIGTERM');
97
+ }
98
+ catch { }
99
+ }
100
+ }
101
+ // Brief wait for the port to actually free up
102
+ const maxWait = 3_000;
103
+ const start = Date.now();
104
+ while (Date.now() - start < maxWait) {
105
+ const stillInUse = await isPortInUse(port);
106
+ if (!stillInUse) {
107
+ console.log(`Port ${port} is now free`);
108
+ return;
109
+ }
110
+ await new Promise((r) => {
111
+ return setTimeout(r, 200);
112
+ });
113
+ }
114
+ // If SIGTERM didn't work on POSIX, try SIGKILL as last resort
115
+ if (process.platform !== 'win32') {
116
+ try {
117
+ const { stdout } = await execPromise(`lsof -ti tcp:${port}`);
118
+ const pids = stdout
119
+ .trim()
120
+ .split('\n')
121
+ .map((s) => {
122
+ return parseInt(s, 10);
123
+ })
124
+ .filter((n) => {
125
+ return !isNaN(n) && n > 0;
126
+ });
127
+ for (const pid of pids) {
128
+ try {
129
+ process.kill(pid, 'SIGKILL');
130
+ }
131
+ catch { }
132
+ }
133
+ }
134
+ catch { }
135
+ }
136
+ }
137
+ catch {
138
+ // Never crash — if anything fails, just continue and let the
139
+ // child process or port-wait logic surface the actual error
140
+ }
141
+ }
33
142
  /**
34
143
  * Parse argv to extract command after `--` separator.
35
144
  * Returns the command array and remaining argv without the command.
@@ -49,9 +158,14 @@ export function parseCommandFromArgv(argv) {
49
158
  */
50
159
  export async function runTunnel(options) {
51
160
  const tunnelId = options.tunnelId ||
52
- crypto.randomUUID().replaceAll('-', '').slice(0, DEFAULT_TUNNEL_ID_LENGTH);
161
+ crypto.randomUUID().replaceAll('-', '').slice(0, DEFAULT_TUNNEL_ID_LENGTH) +
162
+ options.port;
53
163
  const localHost = options.localHost || 'localhost';
54
164
  const port = options.port;
165
+ // Kill existing process on port if requested
166
+ if (options.kill) {
167
+ await killProcessOnPort(port);
168
+ }
55
169
  let child = null;
56
170
  // If command provided, spawn child process with PORT env
57
171
  if (options.command && options.command.length > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "traforo",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "HTTP tunnel via Cloudflare Durable Objects and WebSockets. Edge caching and password protection.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -35,6 +35,7 @@
35
35
  "@types/ws": "^8.18.1",
36
36
  "tsx": "^4.20.5",
37
37
  "typescript": "^5.7.0",
38
+ "undici-types": "~6.21.0",
38
39
  "vite": "^7.1.4",
39
40
  "vitest": "^3.2.4",
40
41
  "wrangler": "^4.24.3"