tailcat-webui 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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +23 -0
  3. package/README.en.md +104 -0
  4. package/README.md +93 -2
  5. package/bin/tailcat-webui.js +12 -0
  6. package/docs/CORE-API.md +343 -0
  7. package/docs/DESIGN.md +378 -0
  8. package/docs/screenshots/01-overview-light.png +0 -0
  9. package/docs/screenshots/02-overview-dark.png +0 -0
  10. package/docs/screenshots/03-ticket-light.png +0 -0
  11. package/docs/screenshots/04-ticket-qr-light.png +0 -0
  12. package/docs/screenshots/05-settings-light.png +0 -0
  13. package/docs/screenshots/06-diagnostics-light.png +0 -0
  14. package/docs/screenshots/07-mobile-overview.png +0 -0
  15. package/docs/screenshots/08-install-missing.png +0 -0
  16. package/package.json +56 -4
  17. package/src/cli.js +238 -0
  18. package/src/config.js +167 -0
  19. package/src/devices.js +163 -0
  20. package/src/errors.js +24 -0
  21. package/src/index.js +19 -0
  22. package/src/installer.js +907 -0
  23. package/src/manager.js +647 -0
  24. package/src/parse.js +207 -0
  25. package/src/paths.js +97 -0
  26. package/src/preferences.js +190 -0
  27. package/src/qr.js +37 -0
  28. package/src/relay.js +76 -0
  29. package/src/runtime/node.js +281 -0
  30. package/src/serve-targets.js +127 -0
  31. package/src/server.js +669 -0
  32. package/src/settings.js +262 -0
  33. package/src/supervisor.js +833 -0
  34. package/vendor/qrcode.mjs +2289 -0
  35. package/web/api.js +114 -0
  36. package/web/boot.js +29 -0
  37. package/web/components.js +504 -0
  38. package/web/dict.js +655 -0
  39. package/web/drawer-access.js +318 -0
  40. package/web/drawer-address.js +271 -0
  41. package/web/drawer-automation.js +223 -0
  42. package/web/drawer-relay.js +128 -0
  43. package/web/drawer-tunnel.js +309 -0
  44. package/web/drawer.js +302 -0
  45. package/web/format.js +252 -0
  46. package/web/icon.svg +11 -0
  47. package/web/index.html +29 -0
  48. package/web/main.js +471 -0
  49. package/web/room-diagnostics.js +426 -0
  50. package/web/room-overview.js +416 -0
  51. package/web/room-settings.js +71 -0
  52. package/web/store.js +168 -0
  53. package/web/styles.css +2741 -0
  54. package/web/ticket.js +212 -0
@@ -0,0 +1,281 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ const DEFAULT_GRACE_MS = 5_000;
7
+ const DEFAULT_PATHEXT = '.COM;.EXE;.BAT;.CMD';
8
+ const DEFAULT_MAX_BYTES = 64 * 1024;
9
+
10
+ /**
11
+ * The process adapter used by the standalone tools. It implements exactly the
12
+ * contract the manager and the supervisor need, using `child_process` without
13
+ * a shell: callers never get to inject quoting rules or shell built-ins.
14
+ * @returns {{ resolveExecutable: (command: string, env?: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<string>, spawn: (spec: object) => object }}
15
+ */
16
+ export function createNodeRuntime() {
17
+ return {
18
+ resolveExecutable(command, env = process.env, signal) {
19
+ return resolveExecutable(command, env, signal);
20
+ },
21
+ spawn(spec) {
22
+ return spawnProcess(spec);
23
+ },
24
+ };
25
+ }
26
+
27
+ /**
28
+ * Resolve a command name against PATH, or validate an explicit path, without
29
+ * executing anything. On Windows the PATHEXT spellings are tried so a bare
30
+ * `tailcat` can find `tailcat.exe`.
31
+ * @param {string} command - PATH name or absolute/relative path.
32
+ * @param {NodeJS.ProcessEnv} env - environment holding PATH.
33
+ * @param {AbortSignal} [signal] - cancellation.
34
+ * @returns {Promise<string>} absolute executable path.
35
+ * @throws {Error} when nothing executable is found.
36
+ */
37
+ async function resolveExecutable(command, env = process.env, signal) {
38
+ if (typeof command !== 'string' || command.trim() === '') {
39
+ throw new Error('Cannot resolve an empty executable name.');
40
+ }
41
+ const name = command.trim();
42
+ for (const candidate of executableCandidates(name, env)) {
43
+ throwIfAborted(signal);
44
+ try {
45
+ const stats = await fsp.stat(candidate);
46
+ if (!stats.isFile()) continue;
47
+ if (process.platform === 'win32') return path.resolve(candidate);
48
+ await fsp.access(candidate, fs.constants.X_OK);
49
+ return path.resolve(candidate);
50
+ } catch {
51
+ // Try the next spelling.
52
+ }
53
+ }
54
+ throw new Error(`Cannot find the executable "${name}".`);
55
+ }
56
+
57
+ /**
58
+ * @param {string} name - command or path.
59
+ * @param {NodeJS.ProcessEnv} env - environment holding PATH and PATHEXT.
60
+ * @returns {string[]} candidate absolute paths in preference order.
61
+ */
62
+ function executableCandidates(name, env) {
63
+ const extensions = extensionSpellings(name, env);
64
+ const hasSeparator = name.includes('/') || name.includes('\\');
65
+ if (path.isAbsolute(name) || hasSeparator) {
66
+ const base = path.isAbsolute(name) ? name : path.resolve(name);
67
+ return extensions.map((extension) => base + extension);
68
+ }
69
+ const pathValue = typeof env?.PATH === 'string' ? env.PATH : typeof env?.Path === 'string' ? env.Path : '';
70
+ const directories = pathValue.split(path.delimiter).filter((directory) => directory !== '');
71
+ const candidates = [];
72
+ for (const directory of directories) {
73
+ for (const extension of extensions) candidates.push(path.join(directory, name + extension));
74
+ }
75
+ return candidates;
76
+ }
77
+
78
+ /**
79
+ * @param {string} name - command name.
80
+ * @param {NodeJS.ProcessEnv} env - environment holding PATHEXT.
81
+ * @returns {string[]} extensions to try, with an empty extension first.
82
+ */
83
+ function extensionSpellings(name, env) {
84
+ if (process.platform !== 'win32') return [''];
85
+ const configured = typeof env?.PATHEXT === 'string' ? env.PATHEXT : DEFAULT_PATHEXT;
86
+ const extensions = configured
87
+ .split(';')
88
+ .map((extension) => extension.trim().toLowerCase())
89
+ .filter((extension) => extension !== '');
90
+ const lower = name.toLowerCase();
91
+ if (extensions.some((extension) => lower.endsWith(extension))) return [''];
92
+ return ['', ...extensions];
93
+ }
94
+
95
+ /**
96
+ * Spawn one process and wrap it in the handle shape the rest of the package
97
+ * expects. A failed spawn reports through `done` as `{ error }` instead of
98
+ * throwing, matching the contract; only an invalid spec throws.
99
+ * @param {object} spec - spawn specification.
100
+ * @returns {object} process handle.
101
+ */
102
+ function spawnProcess(spec) {
103
+ const argv = Array.isArray(spec?.argv) ? spec.argv : [];
104
+ if (argv.length === 0 || typeof argv[0] !== 'string' || argv[0] === '') {
105
+ throw new Error('spawn: argv[0] must be an executable path.');
106
+ }
107
+ const stdoutMode = spec?.stdio?.stdout;
108
+ const stderrMode = spec?.stdio?.stderr;
109
+ const graceMs = Number.isFinite(spec?.graceMs) && spec.graceMs >= 0 ? spec.graceMs : DEFAULT_GRACE_MS;
110
+
111
+ const child = spawn(argv[0], argv.slice(1), {
112
+ cwd: spec?.cwd,
113
+ env: spec?.env,
114
+ stdio: ['ignore', stdoutMode === undefined ? 'ignore' : 'pipe', stderrMode === undefined ? 'ignore' : 'pipe'],
115
+ windowsHide: true,
116
+ signal: spec?.signal,
117
+ });
118
+
119
+ /** @type {Record<string, object>} */
120
+ const collected = {};
121
+ if (isCollectMode(stdoutMode) && child.stdout) collected.stdout = createCollector(child.stdout, stdoutMode.maxBytes);
122
+ if (isCollectMode(stderrMode) && child.stderr) collected.stderr = createCollector(child.stderr, stderrMode.maxBytes);
123
+
124
+ const done = new Promise((resolve) => {
125
+ let settled = false;
126
+ const finish = (outcome) => {
127
+ if (settled) return;
128
+ settled = true;
129
+ resolve(outcome);
130
+ };
131
+ child.once('error', (error) => finish({ error }));
132
+ child.once('close', (exitCode, signal) => finish({ exitCode, signal }));
133
+ });
134
+
135
+ /** Clear the escalation timer once the process is gone. */
136
+ function clearKillTimer() {
137
+ if (killTimer !== null) {
138
+ clearTimeout(killTimer);
139
+ killTimer = null;
140
+ }
141
+ }
142
+ /** @type {ReturnType<typeof setTimeout> | null} */
143
+ let killTimer = null;
144
+ child.once('exit', clearKillTimer);
145
+
146
+ /** Terminate politely, then escalate after the grace period. */
147
+ function terminate() {
148
+ if (child.exitCode !== null || child.signalCode !== null) return;
149
+ if (process.platform === 'win32') {
150
+ killWindows(child.pid, false);
151
+ killTimer = setTimeout(() => killWindows(child.pid, true), graceMs);
152
+ killTimer.unref?.();
153
+ return;
154
+ }
155
+ try {
156
+ child.kill('SIGTERM');
157
+ } catch {
158
+ // The process may already be gone.
159
+ }
160
+ killTimer = setTimeout(() => {
161
+ if (child.exitCode !== null || child.signalCode !== null) return;
162
+ try {
163
+ child.kill('SIGKILL');
164
+ } catch {
165
+ // The process may already be gone.
166
+ }
167
+ }, graceMs);
168
+ killTimer.unref?.();
169
+ }
170
+
171
+ /**
172
+ * Wait for the process to exit, aborting when the optional signal fires.
173
+ * @param {AbortSignal} [signal] - cancellation.
174
+ * @returns {Promise<{ exitCode: number | null }>} exit result.
175
+ */
176
+ function waitForExit(signal) {
177
+ return new Promise((resolve, reject) => {
178
+ let settled = false;
179
+ const finish = (callback, value) => {
180
+ if (settled) return;
181
+ settled = true;
182
+ signal?.removeEventListener('abort', onAbort);
183
+ callback(value);
184
+ };
185
+ const onAbort = () => finish(reject, abortError(signal));
186
+ signal?.addEventListener('abort', onAbort, { once: true });
187
+ done.then((outcome) => {
188
+ if (outcome && 'error' in outcome) finish(reject, outcome.error);
189
+ else finish(resolve, { exitCode: outcome?.exitCode ?? null });
190
+ });
191
+ if (signal?.aborted) onAbort();
192
+ });
193
+ }
194
+
195
+ return {
196
+ stdout: stdoutMode === 'pipe' ? child.stdout : null,
197
+ stderr: stderrMode === 'pipe' ? child.stderr : null,
198
+ collected: Object.keys(collected).length > 0 ? collected : null,
199
+ done,
200
+ terminate,
201
+ waitForExit,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * @param {unknown} mode - stdio mode from the spawn spec.
207
+ * @returns {mode is { maxBytes: number }} whether output is collected in memory.
208
+ */
209
+ function isCollectMode(mode) {
210
+ return mode !== null && typeof mode === 'object' && Number.isFinite(mode.maxBytes) && mode.maxBytes >= 0;
211
+ }
212
+
213
+ /**
214
+ * Collect output up to a byte ceiling. Beyond the ceiling the bytes are
215
+ * counted but not stored: a runaway process must not be able to grow the
216
+ * manager's memory, and diagnostics only need the head of the stream.
217
+ * @param {NodeJS.ReadableStream} stream - child output.
218
+ * @param {number} maxBytes - ceiling for retained bytes.
219
+ * @returns {{ readFrom: (offset?: number) => { text: string, total: number } }} reader.
220
+ */
221
+ function createCollector(stream, maxBytes) {
222
+ const limit = Number.isFinite(maxBytes) && maxBytes >= 0 ? maxBytes : DEFAULT_MAX_BYTES;
223
+ const chunks = [];
224
+ let length = 0;
225
+ let total = 0;
226
+ stream.on('data', (chunk) => {
227
+ total += chunk.length;
228
+ if (length >= limit) return;
229
+ const room = limit - length;
230
+ const piece = chunk.length > room ? chunk.subarray(0, room) : chunk;
231
+ chunks.push(Buffer.from(piece));
232
+ length += piece.length;
233
+ });
234
+ stream.on('error', () => {
235
+ // An output stream error is not a process failure; done reports the exit.
236
+ });
237
+ return {
238
+ readFrom(offset = 0) {
239
+ const start = Math.max(0, Math.min(Number(offset) || 0, length));
240
+ return { text: Buffer.concat(chunks).subarray(start).toString('utf8'), total };
241
+ },
242
+ };
243
+ }
244
+
245
+ /**
246
+ * Force-kill a whole process tree on Windows.
247
+ * @param {number | undefined} pid - child pid.
248
+ * @param {boolean} force - whether to skip a graceful request.
249
+ */
250
+ function killWindows(pid, force) {
251
+ if (!Number.isInteger(pid) || pid <= 0) return;
252
+ const args = ['/pid', String(pid), '/T'];
253
+ if (force) args.push('/F');
254
+ try {
255
+ const killer = spawn('taskkill', args, { stdio: 'ignore', windowsHide: true });
256
+ killer.on('error', () => {
257
+ // taskkill is best effort; the caller's grace timeout is the backstop.
258
+ });
259
+ } catch {
260
+ // Nothing else to try.
261
+ }
262
+ }
263
+
264
+ /**
265
+ * @param {AbortSignal | undefined} signal - cancellation.
266
+ * @returns {Error} an abort-shaped error.
267
+ */
268
+ function abortError(signal) {
269
+ if (signal?.reason instanceof Error) return signal.reason;
270
+ const error = new Error('The operation was aborted.');
271
+ error.name = 'AbortError';
272
+ return error;
273
+ }
274
+
275
+ /**
276
+ * @param {AbortSignal | undefined} signal - cancellation.
277
+ * @throws {Error} when already aborted.
278
+ */
279
+ function throwIfAborted(signal) {
280
+ if (signal?.aborted) throw abortError(signal);
281
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Validation for the port mappings a tunnel exposes.
3
+ *
4
+ * tailcat's serve spec accepts ports, ranges, port mappings and Unix sockets in
5
+ * one comma-separated list. This module deliberately exposes only the mapping
6
+ * subset: one virtual port per row, pointing at a loopback port, a host:port,
7
+ * or a Unix socket. Ranges and service names stay out because they either
8
+ * multiply the exposure silently or need tailcat flags and build tags that
9
+ * cannot be promised on every platform.
10
+ */
11
+
12
+ const CONTROL = /[\u0000-\u001f\u007f]/;
13
+
14
+ /**
15
+ * @param {unknown} value - candidate virtual port.
16
+ * @returns {number} validated port.
17
+ * @throws {Error} when it is not a whole port number in range.
18
+ */
19
+ function normalizeVirtualPort(value) {
20
+ const port = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value.trim()) : value;
21
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
22
+ throw new Error('The virtual port must be a whole number from 1 to 65535.');
23
+ }
24
+ return port;
25
+ }
26
+
27
+ /**
28
+ * @param {unknown} value - target port, host:port or Unix socket path.
29
+ * @returns {string} canonical tailcat target.
30
+ * @throws {Error} when the target is not a single dialable endpoint.
31
+ */
32
+ function normalizeTarget(value) {
33
+ if (typeof value !== 'string') throw new Error('The target must be a port, host:port, or Unix socket path.');
34
+ const text = value.trim();
35
+ if (text === '') throw new Error('The target cannot be empty.');
36
+ if (text.length > 512) throw new Error('The target is too long.');
37
+ if (CONTROL.test(text)) throw new Error('The target contains a control character.');
38
+
39
+ const socket = text.startsWith('unix:') ? text.slice('unix:'.length) : text.startsWith('/') ? text : '';
40
+ if (socket) {
41
+ if (!socket.startsWith('/')) throw new Error('A Unix socket target must use an absolute path.');
42
+ return `unix:${socket}`;
43
+ }
44
+
45
+ if (/^\d+$/.test(text)) {
46
+ const port = Number(text);
47
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('The target port must be from 1 to 65535.');
48
+ return `localhost:${port}`;
49
+ }
50
+
51
+ const bracketed = /^\[([0-9a-fA-F:.]+)\]:(\d+)$/.exec(text);
52
+ if (bracketed) {
53
+ const port = Number(bracketed[2]);
54
+ if (!(port >= 1 && port <= 65535)) throw new Error('The target port must be from 1 to 65535.');
55
+ return `[${bracketed[1]}]:${port}`;
56
+ }
57
+
58
+ const split = text.lastIndexOf(':');
59
+ if (split <= 0) throw new Error('The target must be a port, host:port, or Unix socket path.');
60
+ const host = text.slice(0, split);
61
+ const port = Number(text.slice(split + 1));
62
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('The target port must be from 1 to 65535.');
63
+ if (host === 'localhost') return `localhost:${port}`;
64
+ if (!/^[A-Za-z0-9._-]+$/.test(host) && !/^\[[0-9a-fA-F:.]+\]$/.test(host)) {
65
+ throw new Error('The target host must be a DNS name or an IPv6 address in brackets.');
66
+ }
67
+ return `${host}:${port}`;
68
+ }
69
+
70
+ /**
71
+ * Normalize one row (`virtual` + `target`) into the canonical `virtual:target`
72
+ * form tailcat understands.
73
+ * @param {{ virtual?: unknown, target?: unknown } | string} input - row or canonical string.
74
+ * @returns {string} canonical mapping.
75
+ */
76
+ export function normalizeServeTarget(input) {
77
+ if (typeof input === 'string') {
78
+ const text = input.trim();
79
+ const split = text.indexOf(':');
80
+ if (split <= 0) throw new Error('A serve mapping must contain a virtual port and a target.');
81
+ return normalizeServeTarget({ virtual: text.slice(0, split), target: text.slice(split + 1) });
82
+ }
83
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
84
+ throw new Error('Each port mapping must be an object with a virtual port and a target.');
85
+ }
86
+ const virtual = normalizeVirtualPort(input.virtual);
87
+ const target = normalizeTarget(input.target);
88
+ return `${virtual}:${target}`;
89
+ }
90
+
91
+ /**
92
+ * @param {unknown} value - candidate array.
93
+ * @param {number[]} [reservedPorts] - virtual ports the caller keeps for itself.
94
+ * @returns {string[]} canonical, unique mappings.
95
+ */
96
+ export function normalizeServeTargets(value, reservedPorts = []) {
97
+ if (value === undefined) return [];
98
+ if (!Array.isArray(value)) throw new Error('The port mappings must be an array.');
99
+ if (value.length > 32) throw new Error('At most 32 port mappings can be configured.');
100
+ const reserved = new Set(Array.isArray(reservedPorts) ? reservedPorts.map((port) => String(port)) : []);
101
+ const seen = new Set(reserved);
102
+ const result = [];
103
+ for (const item of value) {
104
+ const canonical = normalizeServeTarget(item);
105
+ const virtual = canonical.slice(0, canonical.indexOf(':'));
106
+ if (seen.has(virtual)) {
107
+ if (reserved.has(virtual)) {
108
+ throw new Error(`Virtual port ${virtual} is reserved by the application and cannot be mapped.`);
109
+ }
110
+ throw new Error(`Virtual port ${virtual} is already used by another port mapping.`);
111
+ }
112
+ seen.add(virtual);
113
+ result.push(canonical);
114
+ }
115
+ return result;
116
+ }
117
+
118
+ /**
119
+ * Turn a canonical mapping back into the two fields the settings panel edits.
120
+ * @param {string} value - canonical `virtual:target`.
121
+ * @returns {{ virtual: string, target: string }} editable row.
122
+ */
123
+ export function serveTargetRow(value) {
124
+ const text = String(value);
125
+ const split = text.indexOf(':');
126
+ return { virtual: text.slice(0, split), target: text.slice(split + 1) };
127
+ }