traforo 0.0.9 → 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/README CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  HTTP tunnel via Cloudflare Durable Objects and WebSockets.
4
4
  Expose local servers to the internet with a simple CLI.
5
+ Infinitely scalable with support for Cloudflare CDN caching and password protection.
5
6
 
6
7
  ## INSTALLATION
7
8
 
@@ -29,12 +30,66 @@ The tunnel URL will be:
29
30
 
30
31
  ## OPTIONS
31
32
 
32
- -p, --port <port> Local port to expose (required)
33
- -t, --tunnel-id [id] Custom tunnel ID (prefer random default)
34
- -h, --host [host] Local host (default: localhost)
35
- -s, --server [url] Custom tunnel server URL
36
- --help Show help
37
- --version Show version
33
+ -p, --port <port> Local port to expose (required)
34
+ -t, --tunnel-id [id] Custom tunnel ID (prefer random default)
35
+ -c, --cache [key] Enable edge caching (optional partition key)
36
+ --password <password> Protect the tunnel with a password
37
+ -h, --host [host] Local host (default: localhost)
38
+ -s, --server [url] Custom tunnel server URL
39
+ --help Show help
40
+ --version Show version
41
+
42
+ ## EDGE CACHING
43
+
44
+ Cache responses at Cloudflare's edge so repeat requests never hit your
45
+ local machine:
46
+
47
+ traforo -p 3000 --cache
48
+
49
+ What gets cached:
50
+
51
+ - GET requests where the origin sends cacheable Cache-Control headers
52
+ (public, max-age, s-maxage)
53
+ - Static asset extensions use Cloudflare-like default fallback TTLs when
54
+ cache headers are missing: 200/301=120m, 302/303=20m, 404/410=3m
55
+
56
+ What never gets cached:
57
+
58
+ - Non-GET requests
59
+ - 206 Partial Content responses (Cache API put() limitation)
60
+ - Responses with Set-Cookie, Cache-Control: no-store/no-cache/private
61
+ - Streaming responses (SSE, ndjson)
62
+ - WebSocket connections
63
+
64
+ Requests with `Authorization`, `Cache-Control: no-cache/no-store/max-age=0`,
65
+ or `Pragma: no-cache` bypass edge cache lookup.
66
+
67
+ Cache partitioning lets you bust all cached content by changing the key:
68
+
69
+ traforo -p 3000 --cache v1 # first deployment
70
+ traforo -p 3000 --cache v2 # new deploy, fresh cache
71
+
72
+ Each key creates a separate cache namespace. Old entries expire via TTL.
73
+
74
+ The X-Traforo-Cache response header shows HIT, MISS, or BYPASS for debugging.
75
+ When BYPASS/MISS comes from the local origin path, X-Traforo-Cache-Reason explains why.
76
+
77
+ ## PASSWORD PROTECTION
78
+
79
+ Restrict tunnel access with a password:
80
+
81
+ traforo -p 3000 --password mysecret
82
+
83
+ Visitors in a browser see a login page. After entering the correct password
84
+ a `traforo-password` cookie is set and they can browse normally.
85
+
86
+ Non-browser clients (curl, APIs) get a 401 Unauthorized response with
87
+ instructions to pass the password as a cookie:
88
+
89
+ curl -b 'traforo-password=mysecret' https://{tunnel-id}-tunnel.traforo.dev
90
+
91
+ WebSocket upgrade requests without the correct cookie are rejected with
92
+ close code 4013.
38
93
 
39
94
  ## HOW IT WORKS
40
95
 
@@ -48,6 +103,7 @@ The tunnel URL will be:
48
103
 
49
104
  /traforo-status Check if tunnel is online
50
105
  /traforo-upstream WebSocket endpoint for local client
106
+ /traforo-login POST endpoint for password login
51
107
  /* All other paths proxied to local server
52
108
 
53
109
  ## LIBRARY USAGE
@@ -58,6 +114,8 @@ The tunnel URL will be:
58
114
  const client = new TunnelClient({
59
115
  localPort: 3000,
60
116
  tunnelId: 'my-app',
117
+ cacheKey: 'v1', // optional: enable edge caching
118
+ password: 'mysecret', // optional: password protection
61
119
  })
62
120
 
63
121
  await client.connect()
package/dist/cli.js CHANGED
@@ -9,10 +9,15 @@ cli
9
9
  .option('-t, --tunnel-id [id]', 'Custom tunnel ID (only for services safe to expose publicly; prefer random default)')
10
10
  .option('-h, --host [host]', 'Local host (default: localhost)')
11
11
  .option('-s, --server [url]', 'Tunnel server URL')
12
+ .option('-c, --cache [key]', 'Enable edge caching for static assets (optional key for cache partitioning, default: "default")')
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')
12
15
  .example(`${CLI_NAME} -p 3000`)
13
16
  .example(`${CLI_NAME} -p 3000 -- next start`)
14
17
  .example(`${CLI_NAME} -p 3000 -- pnpm dev`)
15
18
  .example(`${CLI_NAME} -p 5173 -t my-app -- vite`)
19
+ .example(`${CLI_NAME} -p 3000 --cache`)
20
+ .example(`${CLI_NAME} -p 3000 --cache v2`)
16
21
  .action(async (options) => {
17
22
  if (!options.port) {
18
23
  console.error('Error: --port is required');
@@ -24,12 +29,21 @@ cli
24
29
  console.error(`Error: Invalid port number: ${options.port}`);
25
30
  process.exit(1);
26
31
  }
32
+ // --cache with no value comes as boolean true, --cache v2 comes as string "v2"
33
+ const cacheKey = options.cache
34
+ ? typeof options.cache === 'string'
35
+ ? options.cache
36
+ : 'default'
37
+ : undefined;
27
38
  await runTunnel({
28
39
  port,
29
40
  tunnelId: options.tunnelId,
30
41
  localHost: options.host,
31
42
  serverUrl: options.server,
32
43
  command: command.length > 0 ? command : undefined,
44
+ cacheKey,
45
+ password: options.password,
46
+ kill: options.kill,
33
47
  });
34
48
  });
35
49
  cli.help();
package/dist/client.d.ts CHANGED
@@ -18,16 +18,23 @@ type TunnelClientOptions = {
18
18
  autoReconnect?: boolean;
19
19
  /** Reconnect delay in ms */
20
20
  reconnectDelay?: number;
21
+ /** Enable edge caching with this partition key */
22
+ cacheKey?: string;
23
+ /** Password to protect the tunnel */
24
+ password?: string;
21
25
  };
22
26
  export declare class TunnelClient {
23
27
  private options;
24
28
  private ws;
25
29
  private localWsConnections;
26
30
  private closed;
31
+ private pingInterval;
27
32
  constructor(options: TunnelClientOptions);
28
33
  get url(): string;
29
34
  connect(): Promise<void>;
30
35
  close(): void;
36
+ private startPingInterval;
37
+ private stopPingInterval;
31
38
  private handleMessage;
32
39
  private handleHttpRequest;
33
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 = {
@@ -16,6 +24,7 @@ export class TunnelClient {
16
24
  localHttps: false,
17
25
  autoReconnect: true,
18
26
  reconnectDelay: 3000,
27
+ cacheKey: undefined,
19
28
  ...options,
20
29
  };
21
30
  }
@@ -26,12 +35,19 @@ export class TunnelClient {
26
35
  if (this.closed) {
27
36
  throw new Error('Client is closed');
28
37
  }
29
- const wsUrl = `${this.options.serverUrl}/traforo-upstream?_tunnelId=${this.options.tunnelId}`;
38
+ let wsUrl = `${this.options.serverUrl}/traforo-upstream?_tunnelId=${this.options.tunnelId}`;
39
+ if (this.options.cacheKey) {
40
+ wsUrl += `&_cacheKey=${encodeURIComponent(this.options.cacheKey)}`;
41
+ }
42
+ if (this.options.password) {
43
+ wsUrl += `&_password=${encodeURIComponent(this.options.password)}`;
44
+ }
30
45
  // console.log(`Connecting to ${wsUrl}...`)
31
46
  return new Promise((resolve, reject) => {
32
47
  this.ws = new WebSocket(wsUrl);
33
48
  this.ws.on('open', () => {
34
49
  console.log(`Connected with Traforo! Tunnel URL: ${this.url}`);
50
+ this.startPingInterval();
35
51
  resolve();
36
52
  });
37
53
  this.ws.on('error', (err) => {
@@ -40,6 +56,7 @@ export class TunnelClient {
40
56
  });
41
57
  this.ws.on('close', (code, reason) => {
42
58
  console.log(`Disconnected: ${code} ${reason.toString()}`);
59
+ this.stopPingInterval();
43
60
  this.ws = null;
44
61
  // Close all local WS connections
45
62
  for (const [, localWs] of this.localWsConnections) {
@@ -64,6 +81,7 @@ export class TunnelClient {
64
81
  }
65
82
  close() {
66
83
  this.closed = true;
84
+ this.stopPingInterval();
67
85
  if (this.ws) {
68
86
  this.ws.close();
69
87
  this.ws = null;
@@ -76,6 +94,27 @@ export class TunnelClient {
76
94
  }
77
95
  this.localWsConnections.clear();
78
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
+ }
79
118
  handleMessage(rawMessage) {
80
119
  let msg;
81
120
  try {
@@ -6,6 +6,12 @@ export type RunTunnelOptions = {
6
6
  baseDomain?: string;
7
7
  serverUrl?: string;
8
8
  command?: string[];
9
+ /** Enable edge caching with optional partition key */
10
+ cacheKey?: string;
11
+ /** Password to protect the tunnel */
12
+ password?: string;
13
+ /** Kill any existing process on the port before starting */
14
+ kill?: boolean;
9
15
  };
10
16
  /**
11
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) {
@@ -97,7 +211,15 @@ export async function runTunnel(options) {
97
211
  localHost,
98
212
  ...(options.baseDomain && { baseDomain: options.baseDomain }),
99
213
  ...(options.serverUrl && { serverUrl: options.serverUrl }),
214
+ ...(options.cacheKey && { cacheKey: options.cacheKey }),
215
+ ...(options.password && { password: options.password }),
100
216
  });
217
+ if (options.cacheKey) {
218
+ console.log(`Edge caching enabled (key: ${options.cacheKey})`);
219
+ }
220
+ if (options.password) {
221
+ console.log(`Password protection enabled`);
222
+ }
101
223
  // Handle shutdown
102
224
  const cleanup = () => {
103
225
  console.log('\nShutting down...');
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "traforo",
3
- "version": "0.0.9",
4
- "description": "HTTP tunnel via Cloudflare Durable Objects and WebSockets",
3
+ "version": "0.2.0",
4
+ "description": "HTTP tunnel via Cloudflare Durable Objects and WebSockets. Edge caching and password protection.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": "https://github.com/remorses/traforo",
@@ -30,16 +30,19 @@
30
30
  },
31
31
  "devDependencies": {
32
32
  "@cloudflare/workers-types": "^4.20250712.0",
33
+ "@types/http-cache-semantics": "^4.2.0",
33
34
  "@types/node": "^22.0.0",
34
35
  "@types/ws": "^8.18.1",
35
36
  "tsx": "^4.20.5",
36
37
  "typescript": "^5.7.0",
38
+ "undici-types": "~6.21.0",
37
39
  "vite": "^7.1.4",
38
40
  "vitest": "^3.2.4",
39
41
  "wrangler": "^4.24.3"
40
42
  },
41
43
  "dependencies": {
42
- "goke": "^6.1.2",
44
+ "goke": "^6.3.0",
45
+ "http-cache-semantics": "^4.2.0",
43
46
  "string-dedent": "^3.0.2",
44
47
  "ws": "^8.19.0"
45
48
  },