forked from Lexus2016/claude-code-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtunnel-manager.js
More file actions
298 lines (260 loc) · 9.54 KB
/
tunnel-manager.js
File metadata and controls
298 lines (260 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// ─── Tunnel Manager for Claude Code Studio ──────────────────────────────────
// Manages cloudflared / ngrok tunnel subprocess to expose the server to the internet.
// No external npm dependencies — uses Node 20 built-in child_process.
'use strict';
const EventEmitter = require('events');
const { spawn } = require('child_process');
const { execSync } = require('child_process');
const STARTUP_TIMEOUT = 30_000; // 30s to detect URL
const SHUTDOWN_TIMEOUT = 5_000; // 5s graceful, then SIGKILL
const HEALTH_CHECK_INTERVAL = 30_000; // 30s periodic health check
class TunnelManager extends EventEmitter {
constructor({ log, port }) {
super();
this.log = log || console;
this.port = port;
this._proc = null;
this._state = {
running: false,
provider: null,
publicUrl: null,
startedAt: null,
pid: null,
error: null,
};
this._healthTimer = null;
}
// ─── Public API ─────────────────────────────────────────────────────────────
/**
* Start a tunnel with the given provider.
* @param {'cloudflared'|'ngrok'} provider
* @param {{ ngrokAuthtoken?: string }} config
* @returns {Promise<{ publicUrl: string }>}
*/
async start(provider = 'cloudflared', config = {}) {
if (this._proc) {
throw new Error('Tunnel already running. Stop it first.');
}
// Validate binary exists
this._assertBinaryExists(provider);
this.log.info(`[tunnel] Starting ${provider} tunnel on port ${this.port}`);
return new Promise((resolve, reject) => {
let settled = false;
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
this.stop();
reject(new Error(`Tunnel startup timed out after ${STARTUP_TIMEOUT / 1000}s`));
}, STARTUP_TIMEOUT);
try {
this._proc = this._spawnTunnel(provider, config);
this._state.provider = provider;
this._state.pid = this._proc.pid;
} catch (err) {
settled = true;
clearTimeout(timeout);
reject(err);
return;
}
// Capture process reference — all handlers guard against stale callbacks
// from a previous process after rapid stop/start cycles.
const proc = this._proc;
// Listen for URL on stdout/stderr
const onData = (stream) => (chunk) => {
if (this._proc !== proc) return; // stale handler from previous process
const text = chunk.toString();
this.log.debug(`[tunnel:${stream}] ${text.trim()}`);
const url = this._parseUrl(provider, text);
if (url && !settled) {
settled = true;
clearTimeout(timeout);
this._state.running = true;
this._state.publicUrl = url;
this._state.startedAt = new Date().toISOString();
this._state.error = null;
this.log.info(`[tunnel] Public URL: ${url}`);
this.emit('url', url);
this._startHealthCheck();
resolve({ publicUrl: url });
}
};
proc.stdout?.on('data', onData('stdout'));
proc.stderr?.on('data', onData('stderr'));
proc.on('error', (err) => {
if (this._proc !== proc) return; // stale handler
clearTimeout(timeout);
this.log.error(`[tunnel] Process error: ${err.message}`);
this._cleanup(err.message);
if (!settled) {
settled = true;
reject(err);
}
});
proc.on('exit', (code, signal) => {
if (this._proc !== proc) return; // stale handler
clearTimeout(timeout);
const reason = `Process exited (code=${code}, signal=${signal})`;
this.log.info(`[tunnel] ${reason}`);
const wasRunning = this._state.running;
this._cleanup(reason);
if (!settled) {
settled = true;
reject(new Error(reason));
} else if (wasRunning) {
this.emit('close', reason);
}
});
});
}
/**
* Stop the running tunnel.
*/
stop() {
if (!this._proc) return;
this.log.info('[tunnel] Stopping tunnel...');
this._stopHealthCheck();
const proc = this._proc;
this._proc = null;
// Mark as not running BEFORE kill — prevents exit handler from
// seeing wasRunning=true and emitting a duplicate 'close' event.
this._state.running = false;
// Graceful shutdown — on Windows taskkill /T /F kills the entire process tree
if (process.platform === 'win32' && proc.pid && Number.isInteger(proc.pid)) {
try { execSync(`taskkill /PID ${proc.pid} /T /F`, { stdio: 'ignore' }); } catch {}
} else {
try { proc.kill('SIGTERM'); } catch {}
// Escalate to SIGKILL after timeout (Unix only — Windows already force-killed above)
const forceKill = setTimeout(() => {
try { proc.kill('SIGKILL'); } catch {}
}, SHUTDOWN_TIMEOUT);
forceKill.unref();
proc.once('exit', () => clearTimeout(forceKill));
}
this._cleanup('Stopped by user');
this.emit('close', 'Stopped by user');
}
/**
* Get the current tunnel status.
*/
getStatus() {
return { ...this._state };
}
/**
* Check if the tunnel is currently running.
*/
isRunning() {
return this._state.running;
}
// ─── Internal ───────────────────────────────────────────────────────────────
_spawnTunnel(provider, config) {
// Clean environment — remove CLAUDECODE to prevent subprocess confusion
const env = { ...process.env };
delete env.CLAUDECODE;
// On Windows, tunnel binaries installed via npm/chocolatey may be .cmd wrappers
// that require shell:true to execute (consistent with claude-cli.js approach).
const needsShell = process.platform === 'win32';
if (provider === 'cloudflared') {
return spawn('cloudflared', [
'tunnel', '--url', `http://localhost:${this.port}`, '--no-autoupdate',
], {
stdio: ['ignore', 'pipe', 'pipe'],
env,
shell: needsShell,
});
}
if (provider === 'ngrok') {
const args = ['http', String(this.port), '--log', 'stdout', '--log-format', 'json'];
if (config.ngrokAuthtoken) {
args.push('--authtoken', config.ngrokAuthtoken);
}
return spawn('ngrok', args, {
stdio: ['ignore', 'pipe', 'pipe'],
env,
shell: needsShell,
});
}
throw new Error(`Unknown tunnel provider: ${provider}`);
}
_parseUrl(provider, text) {
if (provider === 'cloudflared') {
// cloudflared writes: "INF ... https://xxx.trycloudflare.com ..."
const match = text.match(/(https:\/\/[a-z0-9-]+\.trycloudflare\.com)/i);
return match ? match[1] : null;
}
if (provider === 'ngrok') {
// ngrok JSON log: {"url":"https://xxx.ngrok-free.app", ...}
// Can appear in multiple JSON lines
for (const line of text.split('\n')) {
try {
const json = JSON.parse(line.trim());
if (json.url && json.url.startsWith('https://')) return json.url;
} catch {
// Also try regex for non-JSON output
const match = line.match(/(https:\/\/[a-z0-9-]+\.ngrok[a-z-]*\.(?:app|io))/i);
if (match) return match[1];
}
}
return null;
}
return null;
}
_assertBinaryExists(provider) {
const binary = provider === 'cloudflared' ? 'cloudflared' : 'ngrok';
const isWin = process.platform === 'win32';
const lookupCmd = isWin ? `where ${binary}` : `which ${binary}`;
try {
execSync(lookupCmd, { stdio: 'ignore' });
} catch {
const installUrl = provider === 'cloudflared'
? 'https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/'
: 'https://ngrok.com/download';
const installCmd = this._getInstallCmd(binary);
const err = new Error(`'${binary}' not found`);
err.installUrl = installUrl;
err.installCmd = installCmd;
err.provider = provider;
throw err;
}
}
_getInstallCmd(binary) {
const platform = process.platform;
if (platform === 'darwin') return `brew install ${binary}`;
if (platform === 'win32') {
return binary === 'cloudflared'
? `winget install Cloudflare.cloudflared`
: `choco install ngrok`;
}
// Linux
if (binary === 'cloudflared') {
return `curl -fsSL https://pkg.cloudflare.com/cloudflared-stable-linux-amd64.deb -o /tmp/cloudflared.deb && sudo dpkg -i /tmp/cloudflared.deb`;
}
return `snap install ngrok`;
}
_startHealthCheck() {
this._stopHealthCheck();
this._healthTimer = setInterval(() => {
if (this._proc && this._proc.exitCode !== null) {
this.log.warn('[tunnel] Process exited unexpectedly during health check');
this._cleanup('Process exited unexpectedly');
this.emit('close', 'Process exited unexpectedly');
}
}, HEALTH_CHECK_INTERVAL);
this._healthTimer.unref(); // Don't prevent Node.js from exiting
}
_stopHealthCheck() {
if (this._healthTimer) {
clearInterval(this._healthTimer);
this._healthTimer = null;
}
}
_cleanup(reason) {
this._stopHealthCheck();
this._state.running = false;
this._state.publicUrl = null;
this._state.pid = null;
this._state.startedAt = null;
this._state.error = reason || null;
this._proc = null;
}
}
module.exports = TunnelManager;