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.
- package/LICENSE +21 -0
- package/NOTICE +29 -0
- package/README.en.md +112 -0
- package/README.md +101 -2
- package/bin/tailcat-webui.js +12 -0
- package/docs/CORE-API.md +343 -0
- package/docs/DESIGN.md +398 -0
- package/docs/assets/character.jpg +0 -0
- package/docs/assets/portrait.jpg +0 -0
- package/docs/screenshots/01-overview-light.png +0 -0
- package/docs/screenshots/02-overview-dark.png +0 -0
- package/docs/screenshots/03-ticket-light.png +0 -0
- package/docs/screenshots/04-ticket-qr-light.png +0 -0
- package/docs/screenshots/05-settings-light.png +0 -0
- package/docs/screenshots/06-diagnostics-light.png +0 -0
- package/docs/screenshots/07-mobile-overview.png +0 -0
- package/docs/screenshots/08-install-missing.png +0 -0
- package/docs/screenshots/09-keeper.png +0 -0
- package/package.json +56 -4
- package/src/cli.js +238 -0
- package/src/config.js +167 -0
- package/src/devices.js +163 -0
- package/src/errors.js +24 -0
- package/src/index.js +19 -0
- package/src/installer.js +907 -0
- package/src/manager.js +647 -0
- package/src/parse.js +207 -0
- package/src/paths.js +97 -0
- package/src/preferences.js +190 -0
- package/src/qr.js +37 -0
- package/src/relay.js +76 -0
- package/src/runtime/node.js +281 -0
- package/src/serve-targets.js +127 -0
- package/src/server.js +674 -0
- package/src/settings.js +262 -0
- package/src/supervisor.js +833 -0
- package/vendor/qrcode.mjs +2289 -0
- package/web/api.js +114 -0
- package/web/assets/portrait.jpg +0 -0
- package/web/boot.js +29 -0
- package/web/components.js +558 -0
- package/web/dict.js +663 -0
- package/web/drawer-access.js +318 -0
- package/web/drawer-address.js +271 -0
- package/web/drawer-automation.js +223 -0
- package/web/drawer-relay.js +128 -0
- package/web/drawer-tunnel.js +309 -0
- package/web/drawer.js +302 -0
- package/web/format.js +252 -0
- package/web/icon.png +0 -0
- package/web/index.html +29 -0
- package/web/main.js +471 -0
- package/web/room-diagnostics.js +426 -0
- package/web/room-overview.js +438 -0
- package/web/room-settings.js +71 -0
- package/web/store.js +168 -0
- package/web/styles.css +2873 -0
- package/web/ticket.js +212 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { defaultStateDir } from './paths.js';
|
|
5
|
+
import { createTailcatWebui } from './server.js';
|
|
6
|
+
|
|
7
|
+
const DEFAULT_PORT = 17_890;
|
|
8
|
+
|
|
9
|
+
/** Local port the client binds when it forwards the tunnel to itself. */
|
|
10
|
+
const DEFAULT_LOCAL_PORT = 18_080;
|
|
11
|
+
const USAGE = `Usage: tailcat-webui [options]
|
|
12
|
+
|
|
13
|
+
A quiet local console for a tailcat tunnel.
|
|
14
|
+
|
|
15
|
+
Options:
|
|
16
|
+
--port <number> Local port for the console (default ${DEFAULT_PORT}).
|
|
17
|
+
--binary <path> tailcat executable name or path (default "tailcat").
|
|
18
|
+
--state-dir <dir> Directory for saved settings and devices.
|
|
19
|
+
--open Open the console in the default browser.
|
|
20
|
+
--no-open Do not open a browser (the default).
|
|
21
|
+
--version Print the version.
|
|
22
|
+
--help Print this help.`;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Run the console until the process is interrupted.
|
|
26
|
+
* @param {string[]} [argv] - command-line arguments (without the executable).
|
|
27
|
+
* @param {{stdout: {write: (text: string) => unknown}, stderr: {write: (text: string) => unknown}}} [io] - output sinks.
|
|
28
|
+
* @returns {Promise<number>} process exit code.
|
|
29
|
+
*/
|
|
30
|
+
export async function main(argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr }) {
|
|
31
|
+
const options = parseArguments(argv);
|
|
32
|
+
if (options.help) {
|
|
33
|
+
io.stdout.write(`${USAGE}\n`);
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
if (options.version) {
|
|
37
|
+
io.stdout.write(`tailcat-webui ${packageVersion()}\n`);
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const logger = {
|
|
42
|
+
info: (message) => io.stdout.write(`${message}\n`),
|
|
43
|
+
warn: (message) => io.stderr.write(`${message}\n`),
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
let app = null;
|
|
47
|
+
app = createTailcatWebui({
|
|
48
|
+
config: { binaryPath: options.binaryPath },
|
|
49
|
+
stateDir: options.stateDir,
|
|
50
|
+
port: options.port,
|
|
51
|
+
host: '127.0.0.1',
|
|
52
|
+
logger,
|
|
53
|
+
serve: { targets: () => app.manager.effectiveSettings().extraTargets },
|
|
54
|
+
pairing: derivePairing(() => app?.manager?.effectiveSettings?.().extraTargets),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
let url;
|
|
58
|
+
try {
|
|
59
|
+
url = await app.start();
|
|
60
|
+
} catch (error) {
|
|
61
|
+
io.stderr.write(`${errorMessage(error)}\n`);
|
|
62
|
+
await app.stop().catch(() => {});
|
|
63
|
+
return 1;
|
|
64
|
+
}
|
|
65
|
+
io.stdout.write(`${url}\n`);
|
|
66
|
+
|
|
67
|
+
let closing = false;
|
|
68
|
+
const shutdown = () => {
|
|
69
|
+
if (closing) return;
|
|
70
|
+
closing = true;
|
|
71
|
+
app.stop().then(
|
|
72
|
+
() => process.exit(0),
|
|
73
|
+
() => process.exit(0),
|
|
74
|
+
);
|
|
75
|
+
};
|
|
76
|
+
process.once('SIGINT', shutdown);
|
|
77
|
+
process.once('SIGTERM', shutdown);
|
|
78
|
+
|
|
79
|
+
if (options.open) openBrowser(url, logger);
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The ticket a client uses once the tunnel is online. The standalone console
|
|
85
|
+
* exposes the first saved port mapping, so the ticket forwards that virtual
|
|
86
|
+
* port to the client's own loopback; with no saved mapping there is nothing to
|
|
87
|
+
* forward yet and only the address and QR remain. The reader is deferred so the
|
|
88
|
+
* app reference can be filled in after construction.
|
|
89
|
+
* @param {() => string[] | undefined} readTargets - current canonical mapping list.
|
|
90
|
+
* @returns {{ localPort: number, virtualPort: () => number | null }} manager pairing options.
|
|
91
|
+
*/
|
|
92
|
+
export function derivePairing(readTargets = () => []) {
|
|
93
|
+
return {
|
|
94
|
+
localPort: DEFAULT_LOCAL_PORT,
|
|
95
|
+
virtualPort() {
|
|
96
|
+
let targets;
|
|
97
|
+
try {
|
|
98
|
+
targets = readTargets();
|
|
99
|
+
} catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const first = Array.isArray(targets) ? targets[0] : null;
|
|
103
|
+
if (typeof first !== 'string') return null;
|
|
104
|
+
const colon = first.indexOf(':');
|
|
105
|
+
if (colon <= 0) return null;
|
|
106
|
+
const port = Number(first.slice(0, colon));
|
|
107
|
+
return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null;
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {string[]} argv - raw arguments.
|
|
114
|
+
* @returns {{port: number, binaryPath: string, stateDir: string, open: boolean, help: boolean, version: boolean}} parsed options.
|
|
115
|
+
*/
|
|
116
|
+
function parseArguments(argv) {
|
|
117
|
+
const options = {
|
|
118
|
+
port: DEFAULT_PORT,
|
|
119
|
+
binaryPath: 'tailcat',
|
|
120
|
+
stateDir: defaultStateDir(),
|
|
121
|
+
open: false,
|
|
122
|
+
help: false,
|
|
123
|
+
version: false,
|
|
124
|
+
};
|
|
125
|
+
const list = Array.isArray(argv) ? argv : [];
|
|
126
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
127
|
+
const argument = String(list[index]);
|
|
128
|
+
if (argument === '--help' || argument === '-h') {
|
|
129
|
+
options.help = true;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (argument === '--version' || argument === '-v') {
|
|
133
|
+
options.version = true;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (argument === '--open') {
|
|
137
|
+
options.open = true;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (argument === '--no-open') {
|
|
141
|
+
options.open = false;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (argument === '--port' || argument.startsWith('--port=')) {
|
|
145
|
+
const { value, next } = takeValue(list, index, argument, '--port');
|
|
146
|
+
index = next;
|
|
147
|
+
options.port = parsePort(value);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (argument === '--binary' || argument.startsWith('--binary=')) {
|
|
151
|
+
const { value, next } = takeValue(list, index, argument, '--binary');
|
|
152
|
+
index = next;
|
|
153
|
+
if (value.trim() === '') throw new Error('--binary needs a non-empty value.');
|
|
154
|
+
options.binaryPath = value.trim();
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (argument === '--state-dir' || argument.startsWith('--state-dir=')) {
|
|
158
|
+
const { value, next } = takeValue(list, index, argument, '--state-dir');
|
|
159
|
+
index = next;
|
|
160
|
+
if (value.trim() === '') throw new Error('--state-dir needs a non-empty value.');
|
|
161
|
+
options.stateDir = path.resolve(value.trim());
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
throw new Error(`Unknown argument "${argument}". Run tailcat-webui --help for usage.`);
|
|
165
|
+
}
|
|
166
|
+
return options;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* @param {string[]} list - arguments.
|
|
171
|
+
* @param {number} index - current index.
|
|
172
|
+
* @param {string} argument - current argument.
|
|
173
|
+
* @param {string} name - flag name for messages.
|
|
174
|
+
* @returns {{ value: string, next: number }} flag value and the index it was read from.
|
|
175
|
+
*/
|
|
176
|
+
function takeValue(list, index, argument, name) {
|
|
177
|
+
const equals = argument.indexOf('=');
|
|
178
|
+
if (equals !== -1) return { value: argument.slice(equals + 1), next: index };
|
|
179
|
+
const value = list[index + 1];
|
|
180
|
+
if (value === undefined) throw new Error(`Missing value for ${name}.`);
|
|
181
|
+
return { value: String(value), next: index + 1 };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* @param {string} value - port text.
|
|
186
|
+
* @returns {number} validated port.
|
|
187
|
+
*/
|
|
188
|
+
function parsePort(value) {
|
|
189
|
+
const port = Number(value);
|
|
190
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
191
|
+
throw new Error('--port needs a whole number from 1 to 65535.');
|
|
192
|
+
}
|
|
193
|
+
return port;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Open the console in the platform browser. Failure is reported but never
|
|
198
|
+
* fatal: the URL is already printed and can be opened by hand.
|
|
199
|
+
* @param {string} url - console URL.
|
|
200
|
+
* @param {{warn: (message: string) => void}} logger - logger.
|
|
201
|
+
*/
|
|
202
|
+
function openBrowser(url, logger) {
|
|
203
|
+
const command =
|
|
204
|
+
process.platform === 'win32'
|
|
205
|
+
? { file: 'cmd', args: ['/c', 'start', '', url] }
|
|
206
|
+
: process.platform === 'darwin'
|
|
207
|
+
? { file: 'open', args: [url] }
|
|
208
|
+
: { file: 'xdg-open', args: [url] };
|
|
209
|
+
try {
|
|
210
|
+
const child = spawn(command.file, command.args, { stdio: 'ignore', detached: true, windowsHide: true });
|
|
211
|
+
child.on('error', (error) => logger.warn(`tailcat-webui: could not open a browser: ${errorMessage(error)}`));
|
|
212
|
+
child.unref();
|
|
213
|
+
} catch (error) {
|
|
214
|
+
logger.warn(`tailcat-webui: could not open a browser: ${errorMessage(error)}`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* @returns {string} package version.
|
|
220
|
+
*/
|
|
221
|
+
function packageVersion() {
|
|
222
|
+
try {
|
|
223
|
+
const text = fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8');
|
|
224
|
+
return JSON.parse(text).version ?? '0.0.0';
|
|
225
|
+
} catch {
|
|
226
|
+
return '0.0.0';
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* @param {unknown} error - thrown value.
|
|
232
|
+
* @returns {string} readable message.
|
|
233
|
+
*/
|
|
234
|
+
function errorMessage(error) {
|
|
235
|
+
return error instanceof Error ? error.message : String(error);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export { USAGE };
|
package/src/config.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { normalizeDerpMapUrl } from './relay.js';
|
|
2
|
+
import { normalizeServeTarget } from './serve-targets.js';
|
|
3
|
+
|
|
4
|
+
/** Minimum tailcat release: Unix-socket serve targets and --log arrived in 0.8.0. */
|
|
5
|
+
export const MIN_TAILCAT_VERSION = '0.8.0';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The documented defaults. The deployment config may override any field, and
|
|
9
|
+
* the panel may override the subset listed in settings.js; these values are
|
|
10
|
+
* what remains when neither layer supplies a valid choice.
|
|
11
|
+
*/
|
|
12
|
+
export const CONFIG_DEFAULTS = Object.freeze({
|
|
13
|
+
binaryPath: 'tailcat',
|
|
14
|
+
keyName: 'tailcat-webui',
|
|
15
|
+
addressMode: 'stable',
|
|
16
|
+
derpMapUrl: '',
|
|
17
|
+
regionMode: 'auto',
|
|
18
|
+
regionValue: '',
|
|
19
|
+
psk: true,
|
|
20
|
+
hybrid: false,
|
|
21
|
+
fullAddress: false,
|
|
22
|
+
verbose: false,
|
|
23
|
+
extraTargets: Object.freeze([]),
|
|
24
|
+
autoStart: true,
|
|
25
|
+
logAccess: true,
|
|
26
|
+
restartEnabled: true,
|
|
27
|
+
maxRestartAttempts: 10,
|
|
28
|
+
restartBaseDelayMs: 500,
|
|
29
|
+
restartMaxDelayMs: 30_000,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Turn a partially invalid config into the normalized shape the runtime reads.
|
|
36
|
+
* Every field falls back on its own, so one typo cannot stop the tunnel from
|
|
37
|
+
* starting; relationships are checked later, when the operator saves them.
|
|
38
|
+
* @param {unknown} [input] - raw config.
|
|
39
|
+
* @param {{ reservedPorts?: number[] }} [options] - virtual ports the caller keeps for itself.
|
|
40
|
+
* @returns {object} resolved config.
|
|
41
|
+
*/
|
|
42
|
+
export function resolveConfig(input, { reservedPorts = [] } = {}) {
|
|
43
|
+
const value = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
|
|
44
|
+
const regionValue = text(value.regionValue, 512);
|
|
45
|
+
const regionMode = ['auto', 'explicit', 'hosts'].includes(value.regionMode) ? value.regionMode : 'auto';
|
|
46
|
+
const restartBaseDelayMs =
|
|
47
|
+
integer(value.restartBaseDelayMs, 100, 60_000) ?? CONFIG_DEFAULTS.restartBaseDelayMs;
|
|
48
|
+
const restartMaxDelayMs = Math.max(
|
|
49
|
+
restartBaseDelayMs,
|
|
50
|
+
integer(value.restartMaxDelayMs, 1_000, 600_000) ?? CONFIG_DEFAULTS.restartMaxDelayMs,
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
binaryPath: name(value.binaryPath, CONFIG_DEFAULTS.binaryPath),
|
|
55
|
+
keyName: `${name(value.keyName, CONFIG_DEFAULTS.keyName).slice(0, 256)}`,
|
|
56
|
+
addressMode: value.addressMode === 'ephemeral' ? 'ephemeral' : 'stable',
|
|
57
|
+
derpMapUrl: derp(value.derpMapUrl),
|
|
58
|
+
regionMode: regionMode !== 'auto' && regionValue === '' ? 'auto' : regionMode,
|
|
59
|
+
regionValue,
|
|
60
|
+
psk: value.psk !== false,
|
|
61
|
+
hybrid: value.hybrid === true,
|
|
62
|
+
fullAddress: value.fullAddress === true,
|
|
63
|
+
verbose: value.verbose === true,
|
|
64
|
+
extraTargets: extraTargets(value.extraTargets, reservedPorts),
|
|
65
|
+
autoStart: value.autoStart !== false,
|
|
66
|
+
logAccess: value.logAccess !== false,
|
|
67
|
+
restartEnabled: value.restartEnabled !== false,
|
|
68
|
+
maxRestartAttempts: integer(value.maxRestartAttempts, 0, 100) ?? CONFIG_DEFAULTS.maxRestartAttempts,
|
|
69
|
+
restartBaseDelayMs,
|
|
70
|
+
restartMaxDelayMs,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The subset of the deployment config the interface may show. No key material,
|
|
76
|
+
* no resolved private paths, no address.
|
|
77
|
+
* @param {ReturnType<typeof resolveConfig>} config - resolved config.
|
|
78
|
+
* @returns {object} display-safe settings.
|
|
79
|
+
*/
|
|
80
|
+
export function configView(config) {
|
|
81
|
+
return {
|
|
82
|
+
binaryPath: config.binaryPath,
|
|
83
|
+
keyName: config.keyName,
|
|
84
|
+
addressMode: config.addressMode,
|
|
85
|
+
autoStart: config.autoStart,
|
|
86
|
+
logAccess: config.logAccess,
|
|
87
|
+
restartEnabled: config.restartEnabled,
|
|
88
|
+
maxRestartAttempts: config.maxRestartAttempts,
|
|
89
|
+
restartBaseDelayMs: config.restartBaseDelayMs,
|
|
90
|
+
restartMaxDelayMs: config.restartMaxDelayMs,
|
|
91
|
+
customDerpMap: config.derpMapUrl !== '',
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* @param {unknown} value - candidate mapping list.
|
|
97
|
+
* @param {number[]} reservedPorts - virtual ports the caller keeps for itself.
|
|
98
|
+
* @returns {string[]} canonical mappings, dropping invalid rows one by one.
|
|
99
|
+
*/
|
|
100
|
+
function extraTargets(value, reservedPorts) {
|
|
101
|
+
if (!Array.isArray(value)) return [];
|
|
102
|
+
const reserved = new Set(Array.isArray(reservedPorts) ? reservedPorts.map((port) => String(port)) : []);
|
|
103
|
+
const seen = new Set(reserved);
|
|
104
|
+
const result = [];
|
|
105
|
+
for (const item of value) {
|
|
106
|
+
if (result.length >= 32) break;
|
|
107
|
+
let canonical;
|
|
108
|
+
try {
|
|
109
|
+
canonical = normalizeServeTarget(item);
|
|
110
|
+
} catch {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const virtual = canonical.slice(0, canonical.indexOf(':'));
|
|
114
|
+
if (seen.has(virtual)) continue;
|
|
115
|
+
seen.add(virtual);
|
|
116
|
+
result.push(canonical);
|
|
117
|
+
}
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* @param {unknown} value - candidate DERP map URL.
|
|
123
|
+
* @returns {string} validated URL, or empty for tailcat's default.
|
|
124
|
+
*/
|
|
125
|
+
function derp(value) {
|
|
126
|
+
if (typeof value !== 'string' || value.trim() === '') return '';
|
|
127
|
+
try {
|
|
128
|
+
return normalizeDerpMapUrl(value);
|
|
129
|
+
} catch {
|
|
130
|
+
return '';
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* @param {unknown} value - candidate text.
|
|
136
|
+
* @param {string} fallback - value used when absent or unusable.
|
|
137
|
+
* @returns {string} trimmed text.
|
|
138
|
+
*/
|
|
139
|
+
function name(value, fallback) {
|
|
140
|
+
if (typeof value !== 'string') return fallback;
|
|
141
|
+
const trimmed = value.trim();
|
|
142
|
+
if (trimmed === '' || CONTROL.test(trimmed)) return fallback;
|
|
143
|
+
return trimmed;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* @param {unknown} value - candidate text.
|
|
148
|
+
* @param {number} maxLength - maximum accepted length.
|
|
149
|
+
* @returns {string} trimmed, bounded text (empty when unusable).
|
|
150
|
+
*/
|
|
151
|
+
function text(value, maxLength) {
|
|
152
|
+
if (typeof value !== 'string') return '';
|
|
153
|
+
const trimmed = value.trim();
|
|
154
|
+
if (trimmed === '' || CONTROL.test(trimmed)) return '';
|
|
155
|
+
return trimmed.length > maxLength ? trimmed.slice(0, maxLength) : trimmed;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* @param {unknown} value - candidate.
|
|
160
|
+
* @param {number} min - lower bound.
|
|
161
|
+
* @param {number} max - upper bound.
|
|
162
|
+
* @returns {number | null} normalized integer, or null when unusable.
|
|
163
|
+
*/
|
|
164
|
+
function integer(value, min, max) {
|
|
165
|
+
if (!Number.isInteger(value) || value < min || value > max) return null;
|
|
166
|
+
return value;
|
|
167
|
+
}
|
package/src/devices.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { RemoteAccessError } from './errors.js';
|
|
4
|
+
import { defaultStateDir } from './paths.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Normalize one pasted key to canonical lower-case `nodekey:<hex>` form.
|
|
8
|
+
* A bare 64-character hex string is accepted because that is what a key file
|
|
9
|
+
* or a shortened CLI output may show.
|
|
10
|
+
* @param {unknown} value - pasted key.
|
|
11
|
+
* @returns {string} canonical key.
|
|
12
|
+
* @throws {RemoteAccessError} when the value is not a client public key.
|
|
13
|
+
*/
|
|
14
|
+
export function normalizeDeviceKey(value) {
|
|
15
|
+
if (typeof value !== 'string') {
|
|
16
|
+
throw new RemoteAccessError('invalid-allow-list', 'Each allowed device must be a nodekey string.', 400);
|
|
17
|
+
}
|
|
18
|
+
const trimmed = value.trim();
|
|
19
|
+
const lower = trimmed.toLowerCase();
|
|
20
|
+
const hex = lower.startsWith('nodekey:') ? lower.slice('nodekey:'.length) : trimmed;
|
|
21
|
+
if (!/^[0-9a-fA-F]{64}$/.test(hex)) {
|
|
22
|
+
throw new RemoteAccessError(
|
|
23
|
+
'invalid-allow-list',
|
|
24
|
+
`Not a tailcat node public key: ${trimmed.slice(0, 24)}${trimmed.length > 24 ? '…' : ''}. Expected nodekey: followed by 64 hex characters.`,
|
|
25
|
+
400,
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return `nodekey:${hex.toLowerCase()}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* One line per key, ignoring blank lines and `#` comments.
|
|
33
|
+
* @param {string} text - textarea contents.
|
|
34
|
+
* @returns {string[]} canonical keys.
|
|
35
|
+
*/
|
|
36
|
+
export function parseDeviceKeys(text) {
|
|
37
|
+
const keys = [];
|
|
38
|
+
for (const raw of String(text).split(/\r?\n/)) {
|
|
39
|
+
const line = raw.trim();
|
|
40
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
41
|
+
keys.push(normalizeDeviceKey(line));
|
|
42
|
+
}
|
|
43
|
+
return [...new Set(keys)];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The durable allow-list of client keys. Address-only mode is the empty list;
|
|
48
|
+
* a non-empty list becomes `tailcat serve --allow=...`.
|
|
49
|
+
*
|
|
50
|
+
* The file is read once at creation and kept in memory; `replace` writes the
|
|
51
|
+
* whole document atomically so a crash cannot leave a half-written list.
|
|
52
|
+
* @param {{ dir?: string, logger?: { warn: (...args: any[]) => void } }} [options] - test/overrides.
|
|
53
|
+
*/
|
|
54
|
+
export function createFileDeviceStore(options = {}) {
|
|
55
|
+
const dir = options.dir ?? defaultStateDir();
|
|
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
|
+
updatedAt = null;
|
|
71
|
+
let text;
|
|
72
|
+
try {
|
|
73
|
+
text = fs.readFileSync(file, 'utf8');
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (error && error.code === 'ENOENT') return;
|
|
76
|
+
warnings.push(`Could not read the device allow-list: ${messageOf(error)}`);
|
|
77
|
+
logger?.warn(`tailcat-webui: ${warnings.at(-1)}`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
let document;
|
|
81
|
+
try {
|
|
82
|
+
document = JSON.parse(text);
|
|
83
|
+
} catch {
|
|
84
|
+
warnings.push('The device allow-list file is not valid JSON; starting in address-only mode.');
|
|
85
|
+
logger?.warn(`tailcat-webui: ${warnings.at(-1)}`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const rows = Array.isArray(document) ? document : Array.isArray(document?.allow) ? document.allow : null;
|
|
89
|
+
if (rows === null) {
|
|
90
|
+
warnings.push('The device allow-list file has an unknown shape; starting in address-only mode.');
|
|
91
|
+
logger?.warn(`tailcat-webui: ${warnings.at(-1)}`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
for (const row of rows) {
|
|
95
|
+
if (typeof row === 'string' && (row.trim() === '' || row.trim().startsWith('#'))) continue;
|
|
96
|
+
try {
|
|
97
|
+
allow.push(normalizeDeviceKey(row));
|
|
98
|
+
} catch {
|
|
99
|
+
warnings.push('Ignored an invalid key in the device allow-list.');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
allow = [...new Set(allow)];
|
|
103
|
+
updatedAt = typeof document?.updatedAt === 'string' ? document.updatedAt : null;
|
|
104
|
+
if (warnings.length > 0) logger?.warn(`tailcat-webui: ${warnings.join(' ')}`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Replace the whole allow-list durably and return the canonical values.
|
|
109
|
+
* @param {string[]} values - keys from the panel or API.
|
|
110
|
+
* @returns {string[]} canonical unique keys.
|
|
111
|
+
* @throws {RemoteAccessError} when any key is invalid.
|
|
112
|
+
*/
|
|
113
|
+
function replace(values) {
|
|
114
|
+
if (!Array.isArray(values)) {
|
|
115
|
+
throw new RemoteAccessError('invalid-allow-list', 'allow must be an array of nodekey strings.', 400);
|
|
116
|
+
}
|
|
117
|
+
const keys = [...new Set(values.map(normalizeDeviceKey))];
|
|
118
|
+
const document = {
|
|
119
|
+
version: 1,
|
|
120
|
+
allow: keys,
|
|
121
|
+
updatedAt: new Date().toISOString(),
|
|
122
|
+
};
|
|
123
|
+
try {
|
|
124
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
125
|
+
const temporary = path.join(dir, `.devices.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`);
|
|
126
|
+
fs.writeFileSync(temporary, `${JSON.stringify(document, null, 2)}\n`, { mode: 0o600 });
|
|
127
|
+
fs.renameSync(temporary, file);
|
|
128
|
+
try {
|
|
129
|
+
fs.chmodSync(file, 0o600);
|
|
130
|
+
} catch {
|
|
131
|
+
// A filesystem without POSIX modes still stores the file.
|
|
132
|
+
}
|
|
133
|
+
} catch (error) {
|
|
134
|
+
throw new Error(`Could not save the device allow-list: ${messageOf(error)}`);
|
|
135
|
+
}
|
|
136
|
+
allow = keys;
|
|
137
|
+
warnings = [];
|
|
138
|
+
updatedAt = document.updatedAt;
|
|
139
|
+
return keys;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** @returns {{ allow: string[], enforced: boolean, count: number, file: string, updatedAt: string | null, warnings: string[] }} */
|
|
143
|
+
function snapshot() {
|
|
144
|
+
return {
|
|
145
|
+
allow: [...allow],
|
|
146
|
+
enforced: allow.length > 0,
|
|
147
|
+
count: allow.length,
|
|
148
|
+
file,
|
|
149
|
+
updatedAt,
|
|
150
|
+
warnings: [...warnings],
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return { file, replace, reload: load, snapshot };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {unknown} error - thrown value.
|
|
159
|
+
* @returns {string} readable text.
|
|
160
|
+
*/
|
|
161
|
+
function messageOf(error) {
|
|
162
|
+
return error instanceof Error ? error.message : String(error);
|
|
163
|
+
}
|
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 interface.
|
|
20
|
+
*/
|
|
21
|
+
export function errorMessage(error) {
|
|
22
|
+
if (error instanceof Error && error.message) return error.message;
|
|
23
|
+
return String(error);
|
|
24
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { createTailcatManager, TailcatManager } from './manager.js';
|
|
2
|
+
export { resolveConfig, configView, CONFIG_DEFAULTS, MIN_TAILCAT_VERSION } from './config.js';
|
|
3
|
+
export { createFilePreferenceStore } from './preferences.js';
|
|
4
|
+
export { createFileDeviceStore } from './devices.js';
|
|
5
|
+
export { createNodeRuntime } from './runtime/node.js';
|
|
6
|
+
export { RemoteAccessError, errorMessage } from './errors.js';
|
|
7
|
+
export { normalizeServeTargets, normalizeServeTarget, serveTargetRow } from './serve-targets.js';
|
|
8
|
+
export {
|
|
9
|
+
buildForwardCommand,
|
|
10
|
+
buildGenkeyArgs,
|
|
11
|
+
buildServeArgs,
|
|
12
|
+
parseAddressLine,
|
|
13
|
+
parseRegionLine,
|
|
14
|
+
parseAccessLine,
|
|
15
|
+
sanitizeLine,
|
|
16
|
+
} from './parse.js';
|
|
17
|
+
export { qrMatrix } from './qr.js';
|
|
18
|
+
export { tailcatKeyPath, userConfigDir, findKnownTailcat, knownTailcatPaths, defaultStateDir } from './paths.js';
|
|
19
|
+
export { TailcatInstaller, TAILCAT_VERSION, TAILCAT_TAG, MANUAL_INSTALL_URL, platformSpec } from './installer.js';
|