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.
- package/LICENSE +21 -0
- package/NOTICE +23 -0
- package/README.en.md +104 -0
- package/README.md +93 -2
- package/bin/tailcat-webui.js +12 -0
- package/docs/CORE-API.md +343 -0
- package/docs/DESIGN.md +378 -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/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 +669 -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/boot.js +29 -0
- package/web/components.js +504 -0
- package/web/dict.js +655 -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.svg +11 -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 +416 -0
- package/web/room-settings.js +71 -0
- package/web/store.js +168 -0
- package/web/styles.css +2741 -0
- package/web/ticket.js +212 -0
package/src/parse.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure parsers and argv builders for the tailcat supervisor and its tests.
|
|
3
|
+
* Nothing here starts a process or reads a file.
|
|
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
|
+
const key = knownOrNull(fields.key);
|
|
46
|
+
const peer = knownOrNull(fields.peer);
|
|
47
|
+
if (tag === 'peer') {
|
|
48
|
+
return {
|
|
49
|
+
kind: 'peer',
|
|
50
|
+
decision: event,
|
|
51
|
+
peer: key === null ? null : sanitizePeer(key),
|
|
52
|
+
reason: fields.reason ?? null,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
if (event === 'refused') {
|
|
56
|
+
return {
|
|
57
|
+
kind: 'connection',
|
|
58
|
+
event: 'refused',
|
|
59
|
+
peer: null,
|
|
60
|
+
protocol: fields.proto ?? 'tcp',
|
|
61
|
+
port: parsePort(fields.port),
|
|
62
|
+
service: fields.service ?? 'forward',
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
kind: 'connection',
|
|
67
|
+
event,
|
|
68
|
+
peer: peer === null ? null : sanitizePeer(peer),
|
|
69
|
+
protocol: fields.proto ?? 'tcp',
|
|
70
|
+
port: parsePort(fields.port),
|
|
71
|
+
service: fields.service ?? 'forward',
|
|
72
|
+
via: knownOrNull(fields.via),
|
|
73
|
+
durationMs: fields.duration ? parseDurationMs(fields.duration) : null,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* tailcat prints the literal `unknown` when it could not determine a field: a
|
|
79
|
+
* connection whose remote address traces back to no peer, or a peer with
|
|
80
|
+
* neither a direct address nor a relay. That is the absence of a value, so
|
|
81
|
+
* report null and let the interface use its own placeholder instead of echoing
|
|
82
|
+
* an English sentinel into a translated view.
|
|
83
|
+
* @param {string | undefined} value - a parsed `key=`, `peer=` or `via=` field.
|
|
84
|
+
* @returns {string | null} the value, or null when tailcat did not know it.
|
|
85
|
+
*/
|
|
86
|
+
function knownOrNull(value) {
|
|
87
|
+
return value === undefined || value === '' || value === 'unknown' ? null : value;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Shorten a node public key for display while keeping enough prefix and suffix
|
|
92
|
+
* to distinguish devices.
|
|
93
|
+
* @param {string} value - full `nodekey:<hex>` value.
|
|
94
|
+
* @returns {string} shortened key.
|
|
95
|
+
*/
|
|
96
|
+
export function sanitizePeer(value) {
|
|
97
|
+
const match = /^([a-z]+):([0-9a-fA-F]+)$/.exec(String(value));
|
|
98
|
+
if (!match) return String(value);
|
|
99
|
+
const [, kind, hex] = match;
|
|
100
|
+
if (hex.length <= 16) return `${kind}:${hex}`;
|
|
101
|
+
return `${kind}:${hex.slice(0, 8)}…${hex.slice(-4)}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Parse a Go duration such as `8.104s`, `532ms`, or `1m3.2s`.
|
|
106
|
+
* @param {string} value - duration text.
|
|
107
|
+
* @returns {number | null} milliseconds, or null when unparsable.
|
|
108
|
+
*/
|
|
109
|
+
export function parseDurationMs(value) {
|
|
110
|
+
const unit = { ns: 1e-6, 'µs': 1e-3, us: 1e-3, ms: 1, s: 1000, m: 60_000, h: 3_600_000 };
|
|
111
|
+
let total = 0;
|
|
112
|
+
let matched = false;
|
|
113
|
+
for (const part of String(value).matchAll(/(\d+(?:\.\d+)?)(ns|µs|us|ms|s|m|h)/g)) {
|
|
114
|
+
total += Number(part[1]) * unit[part[2]];
|
|
115
|
+
matched = true;
|
|
116
|
+
}
|
|
117
|
+
return matched ? Math.round(total) : null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Build the argv for `tailcat serve`. Root flags (`--json`, `--derpmap-url`,
|
|
122
|
+
* `--key`, `--verbose`) precede the subcommand; serve flags follow it. The
|
|
123
|
+
* targets are the complete canonical mapping list the caller owns, so this
|
|
124
|
+
* builder never invents a local endpoint.
|
|
125
|
+
* @param {object} input - effective settings plus the allow-list and targets.
|
|
126
|
+
* @returns {string[]} argv with the executable first.
|
|
127
|
+
* @throws {Error} when no target is supplied.
|
|
128
|
+
*/
|
|
129
|
+
export function buildServeArgs(input) {
|
|
130
|
+
const targets = Array.isArray(input.targets)
|
|
131
|
+
? input.targets.filter((target) => typeof target === 'string' && target !== '')
|
|
132
|
+
: [];
|
|
133
|
+
if (targets.length === 0) {
|
|
134
|
+
throw new Error('buildServeArgs: at least one serve target is required');
|
|
135
|
+
}
|
|
136
|
+
const argv = [input.binaryPath];
|
|
137
|
+
if (input.verbose) argv.push('--verbose');
|
|
138
|
+
argv.push('--json');
|
|
139
|
+
if (input.derpMapUrl) argv.push(`--derpmap-url=${input.derpMapUrl}`);
|
|
140
|
+
argv.push(`--key=${input.addressMode === 'ephemeral' ? 'new' : input.keyName}`);
|
|
141
|
+
argv.push('serve');
|
|
142
|
+
if (input.logAccess) argv.push('--log');
|
|
143
|
+
if (input.fullAddress) argv.push('--full-address');
|
|
144
|
+
if (input.psk === false) argv.push('--psk=false');
|
|
145
|
+
if (input.hybrid) argv.push('--hybrid');
|
|
146
|
+
const allow = Array.isArray(input.allow) ? input.allow.filter((key) => typeof key === 'string' && key !== '') : [];
|
|
147
|
+
if (allow.length > 0) argv.push(`--allow=${allow.join(',')}`);
|
|
148
|
+
argv.push(targets.join(','));
|
|
149
|
+
return argv;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Build the argv for one-shot `tailcat genkey`.
|
|
154
|
+
* @param {{ binaryPath: string, keyName: string, derpMapUrl?: string, force?: boolean, regionMode?: 'auto' | 'explicit' | 'hosts', regionValue?: string, psk?: boolean }} input - key facts.
|
|
155
|
+
* @returns {string[]} argv with the executable first.
|
|
156
|
+
*/
|
|
157
|
+
export function buildGenkeyArgs(input) {
|
|
158
|
+
const argv = [input.binaryPath];
|
|
159
|
+
if (input.derpMapUrl) argv.push(`--derpmap-url=${input.derpMapUrl}`);
|
|
160
|
+
argv.push('genkey');
|
|
161
|
+
if (input.force) argv.push('--force');
|
|
162
|
+
argv.push(`--key=${input.keyName}`);
|
|
163
|
+
if (input.regionMode === 'explicit' || input.regionMode === 'hosts') {
|
|
164
|
+
if (!input.regionValue) throw new Error('buildGenkeyArgs: regionValue is required for an explicit region');
|
|
165
|
+
argv.push(`--region=${input.regionValue}`);
|
|
166
|
+
} else {
|
|
167
|
+
argv.push('--fixed-region');
|
|
168
|
+
}
|
|
169
|
+
if (input.psk === false) argv.push('--psk=false');
|
|
170
|
+
return argv;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The command a client machine runs to expose the tunnel on its own loopback.
|
|
175
|
+
* @param {string} address - tailcat server address.
|
|
176
|
+
* @param {number} port - virtual port inside the tunnel.
|
|
177
|
+
* @param {number} [localPort] - local browser port to bind.
|
|
178
|
+
* @returns {string} shell command.
|
|
179
|
+
*/
|
|
180
|
+
export function buildForwardCommand(address, port, localPort = 18_080) {
|
|
181
|
+
return `tailcat forward ${address} ${localPort}:${port}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Scrub a tailcat address and node keys out of diagnostics before they reach a
|
|
186
|
+
* log line or the interface. The address is a credential: it is sent to the
|
|
187
|
+
* page through the pairing snapshot only.
|
|
188
|
+
* @param {string} line - raw line.
|
|
189
|
+
* @returns {string} scrubbed, bounded text.
|
|
190
|
+
*/
|
|
191
|
+
export function sanitizeLine(line) {
|
|
192
|
+
return String(line)
|
|
193
|
+
.replace(/\btc[A-Za-z0-9+/=_-]{16,}/g, 'tc…')
|
|
194
|
+
.replace(/nodekey:[0-9a-fA-F]{16,}/g, (value) => sanitizePeer(value))
|
|
195
|
+
.trim()
|
|
196
|
+
.slice(0, 500);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* @param {string | undefined} value - port text.
|
|
201
|
+
* @returns {number | null} parsed port.
|
|
202
|
+
*/
|
|
203
|
+
function parsePort(value) {
|
|
204
|
+
if (value === undefined || !/^\d+$/.test(value)) return null;
|
|
205
|
+
const port = Number(value);
|
|
206
|
+
return port >= 0 && port <= 65_535 ? port : null;
|
|
207
|
+
}
|
package/src/paths.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The platform user-config directory tailcat uses for saved keys. This must
|
|
7
|
+
* match Go's os.UserConfigDir: macOS uses Application Support and Windows uses
|
|
8
|
+
* %AppData%, even when XDG_CONFIG_HOME is set.
|
|
9
|
+
* @param {string} [platform] - Node platform.
|
|
10
|
+
* @param {NodeJS.ProcessEnv} [env] - environment.
|
|
11
|
+
* @param {string} [home] - home directory.
|
|
12
|
+
* @returns {string} absolute config root.
|
|
13
|
+
*/
|
|
14
|
+
export function userConfigDir(platform = process.platform, env = process.env, home = os.homedir()) {
|
|
15
|
+
if (platform === 'win32') {
|
|
16
|
+
const configured = env.APPDATA?.trim();
|
|
17
|
+
return configured ? resolveFromHome(configured, home) : path.join(home, 'AppData', 'Roaming');
|
|
18
|
+
}
|
|
19
|
+
if (platform === 'darwin') return path.join(home, 'Library', 'Application Support');
|
|
20
|
+
const configured = env.XDG_CONFIG_HOME?.trim();
|
|
21
|
+
return configured ? resolveFromHome(configured, home) : path.join(home, '.config');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Default parent for devices.json, preferences.json and the managed binary.
|
|
26
|
+
* Configuration rather than state because it holds the saved choices and the
|
|
27
|
+
* device allow-list, which are as important as any config file.
|
|
28
|
+
* @param {string} [platform] - Node platform.
|
|
29
|
+
* @param {NodeJS.ProcessEnv} [env] - environment.
|
|
30
|
+
* @param {string} [home] - home directory.
|
|
31
|
+
* @returns {string} absolute state directory.
|
|
32
|
+
*/
|
|
33
|
+
export function defaultStateDir(platform = process.platform, env = process.env, home = os.homedir()) {
|
|
34
|
+
return path.join(userConfigDir(platform, env, home), 'tailcat-webui');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Common package-manager locations for a user-installed tailcat. */
|
|
38
|
+
export function knownTailcatPaths(platform = process.platform) {
|
|
39
|
+
if (platform === 'darwin') return ['/opt/homebrew/bin/tailcat', '/usr/local/bin/tailcat'];
|
|
40
|
+
if (platform === 'linux') {
|
|
41
|
+
return [
|
|
42
|
+
'/usr/local/bin/tailcat',
|
|
43
|
+
'/usr/bin/tailcat',
|
|
44
|
+
'/bin/tailcat',
|
|
45
|
+
'/snap/bin/tailcat',
|
|
46
|
+
'/home/linuxbrew/.linuxbrew/bin/tailcat',
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Find an executable tailcat in a well-known package-manager location.
|
|
54
|
+
* @param {string} [platform] - Node platform.
|
|
55
|
+
* @returns {string | null} absolute path when present.
|
|
56
|
+
*/
|
|
57
|
+
export function findKnownTailcat(platform = process.platform) {
|
|
58
|
+
for (const candidate of knownTailcatPaths(platform)) {
|
|
59
|
+
try {
|
|
60
|
+
if (fs.statSync(candidate).isFile()) {
|
|
61
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
62
|
+
return candidate;
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
// Keep looking.
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Resolve a tailcat key name or path to the saved-key file tailcat reads.
|
|
73
|
+
* A name maps to `<user config>/tailcat/keys/<name>.private.json`; a value
|
|
74
|
+
* carrying a separator is treated as a path, matching tailcat's own rule.
|
|
75
|
+
* Relative paths resolve from the process home directory, which is also the
|
|
76
|
+
* supervisor's working directory.
|
|
77
|
+
* @param {string} keyName - configured key name or path.
|
|
78
|
+
* @param {string} [platform] - Node platform.
|
|
79
|
+
* @param {NodeJS.ProcessEnv} [env] - environment.
|
|
80
|
+
* @param {string} [home] - home directory.
|
|
81
|
+
* @returns {string} absolute key file path.
|
|
82
|
+
*/
|
|
83
|
+
export function tailcatKeyPath(keyName, platform = process.platform, env = process.env, home = os.homedir()) {
|
|
84
|
+
if (keyName.includes('/') || keyName.includes('\\')) {
|
|
85
|
+
return path.isAbsolute(keyName) ? keyName : path.resolve(home, keyName);
|
|
86
|
+
}
|
|
87
|
+
return path.join(userConfigDir(platform, env, home), 'tailcat', 'keys', `${keyName}.private.json`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {string} value - possibly relative config root.
|
|
92
|
+
* @param {string} home - home directory.
|
|
93
|
+
* @returns {string} absolute path.
|
|
94
|
+
*/
|
|
95
|
+
function resolveFromHome(value, home) {
|
|
96
|
+
return path.isAbsolute(value) ? value : path.resolve(home, value);
|
|
97
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
import { normalizeDerpMapUrl } from './relay.js';
|
|
6
|
+
import { mergeSettings, normalizeSettingsPatch } from './settings.js';
|
|
7
|
+
|
|
8
|
+
const PREFERENCE_VERSION = 2;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Preferences: the small choices the interface owns, as opposed to the
|
|
12
|
+
* deployment settings that live in config. `derpMapUrl` is an optional
|
|
13
|
+
* override of the configured DERP map; `settings` holds only the settings that
|
|
14
|
+
* were changed from the interface, so untouched fields keep following the
|
|
15
|
+
* deployment config.
|
|
16
|
+
*
|
|
17
|
+
* The document is deliberately tiny and forward-compatible: unknown top-level
|
|
18
|
+
* keys are preserved when the file is written, and a malformed file falls back
|
|
19
|
+
* to the defaults with a warning instead of failing activation. The unknown-key
|
|
20
|
+
* rule is what lets another tool keep its own state in the same file.
|
|
21
|
+
* @param {{ dir?: string, logger?: { warn: (...args: any[]) => void } }} [options] - test/overrides.
|
|
22
|
+
*/
|
|
23
|
+
export function createFilePreferenceStore(options = {}) {
|
|
24
|
+
const dir = options.dir ?? defaultStateDir();
|
|
25
|
+
const file = path.join(dir, 'preferences.json');
|
|
26
|
+
const logger = options.logger;
|
|
27
|
+
/** @type {{ derpMapUrl: string, settings: Record<string, unknown> }} */
|
|
28
|
+
let value = defaults();
|
|
29
|
+
/** @type {Record<string, unknown>} */
|
|
30
|
+
let unknown = {};
|
|
31
|
+
/** @type {string[]} */
|
|
32
|
+
let warnings = [];
|
|
33
|
+
let updatedAt = null;
|
|
34
|
+
|
|
35
|
+
load();
|
|
36
|
+
|
|
37
|
+
/** @returns {{ derpMapUrl: string, settings: Record<string, unknown> }} the documented defaults. */
|
|
38
|
+
function defaults() {
|
|
39
|
+
return { derpMapUrl: '', settings: {} };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Read the durable document, tolerating absence and dropping invalid rows. */
|
|
43
|
+
function load() {
|
|
44
|
+
value = defaults();
|
|
45
|
+
unknown = {};
|
|
46
|
+
warnings = [];
|
|
47
|
+
updatedAt = null;
|
|
48
|
+
let text;
|
|
49
|
+
try {
|
|
50
|
+
text = fs.readFileSync(file, 'utf8');
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error && error.code === 'ENOENT') return;
|
|
53
|
+
warnings.push(`Could not read the preferences: ${messageOf(error)}`);
|
|
54
|
+
logger?.warn(`tailcat-webui: ${warnings.at(-1)}`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
let document;
|
|
58
|
+
try {
|
|
59
|
+
document = JSON.parse(text);
|
|
60
|
+
} catch {
|
|
61
|
+
warnings.push('The preferences file is not valid JSON; using the defaults.');
|
|
62
|
+
logger?.warn(`tailcat-webui: ${warnings.at(-1)}`);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (document === null || typeof document !== 'object' || Array.isArray(document)) {
|
|
66
|
+
warnings.push('The preferences file has an unknown shape; using the defaults.');
|
|
67
|
+
logger?.warn(`tailcat-webui: ${warnings.at(-1)}`);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const { version: _version, updatedAt: _updatedAt, derpMapUrl, settings, ...rest } = document;
|
|
71
|
+
if (typeof derpMapUrl === 'string') {
|
|
72
|
+
try {
|
|
73
|
+
value.derpMapUrl = normalizeDerpMapUrl(derpMapUrl);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
warnings.push(`Ignored an invalid derpMapUrl preference: ${messageOf(error)}`);
|
|
76
|
+
}
|
|
77
|
+
} else if (derpMapUrl !== undefined) {
|
|
78
|
+
warnings.push('Ignored a non-string derpMapUrl preference.');
|
|
79
|
+
}
|
|
80
|
+
if (settings !== undefined) {
|
|
81
|
+
if (settings !== null && typeof settings === 'object' && !Array.isArray(settings)) {
|
|
82
|
+
for (const [key, raw] of Object.entries(settings)) {
|
|
83
|
+
try {
|
|
84
|
+
const normalized = normalizeSettingsPatch({ [key]: raw });
|
|
85
|
+
if (normalized[key] === null) continue;
|
|
86
|
+
value.settings[key] = normalized[key];
|
|
87
|
+
} catch (error) {
|
|
88
|
+
warnings.push(`Ignored an invalid ${key} setting: ${messageOf(error)}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
warnings.push('Ignored an invalid settings preference; using no overrides.');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
unknown = rest;
|
|
96
|
+
updatedAt = typeof document.updatedAt === 'string' ? document.updatedAt : null;
|
|
97
|
+
if (warnings.length > 0) logger?.warn(`tailcat-webui: ${warnings.join(' ')}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Persist the optional DERP map URL. An empty string clears the override and
|
|
102
|
+
* makes the deployment config apply. This never rotates the saved key; it
|
|
103
|
+
* only changes the map the next start reads.
|
|
104
|
+
* @param {unknown} mapUrl - absolute HTTP(S) URL, or an empty string.
|
|
105
|
+
* @returns {ReturnType<typeof snapshot>} the persisted preferences.
|
|
106
|
+
* @throws {RemoteAccessError} when the URL is invalid.
|
|
107
|
+
*/
|
|
108
|
+
function setDerpMapUrl(mapUrl) {
|
|
109
|
+
if (typeof mapUrl !== 'string') {
|
|
110
|
+
throw new RemoteAccessError('invalid-derp-map-url', 'The DERP map URL must be a string.', 400);
|
|
111
|
+
}
|
|
112
|
+
const normalized = normalizeDerpMapUrl(mapUrl);
|
|
113
|
+
if (normalized === value.derpMapUrl) return snapshot();
|
|
114
|
+
return persist({ ...value, derpMapUrl: normalized });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Persist a validated settings patch. A null value deletes the override, so
|
|
119
|
+
* that field starts following the deployment config again.
|
|
120
|
+
* @param {unknown} patch - settings patch.
|
|
121
|
+
* @returns {ReturnType<typeof snapshot>} the persisted preferences.
|
|
122
|
+
* @throws {RemoteAccessError} when the patch is invalid.
|
|
123
|
+
*/
|
|
124
|
+
function setSettings(patch) {
|
|
125
|
+
const normalized = normalizeSettingsPatch(patch);
|
|
126
|
+
const next = mergeSettings(value.settings, normalized);
|
|
127
|
+
if (same(next, value.settings)) return snapshot();
|
|
128
|
+
return persist({ ...value, settings: next });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* @param {{ derpMapUrl: string, settings: Record<string, unknown> }} next - complete preference value.
|
|
133
|
+
* @returns {ReturnType<typeof snapshot>} the persisted preferences.
|
|
134
|
+
*/
|
|
135
|
+
function persist(next) {
|
|
136
|
+
const document = {
|
|
137
|
+
...unknown,
|
|
138
|
+
version: PREFERENCE_VERSION,
|
|
139
|
+
...next,
|
|
140
|
+
updatedAt: new Date().toISOString(),
|
|
141
|
+
};
|
|
142
|
+
try {
|
|
143
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
144
|
+
const temporary = path.join(dir, `.preferences.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`);
|
|
145
|
+
fs.writeFileSync(temporary, `${JSON.stringify(document, null, 2)}\n`, { mode: 0o600 });
|
|
146
|
+
fs.renameSync(temporary, file);
|
|
147
|
+
try {
|
|
148
|
+
fs.chmodSync(file, 0o600);
|
|
149
|
+
} catch {
|
|
150
|
+
// A filesystem without POSIX modes still stores the file.
|
|
151
|
+
}
|
|
152
|
+
} catch (error) {
|
|
153
|
+
throw new Error(`Could not save the preferences: ${messageOf(error)}`);
|
|
154
|
+
}
|
|
155
|
+
value = next;
|
|
156
|
+
warnings = [];
|
|
157
|
+
updatedAt = document.updatedAt;
|
|
158
|
+
return snapshot();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @returns {{ derpMapUrl: string, settings: Record<string, unknown>, file: string, updatedAt: string | null, warnings: string[] }} */
|
|
162
|
+
function snapshot() {
|
|
163
|
+
return {
|
|
164
|
+
...value,
|
|
165
|
+
settings: { ...value.settings },
|
|
166
|
+
file,
|
|
167
|
+
updatedAt,
|
|
168
|
+
warnings: [...warnings],
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return { file, setDerpMapUrl, setSettings, reload: load, snapshot };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* @param {unknown} error - thrown value.
|
|
177
|
+
* @returns {string} readable text.
|
|
178
|
+
*/
|
|
179
|
+
function messageOf(error) {
|
|
180
|
+
return error instanceof Error ? error.message : String(error);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* @param {unknown} a - left value.
|
|
185
|
+
* @param {unknown} b - right value.
|
|
186
|
+
* @returns {boolean} structural equality.
|
|
187
|
+
*/
|
|
188
|
+
function same(a, b) {
|
|
189
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
190
|
+
}
|
package/src/qr.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
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() === '') {
|
|
14
|
+
throw new Error('qrMatrix: text must be a non-empty string');
|
|
15
|
+
}
|
|
16
|
+
const maxVersion = Math.min(Math.max(options.maxVersion ?? 20, 1), 40);
|
|
17
|
+
const errorCorrection = options.errorCorrection ?? 'M';
|
|
18
|
+
let lastError;
|
|
19
|
+
for (let version = 1; version <= maxVersion; version += 1) {
|
|
20
|
+
try {
|
|
21
|
+
const qr = qrcode(version, errorCorrection);
|
|
22
|
+
qr.addData(text);
|
|
23
|
+
qr.make();
|
|
24
|
+
const size = qr.getModuleCount();
|
|
25
|
+
const rows = [];
|
|
26
|
+
for (let row = 0; row < size; row += 1) {
|
|
27
|
+
let bits = '';
|
|
28
|
+
for (let column = 0; column < size; column += 1) bits += qr.isDark(row, column) ? '1' : '0';
|
|
29
|
+
rows.push(bits);
|
|
30
|
+
}
|
|
31
|
+
return { version, size, rows };
|
|
32
|
+
} catch (error) {
|
|
33
|
+
lastError = error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
throw new Error(`qrMatrix: text does not fit QR version ${maxVersion} at level ${errorCorrection}: ${String(lastError)}`);
|
|
37
|
+
}
|
package/src/relay.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { RemoteAccessError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
/** Bounded so a malformed preference cannot bloat the argv or the control body. */
|
|
4
|
+
const MAX_DERP_MAP_URL_LENGTH = 2_048;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Normalize the optional DERP map URL owned by the panel. Empty means "no
|
|
8
|
+
* panel override": the deployment config applies, then tailcat's own default
|
|
9
|
+
* map. tailcat fetches the URL as-is, so only absolute HTTP(S) URLs are
|
|
10
|
+
* accepted; credentials and fragments are rejected because they would not
|
|
11
|
+
* survive tailcat's cache key or HTTP request meaningfully.
|
|
12
|
+
* @param {unknown} value - draft or persisted value.
|
|
13
|
+
* @returns {string} trimmed URL, or an empty string.
|
|
14
|
+
* @throws {RemoteAccessError} when the value is not a usable HTTP(S) URL.
|
|
15
|
+
*/
|
|
16
|
+
export function normalizeDerpMapUrl(value) {
|
|
17
|
+
if (value === null || value === undefined) return '';
|
|
18
|
+
if (typeof value !== 'string') {
|
|
19
|
+
throw new RemoteAccessError('invalid-derp-map-url', 'The DERP map URL must be a string.', 400);
|
|
20
|
+
}
|
|
21
|
+
const trimmed = value.trim();
|
|
22
|
+
if (trimmed === '') return '';
|
|
23
|
+
if (trimmed.length > MAX_DERP_MAP_URL_LENGTH) {
|
|
24
|
+
throw new RemoteAccessError(
|
|
25
|
+
'invalid-derp-map-url',
|
|
26
|
+
`The DERP map URL must be at most ${MAX_DERP_MAP_URL_LENGTH} characters.`,
|
|
27
|
+
400,
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = new URL(trimmed);
|
|
33
|
+
} catch {
|
|
34
|
+
throw new RemoteAccessError('invalid-derp-map-url', 'The DERP map URL must be an absolute URL.', 400);
|
|
35
|
+
}
|
|
36
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
37
|
+
throw new RemoteAccessError('invalid-derp-map-url', 'The DERP map URL must use http:// or https://.', 400);
|
|
38
|
+
}
|
|
39
|
+
if (parsed.hostname === '') {
|
|
40
|
+
throw new RemoteAccessError('invalid-derp-map-url', 'The DERP map URL must name a host.', 400);
|
|
41
|
+
}
|
|
42
|
+
if (parsed.username !== '' || parsed.password !== '') {
|
|
43
|
+
throw new RemoteAccessError(
|
|
44
|
+
'invalid-derp-map-url',
|
|
45
|
+
'The DERP map URL must not embed credentials; tailcat shows the URL in its process arguments.',
|
|
46
|
+
400,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
if (parsed.hash !== '') {
|
|
50
|
+
throw new RemoteAccessError('invalid-derp-map-url', 'The DERP map URL must not carry a fragment.', 400);
|
|
51
|
+
}
|
|
52
|
+
return trimmed;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Display-safe relay facts for the interface. The URL is shown because the
|
|
57
|
+
* operator has to copy it to clients; it is kept out of `configView`, which is
|
|
58
|
+
* the deployment-settings surface.
|
|
59
|
+
* @param {string} mapUrl - effective URL, or empty for tailcat's default map.
|
|
60
|
+
* @param {'panel' | 'config' | 'default'} source - where the effective value came from.
|
|
61
|
+
* @param {{ fullAddress?: boolean }} [options] - whether the address embeds its relay nodes.
|
|
62
|
+
* @returns {{ mapUrl: string, custom: boolean, source: 'panel' | 'config' | 'default', insecure: boolean, fullAddress: boolean, needsClientMap: boolean, clientEnv: string }} relay view.
|
|
63
|
+
*/
|
|
64
|
+
export function relayView(mapUrl, source, options = {}) {
|
|
65
|
+
const url = typeof mapUrl === 'string' ? mapUrl : '';
|
|
66
|
+
const fullAddress = options.fullAddress === true;
|
|
67
|
+
return {
|
|
68
|
+
mapUrl: url,
|
|
69
|
+
custom: url !== '',
|
|
70
|
+
source: source === 'panel' || source === 'config' ? source : 'default',
|
|
71
|
+
insecure: /^http:\/\//i.test(url),
|
|
72
|
+
fullAddress,
|
|
73
|
+
needsClientMap: url !== '' && !fullAddress,
|
|
74
|
+
clientEnv: url === '' || fullAddress ? '' : `TAILCAT_DERPMAP_URL=${url}`,
|
|
75
|
+
};
|
|
76
|
+
}
|