tailcat-webui 0.0.0-stage → 0.1.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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +23 -0
  3. package/README.en.md +104 -0
  4. package/README.md +93 -2
  5. package/bin/tailcat-webui.js +12 -0
  6. package/docs/CORE-API.md +343 -0
  7. package/docs/DESIGN.md +378 -0
  8. package/docs/screenshots/01-overview-light.png +0 -0
  9. package/docs/screenshots/02-overview-dark.png +0 -0
  10. package/docs/screenshots/03-ticket-light.png +0 -0
  11. package/docs/screenshots/04-ticket-qr-light.png +0 -0
  12. package/docs/screenshots/05-settings-light.png +0 -0
  13. package/docs/screenshots/06-diagnostics-light.png +0 -0
  14. package/docs/screenshots/07-mobile-overview.png +0 -0
  15. package/docs/screenshots/08-install-missing.png +0 -0
  16. package/package.json +56 -4
  17. package/src/cli.js +238 -0
  18. package/src/config.js +167 -0
  19. package/src/devices.js +163 -0
  20. package/src/errors.js +24 -0
  21. package/src/index.js +19 -0
  22. package/src/installer.js +907 -0
  23. package/src/manager.js +647 -0
  24. package/src/parse.js +207 -0
  25. package/src/paths.js +97 -0
  26. package/src/preferences.js +190 -0
  27. package/src/qr.js +37 -0
  28. package/src/relay.js +76 -0
  29. package/src/runtime/node.js +281 -0
  30. package/src/serve-targets.js +127 -0
  31. package/src/server.js +669 -0
  32. package/src/settings.js +262 -0
  33. package/src/supervisor.js +833 -0
  34. package/vendor/qrcode.mjs +2289 -0
  35. package/web/api.js +114 -0
  36. package/web/boot.js +29 -0
  37. package/web/components.js +504 -0
  38. package/web/dict.js +655 -0
  39. package/web/drawer-access.js +318 -0
  40. package/web/drawer-address.js +271 -0
  41. package/web/drawer-automation.js +223 -0
  42. package/web/drawer-relay.js +128 -0
  43. package/web/drawer-tunnel.js +309 -0
  44. package/web/drawer.js +302 -0
  45. package/web/format.js +252 -0
  46. package/web/icon.svg +11 -0
  47. package/web/index.html +29 -0
  48. package/web/main.js +471 -0
  49. package/web/room-diagnostics.js +426 -0
  50. package/web/room-overview.js +416 -0
  51. package/web/room-settings.js +71 -0
  52. package/web/store.js +168 -0
  53. package/web/styles.css +2741 -0
  54. package/web/ticket.js +212 -0
@@ -0,0 +1,833 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import readline from 'node:readline';
6
+ import { RemoteAccessError, errorMessage } from './errors.js';
7
+ import { findKnownTailcat, tailcatKeyPath } from './paths.js';
8
+ import {
9
+ buildGenkeyArgs,
10
+ buildServeArgs,
11
+ parseAccessLine,
12
+ parseAddressLine,
13
+ parseRegionLine,
14
+ sanitizeLine,
15
+ } from './parse.js';
16
+
17
+ const MAX_RECENT = 20;
18
+ const MAX_STDERR_LINES = 40;
19
+ const MAX_CONNECTIONS = 200;
20
+ const MAX_PENDING_PER_KEY = 8;
21
+ const STABLE_AFTER_MS = 60_000;
22
+
23
+ /**
24
+ * The pairing key shared by a connection's `open` and `close` lines. tailcat
25
+ * prints no per-connection id and no `via` on the `close` line, so these three
26
+ * fields are all a close has to find its open with.
27
+ * @param {{ peer: string | null, protocol: string, port: number | null }} record - access record.
28
+ * @returns {string} pairing key.
29
+ */
30
+ function connectionKey(record) {
31
+ return `${record.peer}|${record.protocol}|${record.port}`;
32
+ }
33
+
34
+ /**
35
+ * Supervises one tailcat server process, its saved key, its allow-list, and
36
+ * the recent access records parsed from `--log`.
37
+ *
38
+ * Everything the supervisor needs from the outside arrives as a callback
39
+ * (`settings`, `targets`, `derpMapUrl`) so that a saved change reaches the next
40
+ * spawn without rebuilding the supervisor.
41
+ */
42
+ export class TailcatSupervisor {
43
+ /**
44
+ * @param {object} options - collaborators.
45
+ * @param {ReturnType<import('./config.js').resolveConfig>} options.config - resolved deployment config.
46
+ * @param {any} [options.logger] - logger.
47
+ * @param {object} options.runtime - process adapter.
48
+ * @param {ReturnType<import('./devices.js').createFileDeviceStore>} options.devices - allow-list store.
49
+ * @param {import('./installer.js').TailcatInstaller} [options.installer] - managed installer.
50
+ * @param {() => string} [options.derpMapUrl] - effective DERP map URL at spawn time.
51
+ * @param {() => object} [options.settings] - effective settings at spawn time.
52
+ * @param {() => string[]} [options.targets] - complete serve mapping list at spawn time.
53
+ * @param {string} [options.label] - what the targets are called in messages.
54
+ */
55
+ constructor(options = {}) {
56
+ this.config = options.config ?? {};
57
+ this.logger = options.logger ?? { info() {}, warn() {}, debug() {} };
58
+ this.runtime = options.runtime;
59
+ this.devices = options.devices ?? { snapshot: () => ({ allow: [] }) };
60
+ this.installer = options.installer;
61
+ this.readDerpMapUrl =
62
+ typeof options.derpMapUrl === 'function' ? options.derpMapUrl : () => this.config.derpMapUrl ?? '';
63
+ this.readSettings = typeof options.settings === 'function' ? options.settings : () => this.config;
64
+ this.readTargets = typeof options.targets === 'function' ? options.targets : () => [];
65
+ this.label = typeof options.label === 'string' && options.label !== '' ? options.label : 'serve target';
66
+ this.events = new EventEmitter();
67
+ this.events.setMaxListeners(50);
68
+
69
+ this.phase = 'stopped';
70
+ this.desired = false;
71
+ this.address = null;
72
+ this.keyMode = this.readSettings().addressMode === 'ephemeral' ? 'ephemeral' : 'saved';
73
+ this.keyFile = null;
74
+ this.region = null;
75
+ this.binary = {
76
+ requested: this.config.binaryPath ?? 'tailcat',
77
+ resolved: null,
78
+ source: null,
79
+ version: null,
80
+ error: null,
81
+ };
82
+ this.restarts = 0;
83
+ this.lastError = null;
84
+ this.lastExit = null;
85
+ this.warnings = [];
86
+ this.recent = [];
87
+ this.refusals = 0;
88
+ this.startedAt = null;
89
+ this.onlineAt = null;
90
+ this.nextRestartAt = null;
91
+
92
+ this.handle = null;
93
+ this.streams = [];
94
+ this.abort = null;
95
+ this.generation = 0;
96
+ this.startPromise = null;
97
+ this.restartTimer = null;
98
+ this.stableTimer = null;
99
+ this.restartAttempt = 0;
100
+ this.openConnections = new Map();
101
+ this.pendingConnections = 0;
102
+ this.stderrLines = [];
103
+ this.disposing = false;
104
+ this.versionPromise = null;
105
+ }
106
+
107
+ /** Set the desired state to running and start when idle. */
108
+ async start() {
109
+ if (this.disposing) throw new RemoteAccessError('disposed', 'The tunnel runtime is shutting down.', 503);
110
+ this.desired = true;
111
+ if (this.handle) return this.snapshot();
112
+ if (this.startPromise) return this.startPromise;
113
+ this.startPromise = this.startInternal().finally(() => {
114
+ this.startPromise = null;
115
+ });
116
+ return this.startPromise;
117
+ }
118
+
119
+ /** Stop the child and leave the runtime stopped. */
120
+ async stop() {
121
+ this.desired = false;
122
+ this.clearRestartTimer();
123
+ const handle = this.handle;
124
+ if (!handle) {
125
+ this.phase = 'stopped';
126
+ this.address = null;
127
+ this.onlineAt = null;
128
+ this.nextRestartAt = null;
129
+ this.lastError = null;
130
+ this.emit();
131
+ return;
132
+ }
133
+ this.phase = 'stopping';
134
+ this.emit();
135
+ handle.terminate();
136
+ try {
137
+ await handle.waitForExit(AbortSignal.timeout(8_000));
138
+ } catch (error) {
139
+ this.logger.warn(`tailcat-webui: failed while waiting for tailcat to stop: ${errorMessage(error)}`);
140
+ }
141
+ this.closeStreams();
142
+ if (this.phase !== 'stopped') {
143
+ this.phase = 'stopped';
144
+ this.address = null;
145
+ this.onlineAt = null;
146
+ this.nextRestartAt = null;
147
+ this.lastError = null;
148
+ this.emit();
149
+ }
150
+ }
151
+
152
+ /** Stop and start again with the same saved key and allow-list. */
153
+ async restart() {
154
+ await this.stop();
155
+ await this.start();
156
+ return this.snapshot();
157
+ }
158
+
159
+ /**
160
+ * Replace the saved stable key (or mint a new ephemeral key) and restart.
161
+ * The old address stops working when the new server starts. A failed key
162
+ * generation restores the previous key file so the tunnel can still be
163
+ * started with the address that worked.
164
+ */
165
+ async rotate() {
166
+ const settings = this.readSettings();
167
+ await this.stop();
168
+ this.restartAttempt = 0;
169
+ if (settings.addressMode === 'stable') {
170
+ const keyFile = tailcatKeyPath(settings.keyName);
171
+ const previous = fs.existsSync(keyFile) ? fs.readFileSync(keyFile) : null;
172
+ try {
173
+ await this.runGenkey(true);
174
+ } catch (error) {
175
+ if (previous) {
176
+ try {
177
+ fs.writeFileSync(keyFile, previous, { mode: 0o600 });
178
+ } catch (restoreError) {
179
+ this.logger.warn(`tailcat-webui: could not restore the previous saved key: ${errorMessage(restoreError)}`);
180
+ }
181
+ }
182
+ this.phase = 'error';
183
+ this.lastError = errorMessage(error);
184
+ this.desired = false;
185
+ this.emit();
186
+ throw error;
187
+ }
188
+ }
189
+ await this.start();
190
+ await this.waitForOnline(30_000);
191
+ return this.snapshot();
192
+ }
193
+
194
+ /** Release the child process and listeners when the runtime shuts down. */
195
+ async dispose() {
196
+ this.disposing = true;
197
+ this.desired = false;
198
+ this.clearRestartTimer();
199
+ if (this.stableTimer) clearTimeout(this.stableTimer);
200
+ this.stableTimer = null;
201
+ const handle = this.handle;
202
+ if (handle) {
203
+ handle.terminate();
204
+ try {
205
+ await handle.waitForExit(AbortSignal.timeout(8_000));
206
+ } catch {
207
+ // The adapter's terminate escalation owns the final cleanup.
208
+ }
209
+ this.closeStreams();
210
+ }
211
+ this.phase = 'stopped';
212
+ this.address = null;
213
+ this.events.removeAllListeners();
214
+ }
215
+
216
+ /** @returns {object} display-safe state, including the address for the operator. */
217
+ snapshot() {
218
+ const settings = this.readSettings();
219
+ return {
220
+ phase: this.phase,
221
+ desired: this.desired,
222
+ address: this.address,
223
+ keyMode: this.keyMode,
224
+ keyName: settings.keyName,
225
+ addressMode: settings.addressMode,
226
+ targets: this.safeTargets(),
227
+ region: this.region,
228
+ binary: {
229
+ requested: this.binary.requested,
230
+ resolved: this.binary.resolved,
231
+ source: this.binary.source,
232
+ version: this.binary.version,
233
+ error: this.binary.error,
234
+ },
235
+ restarts: this.restarts,
236
+ lastError: this.lastError,
237
+ lastExit: this.lastExit,
238
+ warnings: [...this.warnings],
239
+ stderrTail: this.stderrLines.slice(-10),
240
+ recent: [...this.recent],
241
+ refusals: this.refusals,
242
+ startedAt: this.startedAt,
243
+ onlineAt: this.onlineAt,
244
+ nextRestartAt: this.nextRestartAt,
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Wait for the tunnel to report an address (or to fail).
250
+ * @param {number} timeoutMs - bound.
251
+ * @returns {Promise<boolean>} whether the tunnel is online.
252
+ */
253
+ waitForOnline(timeoutMs) {
254
+ if (this.phase === 'online') return Promise.resolve(true);
255
+ if (this.phase === 'error' || this.phase === 'stopped') return Promise.resolve(false);
256
+ return new Promise((resolve) => {
257
+ let timer;
258
+ const check = () => {
259
+ if (this.phase === 'online') {
260
+ cleanup();
261
+ resolve(true);
262
+ } else if (this.phase === 'error' || this.phase === 'stopped') {
263
+ cleanup();
264
+ resolve(false);
265
+ }
266
+ };
267
+ const cleanup = () => {
268
+ clearTimeout(timer);
269
+ this.events.off('change', check);
270
+ };
271
+ timer = setTimeout(() => {
272
+ cleanup();
273
+ resolve(this.phase === 'online');
274
+ }, Math.max(0, timeoutMs));
275
+ timer.unref?.();
276
+ this.events.on('change', check);
277
+ check();
278
+ });
279
+ }
280
+
281
+ /** @returns {void} */
282
+ emit() {
283
+ this.events.emit('change');
284
+ }
285
+
286
+ /** @private */
287
+ async startInternal() {
288
+ if (this.handle) return this.snapshot();
289
+ this.phase = 'starting';
290
+ this.lastError = null;
291
+ this.nextRestartAt = null;
292
+ this.emit();
293
+ try {
294
+ await this.ensureBinary();
295
+ if (!this.desired || this.disposing) {
296
+ this.phase = 'stopped';
297
+ this.emit();
298
+ return this.snapshot();
299
+ }
300
+ if (this.readSettings().addressMode === 'stable') await this.ensureKey();
301
+ if (!this.desired || this.disposing) {
302
+ this.phase = 'stopped';
303
+ this.emit();
304
+ return this.snapshot();
305
+ }
306
+ this.spawnServer();
307
+ return this.snapshot();
308
+ } catch (error) {
309
+ this.phase = 'error';
310
+ this.lastError = errorMessage(error);
311
+ this.binary.error = this.binary.resolved === null ? this.lastError : this.binary.error;
312
+ this.emit();
313
+ throw error;
314
+ }
315
+ }
316
+
317
+ /** Forget the resolved executable so the next start picks up an install. */
318
+ reloadBinary() {
319
+ this.binary.resolved = null;
320
+ this.binary.source = null;
321
+ this.binary.version = null;
322
+ this.binary.error = null;
323
+ this.versionPromise = null;
324
+ }
325
+
326
+ /** @private */
327
+ async ensureBinary() {
328
+ if (this.binary.resolved) return;
329
+ const requested = this.config.binaryPath;
330
+ const managed = this.installer?.binaryPath;
331
+ if (requested === 'tailcat' && managed && this.installer?.hasInstalled()) {
332
+ this.binary.resolved = managed;
333
+ this.binary.source = 'managed';
334
+ this.binary.error = null;
335
+ this.logger.info(`tailcat-webui: using managed tailcat at ${managed}`);
336
+ void this.loadVersion();
337
+ return;
338
+ }
339
+ if (requested === 'tailcat' && this.installer?.system?.compatible === false) {
340
+ throw new RemoteAccessError(
341
+ 'tailcat-version-too-old',
342
+ `The installed tailcat ${this.installer.system.version ?? ''} is too old for this package; install the managed version or upgrade tailcat to 0.8.0 or newer.`,
343
+ 503,
344
+ );
345
+ }
346
+ try {
347
+ let resolved = null;
348
+ try {
349
+ resolved = await this.runtime.resolveExecutable(requested, process.env);
350
+ } catch (error) {
351
+ if (requested !== 'tailcat') throw error;
352
+ resolved =
353
+ this.installer?.system?.status === 'found' ? this.installer.system.path : findKnownTailcat(process.platform);
354
+ if (!resolved) throw error;
355
+ }
356
+ this.binary.resolved = resolved;
357
+ this.binary.source = requested === 'tailcat' ? 'path' : 'config';
358
+ this.binary.error = null;
359
+ this.logger.info(`tailcat-webui: using ${resolved}`);
360
+ } catch (error) {
361
+ this.binary.error = errorMessage(error);
362
+ throw new RemoteAccessError(
363
+ 'tailcat-not-found',
364
+ `Cannot find the tailcat executable "${requested}". Install tailcat, put it on PATH, or set binaryPath in the config. (${errorMessage(error)})`,
365
+ 503,
366
+ );
367
+ }
368
+ void this.loadVersion();
369
+ }
370
+
371
+ /** @private */
372
+ loadVersion() {
373
+ if (this.versionPromise) return this.versionPromise;
374
+ this.versionPromise = (async () => {
375
+ try {
376
+ const result = await this.runCollect([this.binary.resolved, 'version'], 15_000);
377
+ const match = /v?(\d+\.\d+\.\d+)/.exec(`${result.stdout}\n${result.stderr}`);
378
+ if (match) this.binary.version = match[0].startsWith('v') ? match[0] : `v${match[0]}`;
379
+ } catch {
380
+ // A version probe is diagnostic only; serving can still work.
381
+ }
382
+ this.emit();
383
+ })();
384
+ return this.versionPromise;
385
+ }
386
+
387
+ /** @private */
388
+ async ensureKey() {
389
+ const settings = this.readSettings();
390
+ this.keyFile = tailcatKeyPath(settings.keyName);
391
+ if (fs.existsSync(this.keyFile)) return;
392
+ await this.runGenkey(false);
393
+ if (!fs.existsSync(this.keyFile)) {
394
+ throw new RemoteAccessError('key-not-created', `tailcat genkey did not create ${this.keyFile}.`, 500);
395
+ }
396
+ }
397
+
398
+ /**
399
+ * @private
400
+ * @param {boolean} force - overwrite an existing saved key.
401
+ */
402
+ async runGenkey(force) {
403
+ const settings = this.readSettings();
404
+ const argv = buildGenkeyArgs({
405
+ binaryPath: this.binary.resolved ?? this.config.binaryPath,
406
+ keyName: settings.keyName,
407
+ derpMapUrl: this.readDerpMapUrl(),
408
+ force,
409
+ regionMode: settings.regionMode,
410
+ regionValue: settings.regionValue,
411
+ psk: settings.psk,
412
+ });
413
+ this.logger.info(`tailcat-webui: ${force ? 'rotating' : 'creating'} the saved tailcat key`);
414
+ await this.runCollect(argv, 120_000);
415
+ this.keyFile = tailcatKeyPath(settings.keyName);
416
+ this.logger.info('tailcat-webui: saved key ready');
417
+ }
418
+
419
+ /** @private */
420
+ spawnServer() {
421
+ const settings = this.readSettings();
422
+ const targets = this.requireTargets();
423
+ const allow = this.devices.snapshot().allow;
424
+ const argv = buildServeArgs({
425
+ binaryPath: this.binary.resolved ?? this.config.binaryPath,
426
+ targets,
427
+ keyName: settings.keyName,
428
+ addressMode: settings.addressMode,
429
+ allow,
430
+ derpMapUrl: this.readDerpMapUrl(),
431
+ logAccess: settings.logAccess,
432
+ verbose: settings.verbose,
433
+ psk: settings.psk,
434
+ hybrid: settings.hybrid,
435
+ fullAddress: settings.fullAddress,
436
+ });
437
+ const controller = new AbortController();
438
+ let handle;
439
+ try {
440
+ handle = this.runtime.spawn({
441
+ argv,
442
+ cwd: os.homedir(),
443
+ env: childEnv(),
444
+ stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' },
445
+ graceMs: 5_000,
446
+ signal: controller.signal,
447
+ });
448
+ } catch (error) {
449
+ throw new RemoteAccessError('tailcat-spawn-failed', `Could not start tailcat: ${errorMessage(error)}`, 503);
450
+ }
451
+
452
+ this.closeStreams();
453
+ this.handle = handle;
454
+ this.abort = controller;
455
+ this.phase = 'starting';
456
+ this.address = null;
457
+ this.onlineAt = null;
458
+ this.lastExit = null;
459
+ this.lastError = null;
460
+ this.startedAt = new Date().toISOString();
461
+ this.keyMode = settings.addressMode === 'ephemeral' ? 'ephemeral' : 'saved';
462
+ this.stderrLines = [];
463
+ this.clearPairings();
464
+ const generation = ++this.generation;
465
+ this.logger.info(
466
+ `tailcat-webui: started tailcat with ${targets.length} ${this.label} mapping(s) (${allow.length > 0 ? `${allow.length} allowed device(s)` : 'address-only'})`,
467
+ );
468
+
469
+ if (handle.stdout) {
470
+ const output = readline.createInterface({ input: handle.stdout, crlfDelay: Infinity });
471
+ output.on('line', (line) => this.onStdout(generation, line));
472
+ this.streams.push(output);
473
+ }
474
+ if (handle.stderr) {
475
+ const errors = readline.createInterface({ input: handle.stderr, crlfDelay: Infinity });
476
+ errors.on('line', (line) => this.onStderr(generation, line));
477
+ this.streams.push(errors);
478
+ }
479
+ handle.done.then(
480
+ (outcome) => this.onExit(generation, outcome),
481
+ (error) => this.onExit(generation, { error }),
482
+ );
483
+ this.emit();
484
+ }
485
+
486
+ /**
487
+ * @private
488
+ * @returns {string[]} canonical mappings, or a readable error when there are none.
489
+ */
490
+ requireTargets() {
491
+ let targets;
492
+ try {
493
+ targets = this.readTargets();
494
+ } catch (error) {
495
+ throw new RemoteAccessError(
496
+ 'invalid-settings',
497
+ `Could not read the ${this.label} list: ${errorMessage(error)}`,
498
+ 400,
499
+ );
500
+ }
501
+ const list = Array.isArray(targets) ? targets.filter((target) => typeof target === 'string' && target !== '') : [];
502
+ if (list.length === 0) {
503
+ throw new RemoteAccessError(
504
+ 'invalid-settings',
505
+ `There is no ${this.label} to expose. Add at least one ${this.label} before starting the tunnel.`,
506
+ 400,
507
+ );
508
+ }
509
+ return list;
510
+ }
511
+
512
+ /** @private */
513
+ safeTargets() {
514
+ try {
515
+ const targets = this.readTargets();
516
+ return Array.isArray(targets) ? targets.filter((target) => typeof target === 'string' && target !== '') : [];
517
+ } catch {
518
+ return [];
519
+ }
520
+ }
521
+
522
+ /** @private */
523
+ onStdout(generation, line) {
524
+ if (generation !== this.generation) return;
525
+ const text = line.trim();
526
+ if (!text) return;
527
+ let payload;
528
+ try {
529
+ payload = JSON.parse(text);
530
+ } catch {
531
+ return;
532
+ }
533
+ if (typeof payload?.listenAddr === 'string' && payload.listenAddr.startsWith('tc')) {
534
+ this.markOnline(payload.listenAddr, this.readSettings().addressMode === 'ephemeral' ? 'ephemeral' : 'saved');
535
+ }
536
+ }
537
+
538
+ /** @private */
539
+ onStderr(generation, line) {
540
+ if (generation !== this.generation) return;
541
+ const text = line.trim();
542
+ if (!text) return;
543
+ this.stderrLines.push(sanitizeLine(text));
544
+ if (this.stderrLines.length > MAX_STDERR_LINES) this.stderrLines.shift();
545
+
546
+ const region = parseRegionLine(text);
547
+ if (region) {
548
+ this.region = region;
549
+ this.emit();
550
+ }
551
+
552
+ const address = parseAddressLine(text);
553
+ if (address) this.markOnline(address.address, address.mode);
554
+
555
+ if (text.includes('⚠️')) {
556
+ const warning = sanitizeLine(text.replace(/^#\s*/, ''));
557
+ this.warnings.push(warning);
558
+ if (this.warnings.length > 4) this.warnings.shift();
559
+ this.emit();
560
+ }
561
+
562
+ const record = parseAccessLine(text);
563
+ if (!record) return;
564
+ if (record.kind === 'peer' && record.decision === 'refused') {
565
+ this.refusals += 1;
566
+ this.pushRecent({ kind: 'refused', at: new Date().toISOString(), peer: record.peer, reason: record.reason });
567
+ return;
568
+ }
569
+ if (record.kind !== 'connection') return;
570
+ if (record.event === 'refused') {
571
+ this.pushRecent({
572
+ kind: 'refused',
573
+ at: new Date().toISOString(),
574
+ peer: null,
575
+ reason: 'port-not-served',
576
+ protocol: record.protocol,
577
+ port: record.port,
578
+ service: record.service,
579
+ });
580
+ return;
581
+ }
582
+ if (record.event === 'open') {
583
+ const key = connectionKey(record);
584
+ const pending = this.openConnections.get(key) ?? [];
585
+ pending.push({ at: Date.now(), via: record.via });
586
+ this.openConnections.set(key, pending);
587
+ this.pendingConnections += 1;
588
+ if (pending.length > MAX_PENDING_PER_KEY) {
589
+ // Closes pop the head, so the queue has to keep a prefix of the opens
590
+ // to stay aligned with them. Dropping the head instead would pair every
591
+ // later close with the next connection's path: a fabricated value where
592
+ // the honest answer is that this connection has no known path.
593
+ pending.pop();
594
+ this.pendingConnections -= 1;
595
+ }
596
+ if (this.pendingConnections > MAX_CONNECTIONS) this.clearPairings();
597
+ return;
598
+ }
599
+ if (record.event === 'close') {
600
+ const key = connectionKey(record);
601
+ const pending = this.openConnections.get(key);
602
+ const opened = pending?.shift() ?? null;
603
+ if (pending !== undefined && pending.length === 0) this.openConnections.delete(key);
604
+ if (opened !== null) this.pendingConnections -= 1;
605
+ this.pushRecent({
606
+ kind: 'connection',
607
+ at: new Date().toISOString(),
608
+ peer: record.peer,
609
+ protocol: record.protocol,
610
+ port: record.port,
611
+ service: record.service,
612
+ // tailcat prints `via` only on the open line, so a paired open is the
613
+ // only path source today and an unpaired close reports none. A future
614
+ // close line carrying its own `via` names this connection outright.
615
+ via: record.via ?? opened?.via ?? null,
616
+ durationMs: record.durationMs ?? (opened ? Date.now() - opened.at : null),
617
+ });
618
+ }
619
+ }
620
+
621
+ /**
622
+ * @private
623
+ * @param {string} address - tailcat server address.
624
+ * @param {'saved' | 'ephemeral'} mode - key provenance.
625
+ */
626
+ markOnline(address, mode) {
627
+ const changed = this.address !== address;
628
+ this.address = address;
629
+ this.keyMode = mode;
630
+ this.lastError = null;
631
+ this.phase = 'online';
632
+ this.onlineAt = new Date().toISOString();
633
+ if (this.stableTimer) clearTimeout(this.stableTimer);
634
+ this.stableTimer = setTimeout(() => {
635
+ this.restartAttempt = 0;
636
+ this.stableTimer = null;
637
+ }, STABLE_AFTER_MS);
638
+ this.stableTimer.unref?.();
639
+ if (changed) this.logger.info('tailcat-webui: tunnel is online');
640
+ this.emit();
641
+ }
642
+
643
+ /**
644
+ * Forget every remembered open. A restarted tailcat owns new connections, and
645
+ * the pending ceiling means the table is no longer tracking anything useful.
646
+ * @private
647
+ */
648
+ clearPairings() {
649
+ this.openConnections.clear();
650
+ this.pendingConnections = 0;
651
+ }
652
+
653
+ /** @private */
654
+ pushRecent(entry) {
655
+ this.recent.unshift(entry);
656
+ if (this.recent.length > MAX_RECENT) this.recent.length = MAX_RECENT;
657
+ this.emit();
658
+ }
659
+
660
+ /** @private */
661
+ onExit(generation, outcome) {
662
+ if (generation !== this.generation) return;
663
+ this.closeStreams();
664
+ this.handle = null;
665
+ this.abort = null;
666
+ if (this.stableTimer) {
667
+ clearTimeout(this.stableTimer);
668
+ this.stableTimer = null;
669
+ }
670
+ const desired = this.desired && !this.disposing;
671
+ this.address = null;
672
+ this.onlineAt = null;
673
+ this.nextRestartAt = null;
674
+ if (!desired) {
675
+ this.phase = 'stopped';
676
+ this.lastError = null;
677
+ this.emit();
678
+ return;
679
+ }
680
+ const exit = outcome && 'exitCode' in outcome ? outcome : null;
681
+ const failure = outcome?.error ? errorMessage(outcome.error) : null;
682
+ const detail = failure ?? lastFailureLine(this.stderrLines);
683
+ const code = exit?.exitCode;
684
+ const signal = exit?.signal;
685
+ const exitText =
686
+ code !== undefined && code !== null
687
+ ? `tailcat exited with code ${code}`
688
+ : signal
689
+ ? `tailcat was terminated by ${signal}`
690
+ : 'tailcat exited';
691
+ this.lastExit = { code: code ?? null, signal: signal ?? null, at: new Date().toISOString() };
692
+ this.lastError = detail ? `${exitText}: ${detail}` : exitText;
693
+ this.phase = 'error';
694
+ this.emit();
695
+ const settings = this.readSettings();
696
+ if (!settings.restartEnabled || this.restartAttempt >= settings.maxRestartAttempts) {
697
+ this.logger.warn(`tailcat-webui: ${this.lastError}`);
698
+ return;
699
+ }
700
+ this.restartAttempt += 1;
701
+ this.restarts += 1;
702
+ const delay = Math.min(settings.restartBaseDelayMs * 2 ** (this.restartAttempt - 1), settings.restartMaxDelayMs);
703
+ // The documented phase set has no separate "restarting": a scheduled retry
704
+ // is a start that has not run yet, and nextRestartAt carries the countdown.
705
+ this.phase = 'starting';
706
+ this.nextRestartAt = new Date(Date.now() + delay).toISOString();
707
+ this.logger.warn(`tailcat-webui: ${this.lastError}; retrying in ${delay} ms (attempt ${this.restartAttempt})`);
708
+ this.emit();
709
+ this.restartTimer = setTimeout(() => {
710
+ this.restartTimer = null;
711
+ this.nextRestartAt = null;
712
+ if (!this.desired || this.disposing) return;
713
+ this.start().catch((error) => {
714
+ this.phase = 'error';
715
+ this.lastError = errorMessage(error);
716
+ this.emit();
717
+ });
718
+ }, delay);
719
+ this.restartTimer.unref?.();
720
+ }
721
+
722
+ /** @private */
723
+ clearRestartTimer() {
724
+ if (this.restartTimer) clearTimeout(this.restartTimer);
725
+ this.restartTimer = null;
726
+ this.nextRestartAt = null;
727
+ }
728
+
729
+ /** @private */
730
+ closeStreams() {
731
+ for (const stream of this.streams) stream.close();
732
+ this.streams = [];
733
+ }
734
+
735
+ /**
736
+ * @private
737
+ * @param {string[]} argv - executable and arguments.
738
+ * @param {number} timeoutMs - bound for the whole exchange.
739
+ * @returns {Promise<{ stdout: string, stderr: string, exitCode: number | null, signal: NodeJS.Signals | null }>}
740
+ */
741
+ async runCollect(argv, timeoutMs) {
742
+ let handle;
743
+ try {
744
+ handle = this.runtime.spawn({
745
+ argv,
746
+ cwd: os.homedir(),
747
+ env: childEnv(),
748
+ stdio: {
749
+ stdin: 'ignore',
750
+ stdout: { maxBytes: 64 * 1024 },
751
+ stderr: { maxBytes: 64 * 1024 },
752
+ },
753
+ graceMs: 5_000,
754
+ signal: AbortSignal.timeout(timeoutMs),
755
+ });
756
+ } catch (error) {
757
+ throw new RemoteAccessError(
758
+ 'tailcat-spawn-failed',
759
+ `Could not run ${path.basename(argv[0])}: ${errorMessage(error)}`,
760
+ 503,
761
+ );
762
+ }
763
+ let outcome;
764
+ try {
765
+ outcome = await handle.done;
766
+ } catch (error) {
767
+ throw new RemoteAccessError(
768
+ 'tailcat-command-failed',
769
+ `${path.basename(argv[0])} failed: ${errorMessage(error)}`,
770
+ 502,
771
+ );
772
+ }
773
+ if (outcome && 'error' in outcome) {
774
+ throw new RemoteAccessError(
775
+ 'tailcat-command-failed',
776
+ `${path.basename(argv[0])} failed: ${errorMessage(outcome.error)}`,
777
+ 502,
778
+ );
779
+ }
780
+ const stdout = handle.collected?.stdout?.readFrom(0).text ?? '';
781
+ const stderr = handle.collected?.stderr?.readFrom(0).text ?? '';
782
+ if (outcome.exitCode !== 0) {
783
+ const detail = lastFailureLine([stderr, stdout].filter(Boolean).join('\n'));
784
+ throw new RemoteAccessError(
785
+ 'tailcat-command-failed',
786
+ `${path.basename(argv[0])} exited with code ${outcome.exitCode ?? 'null'}${detail ? `: ${detail}` : ''}`,
787
+ 502,
788
+ );
789
+ }
790
+ return { stdout, stderr, exitCode: outcome.exitCode, signal: outcome.signal };
791
+ }
792
+ }
793
+
794
+ /** Environment needed by tailcat's key path and relay cache discovery. */
795
+ function childEnv() {
796
+ const env = { HOME: os.homedir() };
797
+ // tailcat resolves saved keys through Go's os.UserConfigDir: XDG on Linux,
798
+ // Application Support on macOS, and %AppData% on Windows. Forward the
799
+ // platform roots it needs, plus the usual temp locations for its caches.
800
+ for (const name of [
801
+ 'PATH',
802
+ 'APPDATA',
803
+ 'LOCALAPPDATA',
804
+ 'SYSTEMROOT',
805
+ 'TEMP',
806
+ 'TMP',
807
+ 'TMPDIR',
808
+ 'XDG_CONFIG_HOME',
809
+ 'XDG_CACHE_HOME',
810
+ 'XDG_DATA_HOME',
811
+ ]) {
812
+ const value = process.env[name];
813
+ if (value) env[name] = value;
814
+ }
815
+ return env;
816
+ }
817
+
818
+ /**
819
+ * Choose the most useful diagnostic line from captured stderr.
820
+ * @param {string[] | string} lines - already sanitized lines.
821
+ * @returns {string | null} last meaningful line.
822
+ */
823
+ function lastFailureLine(lines) {
824
+ const list = Array.isArray(lines) ? lines : String(lines).split(/\r?\n/);
825
+ for (let index = list.length - 1; index >= 0; index -= 1) {
826
+ const line = list[index].trim();
827
+ if (!line) continue;
828
+ if (line.startsWith('[peer]') || line.startsWith('[conn]')) continue;
829
+ if (line.includes('Server listening with')) continue;
830
+ return line;
831
+ }
832
+ return null;
833
+ }