@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/config.js ADDED
@@ -0,0 +1,126 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+
3
+ /** Virtual port tailcat exposes to clients. */
4
+ export const DEFAULT_PORT = 13080;
5
+
6
+ /**
7
+ * Host config. Every field is optional; the defaults describe the secure
8
+ * common case: a Unix-socket door under DSH_HOME, a saved stable key, and no
9
+ * device-key allow-list (the address stays the only credential).
10
+ */
11
+ export const Config = z.object({
12
+ binaryPath: z
13
+ .string()
14
+ .default('tailcat')
15
+ .description('The tailcat executable: a PATH name or an absolute path. The panel reports it when it cannot be found.'),
16
+ port: z
17
+ .natural()
18
+ .min(1)
19
+ .max(65535)
20
+ .default(DEFAULT_PORT)
21
+ .description('Virtual port inside the tailcat tunnel. Clients reach the Harness on this port; it is not opened on this machine.'),
22
+ listen: z
23
+ .union([z.const('socket'), z.const('tcp')])
24
+ .default('socket')
25
+ .description(
26
+ 'Where the door listens locally. socket creates a 0600 Unix socket under DSH_HOME and is reachable only by tailcat. tcp binds 127.0.0.1 and is also reachable by any local process; use it only when a socket cannot be used.',
27
+ ),
28
+ socketPath: z
29
+ .string()
30
+ .default('')
31
+ .description('Door socket path when listen is socket. Empty uses $DSH_HOME/tailcat-remote.sock.'),
32
+ keyName: z
33
+ .string()
34
+ .default('dsh-tailcat')
35
+ .description('Saved tailcat server-key name (or a path containing a slash). A saved key keeps the tailcat address stable across restarts.'),
36
+ addressMode: z
37
+ .union([z.const('stable'), z.const('ephemeral')])
38
+ .default('stable')
39
+ .description(
40
+ 'stable uses the saved key and keeps the address until you rotate it. ephemeral asks tailcat for a new key on every start, so the address changes after every restart.',
41
+ ),
42
+ derpMapUrl: z
43
+ .string()
44
+ .default('')
45
+ .description('Custom DERP map URL. Empty uses the tailcat default.'),
46
+ autoStart: z.boolean().default(true).description('Start the tunnel when the Host plugin activates.'),
47
+ logAccess: z
48
+ .boolean()
49
+ .default(true)
50
+ .description('Ask tailcat for its access log so the panel can show recent connections and refusals.'),
51
+ restartEnabled: z.boolean().default(true).description('Restart tailcat after an unexpected exit.'),
52
+ maxRestartAttempts: z.natural().min(0).max(100).default(10).description('Consecutive automatic restart attempts before the tunnel stays stopped in the error state.'),
53
+ restartBaseDelayMs: z.natural().min(100).max(60_000).default(500).description('First restart delay in milliseconds; later attempts double it.'),
54
+ restartMaxDelayMs: z.natural().min(1_000).max(600_000).default(30_000).description('Upper bound for one automatic restart delay in milliseconds.'),
55
+ });
56
+
57
+ /**
58
+ * Turn a validated (or absent) config into the normalized shape the runtime
59
+ * reads. Kept independent from the schema so a malformed row still produces
60
+ * safe defaults instead of throwing during activation.
61
+ * @param {Partial<import('@deepseek-ai/schemastery').Schema>} [input] - raw config.
62
+ * @returns {object} resolved config.
63
+ */
64
+ export function resolveConfig(input) {
65
+ const value = input && typeof input === 'object' ? input : {};
66
+ const port = Number.isInteger(value.port) && value.port >= 1 && value.port <= 65535 ? value.port : DEFAULT_PORT;
67
+ const maxRestartAttempts =
68
+ Number.isInteger(value.maxRestartAttempts) && value.maxRestartAttempts >= 0
69
+ ? Math.min(value.maxRestartAttempts, 100)
70
+ : 10;
71
+ const restartBaseDelayMs =
72
+ Number.isInteger(value.restartBaseDelayMs) && value.restartBaseDelayMs >= 100
73
+ ? Math.min(value.restartBaseDelayMs, 60_000)
74
+ : 500;
75
+ const restartMaxDelayMs =
76
+ Number.isInteger(value.restartMaxDelayMs) && value.restartMaxDelayMs >= 1_000
77
+ ? Math.min(value.restartMaxDelayMs, 600_000)
78
+ : 30_000;
79
+
80
+ return {
81
+ binaryPath: nonEmpty(value.binaryPath) ?? 'tailcat',
82
+ port,
83
+ listen: value.listen === 'tcp' ? 'tcp' : 'socket',
84
+ socketPath: nonEmpty(value.socketPath) ?? '',
85
+ keyName: nonEmpty(value.keyName) ?? 'dsh-tailcat',
86
+ addressMode: value.addressMode === 'ephemeral' ? 'ephemeral' : 'stable',
87
+ derpMapUrl: nonEmpty(value.derpMapUrl) ?? '',
88
+ autoStart: value.autoStart !== false,
89
+ logAccess: value.logAccess !== false,
90
+ restartEnabled: value.restartEnabled !== false,
91
+ maxRestartAttempts,
92
+ restartBaseDelayMs,
93
+ restartMaxDelayMs: Math.max(restartBaseDelayMs, restartMaxDelayMs),
94
+ };
95
+ }
96
+
97
+ /**
98
+ * The subset of settings the panel may show. No key material, no resolved
99
+ * private paths, no address.
100
+ * @param {ReturnType<typeof resolveConfig>} config - resolved config.
101
+ * @returns {object} display-safe settings.
102
+ */
103
+ export function configView(config) {
104
+ return {
105
+ binaryPath: config.binaryPath,
106
+ port: config.port,
107
+ listen: config.listen,
108
+ keyName: config.keyName,
109
+ addressMode: config.addressMode,
110
+ autoStart: config.autoStart,
111
+ logAccess: config.logAccess,
112
+ restartEnabled: config.restartEnabled,
113
+ maxRestartAttempts: config.maxRestartAttempts,
114
+ restartBaseDelayMs: config.restartBaseDelayMs,
115
+ restartMaxDelayMs: config.restartMaxDelayMs,
116
+ customDerpMap: config.derpMapUrl !== '',
117
+ };
118
+ }
119
+
120
+ /**
121
+ * @param {unknown} value - candidate.
122
+ * @returns {string | undefined} trimmed non-empty text.
123
+ */
124
+ function nonEmpty(value) {
125
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
126
+ }
package/src/control.js ADDED
@@ -0,0 +1,81 @@
1
+ import { RemoteAccessError, errorMessage } from './errors.js';
2
+
3
+ /** Exact authenticated Fetch route owned by this plugin. */
4
+ export const ROUTE = '/api/tailcat-remote';
5
+
6
+ const MAX_BODY_BYTES = 64 * 1024;
7
+ const HEADERS = {
8
+ 'cache-control': 'no-store',
9
+ 'content-type': 'application/json; charset=utf-8',
10
+ 'referrer-policy': 'no-referrer',
11
+ 'x-content-type-options': 'nosniff',
12
+ };
13
+
14
+ /**
15
+ * Register the owner-only control route.
16
+ * @param {object} ctx - Host plugin context.
17
+ * @param {import('./remote.js').RemoteAccess} remote - runtime.
18
+ * @returns {() => void} route disposer.
19
+ */
20
+ export function registerControl(ctx, remote) {
21
+ return ctx.connection.fetch.register({
22
+ path: ROUTE,
23
+ methods: ['GET', 'POST'],
24
+ requestBody: 'buffered',
25
+ fetch: async (request) => {
26
+ try {
27
+ if (request.method === 'GET') return json({ ok: true, ...remote.snapshot() });
28
+ if (request.method !== 'POST') return json({ ok: false, error: { code: 'method', message: 'Use GET or POST.' } }, 405);
29
+ const text = await request.text();
30
+ if (Buffer.byteLength(text, 'utf8') > MAX_BODY_BYTES) {
31
+ return json({ ok: false, error: { code: 'body-too-large', message: 'Request body is too large.' } }, 413);
32
+ }
33
+ let body;
34
+ try {
35
+ body = JSON.parse(text);
36
+ } catch {
37
+ return json({ ok: false, error: { code: 'invalid-json', message: 'Request body must be JSON.' } }, 400);
38
+ }
39
+ const action = body?.action;
40
+ let result;
41
+ switch (action) {
42
+ case 'start':
43
+ result = await remote.startTunnel();
44
+ break;
45
+ case 'stop':
46
+ result = await remote.stopTunnel();
47
+ break;
48
+ case 'restart':
49
+ result = await remote.restartTunnel();
50
+ break;
51
+ case 'rotate':
52
+ result = await remote.rotateAddress();
53
+ break;
54
+ case 'devices':
55
+ result = await remote.saveDevices(body.allow);
56
+ break;
57
+ default:
58
+ return json(
59
+ { ok: false, error: { code: 'unknown-action', message: `Unknown action ${JSON.stringify(action)}.` } },
60
+ 400,
61
+ );
62
+ }
63
+ return json({ ok: true, ...result });
64
+ } catch (error) {
65
+ const status = error instanceof RemoteAccessError ? error.status : 500;
66
+ const code = error instanceof RemoteAccessError ? error.code : 'internal';
67
+ if (status >= 500) ctx.logger.warn(`tailcat-remote: control action failed: ${errorMessage(error)}`);
68
+ return json({ ok: false, error: { code, message: errorMessage(error) } }, status);
69
+ }
70
+ },
71
+ });
72
+ }
73
+
74
+ /**
75
+ * @param {object} data - JSON payload.
76
+ * @param {number} [status] - HTTP status.
77
+ * @returns {Response} JSON response.
78
+ */
79
+ function json(data, status = 200) {
80
+ return new Response(JSON.stringify(data), { status, headers: HEADERS });
81
+ }
package/src/devices.js ADDED
@@ -0,0 +1,153 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { dataDir } from './paths.js';
4
+ import { RemoteAccessError } from './errors.js';
5
+
6
+ /** A tailcat client identity public key: `nodekey:` plus 32 bytes of hex. */
7
+ const NODE_KEY = /^nodekey:[0-9a-fA-F]{64}$/;
8
+
9
+ /**
10
+ * Normalize one pasted key to canonical lower-case `nodekey:<hex>` form.
11
+ * A bare 64-character hex string is accepted because that is what a key file
12
+ * or a shortened CLI output may show.
13
+ * @param {unknown} value - pasted key.
14
+ * @returns {string} canonical key.
15
+ * @throws {RemoteAccessError} when the value is not a tailcat node public key.
16
+ */
17
+ export function normalizeDeviceKey(value) {
18
+ if (typeof value !== 'string') {
19
+ throw new RemoteAccessError('invalid-device-key', 'Each allowed device must be a nodekey string.', 400);
20
+ }
21
+ const trimmed = value.trim();
22
+ const lower = trimmed.toLowerCase();
23
+ const hex = lower.startsWith('nodekey:') ? lower.slice('nodekey:'.length) : trimmed;
24
+ if (!/^[0-9a-fA-F]{64}$/.test(hex)) {
25
+ throw new RemoteAccessError(
26
+ 'invalid-device-key',
27
+ `Not a tailcat node public key: ${trimmed.slice(0, 24)}${trimmed.length > 24 ? '…' : ''}. Expected nodekey: followed by 64 hex characters.`,
28
+ 400,
29
+ );
30
+ }
31
+ return `nodekey:${hex.toLowerCase()}`;
32
+ }
33
+
34
+ /**
35
+ * One line per key, ignoring blank lines and `#` comments.
36
+ * @param {string} text - textarea contents.
37
+ * @returns {string[]} canonical keys.
38
+ */
39
+ export function parseDeviceKeys(text) {
40
+ const keys = [];
41
+ for (const raw of String(text).split(/\r?\n/)) {
42
+ const line = raw.trim();
43
+ if (line === '' || line.startsWith('#')) continue;
44
+ keys.push(normalizeDeviceKey(line));
45
+ }
46
+ return [...new Set(keys)];
47
+ }
48
+
49
+ /**
50
+ * The durable allow-list of tailcat client keys. Address-only mode is the
51
+ * empty list; a non-empty list becomes `tailcat serve --allow=...`.
52
+ * @param {{ dir?: string, logger?: { warn: (...args: any[]) => void } }} [options] - test/overrides.
53
+ */
54
+ export function createDeviceStore(options = {}) {
55
+ const dir = options.dir ?? dataDir();
56
+ const file = path.join(dir, 'devices.json');
57
+ const logger = options.logger;
58
+ /** @type {string[]} */
59
+ let allow = [];
60
+ /** @type {string[]} */
61
+ let warnings = [];
62
+ let updatedAt = null;
63
+
64
+ load();
65
+
66
+ /** Read the durable document, tolerating absence and dropping invalid rows. */
67
+ function load() {
68
+ allow = [];
69
+ warnings = [];
70
+ let text;
71
+ try {
72
+ text = fs.readFileSync(file, 'utf8');
73
+ } catch (error) {
74
+ if (error && error.code === 'ENOENT') return;
75
+ warnings.push(`Could not read the device allow-list: ${messageOf(error)}`);
76
+ logger?.warn(`tailcat-remote: ${warnings.at(-1)}`);
77
+ return;
78
+ }
79
+ let document;
80
+ try {
81
+ document = JSON.parse(text);
82
+ } catch {
83
+ warnings.push('The device allow-list file is not valid JSON; starting in address-only mode.');
84
+ logger?.warn(`tailcat-remote: ${warnings.at(-1)}`);
85
+ return;
86
+ }
87
+ const rows = Array.isArray(document) ? document : Array.isArray(document?.allow) ? document.allow : null;
88
+ if (rows === null) {
89
+ warnings.push('The device allow-list file has an unknown shape; starting in address-only mode.');
90
+ logger?.warn(`tailcat-remote: ${warnings.at(-1)}`);
91
+ return;
92
+ }
93
+ for (const row of rows) {
94
+ try {
95
+ allow.push(normalizeDeviceKey(row));
96
+ } catch {
97
+ warnings.push('Ignored an invalid key in the device allow-list.');
98
+ }
99
+ }
100
+ allow = [...new Set(allow)];
101
+ updatedAt = typeof document?.updatedAt === 'string' ? document.updatedAt : null;
102
+ if (warnings.length > 0) logger?.warn(`tailcat-remote: ${warnings.join(' ')}`);
103
+ }
104
+
105
+ /**
106
+ * Replace the whole allow-list durably and return the canonical values.
107
+ * @param {string[]} values - keys from the panel or API.
108
+ * @returns {string[]} canonical unique keys.
109
+ * @throws {RemoteAccessError} when any key is invalid or persistence fails.
110
+ */
111
+ function replace(values) {
112
+ if (!Array.isArray(values)) {
113
+ throw new RemoteAccessError('invalid-device-list', 'allow must be an array of nodekey strings.', 400);
114
+ }
115
+ const keys = [...new Set(values.map(normalizeDeviceKey))];
116
+ const document = {
117
+ version: 1,
118
+ allow: keys,
119
+ updatedAt: new Date().toISOString(),
120
+ };
121
+ try {
122
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
123
+ const temporary = path.join(dir, `.devices.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`);
124
+ fs.writeFileSync(temporary, `${JSON.stringify(document, null, 2)}\n`, { mode: 0o600 });
125
+ fs.renameSync(temporary, file);
126
+ fs.chmodSync(file, 0o600);
127
+ } catch (error) {
128
+ throw new RemoteAccessError('device-store-write-failed', `Could not save the device allow-list: ${messageOf(error)}`);
129
+ }
130
+ allow = keys;
131
+ warnings = [];
132
+ updatedAt = document.updatedAt;
133
+ return keys;
134
+ }
135
+
136
+ /** @returns {{ allow: string[], enforced: boolean, count: number, file: string, updatedAt: string | null, warnings: string[] }} */
137
+ function snapshot() {
138
+ return {
139
+ allow: [...allow],
140
+ enforced: allow.length > 0,
141
+ count: allow.length,
142
+ file,
143
+ updatedAt,
144
+ warnings: [...warnings],
145
+ };
146
+ }
147
+
148
+ return { file, replace, reload: load, snapshot };
149
+ }
150
+
151
+ function messageOf(error) {
152
+ return error instanceof Error ? error.message : String(error);
153
+ }