@ds-hu/dsh-tailcat-remote 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.
package/src/parse.js ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Pure parsers and argv builders for the tailcat supervisor, the door, and
3
+ * their tests. Nothing here touches a socket or the Cordis context.
4
+ */
5
+
6
+ /**
7
+ * Parse tailcat's printed listening line.
8
+ * @param {string} line - one stderr line.
9
+ * @returns {{ mode: 'saved' | 'ephemeral', keyName?: string, address: string } | null}
10
+ */
11
+ export function parseAddressLine(line) {
12
+ const match = /Server listening with (?:saved key "([^"]+)"|new address):\s*(\S+)/.exec(line);
13
+ if (!match) return null;
14
+ const address = match[2].trim();
15
+ if (!address.startsWith('tc')) return null;
16
+ return match[1] === undefined
17
+ ? { mode: 'ephemeral', address }
18
+ : { mode: 'saved', keyName: match[1], address };
19
+ }
20
+
21
+ /**
22
+ * Parse the selected bootstrap relay region line.
23
+ * @param {string} line - one stderr line.
24
+ * @returns {{ id: number, name: string } | null}
25
+ */
26
+ export function parseRegionLine(line) {
27
+ const match = /Selected bootstrap relay region (\d+),\s*(.+?)\s*$/.exec(line);
28
+ if (!match) return null;
29
+ return { id: Number(match[1]), name: match[2] };
30
+ }
31
+
32
+ /**
33
+ * Parse one `--log` access record. Lines begin with the standard Go log
34
+ * timestamp; the tagged record is searched anywhere in the line.
35
+ * @param {string} line - one stderr line.
36
+ * @returns {object | null} structured record, or null when the line is not one.
37
+ */
38
+ export function parseAccessLine(line) {
39
+ const match = /\[(peer|conn)\]\s+(allowed|refused|open|close)\b(.*)$/.exec(line);
40
+ if (!match) return null;
41
+ const tag = match[1];
42
+ const event = match[2];
43
+ const fields = {};
44
+ for (const field of match[3].matchAll(/([A-Za-z]+)=([^\s]+)/g)) fields[field[1]] = field[2];
45
+ if (tag === 'peer') {
46
+ return {
47
+ kind: 'peer',
48
+ decision: event,
49
+ peer: fields.key ? sanitizePeer(fields.key) : 'unknown',
50
+ reason: fields.reason ?? null,
51
+ };
52
+ }
53
+ if (event === 'refused') {
54
+ return {
55
+ kind: 'connection',
56
+ event: 'refused',
57
+ peer: null,
58
+ protocol: fields.proto ?? 'tcp',
59
+ port: parsePort(fields.port),
60
+ service: fields.service ?? 'forward',
61
+ };
62
+ }
63
+ return {
64
+ kind: 'connection',
65
+ event,
66
+ peer: fields.peer ? sanitizePeer(fields.peer) : 'unknown',
67
+ protocol: fields.proto ?? 'tcp',
68
+ port: parsePort(fields.port),
69
+ service: fields.service ?? 'forward',
70
+ via: fields.via ?? null,
71
+ durationMs: fields.duration ? parseDurationMs(fields.duration) : null,
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Shorten a node public key for display while keeping enough prefix and
77
+ * suffix to distinguish devices.
78
+ * @param {string} value - full `nodekey:<hex>` value.
79
+ * @returns {string} shortened key.
80
+ */
81
+ export function sanitizePeer(value) {
82
+ const match = /^([a-z]+):([0-9a-fA-F]+)$/.exec(String(value));
83
+ if (!match) return String(value);
84
+ const [, kind, hex] = match;
85
+ if (hex.length <= 16) return `${kind}:${hex}`;
86
+ return `${kind}:${hex.slice(0, 8)}…${hex.slice(-4)}`;
87
+ }
88
+
89
+ /**
90
+ * Parse a Go duration such as `8.104s`, `532ms`, or `1m3.2s`.
91
+ * @param {string} value - duration text.
92
+ * @returns {number | null} milliseconds, or null when unparsable.
93
+ */
94
+ export function parseDurationMs(value) {
95
+ const unit = { ns: 1e-6, 'µs': 1e-3, us: 1e-3, ms: 1, s: 1000, m: 60_000, h: 3_600_000 };
96
+ let total = 0;
97
+ let matched = false;
98
+ for (const part of String(value).matchAll(/(\d+(?:\.\d+)?)(ns|µs|us|ms|s|m|h)/g)) {
99
+ total += Number(part[1]) * unit[part[2]];
100
+ matched = true;
101
+ }
102
+ return matched ? Math.round(total) : null;
103
+ }
104
+
105
+ /**
106
+ * Build the argv for `tailcat serve`. Root flags (`--json`, `--derpmap-url`,
107
+ * `--key`) precede the subcommand; serve flags follow it.
108
+ * @param {object} input - resolved config plus allow-list.
109
+ * @returns {string[]} argv with the executable first.
110
+ */
111
+ export function buildServeArgs(input) {
112
+ const argv = [input.binaryPath, '--json'];
113
+ if (input.derpMapUrl) argv.push(`--derpmap-url=${input.derpMapUrl}`);
114
+ argv.push(`--key=${input.addressMode === 'ephemeral' ? 'new' : input.keyName}`);
115
+ argv.push('serve');
116
+ if (input.logAccess) argv.push('--log');
117
+ const allow = Array.isArray(input.allow) ? input.allow.filter((key) => typeof key === 'string' && key !== '') : [];
118
+ if (allow.length > 0) argv.push(`--allow=${allow.join(',')}`);
119
+ if (input.listen === 'tcp') {
120
+ argv.push(String(input.port));
121
+ } else {
122
+ if (!input.socketPath) throw new Error('buildServeArgs: socketPath is required in socket mode');
123
+ argv.push(`${input.port}:${input.socketPath}`);
124
+ }
125
+ return argv;
126
+ }
127
+
128
+ /**
129
+ * Build the argv for one-shot `tailcat genkey`.
130
+ * @param {{ binaryPath: string, keyName: string, derpMapUrl?: string, force?: boolean }} input - key facts.
131
+ * @returns {string[]} argv with the executable first.
132
+ */
133
+ export function buildGenkeyArgs(input) {
134
+ const argv = [input.binaryPath];
135
+ if (input.derpMapUrl) argv.push(`--derpmap-url=${input.derpMapUrl}`);
136
+ argv.push('genkey');
137
+ if (input.force) argv.push('--force');
138
+ argv.push(`--key=${input.keyName}`, '--fixed-region');
139
+ return argv;
140
+ }
141
+
142
+ /**
143
+ * The command a client machine runs to expose the door on its own loopback.
144
+ * @param {string} address - tailcat server address.
145
+ * @param {number} port - virtual port inside the tunnel.
146
+ * @param {number} [localPort] - local browser port to bind.
147
+ * @returns {string} shell command.
148
+ */
149
+ export function buildForwardCommand(address, port, localPort = 18_080) {
150
+ return `tailcat forward ${address} ${localPort}:${port}`;
151
+ }
152
+
153
+ /**
154
+ * Index of the first byte after the HTTP header block, or -1 when the block
155
+ * is still incomplete.
156
+ * @param {Buffer} buffer - accumulated bytes.
157
+ * @returns {number} body offset.
158
+ */
159
+ export function headerEnd(buffer) {
160
+ const crlf = buffer.indexOf('\r\n\r\n');
161
+ if (crlf !== -1) return crlf + 4;
162
+ const lf = buffer.indexOf('\n\n');
163
+ return lf === -1 ? -1 : lf + 2;
164
+ }
165
+
166
+ /**
167
+ * Parse a raw HTTP/1.x request head. Node's HTTP parser is not involved on
168
+ * the raw door path, so this only needs the request line and header map.
169
+ * @param {Buffer} buffer - bytes containing at least the header block.
170
+ * @returns {{ method: string, target: string, path: string, tokenPresent: boolean, headers: Record<string, string> } | null}
171
+ */
172
+ export function parseRequestHead(buffer) {
173
+ const end = headerEnd(buffer);
174
+ if (end === -1) return null;
175
+ const lines = buffer.subarray(0, end).toString('latin1').split(/\r?\n/);
176
+ const requestLine = lines.shift() ?? '';
177
+ const request = /^(\S+)\s+(\S+)\s+HTTP\/\d(?:\.\d)?$/i.exec(requestLine);
178
+ if (!request) return null;
179
+ const method = request[1].toUpperCase();
180
+ const target = request[2];
181
+ let url;
182
+ try {
183
+ url = new URL(target, 'http://door.invalid');
184
+ } catch {
185
+ return null;
186
+ }
187
+ /** @type {Record<string, string>} */
188
+ const headers = {};
189
+ for (const line of lines) {
190
+ if (!line) continue;
191
+ const colon = line.indexOf(':');
192
+ if (colon <= 0) continue;
193
+ const name = line.slice(0, colon).trim().toLowerCase();
194
+ const value = line.slice(colon + 1).trim();
195
+ if (!name) continue;
196
+ if (headers[name] === undefined) headers[name] = value;
197
+ else if (name === 'cookie') headers[name] = `${headers[name]}; ${value}`;
198
+ else headers[name] = `${headers[name]}, ${value}`;
199
+ }
200
+ return {
201
+ method,
202
+ target,
203
+ path: url.pathname,
204
+ tokenPresent: url.searchParams.has('token'),
205
+ headers,
206
+ };
207
+ }
208
+
209
+ /**
210
+ * Whether a request is the one moment that may exchange the address for a
211
+ * browser session: a top-level GET of `/` without a token parameter.
212
+ * @param {ReturnType<typeof parseRequestHead>} head - parsed request.
213
+ * @returns {boolean} true when the door should consider minting a cookie.
214
+ */
215
+ export function isBootstrapRequest(head) {
216
+ return head !== null && head.method === 'GET' && head.path === '/' && !head.tokenPresent;
217
+ }
218
+
219
+ /**
220
+ * Scrub a tailcat address and node keys out of diagnostics before they reach
221
+ * the Host log or the panel.
222
+ * @param {string} line - raw line.
223
+ * @returns {string} scrubbed, bounded text.
224
+ */
225
+ export function sanitizeLine(line) {
226
+ return String(line)
227
+ .replace(/\btc[A-Za-z0-9+/=_-]{16,}/g, 'tc…')
228
+ .replace(/nodekey:[0-9a-fA-F]{16,}/g, (value) => sanitizePeer(value))
229
+ .trim()
230
+ .slice(0, 500);
231
+ }
232
+
233
+ /**
234
+ * @param {string | undefined} value - port text.
235
+ * @returns {number | null} parsed port.
236
+ */
237
+ function parsePort(value) {
238
+ if (value === undefined || !/^\d+$/.test(value)) return null;
239
+ const port = Number(value);
240
+ return port >= 0 && port <= 65_535 ? port : null;
241
+ }
package/src/paths.js ADDED
@@ -0,0 +1,48 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+
4
+ /** Absolute harness data directory, matching the Host's own DSH_HOME. */
5
+ export function dshHome() {
6
+ const configured = process.env.DSH_HOME?.trim();
7
+ return configured ? path.resolve(configured) : path.join(os.homedir(), '.dsh');
8
+ }
9
+
10
+ /** Plugin-owned runtime-data directory (device allow-list only). */
11
+ export function dataDir() {
12
+ return path.join(dshHome(), 'tailcat-remote');
13
+ }
14
+
15
+ /** Default Unix-domain door socket inside the harness data directory. */
16
+ export function defaultSocketPath() {
17
+ return path.join(dshHome(), 'tailcat-remote.sock');
18
+ }
19
+
20
+ /** The platform user-config directory tailcat uses for saved keys. */
21
+ export function userConfigDir() {
22
+ const configured = process.env.XDG_CONFIG_HOME?.trim();
23
+ return configured ? path.resolve(configured) : path.join(os.homedir(), '.config');
24
+ }
25
+
26
+ /**
27
+ * Resolve a tailcat key name or path to the saved-key file tailcat reads.
28
+ * A name maps to `<user config>/tailcat/keys/<name>.private.json`; a value
29
+ * carrying a separator is treated as a path, matching tailcat's own rule.
30
+ * @param {string} keyName - configured key name or path.
31
+ * @returns {string} absolute key file path.
32
+ */
33
+ export function tailcatKeyPath(keyName) {
34
+ if (keyName.includes('/') || keyName.includes(path.sep)) {
35
+ return path.isAbsolute(keyName) ? keyName : path.resolve(os.homedir(), keyName);
36
+ }
37
+ return path.join(userConfigDir(), 'tailcat', 'keys', `${keyName}.private.json`);
38
+ }
39
+
40
+ /**
41
+ * The local endpoint the door listens on and tailcat maps its virtual port to.
42
+ * @param {{ listen: 'socket' | 'tcp', port: number, socketPath: string }} config - resolved config.
43
+ * @returns {{ mode: 'socket', socketPath: string } | { mode: 'tcp', port: number }} endpoint.
44
+ */
45
+ export function doorEndpoint(config) {
46
+ if (config.listen === 'tcp') return { mode: 'tcp', port: config.port };
47
+ return { mode: 'socket', socketPath: config.socketPath || defaultSocketPath() };
48
+ }
package/src/qr.js ADDED
@@ -0,0 +1,61 @@
1
+ import { qrcode } from '../vendor/qrcode.mjs';
2
+
3
+ /**
4
+ * Encode one ASCII tailcat address as a QR matrix. The generator has no
5
+ * auto-version mode, so try versions from smallest to largest and keep the
6
+ * first that fits. Error-correction level M is the usual screen-scanning
7
+ * compromise for a short URL-like string.
8
+ * @param {string} text - address or other short text.
9
+ * @param {{ maxVersion?: number, errorCorrection?: 'L' | 'M' | 'Q' | 'H' }} [options] - limits.
10
+ * @returns {{ version: number, size: number, rows: string[] }} matrix without a quiet zone.
11
+ */
12
+ export function qrMatrix(text, options = {}) {
13
+ if (typeof text !== 'string' || text.trim() === '') throw new Error('qrMatrix: text must be a non-empty string');
14
+ const maxVersion = Math.min(Math.max(options.maxVersion ?? 20, 1), 40);
15
+ const errorCorrection = options.errorCorrection ?? 'M';
16
+ let lastError;
17
+ for (let version = 1; version <= maxVersion; version += 1) {
18
+ try {
19
+ const qr = qrcode(version, errorCorrection);
20
+ qr.addData(text);
21
+ qr.make();
22
+ const size = qr.getModuleCount();
23
+ const rows = [];
24
+ for (let row = 0; row < size; row += 1) {
25
+ let bits = '';
26
+ for (let column = 0; column < size; column += 1) bits += qr.isDark(row, column) ? '1' : '0';
27
+ rows.push(bits);
28
+ }
29
+ return { version, size, rows };
30
+ } catch (error) {
31
+ lastError = error;
32
+ }
33
+ }
34
+ throw new Error(`qrMatrix: text does not fit QR version ${maxVersion} at level ${errorCorrection}: ${String(lastError)}`);
35
+ }
36
+
37
+ /**
38
+ * Render a matrix as one SVG path command string, including a two-module
39
+ * quiet zone. One path keeps large matrices cheap to mount in React.
40
+ * @param {{ size: number, rows: string[] }} matrix - matrix from {@link qrMatrix}.
41
+ * @param {number} [quietZone] - modules of white border.
42
+ * @returns {{ viewBox: string, path: string }} SVG geometry.
43
+ */
44
+ export function qrSvgGeometry(matrix, quietZone = 2) {
45
+ const total = matrix.size + quietZone * 2;
46
+ let path = '';
47
+ for (let row = 0; row < matrix.rows.length; row += 1) {
48
+ const bits = matrix.rows[row];
49
+ let column = 0;
50
+ while (column < bits.length) {
51
+ if (bits[column] !== '1') {
52
+ column += 1;
53
+ continue;
54
+ }
55
+ const start = column;
56
+ while (column < bits.length && bits[column] === '1') column += 1;
57
+ path += `M${start + quietZone} ${row + quietZone}h${column - start}v1h-${column - start}z`;
58
+ }
59
+ }
60
+ return { viewBox: `0 0 ${total} ${total}`, path };
61
+ }
package/src/remote.js ADDED
@@ -0,0 +1,208 @@
1
+ import fs from 'node:fs';
2
+ import { RemoteAccessError, errorMessage } from './errors.js';
3
+ import { configView } from './config.js';
4
+ import { createDeviceStore } from './devices.js';
5
+ import { Door } from './door.js';
6
+ import { buildForwardCommand } from './parse.js';
7
+ import { qrMatrix } from './qr.js';
8
+ import { TailcatSupervisor } from './tailcat.js';
9
+
10
+ const LOCAL_CLIENT_PORT = 18_080;
11
+ const plugin = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
12
+
13
+ /**
14
+ * Owns the door and the supervisor for one Host plugin instance, and exposes
15
+ * the read model and operations the panel uses. Mutating operations are
16
+ * serialized so two clicks cannot start two tailcat processes.
17
+ */
18
+ export class RemoteAccess {
19
+ /**
20
+ * @param {object} ctx - Host plugin context.
21
+ * @param {ReturnType<import('./config.js').resolveConfig>} config - resolved config.
22
+ */
23
+ constructor(ctx, config) {
24
+ this.ctx = ctx;
25
+ this.config = config;
26
+ this.logger = ctx.logger;
27
+ this.devices = createDeviceStore({ logger: ctx.logger });
28
+ this.tailcat = new TailcatSupervisor(ctx, config, { devices: this.devices, logger: ctx.logger });
29
+ this.door = new Door(ctx, config, ctx.logger);
30
+ this.ops = Promise.resolve();
31
+ this.startPromise = null;
32
+ this.started = false;
33
+ this.disposed = false;
34
+ this.qrCache = null;
35
+ }
36
+
37
+ /** Activate the door, then optionally start the tunnel. */
38
+ start() {
39
+ if (this.startPromise) return this.startPromise;
40
+ this.startPromise = this.enqueue(() => this.activate()).finally(() => {
41
+ this.startPromise = null;
42
+ });
43
+ return this.startPromise;
44
+ }
45
+
46
+ /** @private */
47
+ async activate() {
48
+ if (this.started) return this.snapshot();
49
+ this.started = true;
50
+ try {
51
+ await this.door.start();
52
+ } catch (error) {
53
+ this.door.phase = 'error';
54
+ this.door.lastError = errorMessage(error);
55
+ this.logger.warn(`tailcat-remote: door unavailable: ${errorMessage(error)}`);
56
+ }
57
+ if (this.config.autoStart && this.door.phase === 'listening') {
58
+ try {
59
+ await this.tailcat.start();
60
+ } catch (error) {
61
+ this.logger.warn(`tailcat-remote: tunnel did not start: ${errorMessage(error)}`);
62
+ }
63
+ }
64
+ return this.snapshot();
65
+ }
66
+
67
+ /** Start the tunnel, bringing the door up first if necessary. */
68
+ startTunnel() {
69
+ return this.enqueue(async () => {
70
+ await this.ensureDoor();
71
+ await this.tailcat.start();
72
+ return this.snapshot();
73
+ });
74
+ }
75
+
76
+ /** Stop the tunnel; the door stays bound for a later start. */
77
+ stopTunnel() {
78
+ return this.enqueue(async () => {
79
+ await this.tailcat.stop();
80
+ return this.snapshot();
81
+ });
82
+ }
83
+
84
+ /** Restart the tunnel with the current settings and allow-list. */
85
+ restartTunnel() {
86
+ return this.enqueue(async () => {
87
+ await this.ensureDoor();
88
+ await this.tailcat.restart();
89
+ return this.snapshot();
90
+ });
91
+ }
92
+
93
+ /** Replace the tailcat address and wait until the new server is online. */
94
+ rotateAddress() {
95
+ return this.enqueue(async () => {
96
+ await this.ensureDoor();
97
+ await this.tailcat.rotate();
98
+ return this.snapshot();
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Replace the device allow-list. Persisting the list is the primary
104
+ * operation; a running tunnel is restarted so tailcat applies it. A restart
105
+ * failure leaves the saved list in place and surfaces through status.
106
+ * @param {string[]} allow - canonical or paste-ready keys.
107
+ */
108
+ saveDevices(allow) {
109
+ return this.enqueue(async () => {
110
+ this.devices.replace(allow);
111
+ if (this.tailcat.desired || this.tailcat.handle) {
112
+ try {
113
+ await this.tailcat.restart();
114
+ } catch (error) {
115
+ this.logger.warn(`tailcat-remote: allow-list saved but tailcat did not restart: ${errorMessage(error)}`);
116
+ }
117
+ }
118
+ return this.snapshot();
119
+ });
120
+ }
121
+
122
+ /** Stop both halves and release the plugin's resources. */
123
+ async dispose() {
124
+ this.disposed = true;
125
+ try {
126
+ await this.ops;
127
+ } catch {
128
+ // A rejected operation already surfaced through its caller.
129
+ }
130
+ await this.tailcat.dispose();
131
+ await this.door.stop();
132
+ this.started = false;
133
+ }
134
+
135
+ /** @private */
136
+ async ensureDoor() {
137
+ if (this.door.phase === 'listening') return;
138
+ try {
139
+ await this.door.start();
140
+ } catch (error) {
141
+ this.door.phase = 'error';
142
+ this.door.lastError = errorMessage(error);
143
+ throw error;
144
+ }
145
+ }
146
+
147
+ /** @returns {object} the complete read model sent to the panel. */
148
+ snapshot() {
149
+ const tailcat = this.tailcat.snapshot();
150
+ const pairing = this.pairing(tailcat.address);
151
+ return {
152
+ plugin: { name: plugin.name, version: plugin.version },
153
+ now: new Date().toISOString(),
154
+ web: {
155
+ protocol: this.ctx.webServer.protocol,
156
+ port: this.ctx.webServer.port ?? null,
157
+ },
158
+ config: configView(this.config),
159
+ door: this.door.snapshot(),
160
+ tailcat,
161
+ devices: this.devices.snapshot(),
162
+ pairing,
163
+ safety: {
164
+ allowListEnforced: this.devices.snapshot().enforced,
165
+ rotateRevokesBrowserSessions: false,
166
+ },
167
+ };
168
+ }
169
+
170
+ /** @private */
171
+ pairing(address) {
172
+ if (!address) return null;
173
+ if (this.qrCache?.address !== address) {
174
+ try {
175
+ this.qrCache = { address, matrix: qrMatrix(address) };
176
+ } catch (error) {
177
+ this.logger.warn(`tailcat-remote: could not build the pairing QR: ${errorMessage(error)}`);
178
+ this.qrCache = { address, matrix: null };
179
+ }
180
+ }
181
+ return {
182
+ address,
183
+ port: this.config.port,
184
+ localPort: LOCAL_CLIENT_PORT,
185
+ command: buildForwardCommand(address, this.config.port, LOCAL_CLIENT_PORT),
186
+ qr: this.qrCache.matrix,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * @private
192
+ * @param {() => Promise<unknown>} task - operation.
193
+ * @returns {Promise<unknown>} task result.
194
+ */
195
+ enqueue(task) {
196
+ if (this.disposed) {
197
+ return Promise.reject(new RemoteAccessError('disposed', 'The remote-access runtime is shutting down.', 503));
198
+ }
199
+ const run = this.ops.then(task, task);
200
+ this.ops = run.then(
201
+ () => undefined,
202
+ () => undefined,
203
+ );
204
+ return run;
205
+ }
206
+ }
207
+
208
+ export { RemoteAccessError };