arena-bridge 0.18.12 → 0.18.13

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/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ All notable changes to this project are documented here.
4
4
  The format follows [Keep a Changelog](https://keepachangelog.com/) and the project uses
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## 0.18.13
8
+
9
+ ### Fixed
10
+ - Stop closes the tunnel it opened: the stop path killed the first spawned tunnel handle, which is a corpse after an automatic tunnel restart, and orphaned the live tunnel — the public address stayed open against a dead bridge ("Failed at step 3/4: public address still open after 10 s") while the agent lost the machine.
11
+ - Orphaned bridge generations are retired: the bridge and its tunnel record pid files, the bridge shuts down when its parent process disappears (a SIGKILLed helper, a closed terminal), and the new `stop` command closes the service, the API and orphaned tunnels of this bridge — never tunnels serving other ports.
12
+ - The app reads launchctl exit codes: a failed bootstrap, kickstart or bootout is a failure, so Start falls back to a reload and Stop reports the truth.
13
+ - The stop confirmation matches the bridge pid file or the tunnel binaries by exact name, not any command line containing `cloudflared` — the bridge's own `--bin cloudflared` no longer looks like an open tunnel.
14
+ - `/health` follows the live tunnel (`public_url`, `tunnel_alive`): a dead tunnel is no longer shown as "public address ready", and spent tunnel restarts unpublish the stored public URL.
15
+ - The work log keeps timeline order when records arrive out of order, follows the bridge cursor across log rotations, pages until caught up and refills after a cursor reset.
16
+ - `arena-bridge tunnel` honours the configured tunnel binary, authtoken and domain when the flags are absent.
17
+ - Self-update installs ad-hoc signed builds (nothing to compare) and still refuses a different certificate.
18
+
19
+ ### Added
20
+ - `arena-bridge stop` — stop the service, the API and every tunnel of this bridge, including orphaned processes of previous generations.
21
+
7
22
  ## 0.18.12
8
23
 
9
24
  - Show only the initiator location in the work-log source column: domain/IP, without transport channel or a `local` label.
package/README.md CHANGED
@@ -485,6 +485,7 @@ arena-bridge audit -n 50 # что происходило
485
485
  | `init` | создать `~/.arena-bridge/config.json` с токенами (`--root` повторяемый) |
486
486
  | `start` | локальный API-сервер |
487
487
  | `tunnel` | API + облачный туннель, печатает промпт |
488
+ | `stop` | остановить сервис, API и все туннели этого бриджа, включая осиротевшие процессы |
488
489
  | `hub` / `connect` | режим «хаб»: VPS принимает подключения многих машин |
489
490
  | `prompt` | готовый промпт для чата с агентом |
490
491
  | `tools` | каталог инструментов в JSON |
@@ -564,6 +565,7 @@ arena_bridge/ тот же функционал на Python (stdlib only)
564
565
  | --- | --- |
565
566
  | `port 8787 is already in use` | остановите старый экземпляр (`Ctrl+C`) или `arena-bridge start --port 8788` |
566
567
  | туннель не поднимается | `cloudflared` по умолчанию использует QUIC и может быть заблокирован — `arena-bridge tunnel --protocol http2` (это поведение по умолчанию) |
568
+ | публичный адрес «живой», но агент не подключается, или Stop ругается на незакрытый адрес | `arena-bridge stop` закрывает и осиротевшие туннели прошлых запусков, затем Start заново |
567
569
  | агент не видит файлы | проверьте `arena-bridge doctor` и `roots` в `~/.arena-bridge/config.json`; вне `roots` всё равно `PROTECTED` |
568
570
  | `APPROVAL_PENDING` | при `timeout`/`expired` старый запрос закрыт: согласуйте новый вызов или попросите открыть `arena-bridge trust --for 1h` |
569
571
  | скриншоты не работают | `arena-bridge permissions` — выдайте Arena Bridge Screen Recording и Accessibility (see [macOS permissions](#macos-permissions)) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arena-bridge",
3
- "version": "0.18.12",
3
+ "version": "0.18.13",
4
4
  "description": "Give a cloud AI agent (Arena.ai Agent Mode, Claude, Cursor, ...) controlled access to your own machine over HTTP/MCP: files, shell, Chrome and the macOS desktop, with an approval gate, trust windows and an audit log.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,8 +19,8 @@
19
19
  "node": ">=18"
20
20
  },
21
21
  "scripts": {
22
- "test": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node --test test/test_security.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs && node --test test/log.test.mjs && node --test test/log-paging.test.mjs && node --test test/permissions.test.mjs",
23
- "test:node": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs && node --test test/log.test.mjs && node --test test/log-paging.test.mjs && node --test test/permissions.test.mjs",
22
+ "test": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node --test test/test_security.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs && node --test test/log.test.mjs && node --test test/log-paging.test.mjs && node --test test/permissions.test.mjs && node --test test/tunnel.test.mjs",
23
+ "test:node": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs && node --test test/log.test.mjs && node --test test/log-paging.test.mjs && node --test test/permissions.test.mjs && node --test test/tunnel.test.mjs",
24
24
  "test:python": "python3 test/test_approvals.py && python3 test/test_bridge.py && python3 test/test_browser.py && python3 test/test_mac.py && python3 test/test_service.py && python3 test/test_telegram.py",
25
25
  "pack:check": "npm pack --dry-run"
26
26
  },
package/src/cli.mjs CHANGED
@@ -12,7 +12,8 @@ import { listApprovals, decide } from './approvals.mjs';
12
12
  import { tailAudit, auditDir, listArtifacts, pruneArtifacts } from './audit.mjs';
13
13
  import { pruneInbox } from './telegram.mjs';
14
14
  import { pruneApprovals } from './approvals.mjs';
15
- import { startTunnel, isPortOpen } from './tunnel.mjs';
15
+ import { startTunnel, isPortOpen, killStaleTunnel, killTunnelsForPort, listenerPid } from './tunnel.mjs';
16
+ import { readPid, writePid, clearPid, pidAlive, pidArgs, pidParent, stopPid } from './state.mjs';
16
17
  import { spawn, execSync, spawnSync } from 'node:child_process';
17
18
  import { parseDuration, trustState, openTrust, closeTrust, reconcileTrust } from './trust.mjs';
18
19
  import { bridgeEvent, tunnelEvent } from './lifecycle.mjs';
@@ -84,6 +85,7 @@ Commands:
84
85
  init Create ~/.arena-bridge/config.json with fresh tokens
85
86
  start Run the local API server (direct mode) on this machine
86
87
  tunnel Start the API + a cloudflared quick tunnel, print the ready prompt
88
+ stop Stop the service, the API and every tunnel of this bridge
87
89
  hub Run a relay server that many devices connect to
88
90
  connect Connect this machine to a hub as a device
89
91
  prompt Print the ready-to-paste agent instructions
@@ -189,6 +191,29 @@ function cmdInit(args) {
189
191
  console.log(`\nNext: arena-bridge start (then expose it with a tunnel)`);
190
192
  }
191
193
 
194
+ /**
195
+ * A bridge that outlives its parent serves a dead or duplicate API forever: launchd may
196
+ * SIGKILL the helper without a signal the bridge can catch, and a closed terminal leaves
197
+ * the same orphan. Watching the parent pid turns every orphan into a clean shutdown.
198
+ */
199
+ function watchParent(bye) {
200
+ const parent = process.ppid;
201
+ const timer = setInterval(() => {
202
+ if (process.ppid !== parent) bye();
203
+ }, 1000);
204
+ timer.unref();
205
+ }
206
+
207
+ /** Stop a bridge of a previous generation from its pid file, never a foreign process. */
208
+ function killStaleBridge() {
209
+ const pid = readPid('bridge');
210
+ if (!pid || pid === process.pid || !pidAlive(pid)) return null;
211
+ if (!pidArgs(pid).includes('arena-bridge')) return null;
212
+ stopPid(pid);
213
+ clearPid('bridge', pid);
214
+ return pid;
215
+ }
216
+
192
217
  async function cmdStart(args) {
193
218
  const cfg = loadConfig();
194
219
  if (!cfg.token) {
@@ -228,13 +253,17 @@ async function cmdStart(args) {
228
253
  console.log(buildPrompt(cfg, { tool: engine }));
229
254
  console.log('-----8<-----');
230
255
  });
256
+ writePid('bridge');
231
257
  const bye = () => {
232
258
  bridgeEvent('stop', { reason: 'signal' });
259
+ clearPid('bridge', process.pid);
233
260
  server.close(() => process.exit(0));
234
261
  setTimeout(() => process.exit(0), 2000).unref();
235
262
  };
236
263
  process.on('SIGINT', bye);
237
264
  process.on('SIGTERM', bye);
265
+ process.on('SIGHUP', bye);
266
+ watchParent(bye);
238
267
  }
239
268
 
240
269
  async function cmdTunnel(args) {
@@ -245,7 +274,9 @@ async function cmdTunnel(args) {
245
274
  }
246
275
  const port = Number(args.flags.port || cfg.port || 8787);
247
276
  const protocol = String(args.flags.protocol || 'http2');
248
- const bin = String(args.flags.bin || 'cloudflared');
277
+ const bin = String(args.flags.bin || cfg.tunnel?.bin || 'cloudflared');
278
+ const authtoken = args.flags.authtoken || cfg.tunnel?.authtoken || undefined;
279
+ const domain = (args.flags.domain !== undefined ? String(args.flags.domain) : cfg.tunnel?.domain) || undefined;
249
280
  const engine = new Engine(cfg, { base: cfg.roots?.[0] || os.homedir() });
250
281
 
251
282
  // Auto-open blanket trust window on start (3h, all tools, any agent) per user request
@@ -260,26 +291,45 @@ async function cmdTunnel(args) {
260
291
  } catch {}
261
292
 
262
293
  let server = null;
294
+ let tunnel = null;
295
+ let publicUrl = null;
296
+ if (await isPortOpen(port)) {
297
+ // A bridge whose parent died keeps the port and serves forever; only such an orphan is replaced.
298
+ const listener = listenerPid(port);
299
+ const orphan = listener && listener !== process.pid && pidParent(listener) === 1
300
+ && pidArgs(listener).includes('arena-bridge');
301
+ if (orphan) {
302
+ console.log(`stopping an orphaned bridge (pid ${listener}) from a previous generation…`);
303
+ stopPid(listener);
304
+ clearPid('bridge', listener);
305
+ for (let i = 0; i < 25 && await isPortOpen(port); i++) await new Promise((r) => setTimeout(r, 200));
306
+ }
307
+ }
263
308
  if (await isPortOpen(port)) {
264
309
  console.log(`port ${port} is already serving — reusing the running instance`);
265
310
  } else {
266
- server = createDirectServer(cfg, engine);
311
+ killStaleTunnel();
312
+ killTunnelsForPort(port);
313
+ server = createDirectServer(cfg, engine, () => ({
314
+ tunnel_alive: tunnel.alive(),
315
+ public_url: tunnel.alive() ? publicUrl : null,
316
+ }));
267
317
  await new Promise((r) => server.listen(port, cfg.host, r));
268
318
  bridgeEvent('start', { port });
269
319
  console.log(`arena-bridge API on http://${cfg.host}:${port}`);
270
320
  }
271
321
 
272
322
  console.log(`starting ${bin} (protocol=${protocol})…`);
273
- const { child, urlPromise, onUrl } = startTunnel(cfg, {
323
+ tunnel = startTunnel(cfg, {
274
324
  port,
275
325
  protocol,
276
326
  bin,
277
- authtoken: args.flags.authtoken,
278
- domain: args.flags.domain,
327
+ authtoken,
328
+ domain,
279
329
  onExit: (code) => tunnelEvent('down', { code }),
280
330
  });
331
+ const { urlPromise, onUrl } = tunnel;
281
332
 
282
- let publicUrl;
283
333
  try {
284
334
  publicUrl = await urlPromise;
285
335
  } catch (e) {
@@ -288,12 +338,9 @@ async function cmdTunnel(args) {
288
338
  console.error(` ${bin} is not installed. Install it (macOS: brew install cloudflared) or pass a path: --bin /path/to/cloudflared`);
289
339
  console.error(' Any other tunnel works too: ngrok http 8787, tailscale funnel --bg 8787');
290
340
  }
291
- try {
292
- child.kill();
293
- } catch {
294
- /* ignore */
295
- }
341
+ tunnel.kill();
296
342
  server?.close();
343
+ clearPid('bridge', process.pid);
297
344
  process.exit(1);
298
345
  }
299
346
 
@@ -312,25 +359,38 @@ async function cmdTunnel(args) {
312
359
  console.log('Update the base URL in the agent chat (arena-bridge prompt prints a fresh copy).');
313
360
  });
314
361
 
315
- console.log(`\npublic URL: ${publicUrl} (saved as config.publicUrl)\n`);
362
+ console.log(`\npublic URL: ${publicUrl} (saved for the app and "arena-bridge url")\n`);
316
363
  console.log('Paste this into the agent chat:');
317
364
  console.log('-----8<-----');
318
365
  console.log(buildPrompt(cfg, { tool: engine, baseUrl: publicUrl }));
319
366
  console.log('-----8<-----\n');
320
367
  console.log('Ctrl+C stops both the tunnel and the API.');
321
368
 
369
+ writePid('bridge');
322
370
  const bye = () => {
323
371
  bridgeEvent('stop', { reason: 'signal' });
324
- try {
325
- child.kill();
326
- } catch {
327
- /* ignore */
328
- }
372
+ tunnel.kill();
373
+ clearPid('bridge', process.pid);
329
374
  server?.close();
330
375
  setTimeout(() => process.exit(0), 300).unref();
331
376
  };
332
377
  process.on('SIGINT', bye);
333
378
  process.on('SIGTERM', bye);
379
+ process.on('SIGHUP', bye);
380
+ watchParent(bye);
381
+
382
+ // Every restart spent: the public URL is a lie from here on, so unpublish it at once.
383
+ const spent = setInterval(() => {
384
+ if (!tunnel.spent() || !publicUrl) return;
385
+ clearInterval(spent);
386
+ publicUrl = null;
387
+ cfg.publicUrl = null;
388
+ saveConfig(cfg);
389
+ tunnelEvent('down', { reason: 'restarts exhausted' });
390
+ console.error('\n✗ the tunnel gave up after repeated failures — the public URL is closed.');
391
+ console.error(' Start again: arena-bridge tunnel (or Start in the app)');
392
+ }, 1000);
393
+ spent.unref();
334
394
  }
335
395
 
336
396
  function cmdHub(args) {
@@ -682,6 +742,25 @@ async function cmdUpdate(args) {
682
742
  console.log('restart the bridge to use the new version: arena-bridge tunnel');
683
743
  }
684
744
 
745
+ async function cmdStop(args) {
746
+ const cfg = loadConfig();
747
+ const port = Number(args.flags.port || cfg.port || 8787);
748
+ const label = 'ai.arena.bridge';
749
+ try {
750
+ spawnSync('launchctl', ['bootout', `gui/${process.getuid()}/${label}`], { stdio: 'ignore' });
751
+ } catch {}
752
+ const bridge = readPid('bridge');
753
+ if (bridge && pidAlive(bridge) && pidArgs(bridge).includes('arena-bridge')) stopPid(bridge);
754
+ const listener = listenerPid(port);
755
+ if (listener && listener !== process.pid && pidArgs(listener).includes('arena-bridge')) stopPid(listener);
756
+ for (let i = 0; i < 25 && await isPortOpen(port); i++) await new Promise((r) => setTimeout(r, 200));
757
+ killStaleTunnel();
758
+ const tunnels = killTunnelsForPort(port);
759
+ clearPid('bridge');
760
+ console.log(`✓ bridge stopped${tunnels.length ? ` (closed ${tunnels.length} orphaned tunnel process)` : ''}`);
761
+ console.log(` port ${port} free: ${!(await isPortOpen(port))}`);
762
+ }
763
+
685
764
  function cmdRestart(args) {
686
765
  const cfg = loadConfig();
687
766
  try {
@@ -1155,6 +1234,8 @@ export async function main(argv = process.argv.slice(2)) {
1155
1234
  return cmdService(args);
1156
1235
  case 'restart':
1157
1236
  return cmdRestart(args);
1237
+ case 'stop':
1238
+ return cmdStop(args);
1158
1239
  case 'browser':
1159
1240
  return cmdBrowser(args);
1160
1241
  case 'completion':
package/src/config.mjs CHANGED
@@ -122,8 +122,6 @@ export function saveConfig(cfg) {
122
122
  const already = k in existing;
123
123
  if (already || JSON.stringify(v) !== JSON.stringify(def) || ['token','deviceToken','localToken','hub','device','port','host','mode'].includes(k)) {
124
124
  out[k] = v;
125
- } else if (v !== undefined && v !== null && JSON.stringify(v) !== JSON.stringify(def)) {
126
- out[k] = v;
127
125
  }
128
126
  }
129
127
  const tmp = CONFIG_PATH + '.tmp';
package/src/direct.mjs CHANGED
@@ -15,7 +15,7 @@ import { errorResponse } from './errors.mjs';
15
15
  import { startPoller, parseCommand, sendTelegram, answerCallback, editMessageText } from './telegram.mjs';
16
16
  import { permissionStatus } from './mac.mjs';
17
17
 
18
- export function createDirectServer(cfg, engine) {
18
+ export function createDirectServer(cfg, engine, runtime = null) {
19
19
  const mcpCtx = {
20
20
  cfg,
21
21
  listTools: () => engine.mcpTools(),
@@ -91,7 +91,9 @@ export function createDirectServer(cfg, engine) {
91
91
  trust_active: trustActive,
92
92
  audit_count: auditCount,
93
93
  log_size: logSize,
94
- has_public_url: !!cfg.publicUrl,
94
+ has_public_url: runtime ? !!runtime().public_url : !!cfg.publicUrl,
95
+ public_url: runtime ? runtime().public_url ?? null : cfg.publicUrl ?? null,
96
+ tunnel_alive: runtime ? !!runtime().tunnel_alive : null,
95
97
  });
96
98
  }
97
99
 
package/src/state.mjs CHANGED
@@ -41,6 +41,88 @@ export function saveState(patch) {
41
41
  return next;
42
42
  }
43
43
 
44
+ /* ------------------------------------------------------------------ *
45
+ * pid files: the service and its tunnel outlive a SIGKILLed parent, so
46
+ * every generation records where it lives and the next one cleans up
47
+ * ------------------------------------------------------------------ */
48
+
49
+ import { execFileSync } from 'node:child_process';
50
+
51
+ export const pidPath = (name) => path.join(CONFIG_DIR, `${name}.pid`);
52
+
53
+ export function writePid(name, pid = process.pid) {
54
+ try {
55
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
56
+ fs.writeFileSync(pidPath(name), String(pid), { mode: 0o600 });
57
+ } catch {}
58
+ return pid;
59
+ }
60
+
61
+ export function readPid(name) {
62
+ try {
63
+ const pid = Number(fs.readFileSync(pidPath(name), 'utf8').trim()) || 0;
64
+ return pid > 0 ? pid : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ export function clearPid(name, pid) {
71
+ try {
72
+ if (pid === undefined || readPid(name) === pid) fs.rmSync(pidPath(name), { force: true });
73
+ } catch {}
74
+ }
75
+
76
+ /** True while the process exists, whatever its state. */
77
+ export function pidAlive(pid) {
78
+ try {
79
+ process.kill(pid, 0);
80
+ return true;
81
+ } catch (e) {
82
+ return e.code === 'EPERM';
83
+ }
84
+ }
85
+
86
+ /** The executable name of a process, empty when it is gone; used to never kill a foreign one. */
87
+ export function pidName(pid) {
88
+ try {
89
+ return execFileSync('ps', ['-o', 'comm=', '-p', String(pid)], { encoding: 'utf8' }).trim();
90
+ } catch {
91
+ return '';
92
+ }
93
+ }
94
+
95
+ /** The parent pid of a process, 0 when it is gone; 1 means the original parent died. */
96
+ export function pidParent(pid) {
97
+ try {
98
+ return Number(execFileSync('ps', ['-o', 'ppid=', '-p', String(pid)], { encoding: 'utf8' }).trim()) || 0;
99
+ } catch {
100
+ return 0;
101
+ }
102
+ }
103
+
104
+ /** The whole command line of a process, empty when it is gone. */
105
+ export function pidArgs(pid) {
106
+ try {
107
+ return execFileSync('ps', ['-o', 'args=', '-p', String(pid)], { encoding: 'utf8' }).trim();
108
+ } catch {
109
+ return '';
110
+ }
111
+ }
112
+
113
+ /** SIGTERM a process and wait for it to leave, without ever following it into the grave. */
114
+ export function stopPid(pid, waitMs = 3000) {
115
+ if (!pid || !pidAlive(pid)) return false;
116
+ try {
117
+ process.kill(pid, 'SIGTERM');
118
+ } catch {
119
+ return false;
120
+ }
121
+ const end = Date.now() + waitMs;
122
+ while (Date.now() < end && pidAlive(pid)) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
123
+ return !pidAlive(pid);
124
+ }
125
+
44
126
  export function clearStateKey(key) {
45
127
  let cur = {};
46
128
  try { cur = JSON.parse(fs.readFileSync(STATE_PATH, 'utf8')); } catch {}
package/src/tunnel.mjs CHANGED
@@ -1,5 +1,55 @@
1
1
  import { spawn, execFileSync } from 'node:child_process';
2
2
  import net from 'node:net';
3
+ import { writePid, clearPid, readPid, pidAlive, pidName, pidArgs, stopPid } from './state.mjs';
4
+
5
+ /** Tunnel binaries this bridge may stop; anything else on the machine is untouchable. */
6
+ export const TUNNEL_NAMES = ['cloudflared', 'ngrok'];
7
+
8
+ /** Stop a tunnel of a previous generation from its pid file, never a foreign process. */
9
+ export function killStaleTunnel() {
10
+ const pid = readPid('tunnel');
11
+ if (!pid || !pidAlive(pid)) return null;
12
+ const name = pidName(pid).split('/').pop();
13
+ if (!TUNNEL_NAMES.includes(name)) return null;
14
+ stopPid(pid);
15
+ clearPid('tunnel', pid);
16
+ return pid;
17
+ }
18
+
19
+ /** The pid listening on a TCP port, via lsof; null when the port is free or lsof is missing. */
20
+ export function listenerPid(port) {
21
+ try {
22
+ const out = execFileSync('lsof', ['-t', '-i', `TCP:${port}`, '-s', 'TCP:LISTEN'], { encoding: 'utf8' });
23
+ return Number(out.split('\n')[0].trim()) || null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Stop tunnel processes that serve exactly our local port: orphaned tunnels of a dead
31
+ * bridge generation. Tunnels of the user that point elsewhere keep running.
32
+ */
33
+ export function killTunnelsForPort(port) {
34
+ const target = `127.0.0.1:${port}`;
35
+ const killed = [];
36
+ for (const name of TUNNEL_NAMES) {
37
+ let pids = [];
38
+ try {
39
+ pids = execFileSync('pgrep', ['-x', name], { encoding: 'utf8' }).split('\n').map((s) => s.trim()).filter(Boolean);
40
+ } catch {
41
+ continue;
42
+ }
43
+ for (const pid of pids) {
44
+ const num = Number(pid);
45
+ if (!pidArgs(num).includes(target)) continue;
46
+ stopPid(num);
47
+ if (readPid('tunnel') === num) clearPid('tunnel', num);
48
+ killed.push(num);
49
+ }
50
+ }
51
+ return killed;
52
+ }
3
53
 
4
54
  const URL_RE = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/i;
5
55
  const NGROK_URL_RE = /https:\/\/[a-z0-9-]+\.ngrok(?:-free)?\.(?:app|io|dev)/i;
@@ -65,6 +115,7 @@ export function startTunnel(
65
115
  let buffer = '';
66
116
  let settled = false;
67
117
  let attempt = 0;
118
+ let exhausted = false;
68
119
  let resolveUrl;
69
120
  let rejectUrl;
70
121
  const listeners = new Set();
@@ -87,6 +138,7 @@ export function startTunnel(
87
138
 
88
139
  const spawnChild = () => {
89
140
  child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'] });
141
+ if (child.pid) writePid('tunnel', child.pid);
90
142
  buffer = '';
91
143
  child.stdout.on('data', onChunk);
92
144
  child.stderr.on('data', onChunk);
@@ -98,8 +150,9 @@ export function startTunnel(
98
150
  });
99
151
  child.on('close', (code) => {
100
152
  onExit?.(code);
153
+ const mine = child;
101
154
  if (!settled) {
102
- if (isNgrok && attempt++ < restarts) {
155
+ if (!exhausted && isNgrok && attempt++ < restarts) {
103
156
  killStaleNgrok(domain);
104
157
  setTimeout(spawnChild, delay);
105
158
  return;
@@ -108,20 +161,42 @@ export function startTunnel(
108
161
  rejectUrl(new Error(`${bin} exited with code ${code} before the tunnel URL appeared`));
109
162
  return;
110
163
  }
111
- if (attempt++ < restarts) {
164
+ if (!exhausted && attempt++ < restarts) {
112
165
  setTimeout(spawnChild, delay);
166
+ return;
113
167
  }
168
+ // No restart left: the tunnel stays down and the pid file must not point at a corpse.
169
+ exhausted = true;
170
+ if (child === mine) clearPid('tunnel', mine.pid);
114
171
  });
115
172
  };
116
173
 
117
174
  spawnChild();
118
175
 
119
176
  return {
120
- child,
121
177
  urlPromise,
122
178
  args,
123
179
  target,
124
180
  onUrl: (fn) => listeners.add(fn),
181
+ /** The live tunnel process, so a stop never kills a corpse and orphans a real one. */
182
+ get child() {
183
+ return child;
184
+ },
185
+ /** True while the current tunnel process is alive and restarts are not spent. */
186
+ alive: () => !!child && !exhausted && child.exitCode === null && child.signalCode === null,
187
+ /** True once every restart is spent and the tunnel stays down. */
188
+ spent: () => exhausted,
189
+ kill: () => {
190
+ exhausted = true;
191
+ const pid = child?.pid;
192
+ if (pid) clearPid('tunnel', pid);
193
+ try {
194
+ child?.kill('SIGTERM');
195
+ } catch {
196
+ /* already gone */
197
+ }
198
+ return !!pid;
199
+ },
125
200
  };
126
201
  }
127
202
 
package/src/version.mjs CHANGED
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
 
6
- export const VERSION = "0.18.12";
6
+ export const VERSION = "0.18.13";
7
7
 
8
8
  export function getVersion() {
9
9
  try {