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/server.js
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
import fsp from 'node:fs/promises';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { errorMessage, RemoteAccessError } from './errors.js';
|
|
6
|
+
import { createTailcatManager } from './manager.js';
|
|
7
|
+
|
|
8
|
+
const PACKAGE_WEB_ROOT = path.resolve(fileURLToPath(new URL('../web/', import.meta.url)));
|
|
9
|
+
const DEFAULT_PORT = 17_890;
|
|
10
|
+
const DEFAULT_HOST = '127.0.0.1';
|
|
11
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
12
|
+
const MAX_MESSAGE_LENGTH = 2_000;
|
|
13
|
+
const LOOPBACK_NAMES = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
|
|
14
|
+
const SILENT_LOGGER = Object.freeze({ info() {}, warn() {}, debug() {} });
|
|
15
|
+
|
|
16
|
+
const SECURITY_HEADERS = Object.freeze({
|
|
17
|
+
'x-content-type-options': 'nosniff',
|
|
18
|
+
'referrer-policy': 'no-referrer',
|
|
19
|
+
'content-security-policy':
|
|
20
|
+
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'",
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const CONTENT_TYPES = Object.freeze({
|
|
24
|
+
'.html': 'text/html; charset=utf-8',
|
|
25
|
+
'.htm': 'text/html; charset=utf-8',
|
|
26
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
27
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
28
|
+
'.css': 'text/css; charset=utf-8',
|
|
29
|
+
'.svg': 'image/svg+xml',
|
|
30
|
+
'.png': 'image/png',
|
|
31
|
+
'.jpg': 'image/jpeg',
|
|
32
|
+
'.jpeg': 'image/jpeg',
|
|
33
|
+
'.gif': 'image/gif',
|
|
34
|
+
'.webp': 'image/webp',
|
|
35
|
+
'.ico': 'image/x-icon',
|
|
36
|
+
'.json': 'application/json; charset=utf-8',
|
|
37
|
+
'.webmanifest': 'application/manifest+json',
|
|
38
|
+
'.map': 'application/json; charset=utf-8',
|
|
39
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
40
|
+
'.woff': 'font/woff',
|
|
41
|
+
'.woff2': 'font/woff2',
|
|
42
|
+
'.ttf': 'font/ttf',
|
|
43
|
+
'.otf': 'font/otf',
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Create the standalone console: a loopback-only HTTP surface over the
|
|
48
|
+
* manager, plus the static files shipped in `web/`.
|
|
49
|
+
*
|
|
50
|
+
* The security model is deliberately narrow. The console controls a tunnel, so
|
|
51
|
+
* any page on the machine that can reach it must not be able to call it
|
|
52
|
+
* cross-origin, and a remote page must not be able to reach it through DNS
|
|
53
|
+
* rebinding: the Host, Origin, content type, and a custom header are all
|
|
54
|
+
* checked, and the server refuses to bind anything but loopback.
|
|
55
|
+
* @param {object} [options] - server options.
|
|
56
|
+
* @param {unknown} [options.config] - manager config.
|
|
57
|
+
* @param {string} [options.stateDir] - manager state directory.
|
|
58
|
+
* @param {object} [options.logger] - logger.
|
|
59
|
+
* @param {number} [options.port] - local port; 0 picks a free one.
|
|
60
|
+
* @param {string} [options.host] - loopback bind address.
|
|
61
|
+
* @param {string} [options.webRoot] - static root override.
|
|
62
|
+
* @param {object} [options.manager] - prebuilt manager (embedding and tests).
|
|
63
|
+
* @param {object} [options.serve] - manager serve options (reserved ports, ready, validate, label).
|
|
64
|
+
* @param {object} [options.pairing] - manager pairing options.
|
|
65
|
+
* @param {object} [options.installer] - manager installer options.
|
|
66
|
+
* @param {object} [options.runtime] - process adapter for the manager.
|
|
67
|
+
* @param {object} [options.preferences] - custom preference store.
|
|
68
|
+
* @param {object} [options.devices] - custom allow-list store.
|
|
69
|
+
* @param {string} [options.clientForwardHint] - extra command hint.
|
|
70
|
+
* @returns {{ start: () => Promise<string>, stop: () => Promise<void>, url: string | null, manager: object, server: object | null }}
|
|
71
|
+
*/
|
|
72
|
+
export function createTailcatWebui(options = {}) {
|
|
73
|
+
const port = normalizePort(options.port ?? DEFAULT_PORT);
|
|
74
|
+
const host = normalizeHost(options.host ?? DEFAULT_HOST);
|
|
75
|
+
const logger = options.logger ?? SILENT_LOGGER;
|
|
76
|
+
const webRoot = options.webRoot ? path.resolve(options.webRoot) : PACKAGE_WEB_ROOT;
|
|
77
|
+
|
|
78
|
+
let managerRef = null;
|
|
79
|
+
const ownsManager = !options.manager;
|
|
80
|
+
const manager =
|
|
81
|
+
options.manager ??
|
|
82
|
+
createTailcatManager({
|
|
83
|
+
config: options.config,
|
|
84
|
+
stateDir: options.stateDir,
|
|
85
|
+
logger,
|
|
86
|
+
runtime: options.runtime,
|
|
87
|
+
preferences: options.preferences,
|
|
88
|
+
devices: options.devices,
|
|
89
|
+
serve:
|
|
90
|
+
options.serve && typeof options.serve.targets === 'function'
|
|
91
|
+
? options.serve
|
|
92
|
+
: { targets: () => (managerRef ? managerRef.effectiveSettings().extraTargets : []) },
|
|
93
|
+
pairing: options.pairing,
|
|
94
|
+
installer: options.installer,
|
|
95
|
+
clientForwardHint: options.clientForwardHint,
|
|
96
|
+
});
|
|
97
|
+
managerRef = manager;
|
|
98
|
+
|
|
99
|
+
/** @type {http.Server | null} */
|
|
100
|
+
let server = null;
|
|
101
|
+
let serverUrl = null;
|
|
102
|
+
let actualPort = port;
|
|
103
|
+
let starting = null;
|
|
104
|
+
let stopping = null;
|
|
105
|
+
|
|
106
|
+
/** @returns {string} the console URL. */
|
|
107
|
+
function buildUrl() {
|
|
108
|
+
return `http://${host === '::1' ? '[::1]' : host}:${actualPort}/`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** @returns {{ url: string | null, host: string, port: number }} facts for the API envelope. */
|
|
112
|
+
function serverInfo() {
|
|
113
|
+
return { url: serverUrl, host, port: actualPort };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** @returns {object} snapshot plus the envelope fields. */
|
|
117
|
+
function stateBody() {
|
|
118
|
+
return { ok: true, ...manager.snapshot(), server: serverInfo() };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* @param {http.IncomingMessage} req - request.
|
|
123
|
+
* @param {http.ServerResponse} res - response.
|
|
124
|
+
*/
|
|
125
|
+
function handleRequest(req, res) {
|
|
126
|
+
res.once('finish', () => {
|
|
127
|
+
logger.info?.(`${req.method ?? 'GET'} ${requestPath(req)} ${res.statusCode}`);
|
|
128
|
+
});
|
|
129
|
+
route(req, res).catch((error) => {
|
|
130
|
+
logger.warn?.(`tailcat-webui: request failed: ${errorMessage(error)}`);
|
|
131
|
+
if (res.headersSent) {
|
|
132
|
+
res.end();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
fail(res, 500, 'internal-error', 'The request could not be completed.', wantsJson(requestPath(req)));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {http.IncomingMessage} req - request.
|
|
141
|
+
* @param {http.ServerResponse} res - response.
|
|
142
|
+
* @returns {Promise<void>}
|
|
143
|
+
*/
|
|
144
|
+
async function route(req, res) {
|
|
145
|
+
const method = String(req.method ?? 'GET').toUpperCase();
|
|
146
|
+
const pathname = requestPath(req);
|
|
147
|
+
if (pathname === null) {
|
|
148
|
+
fail(res, 400, 'invalid-request', 'The request path is not valid.', false);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (!hostAllowed(req.headers.host)) {
|
|
152
|
+
fail(res, 421, 'bad-host', 'The request must use a loopback Host header with this server port.', wantsJson(pathname));
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (pathname === '/api/health') {
|
|
156
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
157
|
+
methodNotAllowed(res, ['GET', 'HEAD'], true);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
sendJson(res, 200, { ok: true, now: new Date().toISOString() }, method === 'HEAD');
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (pathname === '/api/state') {
|
|
164
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
165
|
+
methodNotAllowed(res, ['GET', 'HEAD'], true);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
sendJson(res, 200, stateBody(), method === 'HEAD');
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (pathname === '/api/action') {
|
|
172
|
+
if (method !== 'POST') {
|
|
173
|
+
methodNotAllowed(res, ['POST'], true);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
await handleAction(req, res);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (pathname.startsWith('/api/')) {
|
|
180
|
+
fail(res, 404, 'not-found', 'Not found.', true);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
await serveStatic(req, res, method, pathname);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* @param {http.IncomingMessage} req - request.
|
|
188
|
+
* @param {http.ServerResponse} res - response.
|
|
189
|
+
* @returns {Promise<void>}
|
|
190
|
+
*/
|
|
191
|
+
async function handleAction(req, res) {
|
|
192
|
+
const rejection = postRejection(req);
|
|
193
|
+
if (rejection !== null) {
|
|
194
|
+
fail(res, 403, 'forbidden', rejection, true);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
let text;
|
|
198
|
+
try {
|
|
199
|
+
text = await readBody(req);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (error instanceof PayloadTooLarge) {
|
|
202
|
+
fail(res, 413, 'payload-too-large', 'The request body is too large.', true);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
fail(res, 400, 'invalid-request', 'The request body could not be read.', true);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
let body;
|
|
209
|
+
try {
|
|
210
|
+
body = JSON.parse(text);
|
|
211
|
+
} catch {
|
|
212
|
+
fail(res, 400, 'invalid-json', 'The request body must be valid JSON.', true);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body) || typeof body.action !== 'string') {
|
|
216
|
+
fail(res, 400, 'invalid-action', 'The request body must be an object with an action name.', true);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
const snapshot = await manager.action(body.action, body);
|
|
221
|
+
sendJson(res, 200, { ok: true, ...snapshot, server: serverInfo() });
|
|
222
|
+
} catch (error) {
|
|
223
|
+
const status = error instanceof RemoteAccessError ? error.status : 500;
|
|
224
|
+
const code = error instanceof RemoteAccessError ? error.code : 'internal-error';
|
|
225
|
+
const message = errorMessage(error).slice(0, MAX_MESSAGE_LENGTH);
|
|
226
|
+
sendJson(res, status, { ok: false, error: { code, message } });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* @param {http.IncomingMessage} req - request.
|
|
232
|
+
* @returns {string | null} the reason the request is not an allowed action call.
|
|
233
|
+
*/
|
|
234
|
+
function postRejection(req) {
|
|
235
|
+
const contentType = String(req.headers['content-type'] ?? '')
|
|
236
|
+
.split(';')[0]
|
|
237
|
+
.trim()
|
|
238
|
+
.toLowerCase();
|
|
239
|
+
if (contentType !== 'application/json') {
|
|
240
|
+
return 'The action endpoint requires content-type: application/json.';
|
|
241
|
+
}
|
|
242
|
+
const origin = req.headers.origin;
|
|
243
|
+
if (origin !== undefined && String(origin) !== '' && !sameOrigin(String(origin))) {
|
|
244
|
+
return 'The action request must come from the console itself.';
|
|
245
|
+
}
|
|
246
|
+
if (String(req.headers['x-tailcat-webui'] ?? '').trim() !== '1') {
|
|
247
|
+
return 'The action request is missing the x-tailcat-webui: 1 header.';
|
|
248
|
+
}
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* @param {string} origin - Origin header value.
|
|
254
|
+
* @returns {boolean} whether it names this console.
|
|
255
|
+
*/
|
|
256
|
+
function sameOrigin(origin) {
|
|
257
|
+
let parsed;
|
|
258
|
+
try {
|
|
259
|
+
parsed = new URL(origin);
|
|
260
|
+
} catch {
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
if (parsed.protocol !== 'http:') return false;
|
|
264
|
+
const originPort = parsed.port === '' ? 80 : Number(parsed.port);
|
|
265
|
+
if (originPort !== actualPort) return false;
|
|
266
|
+
return isLoopbackName(parsed.hostname);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* @param {string | undefined} value - Host header value.
|
|
271
|
+
* @returns {boolean} whether it names this console on loopback.
|
|
272
|
+
*/
|
|
273
|
+
function hostAllowed(value) {
|
|
274
|
+
if (typeof value !== 'string' || value.trim() === '') return false;
|
|
275
|
+
const parsed = parseHostHeader(value.trim());
|
|
276
|
+
if (parsed === null) return false;
|
|
277
|
+
if (parsed.port !== actualPort) return false;
|
|
278
|
+
return isLoopbackName(parsed.host);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* @param {object} req - request.
|
|
283
|
+
* @returns {string} bounded body text.
|
|
284
|
+
*/
|
|
285
|
+
function readBody(req) {
|
|
286
|
+
return new Promise((resolve, reject) => {
|
|
287
|
+
const chunks = [];
|
|
288
|
+
let length = 0;
|
|
289
|
+
let tooLarge = false;
|
|
290
|
+
req.on('data', (chunk) => {
|
|
291
|
+
if (tooLarge) return;
|
|
292
|
+
length += chunk.length;
|
|
293
|
+
if (length > MAX_BODY_BYTES) {
|
|
294
|
+
tooLarge = true;
|
|
295
|
+
chunks.length = 0;
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
chunks.push(chunk);
|
|
299
|
+
});
|
|
300
|
+
req.on('end', () => {
|
|
301
|
+
if (tooLarge) reject(new PayloadTooLarge());
|
|
302
|
+
else resolve(Buffer.concat(chunks).toString('utf8'));
|
|
303
|
+
});
|
|
304
|
+
req.on('error', (error) => reject(error));
|
|
305
|
+
req.on('aborted', () => reject(new Error('The request was aborted.')));
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* @param {http.IncomingMessage} req - request.
|
|
311
|
+
* @param {http.ServerResponse} res - response.
|
|
312
|
+
* @param {string} method - request method.
|
|
313
|
+
* @param {string} pathname - decoded path.
|
|
314
|
+
* @returns {Promise<void>}
|
|
315
|
+
*/
|
|
316
|
+
async function serveStatic(req, res, method, pathname) {
|
|
317
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
318
|
+
methodNotAllowed(res, ['GET', 'HEAD'], false);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
let decoded;
|
|
322
|
+
try {
|
|
323
|
+
decoded = decodeURIComponent(pathname);
|
|
324
|
+
} catch {
|
|
325
|
+
fail(res, 404, 'not-found', 'Not found.', false);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (decoded.includes('\0')) {
|
|
329
|
+
fail(res, 404, 'not-found', 'Not found.', false);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const file = await resolveStaticFile(decoded);
|
|
333
|
+
if (file === null) {
|
|
334
|
+
fail(res, 404, 'not-found', 'Not found.', false);
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
let data;
|
|
338
|
+
try {
|
|
339
|
+
data = await fsp.readFile(file);
|
|
340
|
+
} catch {
|
|
341
|
+
fail(res, 404, 'not-found', 'Not found.', false);
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
res.statusCode = 200;
|
|
345
|
+
res.setHeader('content-type', contentTypeFor(file));
|
|
346
|
+
res.setHeader('cache-control', 'no-store');
|
|
347
|
+
applySecurityHeaders(res);
|
|
348
|
+
res.setHeader('content-length', data.length);
|
|
349
|
+
if (method === 'HEAD') res.end();
|
|
350
|
+
else res.end(data);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Resolve a URL path to a file inside the static root. `/assets/*` is served
|
|
355
|
+
* from `web/assets/*` and also from `web/*`, so a flat or nested asset layout
|
|
356
|
+
* both work. Every resolved path is checked against the root again, which is
|
|
357
|
+
* the traversal guard that survives encoded separators.
|
|
358
|
+
* @param {string} pathname - decoded path.
|
|
359
|
+
* @returns {Promise<string | null>} absolute file path.
|
|
360
|
+
*/
|
|
361
|
+
async function resolveStaticFile(pathname) {
|
|
362
|
+
if (pathname === '/' || pathname === '/index.html') return firstFile([['index.html']]);
|
|
363
|
+
if (pathname === '/icon.png') {
|
|
364
|
+
return firstFile([['icon.png'], ['assets', 'icon.png'], ['icon.svg'], ['assets', 'icon.svg']]);
|
|
365
|
+
}
|
|
366
|
+
if (pathname === '/icon.svg') {
|
|
367
|
+
return firstFile([['icon.svg'], ['assets', 'icon.svg'], ['icon.png'], ['assets', 'icon.png']]);
|
|
368
|
+
}
|
|
369
|
+
if (pathname.startsWith('/assets/')) {
|
|
370
|
+
const segments = safeSegments(pathname.slice('/assets/'.length));
|
|
371
|
+
if (segments === null) return null;
|
|
372
|
+
return firstFile([['assets', ...segments], segments]);
|
|
373
|
+
}
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* @param {string[][]} candidates - segment lists relative to the static root.
|
|
379
|
+
* @returns {Promise<string | null>} first existing file inside the root.
|
|
380
|
+
*/
|
|
381
|
+
async function firstFile(candidates) {
|
|
382
|
+
const root = path.resolve(webRoot);
|
|
383
|
+
for (const segments of candidates) {
|
|
384
|
+
const resolved = path.resolve(path.join(root, ...segments));
|
|
385
|
+
if (resolved !== root && !resolved.startsWith(root + path.sep)) continue;
|
|
386
|
+
try {
|
|
387
|
+
const stats = await fsp.stat(resolved);
|
|
388
|
+
if (stats.isFile()) return resolved;
|
|
389
|
+
} catch {
|
|
390
|
+
// Try the next layout.
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* @param {string} relative - path below /assets/.
|
|
398
|
+
* @returns {string[] | null} safe segments.
|
|
399
|
+
*/
|
|
400
|
+
function safeSegments(relative) {
|
|
401
|
+
const segments = [];
|
|
402
|
+
for (const raw of relative.split('/')) {
|
|
403
|
+
if (raw === '' || raw === '.') continue;
|
|
404
|
+
if (raw === '..' || raw.includes('\\') || raw.includes('\0')) return null;
|
|
405
|
+
segments.push(raw);
|
|
406
|
+
}
|
|
407
|
+
return segments;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Bind the listener, then activate the manager. */
|
|
411
|
+
async function start() {
|
|
412
|
+
if (server !== null) return serverUrl;
|
|
413
|
+
if (starting !== null) return starting;
|
|
414
|
+
starting = (async () => {
|
|
415
|
+
const created = http.createServer((req, res) => {
|
|
416
|
+
handleRequest(req, res);
|
|
417
|
+
});
|
|
418
|
+
created.on('clientError', (error, socket) => {
|
|
419
|
+
if (socket.writable) socket.end('HTTP/1.1 400 Bad Request\r\nconnection: close\r\n\r\n');
|
|
420
|
+
});
|
|
421
|
+
try {
|
|
422
|
+
await listen(created);
|
|
423
|
+
} catch (error) {
|
|
424
|
+
created.close();
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
created.on('error', (error) => logger.warn?.(`tailcat-webui: server error: ${errorMessage(error)}`));
|
|
428
|
+
server = created;
|
|
429
|
+
const address = created.address();
|
|
430
|
+
if (address !== null && typeof address === 'object') actualPort = address.port;
|
|
431
|
+
serverUrl = buildUrl();
|
|
432
|
+
logger.info?.(`tailcat-webui: listening on ${serverUrl}`);
|
|
433
|
+
try {
|
|
434
|
+
await manager.activate();
|
|
435
|
+
} catch (error) {
|
|
436
|
+
logger.warn?.(`tailcat-webui: activation failed: ${errorMessage(error)}`);
|
|
437
|
+
}
|
|
438
|
+
return serverUrl;
|
|
439
|
+
})().finally(() => {
|
|
440
|
+
starting = null;
|
|
441
|
+
});
|
|
442
|
+
return starting;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Close the listener and dispose the manager this console owns. */
|
|
446
|
+
async function stop() {
|
|
447
|
+
if (stopping !== null) return stopping;
|
|
448
|
+
stopping = (async () => {
|
|
449
|
+
const current = server;
|
|
450
|
+
server = null;
|
|
451
|
+
serverUrl = null;
|
|
452
|
+
if (current !== null) await closeServer(current);
|
|
453
|
+
if (ownsManager) {
|
|
454
|
+
try {
|
|
455
|
+
await manager.dispose();
|
|
456
|
+
} catch (error) {
|
|
457
|
+
logger.warn?.(`tailcat-webui: shutdown failed: ${errorMessage(error)}`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
})().finally(() => {
|
|
461
|
+
stopping = null;
|
|
462
|
+
});
|
|
463
|
+
return stopping;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* @param {http.Server} target - server to listen.
|
|
468
|
+
* @returns {Promise<void>}
|
|
469
|
+
*/
|
|
470
|
+
function listen(target) {
|
|
471
|
+
return new Promise((resolve, reject) => {
|
|
472
|
+
const onError = (error) => {
|
|
473
|
+
target.off('listening', onListening);
|
|
474
|
+
reject(listenError(error, actualPort));
|
|
475
|
+
};
|
|
476
|
+
const onListening = () => {
|
|
477
|
+
target.off('error', onError);
|
|
478
|
+
resolve();
|
|
479
|
+
};
|
|
480
|
+
target.once('error', onError);
|
|
481
|
+
target.once('listening', onListening);
|
|
482
|
+
target.listen({ host, port, exclusive: true });
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return {
|
|
487
|
+
start,
|
|
488
|
+
stop,
|
|
489
|
+
get url() {
|
|
490
|
+
return serverUrl;
|
|
491
|
+
},
|
|
492
|
+
get manager() {
|
|
493
|
+
return manager;
|
|
494
|
+
},
|
|
495
|
+
get server() {
|
|
496
|
+
return server;
|
|
497
|
+
},
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** The body-size rejection is a distinct type so the handler can answer 413. */
|
|
502
|
+
class PayloadTooLarge extends Error {}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* @param {http.ServerResponse} res - response.
|
|
506
|
+
* @param {number} status - status code.
|
|
507
|
+
* @param {object} body - JSON body.
|
|
508
|
+
* @param {boolean} [headOnly] - send headers without the body.
|
|
509
|
+
*/
|
|
510
|
+
function sendJson(res, status, body, headOnly = false) {
|
|
511
|
+
if (res.headersSent) return;
|
|
512
|
+
const text = JSON.stringify(body);
|
|
513
|
+
res.statusCode = status;
|
|
514
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
515
|
+
res.setHeader('cache-control', 'no-store');
|
|
516
|
+
applySecurityHeaders(res);
|
|
517
|
+
res.setHeader('content-length', Buffer.byteLength(text));
|
|
518
|
+
if (headOnly) res.end();
|
|
519
|
+
else res.end(text);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* @param {http.ServerResponse} res - response.
|
|
524
|
+
* @param {number} status - status code.
|
|
525
|
+
* @param {string} code - machine-readable reason.
|
|
526
|
+
* @param {string} message - operator-facing text.
|
|
527
|
+
* @param {boolean} asJson - whether the caller expects JSON.
|
|
528
|
+
*/
|
|
529
|
+
function fail(res, status, code, message, asJson) {
|
|
530
|
+
if (res.headersSent) return;
|
|
531
|
+
if (asJson) {
|
|
532
|
+
sendJson(res, status, { ok: false, error: { code, message } });
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
const text = `${message}\n`;
|
|
536
|
+
res.statusCode = status;
|
|
537
|
+
res.setHeader('content-type', 'text/plain; charset=utf-8');
|
|
538
|
+
res.setHeader('cache-control', 'no-store');
|
|
539
|
+
applySecurityHeaders(res);
|
|
540
|
+
res.setHeader('content-length', Buffer.byteLength(text));
|
|
541
|
+
res.end(text);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* @param {http.ServerResponse} res - response.
|
|
546
|
+
* @param {string[]} allowed - allowed methods.
|
|
547
|
+
* @param {boolean} asJson - whether the caller expects JSON.
|
|
548
|
+
*/
|
|
549
|
+
function methodNotAllowed(res, allowed, asJson) {
|
|
550
|
+
res.setHeader('allow', allowed.join(', '));
|
|
551
|
+
fail(res, 405, 'method-not-allowed', `Method not allowed. Use ${allowed.join(' or ')}.`, asJson);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** @param {http.ServerResponse} res - response. */
|
|
555
|
+
function applySecurityHeaders(res) {
|
|
556
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS)) res.setHeader(name, value);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* @param {http.IncomingMessage} req - request.
|
|
561
|
+
* @returns {string | null} the request path, or null when the URL is unusable.
|
|
562
|
+
*/
|
|
563
|
+
function requestPath(req) {
|
|
564
|
+
try {
|
|
565
|
+
return new URL(req.url ?? '/', 'http://127.0.0.1').pathname.slice(0, 512);
|
|
566
|
+
} catch {
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* @param {string} pathname - request path.
|
|
573
|
+
* @returns {boolean} whether an error for this path should be JSON.
|
|
574
|
+
*/
|
|
575
|
+
function wantsJson(pathname) {
|
|
576
|
+
return typeof pathname === 'string' && pathname.startsWith('/api/');
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* @param {string} value - Host header.
|
|
581
|
+
* @returns {{ host: string, port: number } | null} parsed loopback host and port.
|
|
582
|
+
*/
|
|
583
|
+
function parseHostHeader(value) {
|
|
584
|
+
const text = value.toLowerCase();
|
|
585
|
+
if (text.startsWith('[')) {
|
|
586
|
+
const end = text.indexOf(']');
|
|
587
|
+
if (end === -1) return null;
|
|
588
|
+
const host = text.slice(0, end + 1);
|
|
589
|
+
const rest = text.slice(end + 1);
|
|
590
|
+
if (!rest.startsWith(':')) return null;
|
|
591
|
+
return portPair(host, rest.slice(1));
|
|
592
|
+
}
|
|
593
|
+
const colon = text.lastIndexOf(':');
|
|
594
|
+
if (colon <= 0) return null;
|
|
595
|
+
return portPair(text.slice(0, colon), text.slice(colon + 1));
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* @param {string} host - host text.
|
|
600
|
+
* @param {string} portText - port text.
|
|
601
|
+
* @returns {{ host: string, port: number } | null} parsed host and port.
|
|
602
|
+
*/
|
|
603
|
+
function portPair(host, portText) {
|
|
604
|
+
if (!/^\d+$/.test(portText)) return null;
|
|
605
|
+
const port = Number(portText);
|
|
606
|
+
if (port < 1 || port > 65535) return null;
|
|
607
|
+
return { host, port };
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* @param {string} name - lowercase host name.
|
|
612
|
+
* @returns {boolean} whether it is a loopback name.
|
|
613
|
+
*/
|
|
614
|
+
function isLoopbackName(name) {
|
|
615
|
+
return LOOPBACK_NAMES.has(String(name).toLowerCase());
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* @param {string} file - resolved file path.
|
|
620
|
+
* @returns {string} content type.
|
|
621
|
+
*/
|
|
622
|
+
function contentTypeFor(file) {
|
|
623
|
+
return CONTENT_TYPES[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* @param {number} value - candidate port.
|
|
628
|
+
* @returns {number} validated port; 0 means "pick a free port".
|
|
629
|
+
*/
|
|
630
|
+
function normalizePort(value) {
|
|
631
|
+
if (!Number.isInteger(value) || value < 0 || value > 65535) {
|
|
632
|
+
throw new Error('The port must be a whole number from 0 to 65535.');
|
|
633
|
+
}
|
|
634
|
+
return value;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* @param {string} value - candidate bind address.
|
|
639
|
+
* @returns {string} loopback address.
|
|
640
|
+
*/
|
|
641
|
+
function normalizeHost(value) {
|
|
642
|
+
const host = String(value ?? '').trim();
|
|
643
|
+
if (host !== '127.0.0.1' && host !== '::1') {
|
|
644
|
+
throw new Error('The console only binds loopback addresses (127.0.0.1 or ::1).');
|
|
645
|
+
}
|
|
646
|
+
return host;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* @param {unknown} error - listen failure.
|
|
651
|
+
* @param {number} port - requested port.
|
|
652
|
+
* @returns {Error} operator-facing error.
|
|
653
|
+
*/
|
|
654
|
+
function listenError(error, port) {
|
|
655
|
+
const code = error instanceof Error && typeof error.code === 'string' ? error.code : '';
|
|
656
|
+
if (code === 'EADDRINUSE') {
|
|
657
|
+
return new Error(`Port ${port} is already in use. Stop the other process or start with --port <number>.`);
|
|
658
|
+
}
|
|
659
|
+
if (code === 'EACCES') {
|
|
660
|
+
return new Error(`Permission denied while binding port ${port}. Use a port above 1023.`);
|
|
661
|
+
}
|
|
662
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* @param {http.Server} target - server to close.
|
|
667
|
+
* @returns {Promise<void>}
|
|
668
|
+
*/
|
|
669
|
+
function closeServer(target) {
|
|
670
|
+
return new Promise((resolve) => {
|
|
671
|
+
target.close(() => resolve());
|
|
672
|
+
target.closeAllConnections?.();
|
|
673
|
+
});
|
|
674
|
+
}
|