@ds-hu/dsh-tailcat-remote 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/NOTICE +33 -0
- package/README.en.md +115 -0
- package/README.md +114 -2
- package/client.js +1205 -0
- package/cordis.patch.yml +39 -0
- package/docs/CONTRACT.md +186 -0
- package/docs/SECURITY.md +97 -0
- package/docs/TECHNICAL.md +156 -0
- package/docs/screenshots/01-pairing.png +0 -0
- package/docs/screenshots/02-security.png +0 -0
- package/docs/screenshots/03-install.png +0 -0
- package/icon.svg +18 -0
- package/index.js +34 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +78 -4
- package/src/config.js +130 -0
- package/src/control.js +84 -0
- package/src/devices.js +153 -0
- package/src/door.js +472 -0
- package/src/errors.js +24 -0
- package/src/installer.js +824 -0
- package/src/parse.js +241 -0
- package/src/paths.js +109 -0
- package/src/qr.js +61 -0
- package/src/remote.js +272 -0
- package/src/tailcat.js +715 -0
- package/vendor/qrcode.mjs +2289 -0
package/src/tailcat.js
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
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 { doorEndpoint, 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 STABLE_AFTER_MS = 60_000;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Supervises one tailcat server process, its saved key, its allow-list, and
|
|
24
|
+
* the recent access records parsed from `--log`.
|
|
25
|
+
*/
|
|
26
|
+
export class TailcatSupervisor {
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} ctx - Host plugin context.
|
|
29
|
+
* @param {ReturnType<import('./config.js').resolveConfig>} config - resolved config.
|
|
30
|
+
* @param {{ devices: ReturnType<import('./devices.js').createDeviceStore>, logger: any, installer?: import('./installer.js').TailcatInstaller }} options - collaborators.
|
|
31
|
+
*/
|
|
32
|
+
constructor(ctx, config, { devices, logger, installer }) {
|
|
33
|
+
this.ctx = ctx;
|
|
34
|
+
this.config = config;
|
|
35
|
+
this.devices = devices;
|
|
36
|
+
this.logger = logger;
|
|
37
|
+
this.installer = installer;
|
|
38
|
+
this.events = new EventEmitter();
|
|
39
|
+
this.events.setMaxListeners(50);
|
|
40
|
+
|
|
41
|
+
this.phase = 'stopped';
|
|
42
|
+
this.desired = false;
|
|
43
|
+
this.address = null;
|
|
44
|
+
this.keyMode = config.addressMode === 'ephemeral' ? 'ephemeral' : 'saved';
|
|
45
|
+
this.keyFile = null;
|
|
46
|
+
this.region = null;
|
|
47
|
+
this.binary = { requested: config.binaryPath, resolved: null, source: null, version: null, error: null };
|
|
48
|
+
this.restarts = 0;
|
|
49
|
+
this.lastError = null;
|
|
50
|
+
this.lastExit = null;
|
|
51
|
+
this.warnings = [];
|
|
52
|
+
this.recent = [];
|
|
53
|
+
this.refusals = 0;
|
|
54
|
+
this.startedAt = null;
|
|
55
|
+
this.onlineAt = null;
|
|
56
|
+
this.nextRestartAt = null;
|
|
57
|
+
|
|
58
|
+
this.handle = null;
|
|
59
|
+
this.streams = [];
|
|
60
|
+
this.abort = null;
|
|
61
|
+
this.generation = 0;
|
|
62
|
+
this.startPromise = null;
|
|
63
|
+
this.restartTimer = null;
|
|
64
|
+
this.stableTimer = null;
|
|
65
|
+
this.restartAttempt = 0;
|
|
66
|
+
this.openConnections = new Map();
|
|
67
|
+
this.stderrLines = [];
|
|
68
|
+
this.disposing = false;
|
|
69
|
+
this.versionPromise = null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Set the desired state to running and start when idle. */
|
|
73
|
+
async start() {
|
|
74
|
+
if (this.disposing) throw new RemoteAccessError('disposed', 'The remote-access runtime is shutting down.');
|
|
75
|
+
this.desired = true;
|
|
76
|
+
if (this.handle) return this.snapshot();
|
|
77
|
+
if (this.startPromise) return this.startPromise;
|
|
78
|
+
this.startPromise = this.startInternal().finally(() => {
|
|
79
|
+
this.startPromise = null;
|
|
80
|
+
});
|
|
81
|
+
return this.startPromise;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Stop the child and leave the runtime stopped (the door stays listening). */
|
|
85
|
+
async stop() {
|
|
86
|
+
this.desired = false;
|
|
87
|
+
this.clearRestartTimer();
|
|
88
|
+
const handle = this.handle;
|
|
89
|
+
if (!handle) {
|
|
90
|
+
this.phase = 'stopped';
|
|
91
|
+
this.address = null;
|
|
92
|
+
this.onlineAt = null;
|
|
93
|
+
this.nextRestartAt = null;
|
|
94
|
+
this.lastError = null;
|
|
95
|
+
this.emit();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
this.phase = 'stopping';
|
|
99
|
+
this.emit();
|
|
100
|
+
handle.terminate();
|
|
101
|
+
try {
|
|
102
|
+
await handle.waitForExit(AbortSignal.timeout(8_000));
|
|
103
|
+
} catch (error) {
|
|
104
|
+
this.logger.warn(`tailcat-remote: failed while waiting for tailcat to stop: ${errorMessage(error)}`);
|
|
105
|
+
}
|
|
106
|
+
this.closeStreams();
|
|
107
|
+
if (this.phase !== 'stopped') {
|
|
108
|
+
this.phase = 'stopped';
|
|
109
|
+
this.address = null;
|
|
110
|
+
this.onlineAt = null;
|
|
111
|
+
this.nextRestartAt = null;
|
|
112
|
+
this.lastError = null;
|
|
113
|
+
this.emit();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Stop and start again with the same saved key and allow-list. */
|
|
118
|
+
async restart() {
|
|
119
|
+
await this.stop();
|
|
120
|
+
await this.start();
|
|
121
|
+
return this.snapshot();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Replace the saved stable key (or mint a new ephemeral key) and restart.
|
|
126
|
+
* The old tailcat address stops working when the new server starts.
|
|
127
|
+
*/
|
|
128
|
+
async rotate() {
|
|
129
|
+
await this.stop();
|
|
130
|
+
this.restartAttempt = 0;
|
|
131
|
+
if (this.config.addressMode === 'stable') {
|
|
132
|
+
try {
|
|
133
|
+
await this.runGenkey(true);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
this.phase = 'error';
|
|
136
|
+
this.lastError = errorMessage(error);
|
|
137
|
+
this.desired = false;
|
|
138
|
+
this.emit();
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
await this.start();
|
|
143
|
+
await this.waitForOnline(30_000);
|
|
144
|
+
return this.snapshot();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Release the child process and listeners for plugin unload. */
|
|
148
|
+
async dispose() {
|
|
149
|
+
this.disposing = true;
|
|
150
|
+
this.desired = false;
|
|
151
|
+
this.clearRestartTimer();
|
|
152
|
+
if (this.stableTimer) clearTimeout(this.stableTimer);
|
|
153
|
+
this.stableTimer = null;
|
|
154
|
+
const handle = this.handle;
|
|
155
|
+
if (handle) {
|
|
156
|
+
handle.terminate();
|
|
157
|
+
try {
|
|
158
|
+
await handle.waitForExit(AbortSignal.timeout(8_000));
|
|
159
|
+
} catch {
|
|
160
|
+
// The provider's terminate escalation owns the final cleanup.
|
|
161
|
+
}
|
|
162
|
+
this.closeStreams();
|
|
163
|
+
}
|
|
164
|
+
this.phase = 'stopped';
|
|
165
|
+
this.address = null;
|
|
166
|
+
this.events.removeAllListeners();
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** @returns {object} display-safe state, including the address for the owner. */
|
|
170
|
+
snapshot() {
|
|
171
|
+
const endpoint = doorEndpoint(this.config);
|
|
172
|
+
return {
|
|
173
|
+
phase: this.phase,
|
|
174
|
+
desired: this.desired,
|
|
175
|
+
address: this.address,
|
|
176
|
+
keyMode: this.keyMode,
|
|
177
|
+
keyName: this.config.keyName,
|
|
178
|
+
addressMode: this.config.addressMode,
|
|
179
|
+
port: this.config.port,
|
|
180
|
+
listen: this.config.listen,
|
|
181
|
+
endpoint,
|
|
182
|
+
region: this.region,
|
|
183
|
+
binary: {
|
|
184
|
+
requested: this.binary.requested,
|
|
185
|
+
resolved: this.binary.resolved,
|
|
186
|
+
source: this.binary.source,
|
|
187
|
+
version: this.binary.version,
|
|
188
|
+
error: this.binary.error,
|
|
189
|
+
},
|
|
190
|
+
restarts: this.restarts,
|
|
191
|
+
lastError: this.lastError,
|
|
192
|
+
lastExit: this.lastExit,
|
|
193
|
+
warnings: [...this.warnings],
|
|
194
|
+
stderrTail: this.stderrLines.slice(-10),
|
|
195
|
+
recent: [...this.recent],
|
|
196
|
+
refusals: this.refusals,
|
|
197
|
+
startedAt: this.startedAt,
|
|
198
|
+
onlineAt: this.onlineAt,
|
|
199
|
+
nextRestartAt: this.nextRestartAt,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Wait for the tunnel to report an address (or to fail).
|
|
205
|
+
* @param {number} timeoutMs - bound.
|
|
206
|
+
* @returns {Promise<boolean>} whether the tunnel is online.
|
|
207
|
+
*/
|
|
208
|
+
waitForOnline(timeoutMs) {
|
|
209
|
+
if (this.phase === 'online') return Promise.resolve(true);
|
|
210
|
+
if (this.phase === 'error' || this.phase === 'stopped') return Promise.resolve(false);
|
|
211
|
+
return new Promise((resolve) => {
|
|
212
|
+
let timer;
|
|
213
|
+
const check = () => {
|
|
214
|
+
if (this.phase === 'online') {
|
|
215
|
+
cleanup();
|
|
216
|
+
resolve(true);
|
|
217
|
+
} else if (this.phase === 'error' || this.phase === 'stopped') {
|
|
218
|
+
cleanup();
|
|
219
|
+
resolve(false);
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
const cleanup = () => {
|
|
223
|
+
clearTimeout(timer);
|
|
224
|
+
this.events.off('change', check);
|
|
225
|
+
};
|
|
226
|
+
timer = setTimeout(() => {
|
|
227
|
+
cleanup();
|
|
228
|
+
resolve(this.phase === 'online');
|
|
229
|
+
}, Math.max(0, timeoutMs));
|
|
230
|
+
timer.unref?.();
|
|
231
|
+
this.events.on('change', check);
|
|
232
|
+
check();
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** @returns {void} */
|
|
237
|
+
emit() {
|
|
238
|
+
this.events.emit('change');
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** @private */
|
|
242
|
+
async startInternal() {
|
|
243
|
+
if (this.handle) return this.snapshot();
|
|
244
|
+
this.phase = 'starting';
|
|
245
|
+
this.lastError = null;
|
|
246
|
+
this.nextRestartAt = null;
|
|
247
|
+
this.emit();
|
|
248
|
+
try {
|
|
249
|
+
await this.ensureBinary();
|
|
250
|
+
if (!this.desired || this.disposing) {
|
|
251
|
+
this.phase = 'stopped';
|
|
252
|
+
this.emit();
|
|
253
|
+
return this.snapshot();
|
|
254
|
+
}
|
|
255
|
+
if (this.config.addressMode === 'stable') await this.ensureKey();
|
|
256
|
+
if (!this.desired || this.disposing) {
|
|
257
|
+
this.phase = 'stopped';
|
|
258
|
+
this.emit();
|
|
259
|
+
return this.snapshot();
|
|
260
|
+
}
|
|
261
|
+
this.spawnServer();
|
|
262
|
+
return this.snapshot();
|
|
263
|
+
} catch (error) {
|
|
264
|
+
this.phase = 'error';
|
|
265
|
+
this.lastError = errorMessage(error);
|
|
266
|
+
this.binary.error = this.binary.resolved === null ? this.lastError : this.binary.error;
|
|
267
|
+
this.emit();
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Forget the resolved executable so the next start picks up an install. */
|
|
273
|
+
reloadBinary() {
|
|
274
|
+
this.binary.resolved = null;
|
|
275
|
+
this.binary.source = null;
|
|
276
|
+
this.binary.version = null;
|
|
277
|
+
this.binary.error = null;
|
|
278
|
+
this.versionPromise = null;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** @private */
|
|
282
|
+
async ensureBinary() {
|
|
283
|
+
if (this.binary.resolved) return;
|
|
284
|
+
const requested = this.config.binaryPath;
|
|
285
|
+
const managed = this.installer?.binaryPath;
|
|
286
|
+
if (requested === 'tailcat' && managed && this.installer?.hasInstalled()) {
|
|
287
|
+
this.binary.resolved = managed;
|
|
288
|
+
this.binary.source = 'managed';
|
|
289
|
+
this.binary.error = null;
|
|
290
|
+
this.logger.info(`tailcat-remote: using managed tailcat at ${managed}`);
|
|
291
|
+
void this.loadVersion();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (requested === 'tailcat' && this.installer?.system?.compatible === false) {
|
|
295
|
+
throw new RemoteAccessError(
|
|
296
|
+
'tailcat-version-too-old',
|
|
297
|
+
`The installed tailcat ${this.installer.system.version ?? ''} is too old for remote access; install the managed version from Remote Access or upgrade tailcat to 0.8.0 or newer.`,
|
|
298
|
+
503,
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
try {
|
|
302
|
+
let resolved = null;
|
|
303
|
+
try {
|
|
304
|
+
resolved = await this.ctx.subprocess.resolveExecutable(requested, process.env);
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (requested !== 'tailcat') throw error;
|
|
307
|
+
resolved =
|
|
308
|
+
this.installer?.system?.status === 'found' ? this.installer.system.path : findKnownTailcat(process.platform);
|
|
309
|
+
if (!resolved) throw error;
|
|
310
|
+
}
|
|
311
|
+
this.binary.resolved = resolved;
|
|
312
|
+
this.binary.source = requested === 'tailcat' ? 'path' : 'config';
|
|
313
|
+
this.binary.error = null;
|
|
314
|
+
this.logger.info(`tailcat-remote: using ${resolved}`);
|
|
315
|
+
} catch (error) {
|
|
316
|
+
this.binary.error = errorMessage(error);
|
|
317
|
+
throw new RemoteAccessError(
|
|
318
|
+
'tailcat-not-found',
|
|
319
|
+
`Cannot find the tailcat executable "${requested}". Use the install button in Remote Access, put tailcat on PATH, or set binaryPath in the plugin config. (${errorMessage(error)})`,
|
|
320
|
+
503,
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
void this.loadVersion();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** @private */
|
|
327
|
+
loadVersion() {
|
|
328
|
+
if (this.versionPromise) return this.versionPromise;
|
|
329
|
+
this.versionPromise = (async () => {
|
|
330
|
+
try {
|
|
331
|
+
const result = await this.runCollect([this.binary.resolved, 'version'], 15_000);
|
|
332
|
+
const match = /v?(\d+\.\d+\.\d+)/.exec(`${result.stdout}\n${result.stderr}`);
|
|
333
|
+
if (match) this.binary.version = match[0].startsWith('v') ? match[0] : `v${match[0]}`;
|
|
334
|
+
} catch {
|
|
335
|
+
// A version probe is diagnostic only; serving can still work.
|
|
336
|
+
}
|
|
337
|
+
this.emit();
|
|
338
|
+
})();
|
|
339
|
+
return this.versionPromise;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** @private */
|
|
343
|
+
async ensureKey() {
|
|
344
|
+
this.keyFile = tailcatKeyPath(this.config.keyName);
|
|
345
|
+
if (fs.existsSync(this.keyFile)) return;
|
|
346
|
+
await this.runGenkey(false);
|
|
347
|
+
if (!fs.existsSync(this.keyFile)) {
|
|
348
|
+
throw new RemoteAccessError('key-not-created', `tailcat genkey did not create ${this.keyFile}.`, 500);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* @private
|
|
354
|
+
* @param {boolean} force - overwrite an existing saved key.
|
|
355
|
+
*/
|
|
356
|
+
async runGenkey(force) {
|
|
357
|
+
const argv = buildGenkeyArgs({
|
|
358
|
+
binaryPath: this.binary.resolved ?? this.config.binaryPath,
|
|
359
|
+
keyName: this.config.keyName,
|
|
360
|
+
derpMapUrl: this.config.derpMapUrl,
|
|
361
|
+
force,
|
|
362
|
+
});
|
|
363
|
+
this.logger.info(`tailcat-remote: ${force ? 'rotating' : 'creating'} the saved tailcat key`);
|
|
364
|
+
await this.runCollect(argv, 120_000);
|
|
365
|
+
this.keyFile = tailcatKeyPath(this.config.keyName);
|
|
366
|
+
this.logger.info('tailcat-remote: saved key ready');
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** @private */
|
|
370
|
+
spawnServer() {
|
|
371
|
+
const endpoint = doorEndpoint(this.config);
|
|
372
|
+
if (endpoint.mode === 'socket' && !fs.existsSync(endpoint.socketPath)) {
|
|
373
|
+
throw new RemoteAccessError(
|
|
374
|
+
'door-socket-missing',
|
|
375
|
+
`The door socket ${endpoint.socketPath} does not exist. tailcat cannot start until the door is listening.`,
|
|
376
|
+
503,
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
const allow = this.devices.snapshot().allow;
|
|
380
|
+
const argv = buildServeArgs({
|
|
381
|
+
binaryPath: this.binary.resolved ?? this.config.binaryPath,
|
|
382
|
+
port: this.config.port,
|
|
383
|
+
listen: this.config.listen,
|
|
384
|
+
socketPath: endpoint.mode === 'socket' ? endpoint.socketPath : '',
|
|
385
|
+
keyName: this.config.keyName,
|
|
386
|
+
addressMode: this.config.addressMode,
|
|
387
|
+
allow,
|
|
388
|
+
derpMapUrl: this.config.derpMapUrl,
|
|
389
|
+
logAccess: this.config.logAccess,
|
|
390
|
+
});
|
|
391
|
+
const controller = new AbortController();
|
|
392
|
+
let handle;
|
|
393
|
+
try {
|
|
394
|
+
handle = this.ctx.subprocess.spawn({
|
|
395
|
+
argv,
|
|
396
|
+
cwd: os.homedir(),
|
|
397
|
+
env: childEnv(),
|
|
398
|
+
stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' },
|
|
399
|
+
graceMs: 5_000,
|
|
400
|
+
signal: controller.signal,
|
|
401
|
+
});
|
|
402
|
+
} catch (error) {
|
|
403
|
+
throw new RemoteAccessError('tailcat-spawn-failed', `Could not start tailcat: ${errorMessage(error)}`, 503);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
this.closeStreams();
|
|
407
|
+
this.handle = handle;
|
|
408
|
+
this.abort = controller;
|
|
409
|
+
this.phase = 'starting';
|
|
410
|
+
this.address = null;
|
|
411
|
+
this.onlineAt = null;
|
|
412
|
+
this.lastExit = null;
|
|
413
|
+
this.lastError = null;
|
|
414
|
+
this.startedAt = new Date().toISOString();
|
|
415
|
+
this.keyMode = this.config.addressMode === 'ephemeral' ? 'ephemeral' : 'saved';
|
|
416
|
+
this.stderrLines = [];
|
|
417
|
+
this.openConnections.clear();
|
|
418
|
+
const generation = ++this.generation;
|
|
419
|
+
this.logger.info(
|
|
420
|
+
`tailcat-remote: started tailcat on ${endpoint.mode === 'socket' ? endpoint.socketPath : `127.0.0.1:${endpoint.port}`} (${allow.length > 0 ? `${allow.length} allowed device(s)` : 'address-only'})`,
|
|
421
|
+
);
|
|
422
|
+
|
|
423
|
+
if (handle.stdout) {
|
|
424
|
+
const output = readline.createInterface({ input: handle.stdout, crlfDelay: Infinity });
|
|
425
|
+
output.on('line', (line) => this.onStdout(generation, line));
|
|
426
|
+
this.streams.push(output);
|
|
427
|
+
}
|
|
428
|
+
if (handle.stderr) {
|
|
429
|
+
const errors = readline.createInterface({ input: handle.stderr, crlfDelay: Infinity });
|
|
430
|
+
errors.on('line', (line) => this.onStderr(generation, line));
|
|
431
|
+
this.streams.push(errors);
|
|
432
|
+
}
|
|
433
|
+
handle.done.then(
|
|
434
|
+
(outcome) => this.onExit(generation, outcome),
|
|
435
|
+
(error) => this.onExit(generation, { error }),
|
|
436
|
+
);
|
|
437
|
+
this.emit();
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** @private */
|
|
441
|
+
onStdout(generation, line) {
|
|
442
|
+
if (generation !== this.generation) return;
|
|
443
|
+
const text = line.trim();
|
|
444
|
+
if (!text) return;
|
|
445
|
+
let payload;
|
|
446
|
+
try {
|
|
447
|
+
payload = JSON.parse(text);
|
|
448
|
+
} catch {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (typeof payload?.listenAddr === 'string' && payload.listenAddr.startsWith('tc')) {
|
|
452
|
+
this.markOnline(payload.listenAddr, this.config.addressMode === 'ephemeral' ? 'ephemeral' : 'saved');
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** @private */
|
|
457
|
+
onStderr(generation, line) {
|
|
458
|
+
if (generation !== this.generation) return;
|
|
459
|
+
const text = line.trim();
|
|
460
|
+
if (!text) return;
|
|
461
|
+
this.stderrLines.push(sanitizeLine(text));
|
|
462
|
+
if (this.stderrLines.length > MAX_STDERR_LINES) this.stderrLines.shift();
|
|
463
|
+
|
|
464
|
+
const region = parseRegionLine(text);
|
|
465
|
+
if (region) {
|
|
466
|
+
this.region = region;
|
|
467
|
+
this.emit();
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const address = parseAddressLine(text);
|
|
471
|
+
if (address) this.markOnline(address.address, address.mode);
|
|
472
|
+
|
|
473
|
+
if (text.includes('⚠️')) {
|
|
474
|
+
const warning = sanitizeLine(text.replace(/^#\s*/, ''));
|
|
475
|
+
this.warnings.push(warning);
|
|
476
|
+
if (this.warnings.length > 4) this.warnings.shift();
|
|
477
|
+
this.emit();
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const record = parseAccessLine(text);
|
|
481
|
+
if (!record) return;
|
|
482
|
+
if (record.kind === 'peer' && record.decision === 'refused') {
|
|
483
|
+
this.refusals += 1;
|
|
484
|
+
this.pushRecent({
|
|
485
|
+
kind: 'refused',
|
|
486
|
+
at: new Date().toISOString(),
|
|
487
|
+
peer: record.peer,
|
|
488
|
+
reason: record.reason,
|
|
489
|
+
});
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
if (record.kind !== 'connection') return;
|
|
493
|
+
if (record.event === 'refused') {
|
|
494
|
+
this.pushRecent({
|
|
495
|
+
kind: 'refused',
|
|
496
|
+
at: new Date().toISOString(),
|
|
497
|
+
peer: null,
|
|
498
|
+
reason: 'port-not-served',
|
|
499
|
+
protocol: record.protocol,
|
|
500
|
+
port: record.port,
|
|
501
|
+
service: record.service,
|
|
502
|
+
});
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (record.event === 'open') {
|
|
506
|
+
const key = `${record.peer}|${record.protocol}|${record.port}`;
|
|
507
|
+
if (this.openConnections.size > MAX_CONNECTIONS) this.openConnections.clear();
|
|
508
|
+
this.openConnections.set(key, { at: Date.now(), via: record.via });
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (record.event === 'close') {
|
|
512
|
+
const key = `${record.peer}|${record.protocol}|${record.port}`;
|
|
513
|
+
const opened = this.openConnections.get(key);
|
|
514
|
+
this.openConnections.delete(key);
|
|
515
|
+
this.pushRecent({
|
|
516
|
+
kind: 'connection',
|
|
517
|
+
at: new Date().toISOString(),
|
|
518
|
+
peer: record.peer,
|
|
519
|
+
protocol: record.protocol,
|
|
520
|
+
port: record.port,
|
|
521
|
+
service: record.service,
|
|
522
|
+
via: opened?.via ?? record.via ?? 'unknown',
|
|
523
|
+
durationMs: record.durationMs ?? (opened ? Date.now() - opened.at : null),
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* @private
|
|
530
|
+
* @param {string} address - tailcat server address.
|
|
531
|
+
* @param {'saved' | 'ephemeral'} mode - key provenance.
|
|
532
|
+
*/
|
|
533
|
+
markOnline(address, mode) {
|
|
534
|
+
const changed = this.address !== address;
|
|
535
|
+
this.address = address;
|
|
536
|
+
this.keyMode = mode;
|
|
537
|
+
this.lastError = null;
|
|
538
|
+
this.phase = 'online';
|
|
539
|
+
this.onlineAt = new Date().toISOString();
|
|
540
|
+
if (this.stableTimer) clearTimeout(this.stableTimer);
|
|
541
|
+
this.stableTimer = setTimeout(() => {
|
|
542
|
+
this.restartAttempt = 0;
|
|
543
|
+
this.stableTimer = null;
|
|
544
|
+
}, STABLE_AFTER_MS);
|
|
545
|
+
this.stableTimer.unref?.();
|
|
546
|
+
if (changed) this.logger.info('tailcat-remote: tunnel is online');
|
|
547
|
+
this.emit();
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** @private */
|
|
551
|
+
pushRecent(entry) {
|
|
552
|
+
this.recent.unshift(entry);
|
|
553
|
+
if (this.recent.length > MAX_RECENT) this.recent.length = MAX_RECENT;
|
|
554
|
+
this.emit();
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** @private */
|
|
558
|
+
onExit(generation, outcome) {
|
|
559
|
+
if (generation !== this.generation) return;
|
|
560
|
+
this.closeStreams();
|
|
561
|
+
this.handle = null;
|
|
562
|
+
this.abort = null;
|
|
563
|
+
if (this.stableTimer) {
|
|
564
|
+
clearTimeout(this.stableTimer);
|
|
565
|
+
this.stableTimer = null;
|
|
566
|
+
}
|
|
567
|
+
const desired = this.desired && !this.disposing;
|
|
568
|
+
this.address = null;
|
|
569
|
+
this.onlineAt = null;
|
|
570
|
+
this.nextRestartAt = null;
|
|
571
|
+
if (!desired) {
|
|
572
|
+
this.phase = 'stopped';
|
|
573
|
+
this.lastError = null;
|
|
574
|
+
this.emit();
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
const exit = outcome && 'exitCode' in outcome ? outcome : null;
|
|
578
|
+
const failure = outcome?.error ? errorMessage(outcome.error) : null;
|
|
579
|
+
const detail = failure ?? lastFailureLine(this.stderrLines);
|
|
580
|
+
const code = exit?.exitCode;
|
|
581
|
+
const signal = exit?.signal;
|
|
582
|
+
const exitText =
|
|
583
|
+
code !== undefined && code !== null
|
|
584
|
+
? `tailcat exited with code ${code}`
|
|
585
|
+
: signal
|
|
586
|
+
? `tailcat was terminated by ${signal}`
|
|
587
|
+
: 'tailcat exited';
|
|
588
|
+
this.lastExit = { code: code ?? null, signal: signal ?? null, at: new Date().toISOString() };
|
|
589
|
+
this.lastError = detail ? `${exitText}: ${detail}` : exitText;
|
|
590
|
+
this.phase = 'error';
|
|
591
|
+
this.emit();
|
|
592
|
+
if (!this.config.restartEnabled || this.restartAttempt >= this.config.maxRestartAttempts) {
|
|
593
|
+
this.logger.warn(`tailcat-remote: ${this.lastError}`);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
this.restartAttempt += 1;
|
|
597
|
+
this.restarts += 1;
|
|
598
|
+
const delay = Math.min(
|
|
599
|
+
this.config.restartBaseDelayMs * 2 ** (this.restartAttempt - 1),
|
|
600
|
+
this.config.restartMaxDelayMs,
|
|
601
|
+
);
|
|
602
|
+
this.phase = 'restarting';
|
|
603
|
+
this.nextRestartAt = new Date(Date.now() + delay).toISOString();
|
|
604
|
+
this.logger.warn(`tailcat-remote: ${this.lastError}; retrying in ${delay} ms (attempt ${this.restartAttempt})`);
|
|
605
|
+
this.emit();
|
|
606
|
+
this.restartTimer = setTimeout(() => {
|
|
607
|
+
this.restartTimer = null;
|
|
608
|
+
this.nextRestartAt = null;
|
|
609
|
+
if (!this.desired || this.disposing) return;
|
|
610
|
+
this.start().catch((error) => {
|
|
611
|
+
this.phase = 'error';
|
|
612
|
+
this.lastError = errorMessage(error);
|
|
613
|
+
this.emit();
|
|
614
|
+
});
|
|
615
|
+
}, delay);
|
|
616
|
+
this.restartTimer.unref?.();
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** @private */
|
|
620
|
+
clearRestartTimer() {
|
|
621
|
+
if (this.restartTimer) clearTimeout(this.restartTimer);
|
|
622
|
+
this.restartTimer = null;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** @private */
|
|
626
|
+
closeStreams() {
|
|
627
|
+
for (const stream of this.streams) stream.close();
|
|
628
|
+
this.streams = [];
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* @private
|
|
633
|
+
* @param {string[]} argv - executable and arguments.
|
|
634
|
+
* @param {number} timeoutMs - bound for the whole exchange.
|
|
635
|
+
* @returns {Promise<{ stdout: string, stderr: string, exitCode: number | null, signal: NodeJS.Signals | null }>}
|
|
636
|
+
*/
|
|
637
|
+
async runCollect(argv, timeoutMs) {
|
|
638
|
+
let handle;
|
|
639
|
+
try {
|
|
640
|
+
handle = this.ctx.subprocess.spawn({
|
|
641
|
+
argv,
|
|
642
|
+
cwd: os.homedir(),
|
|
643
|
+
env: childEnv(),
|
|
644
|
+
stdio: {
|
|
645
|
+
stdin: 'ignore',
|
|
646
|
+
stdout: { maxBytes: 64 * 1024 },
|
|
647
|
+
stderr: { maxBytes: 64 * 1024 },
|
|
648
|
+
},
|
|
649
|
+
graceMs: 5_000,
|
|
650
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
651
|
+
});
|
|
652
|
+
} catch (error) {
|
|
653
|
+
throw new RemoteAccessError('tailcat-spawn-failed', `Could not run ${path.basename(argv[0])}: ${errorMessage(error)}`, 503);
|
|
654
|
+
}
|
|
655
|
+
let outcome;
|
|
656
|
+
try {
|
|
657
|
+
outcome = await handle.done;
|
|
658
|
+
} catch (error) {
|
|
659
|
+
throw new RemoteAccessError('tailcat-command-failed', `${path.basename(argv[0])} failed: ${errorMessage(error)}`, 502);
|
|
660
|
+
}
|
|
661
|
+
const stdout = handle.collected.stdout?.readFrom(0).text ?? '';
|
|
662
|
+
const stderr = handle.collected.stderr?.readFrom(0).text ?? '';
|
|
663
|
+
if (outcome.exitCode !== 0) {
|
|
664
|
+
const detail = lastFailureLine([stderr, stdout].filter(Boolean).join('\n'));
|
|
665
|
+
throw new RemoteAccessError(
|
|
666
|
+
'tailcat-command-failed',
|
|
667
|
+
`${path.basename(argv[0])} exited with code ${outcome.exitCode ?? 'null'}${detail ? `: ${detail}` : ''}`,
|
|
668
|
+
502,
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
return { stdout, stderr, exitCode: outcome.exitCode, signal: outcome.signal };
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** Environment needed by tailcat's key path and DERP cache discovery. */
|
|
676
|
+
function childEnv() {
|
|
677
|
+
const env = { HOME: os.homedir() };
|
|
678
|
+
// tailcat resolves saved keys through Go's os.UserConfigDir: XDG on Linux,
|
|
679
|
+
// Application Support on macOS, and %AppData% on Windows. Forward the
|
|
680
|
+
// platform roots it needs, plus the usual temp locations for its caches.
|
|
681
|
+
for (const name of [
|
|
682
|
+
'PATH',
|
|
683
|
+
'APPDATA',
|
|
684
|
+
'LOCALAPPDATA',
|
|
685
|
+
'USERPROFILE',
|
|
686
|
+
'SYSTEMROOT',
|
|
687
|
+
'TEMP',
|
|
688
|
+
'TMP',
|
|
689
|
+
'TMPDIR',
|
|
690
|
+
'XDG_CONFIG_HOME',
|
|
691
|
+
'XDG_CACHE_HOME',
|
|
692
|
+
'XDG_DATA_HOME',
|
|
693
|
+
]) {
|
|
694
|
+
const value = process.env[name];
|
|
695
|
+
if (value) env[name] = value;
|
|
696
|
+
}
|
|
697
|
+
return env;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Choose the most useful diagnostic line from captured stderr.
|
|
702
|
+
* @param {string[]} lines - already sanitized lines.
|
|
703
|
+
* @returns {string | null} last meaningful line.
|
|
704
|
+
*/
|
|
705
|
+
function lastFailureLine(lines) {
|
|
706
|
+
const list = Array.isArray(lines) ? lines : String(lines).split(/\r?\n/);
|
|
707
|
+
for (let index = list.length - 1; index >= 0; index -= 1) {
|
|
708
|
+
const line = list[index].trim();
|
|
709
|
+
if (!line) continue;
|
|
710
|
+
if (line.startsWith('[peer]') || line.startsWith('[conn]')) continue;
|
|
711
|
+
if (line.includes('Server listening with')) continue;
|
|
712
|
+
return line;
|
|
713
|
+
}
|
|
714
|
+
return null;
|
|
715
|
+
}
|