@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/src/door.js ADDED
@@ -0,0 +1,472 @@
1
+ import fs from 'node:fs';
2
+ import net from 'node:net';
3
+ import path from 'node:path';
4
+ import { RemoteAccessError, errorMessage } from './errors.js';
5
+ import { doorEndpoint } from './paths.js';
6
+ import { headerEnd, isBootstrapRequest, parseRequestHead } from './parse.js';
7
+
8
+ const MAX_HEADER_BYTES = 32 * 1024;
9
+ const HEADER_TIMEOUT_MS = 10_000;
10
+ const UPSTREAM_TIMEOUT_MS = 10_000;
11
+ /**
12
+ * Probe an existing Unix socket before taking it over. A socket left by a
13
+ * crash refuses connections; one owned by a live process accepts them.
14
+ * @param {string} socketPath - path from the config.
15
+ * @returns {Promise<boolean>} whether another listener answered.
16
+ */
17
+ function socketIsLive(socketPath) {
18
+ return new Promise((resolve) => {
19
+ let settled = false;
20
+ const probe = net.connect(socketPath);
21
+ const finish = (live) => {
22
+ if (settled) return;
23
+ settled = true;
24
+ clearTimeout(timer);
25
+ probe.destroy();
26
+ resolve(live);
27
+ };
28
+ const timer = setTimeout(() => finish(false), 300);
29
+ timer.unref?.();
30
+ probe.once('connect', () => finish(true));
31
+ probe.once('error', () => finish(false));
32
+ });
33
+ }
34
+
35
+ const STATUS_TEXT = {
36
+ 303: 'See Other',
37
+ 400: 'Bad Request',
38
+ 403: 'Forbidden',
39
+ 408: 'Request Timeout',
40
+ 413: 'Payload Too Large',
41
+ 431: 'Request Header Fields Too Large',
42
+ 500: 'Internal Server Error',
43
+ 502: 'Bad Gateway',
44
+ 503: 'Service Unavailable',
45
+ 504: 'Gateway Timeout',
46
+ };
47
+
48
+ /**
49
+ * The tailnet-only door. tailcat maps its virtual port onto this local
50
+ * endpoint; the door lets a peer with the tailcat address exchange that
51
+ * address for the ordinary DSH browser session cookie. Every other request
52
+ * (assets, API, WebSocket upgrades) is a raw byte splice to the real Web
53
+ * listener, preserving the Host header and the bytes on the wire.
54
+ */
55
+ export class Door {
56
+ /**
57
+ * @param {object} ctx - Host plugin context.
58
+ * @param {ReturnType<import('./config.js').resolveConfig>} config - resolved config.
59
+ * @param {any} logger - Host logger.
60
+ */
61
+ constructor(ctx, config, logger) {
62
+ this.ctx = ctx;
63
+ this.config = config;
64
+ this.logger = logger;
65
+ this.endpoint = doorEndpoint(config);
66
+ this.server = null;
67
+ this.sockets = new Set();
68
+ this.phase = 'stopped';
69
+ this.lastError = null;
70
+ this.createdSocket = false;
71
+ this.disposed = false;
72
+ }
73
+
74
+ /** Bind the local endpoint and start accepting tailcat connections. */
75
+ async start() {
76
+ if (this.server) return;
77
+ this.disposed = false;
78
+ const web = this.ctx.webServer;
79
+ if (web.protocol !== 'http:') {
80
+ throw new RemoteAccessError(
81
+ 'door-tls-unsupported',
82
+ 'The door requires a plain-HTTP Web listener. The current listener serves HTTPS, so the DSH browser cookie could not be replayed through tailcat.',
83
+ 409,
84
+ );
85
+ }
86
+ await this.waitForWebPort();
87
+ this.lastError = null;
88
+ this.phase = 'starting';
89
+ if (this.endpoint.mode === 'socket') await this.prepareSocket();
90
+ const server = net.createServer((socket) => this.accept(socket));
91
+ this.server = server;
92
+ server.on('error', (error) => {
93
+ this.lastError = errorMessage(error);
94
+ this.logger.warn(`tailcat-remote: door error: ${this.lastError}`);
95
+ });
96
+ try {
97
+ await new Promise((resolve, reject) => {
98
+ const onError = (error) => reject(error);
99
+ server.once('error', onError);
100
+ const listenOptions =
101
+ this.endpoint.mode === 'socket'
102
+ ? { path: this.endpoint.socketPath }
103
+ : { host: '127.0.0.1', port: this.endpoint.port };
104
+ server.listen(listenOptions, () => {
105
+ server.off('error', onError);
106
+ resolve();
107
+ });
108
+ });
109
+ } catch (error) {
110
+ this.server = null;
111
+ try {
112
+ server.close();
113
+ } catch {
114
+ // The listener never bound; closing is best-effort.
115
+ }
116
+ this.phase = 'error';
117
+ this.lastError = errorMessage(error);
118
+ this.removeSocket();
119
+ throw new RemoteAccessError(
120
+ 'door-listen-failed',
121
+ `Could not start the tailcat door on ${
122
+ this.endpoint.mode === 'socket' ? this.endpoint.socketPath : `127.0.0.1:${this.endpoint.port}`
123
+ }: ${errorMessage(error)}`,
124
+ 503,
125
+ );
126
+ }
127
+ if (this.endpoint.mode === 'socket') {
128
+ try {
129
+ fs.chmodSync(this.endpoint.socketPath, 0o600);
130
+ } catch (error) {
131
+ this.logger.warn(`tailcat-remote: could not restrict the door socket mode: ${errorMessage(error)}`);
132
+ }
133
+ }
134
+ this.phase = 'listening';
135
+ this.logger.info(
136
+ `tailcat-remote: door listening on ${
137
+ this.endpoint.mode === 'socket' ? this.endpoint.socketPath : `127.0.0.1:${this.endpoint.port}`
138
+ }`,
139
+ );
140
+ }
141
+
142
+ /** Stop accepting connections and remove the owned Unix socket. */
143
+ async stop() {
144
+ const server = this.server;
145
+ this.server = null;
146
+ for (const socket of this.sockets) socket.destroy();
147
+ this.sockets.clear();
148
+ if (server) {
149
+ await new Promise((resolve) => {
150
+ let settled = false;
151
+ const done = () => {
152
+ if (settled) return;
153
+ settled = true;
154
+ resolve();
155
+ };
156
+ try {
157
+ server.close(done);
158
+ } catch {
159
+ done();
160
+ }
161
+ });
162
+ }
163
+ this.removeSocket();
164
+ this.phase = 'stopped';
165
+ }
166
+
167
+ /** @returns {object} display-safe state. */
168
+ snapshot() {
169
+ const target = this.targetOrNull();
170
+ return {
171
+ phase: this.phase,
172
+ listening: this.phase === 'listening',
173
+ mode: this.endpoint.mode,
174
+ socketPath: this.endpoint.mode === 'socket' ? this.endpoint.socketPath : null,
175
+ port: this.endpoint.mode === 'tcp' ? this.endpoint.port : null,
176
+ target,
177
+ lastError: this.lastError,
178
+ };
179
+ }
180
+
181
+ /** @private */
182
+ async waitForWebPort() {
183
+ const deadline = Date.now() + 20_000;
184
+ while (this.ctx.webServer.port === undefined) {
185
+ if (this.disposed) throw new RemoteAccessError('disposed', 'The remote-access runtime is shutting down.');
186
+ if (Date.now() > deadline) {
187
+ throw new RemoteAccessError(
188
+ 'web-not-listening',
189
+ 'The Web listener did not report a port within 20 seconds; the tailcat door cannot start.',
190
+ 503,
191
+ );
192
+ }
193
+ await new Promise((resolve) => {
194
+ const timer = setTimeout(resolve, 50);
195
+ timer.unref?.();
196
+ });
197
+ }
198
+ }
199
+
200
+ /** @private */
201
+ async prepareSocket() {
202
+ const socketPath = this.endpoint.socketPath;
203
+ const existing = fs.lstatSync(socketPath, { throwIfNoEntry: false });
204
+ if (existing) {
205
+ if (!existing.isSocket()) {
206
+ throw new RemoteAccessError(
207
+ 'door-path-occupied',
208
+ `The configured door path ${socketPath} exists and is not a Unix socket; refusing to remove it.`,
209
+ 409,
210
+ );
211
+ }
212
+ if (await socketIsLive(socketPath)) {
213
+ throw new RemoteAccessError(
214
+ 'door-in-use',
215
+ `Another process is already accepting connections on ${socketPath}; refusing to remove its door socket.`,
216
+ 409,
217
+ );
218
+ }
219
+ fs.unlinkSync(socketPath);
220
+ }
221
+ const parent = path.dirname(socketPath);
222
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
223
+ this.createdSocket = true;
224
+ }
225
+
226
+ /** @private */
227
+ removeSocket() {
228
+ if (!this.createdSocket || this.endpoint.mode !== 'socket') return;
229
+ this.createdSocket = false;
230
+ try {
231
+ fs.unlinkSync(this.endpoint.socketPath);
232
+ } catch (error) {
233
+ if (error?.code !== 'ENOENT') {
234
+ this.logger.warn(`tailcat-remote: could not remove the door socket: ${errorMessage(error)}`);
235
+ }
236
+ }
237
+ }
238
+
239
+ /** @private */
240
+ accept(socket) {
241
+ this.sockets.add(socket);
242
+ socket.on('close', () => this.sockets.delete(socket));
243
+ socket.on('error', () => socket.destroy());
244
+ socket.setNoDelay(true);
245
+ socket.pause();
246
+
247
+ const chunks = [];
248
+ let size = 0;
249
+ let settled = false;
250
+ const settle = () => {
251
+ if (settled) return;
252
+ settled = true;
253
+ clearTimeout(timer);
254
+ socket.off('data', onData);
255
+ socket.pause();
256
+ };
257
+ const onData = (chunk) => {
258
+ chunks.push(chunk);
259
+ size += chunk.length;
260
+ const buffer = Buffer.concat(chunks, size);
261
+ if (headerEnd(buffer) !== -1) {
262
+ settle();
263
+ this.dispatch(socket, buffer);
264
+ return;
265
+ }
266
+ if (size > MAX_HEADER_BYTES) {
267
+ settle();
268
+ this.respond(socket, 431, 'Request header fields too large\n');
269
+ }
270
+ };
271
+ const onClose = () => {
272
+ settle();
273
+ };
274
+ const timer = setTimeout(() => {
275
+ if (settled) return;
276
+ settle();
277
+ this.respond(socket, 408, 'Request timed out\n');
278
+ }, HEADER_TIMEOUT_MS);
279
+ timer.unref?.();
280
+ socket.on('data', onData);
281
+ socket.on('close', onClose);
282
+ socket.resume();
283
+ }
284
+
285
+ /** @private */
286
+ dispatch(socket, buffer) {
287
+ const head = parseRequestHead(buffer);
288
+ if (!head) {
289
+ this.respond(socket, 400, 'Bad request\n');
290
+ return;
291
+ }
292
+ if (!isBootstrapRequest(head)) {
293
+ this.splice(socket, buffer);
294
+ return;
295
+ }
296
+ let rejection;
297
+ try {
298
+ rejection = this.ctx.connection.requestRejection({
299
+ method: head.method,
300
+ url: head.target,
301
+ headers: head.headers,
302
+ });
303
+ } catch (error) {
304
+ this.logger.warn(`tailcat-remote: door trust check failed: ${errorMessage(error)}`);
305
+ this.respond(socket, 400, 'Bad request\n');
306
+ return;
307
+ }
308
+ if (rejection === 403) {
309
+ this.respond(socket, 403, 'Forbidden\n');
310
+ return;
311
+ }
312
+ if (rejection === undefined) {
313
+ this.splice(socket, buffer);
314
+ return;
315
+ }
316
+ if (rejection !== 401) {
317
+ this.respond(socket, 400, 'Bad request\n');
318
+ return;
319
+ }
320
+ this.mintCookie(socket, head);
321
+ }
322
+
323
+ /** @private */
324
+ mintCookie(socket, head) {
325
+ if (!head.headers.host) {
326
+ this.respond(socket, 400, 'Bad request\n');
327
+ return;
328
+ }
329
+ let token;
330
+ try {
331
+ token = this.launchToken();
332
+ } catch (error) {
333
+ this.logger.warn(`tailcat-remote: could not read the launch token: ${errorMessage(error)}`);
334
+ this.respond(socket, 500, 'Internal error\n');
335
+ return;
336
+ }
337
+ const capture = {
338
+ status: 0,
339
+ headers: {},
340
+ body: Buffer.alloc(0),
341
+ writeHead(status, headers) {
342
+ this.status = status;
343
+ this.headers = headers && typeof headers === 'object' ? headers : {};
344
+ },
345
+ end(chunk) {
346
+ if (chunk !== undefined && chunk !== null) this.body = Buffer.from(chunk);
347
+ },
348
+ };
349
+ try {
350
+ const authenticated = this.ctx.connection.authorizeIndex(
351
+ { method: 'GET', url: `/?token=${encodeURIComponent(token)}`, headers: { host: head.headers.host } },
352
+ capture,
353
+ );
354
+ if (authenticated) {
355
+ this.respond(socket, 401, 'Unauthorized\n');
356
+ return;
357
+ }
358
+ } catch (error) {
359
+ this.logger.warn(`tailcat-remote: door cookie mint failed: ${errorMessage(error)}`);
360
+ this.respond(socket, 500, 'Internal error\n');
361
+ return;
362
+ }
363
+ if (capture.status !== 303) {
364
+ this.respond(socket, 401, 'Unauthorized\n');
365
+ return;
366
+ }
367
+ const lines = [`HTTP/1.1 303 ${STATUS_TEXT[303]}`];
368
+ for (const [name, value] of Object.entries(capture.headers)) {
369
+ const lower = name.toLowerCase();
370
+ if (lower === 'content-length' || lower === 'connection') continue;
371
+ if (Array.isArray(value)) {
372
+ for (const item of value) lines.push(`${name}: ${item}`);
373
+ } else {
374
+ lines.push(`${name}: ${value}`);
375
+ }
376
+ }
377
+ lines.push('content-length: 0', 'connection: close');
378
+ socket.end(`${lines.join('\r\n')}\r\n\r\n`);
379
+ }
380
+
381
+ /** @private */
382
+ launchToken() {
383
+ this.cachedToken ??= new URL(this.ctx.connection.authenticatedUrl('http://door.invalid/')).searchParams.get('token');
384
+ if (!this.cachedToken) throw new Error('the Connection service did not publish a launch token');
385
+ return this.cachedToken;
386
+ }
387
+
388
+ /** @private */
389
+ splice(socket, buffer) {
390
+ let target;
391
+ try {
392
+ target = this.target();
393
+ } catch (error) {
394
+ this.respond(socket, 503, 'Service unavailable\n');
395
+ this.logger.warn(`tailcat-remote: ${errorMessage(error)}`);
396
+ return;
397
+ }
398
+ const upstream = net.connect({ host: target.host, port: target.port, allowHalfOpen: false });
399
+ let connected = false;
400
+ upstream.setNoDelay?.(true);
401
+ const timer = setTimeout(() => {
402
+ if (connected) return;
403
+ upstream.destroy();
404
+ this.respond(socket, 504, 'Upstream timed out\n');
405
+ }, UPSTREAM_TIMEOUT_MS);
406
+ timer.unref?.();
407
+ upstream.once('connect', () => {
408
+ connected = true;
409
+ clearTimeout(timer);
410
+ upstream.setNoDelay(true);
411
+ upstream.write(buffer);
412
+ socket.resume();
413
+ socket.pipe(upstream);
414
+ upstream.pipe(socket);
415
+ });
416
+ upstream.on('error', (error) => {
417
+ clearTimeout(timer);
418
+ if (!connected) {
419
+ this.logger.warn(`tailcat-remote: door upstream failed: ${errorMessage(error)}`);
420
+ this.respond(socket, 502, 'Bad gateway\n');
421
+ } else {
422
+ socket.destroy();
423
+ }
424
+ });
425
+ upstream.on('close', () => clearTimeout(timer));
426
+ socket.on('close', () => {
427
+ clearTimeout(timer);
428
+ upstream.destroy();
429
+ });
430
+ socket.on('error', () => {
431
+ clearTimeout(timer);
432
+ upstream.destroy();
433
+ });
434
+ }
435
+
436
+ /** @private */
437
+ target() {
438
+ const web = this.ctx.webServer;
439
+ if (web.port === undefined) throw new RemoteAccessError('web-not-listening', 'The Web listener has no port.');
440
+ let host = web.host;
441
+ if (host === '0.0.0.0') host = '127.0.0.1';
442
+ else if (host === '::') host = '::1';
443
+ return { host, port: web.port };
444
+ }
445
+
446
+ /** @private */
447
+ targetOrNull() {
448
+ try {
449
+ return this.target();
450
+ } catch {
451
+ return null;
452
+ }
453
+ }
454
+
455
+ /** @private */
456
+ respond(socket, status, body) {
457
+ if (socket.destroyed || !socket.writable) {
458
+ socket.destroy();
459
+ return;
460
+ }
461
+ const payload = Buffer.from(body);
462
+ socket.end(
463
+ `HTTP/1.1 ${status} ${STATUS_TEXT[status] ?? 'Error'}\r\n` +
464
+ 'content-type: text/plain; charset=utf-8\r\n' +
465
+ 'cache-control: no-store\r\n' +
466
+ 'referrer-policy: no-referrer\r\n' +
467
+ `content-length: ${payload.length}\r\n` +
468
+ 'connection: close\r\n\r\n' +
469
+ payload.toString('utf8'),
470
+ );
471
+ }
472
+ }
package/src/errors.js ADDED
@@ -0,0 +1,24 @@
1
+ /** Errors that cross the control API with a stable code and HTTP status. */
2
+ export class RemoteAccessError extends Error {
3
+ /**
4
+ * @param {string} code - machine-readable reason.
5
+ * @param {string} message - operator-facing text.
6
+ * @param {number} [status] - HTTP status the control route should return.
7
+ */
8
+ constructor(code, message, status = 500) {
9
+ super(message);
10
+ this.name = 'RemoteAccessError';
11
+ this.code = code;
12
+ this.status = status;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Normalize any thrown value into an operator-facing message.
18
+ * @param {unknown} error - thrown value.
19
+ * @returns {string} text safe to show in the panel.
20
+ */
21
+ export function errorMessage(error) {
22
+ if (error instanceof Error && error.message) return error.message;
23
+ return String(error);
24
+ }