tailcat-webui 0.0.0-stage → 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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +112 -0
  4. package/README.md +101 -2
  5. package/bin/tailcat-webui.js +12 -0
  6. package/docs/CORE-API.md +343 -0
  7. package/docs/DESIGN.md +398 -0
  8. package/docs/assets/character.jpg +0 -0
  9. package/docs/assets/portrait.jpg +0 -0
  10. package/docs/screenshots/01-overview-light.png +0 -0
  11. package/docs/screenshots/02-overview-dark.png +0 -0
  12. package/docs/screenshots/03-ticket-light.png +0 -0
  13. package/docs/screenshots/04-ticket-qr-light.png +0 -0
  14. package/docs/screenshots/05-settings-light.png +0 -0
  15. package/docs/screenshots/06-diagnostics-light.png +0 -0
  16. package/docs/screenshots/07-mobile-overview.png +0 -0
  17. package/docs/screenshots/08-install-missing.png +0 -0
  18. package/docs/screenshots/09-keeper.png +0 -0
  19. package/package.json +56 -4
  20. package/src/cli.js +238 -0
  21. package/src/config.js +167 -0
  22. package/src/devices.js +163 -0
  23. package/src/errors.js +24 -0
  24. package/src/index.js +19 -0
  25. package/src/installer.js +907 -0
  26. package/src/manager.js +647 -0
  27. package/src/parse.js +207 -0
  28. package/src/paths.js +97 -0
  29. package/src/preferences.js +190 -0
  30. package/src/qr.js +37 -0
  31. package/src/relay.js +76 -0
  32. package/src/runtime/node.js +281 -0
  33. package/src/serve-targets.js +127 -0
  34. package/src/server.js +674 -0
  35. package/src/settings.js +262 -0
  36. package/src/supervisor.js +833 -0
  37. package/vendor/qrcode.mjs +2289 -0
  38. package/web/api.js +114 -0
  39. package/web/assets/portrait.jpg +0 -0
  40. package/web/boot.js +29 -0
  41. package/web/components.js +558 -0
  42. package/web/dict.js +663 -0
  43. package/web/drawer-access.js +318 -0
  44. package/web/drawer-address.js +271 -0
  45. package/web/drawer-automation.js +223 -0
  46. package/web/drawer-relay.js +128 -0
  47. package/web/drawer-tunnel.js +309 -0
  48. package/web/drawer.js +302 -0
  49. package/web/format.js +252 -0
  50. package/web/icon.png +0 -0
  51. package/web/index.html +29 -0
  52. package/web/main.js +471 -0
  53. package/web/room-diagnostics.js +426 -0
  54. package/web/room-overview.js +438 -0
  55. package/web/room-settings.js +71 -0
  56. package/web/store.js +168 -0
  57. package/web/styles.css +2873 -0
  58. package/web/ticket.js +212 -0
package/src/manager.js ADDED
@@ -0,0 +1,647 @@
1
+ import path from 'node:path';
2
+ import { configView, resolveConfig } from './config.js';
3
+ import { createFileDeviceStore } from './devices.js';
4
+ import { RemoteAccessError, errorMessage } from './errors.js';
5
+ import { TailcatInstaller } from './installer.js';
6
+ import { buildForwardCommand } from './parse.js';
7
+ import { createFilePreferenceStore } from './preferences.js';
8
+ import { qrMatrix } from './qr.js';
9
+ import { relayView } from './relay.js';
10
+ import { createNodeRuntime } from './runtime/node.js';
11
+ import {
12
+ effectiveSettings as resolveEffectiveSettings,
13
+ mergeSettings,
14
+ normalizeSettingsPatch,
15
+ settingsNeedRestart,
16
+ settingsSources,
17
+ validateEffectiveSettings,
18
+ } from './settings.js';
19
+ import { TailcatSupervisor } from './supervisor.js';
20
+
21
+ /** Local port the client browser binds when forwarding the tunnel. */
22
+ const DEFAULT_LOCAL_PORT = 18_080;
23
+
24
+ /** A logger that drops messages, so an embedded manager stays quiet by default. */
25
+ const SILENT_LOGGER = Object.freeze({ info() {}, warn() {}, debug() {} });
26
+
27
+ /**
28
+ * Owns the supervisor, the stores, and the installer for one tunnel instance,
29
+ * and exposes the read model and the operations the interface calls. Mutating
30
+ * operations are serialized so two clicks cannot start two tailcat processes.
31
+ */
32
+ export class TailcatManager {
33
+ /**
34
+ * @param {object} options - manager options.
35
+ * @param {unknown} options.config - raw or resolved config.
36
+ * @param {string} options.stateDir - parent for preferences, devices, and the managed binary.
37
+ * @param {{info: Function, warn: Function, debug?: Function}} [options.logger] - logger.
38
+ * @param {object} [options.runtime] - process adapter; defaults to the Node adapter.
39
+ * @param {object} [options.preferences] - custom preference store.
40
+ * @param {object} [options.devices] - custom allow-list store.
41
+ * @param {{targets: () => string[], reservedPorts?: () => number[], ready?: () => Promise<void>, validate?: (settings: object) => void, label?: string}} options.serve - tunnel targets and hooks.
42
+ * @param {{virtualPort?: () => number | null, localPort?: number}} [options.pairing] - ticket facts.
43
+ * @param {{enabled?: boolean, installDir?: string, releaseTag?: string, paths?: {dataDir?: string, binaryDir?: string, binaryPath?: string, stagingRoot?: string}}} [options.installer] - managed installer options.
44
+ * @param {string} [options.clientForwardHint] - extra text a caller may show next to the command.
45
+ */
46
+ constructor(options = {}) {
47
+ if (typeof options.stateDir !== 'string' || options.stateDir.trim() === '') {
48
+ throw new Error('createTailcatManager: stateDir is required.');
49
+ }
50
+ if (!options.serve || typeof options.serve.targets !== 'function') {
51
+ throw new Error('createTailcatManager: serve.targets is required.');
52
+ }
53
+ this.stateDir = path.resolve(options.stateDir);
54
+ this.logger = options.logger ?? SILENT_LOGGER;
55
+ this.runtime = options.runtime ?? createNodeRuntime();
56
+ this.serve = options.serve;
57
+ this.clientForwardHint = typeof options.clientForwardHint === 'string' ? options.clientForwardHint : null;
58
+
59
+ this.config = resolveConfig(options.config, { reservedPorts: this.reservedPorts() });
60
+ this.preferences = options.preferences ?? createFilePreferenceStore({ dir: this.stateDir, logger: this.logger });
61
+ this.devices = options.devices ?? createFileDeviceStore({ dir: this.stateDir, logger: this.logger });
62
+
63
+ const installerOptions = options.installer && typeof options.installer === 'object' ? options.installer : {};
64
+ const installDir = installerOptions.installDir ?? path.join(this.stateDir, 'bin');
65
+ const pathOverrides = installerOptions.paths && typeof installerOptions.paths === 'object' ? installerOptions.paths : {};
66
+ const dataDir = pathOverrides.dataDir ?? path.dirname(installDir);
67
+ const binaryDir = pathOverrides.binaryDir ?? installDir;
68
+ const binaryPath =
69
+ pathOverrides.binaryPath ?? path.join(binaryDir, process.platform === 'win32' ? 'tailcat.exe' : 'tailcat');
70
+ this.installer = new TailcatInstaller({
71
+ logger: this.logger,
72
+ runtime: this.runtime,
73
+ releaseTag: installerOptions.releaseTag ?? 'v0.0.0',
74
+ requestedBinary: this.config.binaryPath,
75
+ enabled: installerOptions.enabled !== false,
76
+ paths: {
77
+ dataDir,
78
+ binaryDir,
79
+ binaryPath,
80
+ stagingRoot: pathOverrides.stagingRoot ?? path.join(dataDir, '.install'),
81
+ },
82
+ fetchImpl: installerOptions.fetchImpl,
83
+ resolveExecutable: installerOptions.resolveExecutable,
84
+ runCommand: installerOptions.runCommand,
85
+ platform: installerOptions.platform,
86
+ arch: installerOptions.arch,
87
+ });
88
+
89
+ this.tailcat = new TailcatSupervisor({
90
+ config: this.config,
91
+ logger: this.logger,
92
+ runtime: this.runtime,
93
+ devices: this.devices,
94
+ installer: this.installer,
95
+ derpMapUrl: () => this.effectiveDerpMapUrl(),
96
+ settings: () => this.effectiveSettings(),
97
+ targets: () => this.readServeTargets(),
98
+ label: typeof this.serve.label === 'string' ? this.serve.label : undefined,
99
+ });
100
+
101
+ const pairing = options.pairing && typeof options.pairing === 'object' ? options.pairing : {};
102
+ this.pairingOptions = pairing;
103
+ this.localPort =
104
+ Number.isInteger(pairing.localPort) && pairing.localPort >= 1 && pairing.localPort <= 65535
105
+ ? pairing.localPort
106
+ : DEFAULT_LOCAL_PORT;
107
+
108
+ this.ops = Promise.resolve();
109
+ this.activation = null;
110
+ this.activated = false;
111
+ this.disposed = false;
112
+ this.qrCache = null;
113
+ }
114
+
115
+ /**
116
+ * Probe tailcat, then optionally start the tunnel. A failed start is logged
117
+ * and reported through the snapshot instead of thrown, because activation is
118
+ * not an operator action and must not fail the caller.
119
+ * @returns {Promise<object>} snapshot.
120
+ */
121
+ activate() {
122
+ if (this.activation) return this.activation;
123
+ this.activation = this.enqueue(() => this.activateInternal()).finally(() => {
124
+ this.activation = null;
125
+ });
126
+ return this.activation;
127
+ }
128
+
129
+ /**
130
+ * Start the tunnel with the current settings and allow-list.
131
+ * @returns {Promise<object>} snapshot.
132
+ */
133
+ startTunnel() {
134
+ return this.enqueue(async () => {
135
+ await this.startInternal();
136
+ return this.snapshot();
137
+ });
138
+ }
139
+
140
+ /**
141
+ * Stop the tunnel.
142
+ * @returns {Promise<object>} snapshot.
143
+ */
144
+ stopTunnel() {
145
+ return this.enqueue(async () => {
146
+ await this.tailcat.stop();
147
+ return this.snapshot();
148
+ });
149
+ }
150
+
151
+ /**
152
+ * Restart the tunnel with the current settings and allow-list.
153
+ * @returns {Promise<object>} snapshot.
154
+ */
155
+ restartTunnel() {
156
+ return this.enqueue(async () => {
157
+ await this.ensureReady();
158
+ await this.installer.detectSystem();
159
+ await this.tailcat.restart();
160
+ return this.snapshot();
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Replace the tailcat address and wait until the new server is online. An
166
+ * optional region patch is saved first, because a region only matters at
167
+ * key-generation time; saving it does not restart the tunnel on its own.
168
+ * @param {{regionMode?: string, regionValue?: string}} [region] - region patch.
169
+ * @returns {Promise<object>} snapshot.
170
+ */
171
+ rotateAddress(region) {
172
+ return this.enqueue(async () => {
173
+ const settings = this.effectiveSettings();
174
+ if (region && typeof region === 'object') {
175
+ if (settings.addressMode === 'ephemeral') {
176
+ throw new RemoteAccessError(
177
+ 'invalid-settings',
178
+ 'An ephemeral key has no region to pin; switch to the stable key first.',
179
+ 400,
180
+ );
181
+ }
182
+ const patch = {};
183
+ if (region.regionMode !== undefined) patch.regionMode = region.regionMode;
184
+ if (region.regionValue !== undefined) patch.regionValue = region.regionValue;
185
+ if (Object.keys(patch).length > 0) {
186
+ const normalized = normalizeSettingsPatch(patch);
187
+ const next = resolveEffectiveSettings(this.config, mergeSettings(this.preferences.snapshot().settings, normalized));
188
+ this.validateSettings(next);
189
+ this.preferences.setSettings(patch);
190
+ }
191
+ }
192
+ await this.ensureReady();
193
+ await this.installer.detectSystem();
194
+ await this.tailcat.rotate();
195
+ return this.snapshot();
196
+ });
197
+ }
198
+
199
+ /**
200
+ * Persist a settings patch and apply it. Fields tailcat reads only at spawn
201
+ * time restart a running tunnel; the previous overrides are restored if the
202
+ * new settings cannot come online. Region fields are saved without a restart
203
+ * because they are only read by the next explicit rotation.
204
+ * @param {unknown} patch - partial settings from the interface.
205
+ * @returns {Promise<object>} snapshot.
206
+ */
207
+ saveSettings(patch) {
208
+ return this.enqueue(async () => {
209
+ const overrides = this.preferences.snapshot().settings;
210
+ const before = this.effectiveSettings();
211
+ const normalized = normalizeSettingsPatch(patch);
212
+ const nextOverrides = mergeSettings(overrides, normalized);
213
+ const after = resolveEffectiveSettings(this.config, nextOverrides);
214
+ this.validateSettings(after);
215
+ if (JSON.stringify(before) === JSON.stringify(after)) return this.snapshot();
216
+
217
+ this.preferences.setSettings(patch);
218
+ const wasRunning = this.tailcat.desired || Boolean(this.tailcat.handle);
219
+ if (!wasRunning || !settingsNeedRestart(before, after) || this.disposed) return this.snapshot();
220
+
221
+ try {
222
+ await this.ensureReady();
223
+ await this.installer.detectSystem();
224
+ await this.tailcat.restart();
225
+ if (!(await this.tailcat.waitForOnline(30_000))) {
226
+ throw new RemoteAccessError(
227
+ 'settings-start-failed',
228
+ 'tailcat did not come online with the new settings. The previous settings were restored.',
229
+ 502,
230
+ );
231
+ }
232
+ return this.snapshot();
233
+ } catch (error) {
234
+ this.logger.warn(`tailcat-webui: settings did not apply: ${errorMessage(error)}`);
235
+ try {
236
+ this.restoreSettings(overrides);
237
+ } catch (restoreError) {
238
+ this.logger.warn(`tailcat-webui: could not restore the previous settings: ${errorMessage(restoreError)}`);
239
+ }
240
+ if (!this.disposed) {
241
+ try {
242
+ await this.ensureReady();
243
+ await this.tailcat.restart();
244
+ await this.tailcat.waitForOnline(15_000);
245
+ } catch (restartError) {
246
+ this.logger.warn(
247
+ `tailcat-webui: could not restart with the previous settings: ${errorMessage(restartError)}`,
248
+ );
249
+ }
250
+ }
251
+ if (error instanceof RemoteAccessError) throw error;
252
+ throw new RemoteAccessError(
253
+ 'settings-apply-failed',
254
+ `Could not apply the tailcat settings: ${errorMessage(error)}`,
255
+ 502,
256
+ );
257
+ }
258
+ });
259
+ }
260
+
261
+ /**
262
+ * Replace the device allow-list. Persisting the list is the primary
263
+ * operation; a running tunnel is restarted so tailcat applies it. A restart
264
+ * failure leaves the saved list in place and surfaces through the snapshot.
265
+ * @param {string[]} allow - canonical or paste-ready keys.
266
+ * @returns {Promise<object>} snapshot.
267
+ */
268
+ saveDevices(allow) {
269
+ return this.enqueue(async () => {
270
+ this.devices.replace(allow);
271
+ if (this.tailcat.desired || this.tailcat.handle) {
272
+ try {
273
+ await this.installer.detectSystem();
274
+ await this.tailcat.restart();
275
+ } catch (error) {
276
+ this.logger.warn(`tailcat-webui: allow-list saved but tailcat did not restart: ${errorMessage(error)}`);
277
+ }
278
+ }
279
+ return this.snapshot();
280
+ });
281
+ }
282
+
283
+ /**
284
+ * Save the optional DERP map URL and apply it to a running tunnel. The key is
285
+ * never regenerated: a stable saved key keeps the same address, and the new
286
+ * map must contain that key's region. A restart that cannot come online is
287
+ * rolled back to the previous preference so editing the map cannot silently
288
+ * leave the tunnel down.
289
+ * @param {unknown} mapUrl - absolute HTTP(S) URL; empty restores the config value.
290
+ * @returns {Promise<object>} snapshot.
291
+ */
292
+ saveDerpMapUrl(mapUrl) {
293
+ return this.enqueue(async () => {
294
+ const previousPreference = this.preferences.snapshot().derpMapUrl;
295
+ const previousMapUrl = this.effectiveDerpMapUrl();
296
+ this.preferences.setDerpMapUrl(mapUrl);
297
+ const nextMapUrl = this.effectiveDerpMapUrl();
298
+ if (nextMapUrl === previousMapUrl) return this.snapshot();
299
+
300
+ const wasRunning = this.tailcat.desired || Boolean(this.tailcat.handle);
301
+ if (!wasRunning) return this.snapshot();
302
+ try {
303
+ await this.ensureReady();
304
+ await this.installer.detectSystem();
305
+ await this.tailcat.restart();
306
+ if (!(await this.tailcat.waitForOnline(30_000))) {
307
+ throw new RemoteAccessError(
308
+ 'derp-map-start-failed',
309
+ 'tailcat did not come online with the new DERP map. The previous map was restored; the address was not rotated.',
310
+ 502,
311
+ );
312
+ }
313
+ return this.snapshot();
314
+ } catch (error) {
315
+ this.logger.warn(`tailcat-webui: custom DERP map did not apply: ${errorMessage(error)}`);
316
+ try {
317
+ this.preferences.setDerpMapUrl(previousPreference);
318
+ } catch (restoreError) {
319
+ this.logger.warn(`tailcat-webui: could not restore the previous DERP map: ${errorMessage(restoreError)}`);
320
+ }
321
+ if (!this.disposed) {
322
+ try {
323
+ await this.ensureReady();
324
+ await this.tailcat.restart();
325
+ await this.tailcat.waitForOnline(15_000);
326
+ } catch (restartError) {
327
+ this.logger.warn(
328
+ `tailcat-webui: could not restart with the previous DERP map: ${errorMessage(restartError)}`,
329
+ );
330
+ }
331
+ }
332
+ if (error instanceof RemoteAccessError) throw error;
333
+ throw new RemoteAccessError(
334
+ 'derp-map-apply-failed',
335
+ `Could not apply the custom DERP map: ${errorMessage(error)}`,
336
+ 502,
337
+ );
338
+ }
339
+ });
340
+ }
341
+
342
+ /**
343
+ * Install the managed tailcat, then restore the previous desired tunnel
344
+ * state. A user-installed tailcat elsewhere is never modified.
345
+ * @param {{force?: boolean}} [options] - reinstall even when a managed copy exists.
346
+ * @returns {Promise<object>} snapshot.
347
+ */
348
+ installTailcat(options = {}) {
349
+ return this.enqueue(async () => {
350
+ if (this.config.binaryPath !== 'tailcat') {
351
+ throw new RemoteAccessError(
352
+ 'tailcat-binary-overridden',
353
+ `binaryPath is set to "${this.config.binaryPath}", so the managed install would not be used. Set binaryPath back to "tailcat" or install there manually.`,
354
+ 409,
355
+ );
356
+ }
357
+ if (this.installer.busy) {
358
+ throw new RemoteAccessError('install-busy', 'A tailcat install is already running.', 409);
359
+ }
360
+ await this.installer.detectSystem();
361
+ const wasDesired = this.tailcat.desired || Boolean(this.tailcat.handle);
362
+ if (this.tailcat.handle) await this.tailcat.stop();
363
+ try {
364
+ await this.installer.install({ force: options.force === true });
365
+ } catch (error) {
366
+ if (wasDesired && !this.disposed) {
367
+ try {
368
+ await this.ensureReady();
369
+ await this.tailcat.start();
370
+ } catch (restartError) {
371
+ this.logger.warn(`tailcat-webui: could not restart the previous tailcat: ${errorMessage(restartError)}`);
372
+ }
373
+ }
374
+ throw error;
375
+ }
376
+ this.tailcat.reloadBinary();
377
+ if (wasDesired && !this.disposed) {
378
+ try {
379
+ await this.ensureReady();
380
+ await this.tailcat.start();
381
+ } catch (error) {
382
+ this.logger.warn(`tailcat-webui: installed tailcat but could not start it: ${errorMessage(error)}`);
383
+ }
384
+ }
385
+ return this.snapshot();
386
+ });
387
+ }
388
+
389
+ /**
390
+ * Probe for a tailcat installed outside this package without downloading or
391
+ * writing anything.
392
+ * @returns {Promise<object>} detection result.
393
+ */
394
+ detectSystem() {
395
+ return this.installer.detectSystem();
396
+ }
397
+
398
+ /**
399
+ * Dispatch one named operation.
400
+ * @param {string} action - action name.
401
+ * @param {object} [payload] - action payload.
402
+ * @returns {Promise<object>} snapshot.
403
+ */
404
+ action(action, payload) {
405
+ const body = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
406
+ switch (action) {
407
+ case 'start':
408
+ return this.startTunnel();
409
+ case 'stop':
410
+ return this.stopTunnel();
411
+ case 'restart':
412
+ return this.restartTunnel();
413
+ case 'rotate':
414
+ return this.rotateAddress(body.region);
415
+ case 'settings':
416
+ return this.saveSettings(body.settings);
417
+ case 'devices':
418
+ return this.saveDevices(body.allow);
419
+ case 'derpMap':
420
+ return this.saveDerpMapUrl(body.derpMapUrl);
421
+ case 'install':
422
+ return this.installTailcat({ force: body.force === true });
423
+ default:
424
+ return Promise.reject(new RemoteAccessError('unknown-action', `Unknown action ${JSON.stringify(action)}.`, 400));
425
+ }
426
+ }
427
+
428
+ /**
429
+ * The effective settings, after saved overrides are folded over the config.
430
+ * @param {Record<string, unknown>} [overrides] - raw overrides; defaults to the saved set.
431
+ * @returns {object} effective settings.
432
+ */
433
+ effectiveSettings(overrides) {
434
+ return resolveEffectiveSettings(this.config, overrides ?? this.preferences.snapshot().settings);
435
+ }
436
+
437
+ /**
438
+ * The map tailcat should read: the saved override first, then the config,
439
+ * then tailcat's own default.
440
+ * @returns {string} effective DERP map URL, or empty for tailcat's default.
441
+ */
442
+ effectiveDerpMapUrl() {
443
+ const preference = this.preferences.snapshot().derpMapUrl;
444
+ return preference !== '' ? preference : this.config.derpMapUrl;
445
+ }
446
+
447
+ /**
448
+ * @returns {number[]} virtual ports the caller keeps for itself.
449
+ */
450
+ reservedPorts() {
451
+ try {
452
+ const value = this.serve?.reservedPorts?.();
453
+ return Array.isArray(value) ? value.filter((port) => Number.isInteger(port)) : [];
454
+ } catch {
455
+ return [];
456
+ }
457
+ }
458
+
459
+ /**
460
+ * @returns {string[]} the complete canonical serve mapping list.
461
+ * @throws {Error} when the caller's hook throws.
462
+ */
463
+ readServeTargets() {
464
+ const value = this.serve.targets();
465
+ return Array.isArray(value) ? value.filter((target) => typeof target === 'string' && target !== '') : [];
466
+ }
467
+
468
+ /**
469
+ * @returns {object} the complete read model sent to the interface.
470
+ */
471
+ snapshot() {
472
+ const overrides = this.preferences.snapshot().settings;
473
+ const settings = resolveEffectiveSettings(this.config, overrides);
474
+ const tailcat = this.tailcat.snapshot();
475
+ const installer = this.installer.snapshot();
476
+ const devices = this.devices.snapshot();
477
+ const preferences = this.preferences.snapshot();
478
+ const warnings = [
479
+ ...devices.warnings,
480
+ ...preferences.warnings,
481
+ ...(installer.error ? [installer.error] : []),
482
+ ];
483
+ return {
484
+ now: new Date().toISOString(),
485
+ config: configView(this.config),
486
+ settings: { ...settings, sources: settingsSources(this.config, overrides) },
487
+ relay: this.relaySnapshot(),
488
+ tailcat,
489
+ installer,
490
+ devices,
491
+ preferences,
492
+ pairing: this.pairing(tailcat.address),
493
+ warnings,
494
+ };
495
+ }
496
+
497
+ /** Stop the child, cancel any install, and wait for the operation queue. */
498
+ async dispose() {
499
+ this.disposed = true;
500
+ this.installer.dispose();
501
+ try {
502
+ await this.ops;
503
+ } catch {
504
+ // A rejected operation already surfaced through its caller.
505
+ }
506
+ await this.tailcat.dispose();
507
+ }
508
+
509
+ /** @private */
510
+ async activateInternal() {
511
+ if (this.activated) return this.snapshot();
512
+ this.activated = true;
513
+ try {
514
+ await this.installer.detectSystem();
515
+ } catch (error) {
516
+ this.logger.warn(`tailcat-webui: could not inspect an existing tailcat: ${errorMessage(error)}`);
517
+ }
518
+ if (this.effectiveSettings().autoStart && this.safeTargets().length > 0) {
519
+ try {
520
+ await this.startInternal();
521
+ } catch (error) {
522
+ this.logger.warn(`tailcat-webui: tunnel did not start: ${errorMessage(error)}`);
523
+ }
524
+ }
525
+ return this.snapshot();
526
+ }
527
+
528
+ /** @private */
529
+ async startInternal() {
530
+ await this.ensureReady();
531
+ await this.installer.detectSystem();
532
+ await this.tailcat.start();
533
+ }
534
+
535
+ /** @private */
536
+ async ensureReady() {
537
+ if (this.serve && typeof this.serve.ready === 'function') await this.serve.ready();
538
+ }
539
+
540
+ /**
541
+ * @private
542
+ * @param {object} settings - effective settings to validate.
543
+ */
544
+ validateSettings(settings) {
545
+ validateEffectiveSettings(settings, this.reservedPorts());
546
+ if (typeof this.serve.validate === 'function') {
547
+ try {
548
+ this.serve.validate(settings);
549
+ } catch (error) {
550
+ if (error instanceof RemoteAccessError) throw error;
551
+ throw new RemoteAccessError('invalid-settings', errorMessage(error), 400);
552
+ }
553
+ }
554
+ }
555
+
556
+ /**
557
+ * @private
558
+ * @param {Record<string, unknown>} overrides - complete previous override set.
559
+ */
560
+ restoreSettings(overrides) {
561
+ const patch = {};
562
+ for (const key of Object.keys(this.preferences.snapshot().settings)) patch[key] = null;
563
+ for (const [key, value] of Object.entries(overrides ?? {})) patch[key] = value;
564
+ this.preferences.setSettings(patch);
565
+ }
566
+
567
+ /**
568
+ * @private
569
+ * @returns {object | null} pairing facts, or null without an address.
570
+ */
571
+ pairing(address) {
572
+ if (!address) return null;
573
+ const port = this.virtualPort();
574
+ if (this.qrCache?.address !== address) {
575
+ try {
576
+ this.qrCache = { address, matrix: qrMatrix(address) };
577
+ } catch (error) {
578
+ this.logger.warn(`tailcat-webui: could not build the pairing QR: ${errorMessage(error)}`);
579
+ this.qrCache = { address, matrix: null };
580
+ }
581
+ }
582
+ const matrix = this.qrCache.matrix;
583
+ return {
584
+ address,
585
+ port,
586
+ localPort: this.localPort,
587
+ command: port === null ? null : buildForwardCommand(address, port, this.localPort),
588
+ qr: matrix === null ? null : { size: matrix.size, rows: matrix.rows },
589
+ targets: this.safeTargets(),
590
+ };
591
+ }
592
+
593
+ /** @private */
594
+ virtualPort() {
595
+ try {
596
+ const value = typeof this.pairingOptions.virtualPort === 'function'
597
+ ? this.pairingOptions.virtualPort()
598
+ : this.pairingOptions.virtualPort;
599
+ return Number.isInteger(value) && value >= 1 && value <= 65535 ? value : null;
600
+ } catch {
601
+ return null;
602
+ }
603
+ }
604
+
605
+ /** @private */
606
+ safeTargets() {
607
+ try {
608
+ return this.readServeTargets();
609
+ } catch {
610
+ return [];
611
+ }
612
+ }
613
+
614
+ /** @private */
615
+ relaySnapshot() {
616
+ const fullAddress = this.effectiveSettings().fullAddress;
617
+ const preference = this.preferences.snapshot().derpMapUrl;
618
+ if (preference !== '') return relayView(preference, 'panel', { fullAddress });
619
+ if (this.config.derpMapUrl !== '') return relayView(this.config.derpMapUrl, 'config', { fullAddress });
620
+ return relayView('', 'default', { fullAddress });
621
+ }
622
+
623
+ /**
624
+ * @private
625
+ * @param {() => Promise<unknown>} task - operation.
626
+ * @returns {Promise<unknown>} task result.
627
+ */
628
+ enqueue(task) {
629
+ if (this.disposed) {
630
+ return Promise.reject(new RemoteAccessError('disposed', 'The tunnel runtime is shutting down.', 503));
631
+ }
632
+ const run = this.ops.then(task, task);
633
+ this.ops = run.then(
634
+ () => undefined,
635
+ () => undefined,
636
+ );
637
+ return run;
638
+ }
639
+ }
640
+
641
+ /**
642
+ * @param {object} options - manager options.
643
+ * @returns {TailcatManager} new manager.
644
+ */
645
+ export function createTailcatManager(options = {}) {
646
+ return new TailcatManager(options);
647
+ }