@ulm0/gonogo 0.0.0-stage → 0.1.1

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/README.md +30 -2
  3. package/bin/gonogo.js +18 -0
  4. package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
  7. package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  8. package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  9. package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  10. package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  11. package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
  12. package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
  13. package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  18. package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  19. package/dist/client/assets/index-B6MsSoeo.css +1 -0
  20. package/dist/client/assets/index-DRtiRh1Y.js +31 -0
  21. package/dist/client/favicon.ico +0 -0
  22. package/dist/client/favicon.svg +1 -0
  23. package/dist/client/index.html +19 -0
  24. package/dist/server/cleanroom.js +214 -0
  25. package/dist/server/cli.js +630 -0
  26. package/dist/server/command.js +44 -0
  27. package/dist/server/constants.js +427 -0
  28. package/dist/server/docking.js +541 -0
  29. package/dist/server/downlink.js +191 -0
  30. package/dist/server/home.js +497 -0
  31. package/dist/server/hooks.js +166 -0
  32. package/dist/server/hub.js +2484 -0
  33. package/dist/server/launcher.js +542 -0
  34. package/dist/server/livery.js +210 -0
  35. package/dist/server/logsearch.js +112 -0
  36. package/dist/server/mcp.js +196 -0
  37. package/dist/server/migrate.js +119 -0
  38. package/dist/server/missionlog.js +209 -0
  39. package/dist/server/payload.js +168 -0
  40. package/dist/server/propellant.js +314 -0
  41. package/dist/server/providers.js +137 -0
  42. package/dist/server/relay.js +300 -0
  43. package/dist/server/relaykinds.js +182 -0
  44. package/dist/server/schedules.js +277 -0
  45. package/dist/server/tasks.js +272 -0
  46. package/dist/server/terminal.js +635 -0
  47. package/dist/server/uplinks.js +356 -0
  48. package/dist/server/web.js +1466 -0
  49. package/dist/shared/cron.js +149 -0
  50. package/dist/shared/fuel.js +18 -0
  51. package/dist/shared/livery.js +348 -0
  52. package/dist/shared/positions.js +132 -0
  53. package/dist/shared/protocol.js +212 -0
  54. package/package.json +84 -3
@@ -0,0 +1,1466 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { open, stat } from 'node:fs/promises';
3
+ import { createServer } from 'node:http';
4
+ import { extname, join, resolve as resolvePath, sep } from 'node:path';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { WebSocket, WebSocketServer } from 'ws';
7
+ import { PERMISSION_MODES, PROVIDERS, WS_BINARY_OUTPUT, WS_SUBPROTOCOL, WS_TOKEN_PROTOCOL_PREFIX } from '../shared/protocol.js';
8
+ import { AGENT_NAME_PATTERN, CLEAN_ROOM_HOST, MAX_COLS, MAX_REST_BODY_BYTES, MAX_ROWS, MIN_COLS, MIN_ROWS, UPLINK_BODY_MAX_BYTES, DOCK_BODY_MAX_BYTES, WS_CLOSE_BACKPRESSURE, WS_CLOSE_GOING_AWAY, WS_MAX_BUFFERED_BYTES, WS_MAX_FRAME_BYTES, WS_PING_INTERVAL_MS, } from './constants.js';
9
+ import { bearerToken, createHookHandler, hubErrorInfo, isRecord, readBody, sendApiError, sendJson, sendMethodNotAllowed, sendNotFound, sendText, sendUnauthorized, } from './hooks.js';
10
+ import { readCustomCommand } from './command.js';
11
+ import { DOCK_ROUTES } from './docking.js';
12
+ import { createMcpHandler } from './mcp.js';
13
+ import { parsePropellantRequest } from './propellant.js';
14
+ const NO_PROPELLANT = {
15
+ room: { used: { '5h': 0, day: 0, week: 0, month: 0 }, limits: {} },
16
+ agents: {},
17
+ };
18
+ const ERROR_STATUS = {
19
+ bad_request: 400,
20
+ unauthorized: 401,
21
+ forbidden: 403,
22
+ not_found: 404,
23
+ conflict: 409,
24
+ too_large: 413,
25
+ unsupported: 415,
26
+ internal: 500,
27
+ unavailable: 503,
28
+ rate_limited: 429,
29
+ };
30
+ const MIME = {
31
+ '.html': 'text/html; charset=utf-8',
32
+ '.js': 'text/javascript; charset=utf-8',
33
+ '.mjs': 'text/javascript; charset=utf-8',
34
+ '.css': 'text/css; charset=utf-8',
35
+ '.json': 'application/json; charset=utf-8',
36
+ '.svg': 'image/svg+xml',
37
+ '.png': 'image/png',
38
+ '.jpg': 'image/jpeg',
39
+ '.ico': 'image/x-icon',
40
+ '.woff2': 'font/woff2',
41
+ '.map': 'application/json; charset=utf-8',
42
+ '.txt': 'text/plain; charset=utf-8',
43
+ };
44
+ const STATUS_TEXT = {
45
+ 401: 'Unauthorized',
46
+ 403: 'Forbidden',
47
+ 404: 'Not Found',
48
+ 405: 'Method Not Allowed',
49
+ 503: 'Service Unavailable',
50
+ };
51
+ const noop = () => undefined;
52
+ const sha256 = (text) => createHash('sha256').update(text, 'utf8').digest();
53
+ function isPermissionMode(x) {
54
+ return typeof x === 'string' && PERMISSION_MODES.includes(x);
55
+ }
56
+ /** Host part of a Host header (port stripped, brackets removed, lower-cased), or null when it is not host[:port]. Exported for the tests. */
57
+ export function hostName(value) {
58
+ const v = value.trim().toLowerCase();
59
+ if (v === '')
60
+ return null;
61
+ if (v.startsWith('[')) {
62
+ const end = v.indexOf(']');
63
+ if (end < 2)
64
+ return null;
65
+ const rest = v.slice(end + 1);
66
+ return rest === '' || /^:\d{1,5}$/.test(rest) ? v.slice(1, end) : null;
67
+ }
68
+ const colon = v.indexOf(':');
69
+ if (colon === -1)
70
+ return v;
71
+ // an IPv6 address without brackets cannot carry a port, so it is not a valid Host value
72
+ if (v.indexOf(':', colon + 1) !== -1)
73
+ return null;
74
+ return /^\d{1,5}$/.test(v.slice(colon + 1)) ? v.slice(0, colon) : null;
75
+ }
76
+ /** An allow-list entry or the bind host, in the same form hostName gives for a Host header. */
77
+ function listedHost(entry) {
78
+ return hostName(entry) ?? entry.trim().toLowerCase();
79
+ }
80
+ const WILDCARD_HOSTS = ['0.0.0.0', '::'];
81
+ const LOOPBACK_HOSTS = ['127.0.0.1', '::1', 'localhost'];
82
+ /** A specific bind address that is not loopback also needs a 127.0.0.1 listener: agents are only ever told the loopback URL (contract 2.7). Exported for the tests. */
83
+ export function needsLoopbackTwin(host) {
84
+ const h = host.trim().toLowerCase().replace(/^\[|\]$/g, '');
85
+ return !WILDCARD_HOSTS.includes(h) && !LOOPBACK_HOSTS.includes(h);
86
+ }
87
+ /**
88
+ * The decoded path segments of a request target, or null for anything the server will not look at: no leading slash, a
89
+ * leading `//`, bad percent-encoding, a NUL byte. Never goes through `new URL` (it throws on `//` and `//[`, contract 3.2).
90
+ */
91
+ function parseTarget(rawUrl) {
92
+ const url = rawUrl ?? '';
93
+ const q = url.indexOf('?');
94
+ const path = q === -1 ? url : url.slice(0, q);
95
+ if (!path.startsWith('/') || path.startsWith('//') || path.includes('\0'))
96
+ return null;
97
+ const segments = [];
98
+ for (const raw of path.slice(1).split('/')) {
99
+ let segment;
100
+ try {
101
+ segment = decodeURIComponent(raw);
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ if (segment.includes('\0'))
107
+ return null;
108
+ segments.push(segment);
109
+ }
110
+ return segments;
111
+ }
112
+ function classify(segments) {
113
+ switch (segments[0]) {
114
+ case 'api':
115
+ return 'api';
116
+ case 'hook':
117
+ return 'hook';
118
+ case 'mcp':
119
+ return 'mcp';
120
+ case 'uplink':
121
+ return 'uplink';
122
+ case 'dock':
123
+ return 'dock';
124
+ case 'ws':
125
+ return 'ws';
126
+ default:
127
+ return 'static';
128
+ }
129
+ }
130
+ const ALLOW_BY_KIND = {
131
+ api: 'GET, POST, PATCH, DELETE',
132
+ hook: 'POST',
133
+ mcp: 'POST',
134
+ uplink: 'POST',
135
+ dock: 'GET, POST',
136
+ ws: 'GET',
137
+ static: 'GET, HEAD',
138
+ };
139
+ function fitSize(cols, rows) {
140
+ if (typeof cols !== 'number' || typeof rows !== 'number' || !Number.isInteger(cols) || !Number.isInteger(rows))
141
+ return null;
142
+ return { cols: Math.min(MAX_COLS, Math.max(MIN_COLS, cols)), rows: Math.min(MAX_ROWS, Math.max(MIN_ROWS, rows)) };
143
+ }
144
+ function fieldError(field, expected) {
145
+ return { ok: false, error: `${field} must be ${expected}`, field };
146
+ }
147
+ function isProvider(x) {
148
+ return typeof x === 'string' && PROVIDERS.includes(x);
149
+ }
150
+ /** A command the launcher could not read is refused here, so nothing is hired or saved for it. */
151
+ function commandProblem(command) {
152
+ try {
153
+ readCustomCommand(command);
154
+ return null;
155
+ }
156
+ catch (error) {
157
+ return { ok: false, error: error instanceof Error ? error.message : String(error), field: 'command' };
158
+ }
159
+ }
160
+ function parseHire(o) {
161
+ const { name, role, dir, mode, confirmBypass, position, provider, command, payload, cleanRoom } = o;
162
+ if (typeof name !== 'string')
163
+ return fieldError('name', 'a string');
164
+ if (typeof role !== 'string')
165
+ return fieldError('role', 'a string');
166
+ if (typeof dir !== 'string')
167
+ return fieldError('dir', 'a string');
168
+ if (!isPermissionMode(mode))
169
+ return fieldError('mode', `one of ${PERMISSION_MODES.join(', ')}`);
170
+ if (confirmBypass !== undefined && typeof confirmBypass !== 'boolean')
171
+ return fieldError('confirmBypass', 'true or false');
172
+ const value = { name, role, dir, mode };
173
+ if (confirmBypass !== undefined)
174
+ value.confirmBypass = confirmBypass;
175
+ if (position !== undefined) {
176
+ if (typeof position !== 'string')
177
+ return fieldError('position', 'a string');
178
+ value.position = position;
179
+ }
180
+ if (provider !== undefined) {
181
+ if (!isProvider(provider))
182
+ return fieldError('provider', `one of ${PROVIDERS.join(', ')}`);
183
+ value.provider = provider;
184
+ }
185
+ if (command !== undefined) {
186
+ if (typeof command !== 'string')
187
+ return fieldError('command', 'a string');
188
+ const problem = commandProblem(command);
189
+ if (problem)
190
+ return problem;
191
+ value.command = command;
192
+ }
193
+ // The hub reads the inside of a payload and names the field that is wrong.
194
+ if (payload !== undefined) {
195
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload))
196
+ return fieldError('payload', 'an object');
197
+ value.payload = payload;
198
+ }
199
+ if (cleanRoom !== undefined) {
200
+ if (typeof cleanRoom !== 'object' || cleanRoom === null || Array.isArray(cleanRoom))
201
+ return fieldError('cleanRoom', 'an object');
202
+ value.cleanRoom = cleanRoom;
203
+ }
204
+ return { ok: true, value };
205
+ }
206
+ function parsePoll(o) {
207
+ const value = {};
208
+ if (o.agents !== undefined) {
209
+ if (!Array.isArray(o.agents) || !o.agents.every((a) => typeof a === 'string'))
210
+ return fieldError('agents', 'a list of names');
211
+ value.agents = o.agents;
212
+ }
213
+ return { ok: true, value };
214
+ }
215
+ function parseGovernor(o) {
216
+ // range (1 to MAX_AGENTS) is the hub's to judge; here only the type
217
+ if (o.limit !== null && (typeof o.limit !== 'number' || !Number.isInteger(o.limit)))
218
+ return fieldError('limit', 'a whole number or null');
219
+ return { ok: true, value: { limit: o.limit } };
220
+ }
221
+ function parseAnswer(o) {
222
+ if (typeof o.go !== 'boolean')
223
+ return fieldError('go', 'true or false');
224
+ return { ok: true, value: { go: o.go } };
225
+ }
226
+ function parseEdit(o) {
227
+ const value = {};
228
+ for (const key of ['name', 'role', 'dir']) {
229
+ const v = o[key];
230
+ if (v === undefined)
231
+ continue;
232
+ if (typeof v !== 'string')
233
+ return fieldError(key, 'a string');
234
+ value[key] = v;
235
+ }
236
+ if (o.mode !== undefined) {
237
+ if (!isPermissionMode(o.mode))
238
+ return fieldError('mode', `one of ${PERMISSION_MODES.join(', ')}`);
239
+ value.mode = o.mode;
240
+ }
241
+ if (o.confirmBypass !== undefined) {
242
+ if (typeof o.confirmBypass !== 'boolean')
243
+ return fieldError('confirmBypass', 'true or false');
244
+ value.confirmBypass = o.confirmBypass;
245
+ }
246
+ if (o.position !== undefined) {
247
+ if (o.position !== null && typeof o.position !== 'string')
248
+ return fieldError('position', 'a string or null');
249
+ value.position = o.position;
250
+ }
251
+ if (o.command !== undefined) {
252
+ if (typeof o.command !== 'string')
253
+ return fieldError('command', 'a string');
254
+ const problem = commandProblem(o.command);
255
+ if (problem)
256
+ return problem;
257
+ value.command = o.command;
258
+ }
259
+ if (o.payload !== undefined) {
260
+ if (o.payload !== null && (typeof o.payload !== 'object' || Array.isArray(o.payload)))
261
+ return fieldError('payload', 'an object or null');
262
+ value.payload = o.payload;
263
+ }
264
+ if (o.cleanRoom !== undefined) {
265
+ if (o.cleanRoom !== null && (typeof o.cleanRoom !== 'object' || Array.isArray(o.cleanRoom)))
266
+ return fieldError('cleanRoom', 'an object or null');
267
+ value.cleanRoom = o.cleanRoom;
268
+ }
269
+ return { ok: true, value };
270
+ }
271
+ function parseUserMessage(o) {
272
+ const { to, subject, body, inReplyTo } = o;
273
+ if (typeof to !== 'string')
274
+ return fieldError('to', 'a string');
275
+ if (typeof body !== 'string')
276
+ return fieldError('body', 'a string');
277
+ if (subject !== undefined && typeof subject !== 'string')
278
+ return fieldError('subject', 'a string');
279
+ if (inReplyTo !== undefined && typeof inReplyTo !== 'string')
280
+ return fieldError('inReplyTo', 'a string');
281
+ const value = { to, body };
282
+ if (subject !== undefined)
283
+ value.subject = subject;
284
+ if (inReplyTo !== undefined)
285
+ value.inReplyTo = inReplyTo;
286
+ return { ok: true, value };
287
+ }
288
+ function rawToString(data) {
289
+ if (Buffer.isBuffer(data))
290
+ return data.toString('utf8');
291
+ if (Array.isArray(data))
292
+ return Buffer.concat(data).toString('utf8');
293
+ return Buffer.from(data).toString('utf8');
294
+ }
295
+ /** Answers an upgrade request that must not become a WebSocket: a plain HTTP response, then the socket goes. */
296
+ function rejectUpgrade(socket, status, contentType, body, extra = []) {
297
+ const head = [
298
+ `HTTP/1.1 ${status} ${STATUS_TEXT[status] ?? 'Error'}`,
299
+ 'Connection: close',
300
+ `Content-Type: ${contentType}`,
301
+ `Content-Length: ${Buffer.byteLength(body)}`,
302
+ 'X-Content-Type-Options: nosniff',
303
+ 'Referrer-Policy: no-referrer',
304
+ 'X-Frame-Options: DENY',
305
+ ...extra,
306
+ ];
307
+ socket.once('finish', () => socket.destroy());
308
+ socket.end(head.join('\r\n') + '\r\n\r\n' + body);
309
+ }
310
+ export function createWebServer(options) {
311
+ const { hub, terminals, log } = options;
312
+ const nameRe = new RegExp(AGENT_NAME_PATTERN);
313
+ const tokenDigest = sha256(options.browserToken);
314
+ const hookHandler = createHookHandler({ hub, resolveToken: options.resolveToken, log: log.child('hook') });
315
+ const mcpHandler = createMcpHandler({
316
+ hub,
317
+ resolveToken: options.resolveToken,
318
+ tasks: options.tasks,
319
+ missionLog: options.missionLog,
320
+ liveries: options.liveries,
321
+ log: log.child('mcp'),
322
+ version: () => options.info().version,
323
+ });
324
+ const allowedNames = new Set(['127.0.0.1', 'localhost', '::1']);
325
+ for (const entry of options.allowedHosts) {
326
+ const listed = listedHost(entry);
327
+ if (listed !== '')
328
+ allowedNames.add(listed);
329
+ }
330
+ if (!WILDCARD_HOSTS.includes(options.host))
331
+ allowedNames.add(listedHost(options.host));
332
+ const staticRoot = options.staticDir === null ? null : resolvePath(options.staticDir);
333
+ const clients = new Set();
334
+ const servers = [];
335
+ let pingTimer = null;
336
+ let started = null;
337
+ let closing = null;
338
+ /* ---------------------------------------------------------------- checks of contract 3.2 */
339
+ const tokenMatches = (candidate) => timingSafeEqual(sha256(candidate), tokenDigest);
340
+ const restAuthorized = (req) => {
341
+ const token = bearerToken(req.headers.authorization);
342
+ return token !== null && tokenMatches(token);
343
+ };
344
+ const wsAuthorized = (req) => {
345
+ const offered = req.headers['sec-websocket-protocol'];
346
+ if (typeof offered !== 'string')
347
+ return false;
348
+ for (const entry of offered.split(',')) {
349
+ const protocol = entry.trim();
350
+ if (protocol.startsWith(WS_TOKEN_PROTOCOL_PREFIX))
351
+ return tokenMatches(protocol.slice(WS_TOKEN_PROTOCOL_PREFIX.length));
352
+ }
353
+ return false;
354
+ };
355
+ const hostAllowed = (hostHeader) => {
356
+ const name = hostHeader === undefined ? null : hostName(hostHeader);
357
+ return name !== null && allowedNames.has(name);
358
+ };
359
+ /** Browser routes need an Origin that is this very server; hooks, MCP, uplinks and docks never get one from their senders, so any Origin is a web page. */
360
+ const originAllowed = (req, kind) => {
361
+ const origin = req.headers.origin;
362
+ if (origin === undefined)
363
+ return true;
364
+ if (kind === 'hook' || kind === 'mcp' || kind === 'uplink' || kind === 'dock')
365
+ return false;
366
+ let url;
367
+ try {
368
+ url = new URL(origin);
369
+ }
370
+ catch {
371
+ return false;
372
+ }
373
+ const host = req.headers.host ?? '';
374
+ return url.host.toLowerCase() === host.toLowerCase() && hostAllowed(url.host);
375
+ };
376
+ /* ---------------------------------------------------------------- REST */
377
+ function broadcast(event) {
378
+ if (clients.size === 0)
379
+ return;
380
+ try {
381
+ const text = JSON.stringify(event);
382
+ for (const client of clients)
383
+ sendRaw(client, text, false);
384
+ }
385
+ catch (e) {
386
+ log.error('broadcast failed', e);
387
+ }
388
+ }
389
+ const snapshot = () => ({
390
+ agents: hub.views(),
391
+ activity: hub.activity(),
392
+ info: options.info(),
393
+ poll: hub.poll(),
394
+ governor: hub.governor(),
395
+ propellant: options.propellant?.view() ?? NO_PROPELLANT,
396
+ schedules: options.schedules?.list() ?? [],
397
+ uplinks: options.uplinks?.list() ?? [],
398
+ tasks: options.tasks?.list() ?? [],
399
+ downlink: options.downlink?.view() ?? { unread: 0, items: [] },
400
+ livery: options.liveries?.view(),
401
+ docking: options.docking?.view(),
402
+ });
403
+ const sendHubError = (res, e) => {
404
+ const info = hubErrorInfo(e);
405
+ if (info) {
406
+ sendApiError(res, ERROR_STATUS[info.code], info.message, info.code, info.field, info.code === 'rate_limited' ? { 'Retry-After': '60' } : {});
407
+ return;
408
+ }
409
+ log.error('request failed', e);
410
+ sendApiError(res, 500, 'internal error', 'internal');
411
+ };
412
+ const hasBody = (req) => req.headers['transfer-encoding'] !== undefined || Number(req.headers['content-length'] ?? 0) > 0;
413
+ const isJsonRequest = (req) => (req.headers['content-type'] ?? '').split(';')[0]?.trim().toLowerCase() === 'application/json';
414
+ /** The JSON object in the body, or null after the error answer went out. */
415
+ const jsonObject = async (req, res) => {
416
+ const body = await readBody(req, MAX_REST_BODY_BYTES);
417
+ if (!body.ok) {
418
+ if (body.reason === 'too_large')
419
+ sendApiError(res, 413, 'request body too large', 'too_large');
420
+ else
421
+ res.destroy();
422
+ return null;
423
+ }
424
+ let value = null;
425
+ try {
426
+ value = JSON.parse(body.body.toString('utf8'));
427
+ }
428
+ catch {
429
+ // answered below, like a body that parses to something else than an object
430
+ }
431
+ if (!isRecord(value)) {
432
+ sendApiError(res, 400, 'request body must be a JSON object', 'bad_request');
433
+ return null;
434
+ }
435
+ return value;
436
+ };
437
+ const agentName = (res, raw) => {
438
+ if (raw !== undefined && nameRe.test(raw))
439
+ return raw;
440
+ sendNotFound(res, 'unknown agent');
441
+ return null;
442
+ };
443
+ const matchApi = (s) => {
444
+ if (s.length === 2 && s[1] === 'state') {
445
+ return { allow: ['GET'], run: (_req, res) => sendJson(res, 200, snapshot()) };
446
+ }
447
+ if (s.length === 2 && s[1] === 'agents') {
448
+ return {
449
+ allow: ['POST'],
450
+ run: async (req, res) => {
451
+ const body = await jsonObject(req, res);
452
+ if (!body)
453
+ return;
454
+ const parsed = parseHire(body);
455
+ if (!parsed.ok)
456
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
457
+ else
458
+ sendJson(res, 201, await hub.hire(parsed.value));
459
+ },
460
+ };
461
+ }
462
+ if (s.length === 2 && s[1] === 'messages') {
463
+ return {
464
+ allow: ['POST'],
465
+ run: async (req, res) => {
466
+ const body = await jsonObject(req, res);
467
+ if (!body)
468
+ return;
469
+ const parsed = parseUserMessage(body);
470
+ if (!parsed.ok)
471
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
472
+ else
473
+ sendJson(res, 201, hub.sendFromUser(parsed.value));
474
+ },
475
+ };
476
+ }
477
+ if (s.length === 2 && s[1] === 'governor') {
478
+ return {
479
+ allow: ['PUT'],
480
+ run: async (req, res) => {
481
+ const body = await jsonObject(req, res);
482
+ if (!body)
483
+ return;
484
+ const parsed = parseGovernor(body);
485
+ if (!parsed.ok)
486
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
487
+ else
488
+ sendJson(res, 200, hub.setGovernor(parsed.value));
489
+ },
490
+ };
491
+ }
492
+ if (s.length === 2 && s[1] === 'propellant') {
493
+ return {
494
+ allow: ['PUT'],
495
+ run: async (req, res) => {
496
+ const propellant = options.propellant;
497
+ if (!propellant) {
498
+ sendNotFound(res);
499
+ return;
500
+ }
501
+ const body = await jsonObject(req, res);
502
+ if (!body)
503
+ return;
504
+ const parsed = parsePropellantRequest(body);
505
+ if (!parsed.ok) {
506
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
507
+ return;
508
+ }
509
+ const view = await propellant.setLimits(parsed.value);
510
+ broadcast({ t: 'propellant', propellant: view });
511
+ sendJson(res, 200, view);
512
+ },
513
+ };
514
+ }
515
+ if (s[1] === 'schedules' && s.length <= 4) {
516
+ const schedules = options.schedules;
517
+ if (!schedules)
518
+ return null;
519
+ if (s.length === 2) {
520
+ return {
521
+ allow: ['GET', 'POST'],
522
+ run: async (req, res) => {
523
+ if (req.method === 'GET') {
524
+ sendJson(res, 200, schedules.list());
525
+ return;
526
+ }
527
+ const body = await jsonObject(req, res);
528
+ if (body)
529
+ sendJson(res, 201, await schedules.create(body));
530
+ },
531
+ };
532
+ }
533
+ const id = s[2] ?? '';
534
+ if (s.length === 3) {
535
+ return {
536
+ allow: ['PATCH', 'DELETE'],
537
+ run: async (req, res) => {
538
+ if (req.method === 'DELETE') {
539
+ await schedules.remove(id);
540
+ res.writeHead(204);
541
+ res.end();
542
+ return;
543
+ }
544
+ const body = await jsonObject(req, res);
545
+ if (body)
546
+ sendJson(res, 200, await schedules.update(id, body));
547
+ },
548
+ };
549
+ }
550
+ if (s[3] === 'run')
551
+ return { allow: ['POST'], run: async (_req, res) => sendJson(res, 200, await schedules.run(id)) };
552
+ return null;
553
+ }
554
+ if (s[1] === 'uplinks' && s.length <= 4) {
555
+ const uplinks = options.uplinks;
556
+ if (!uplinks)
557
+ return null;
558
+ if (s.length === 2) {
559
+ return {
560
+ allow: ['GET', 'POST'],
561
+ run: async (req, res) => {
562
+ if (req.method === 'GET') {
563
+ sendJson(res, 200, uplinks.list());
564
+ return;
565
+ }
566
+ const body = await jsonObject(req, res);
567
+ if (body)
568
+ sendJson(res, 201, await uplinks.create(body));
569
+ },
570
+ };
571
+ }
572
+ const id = s[2] ?? '';
573
+ if (s.length === 3) {
574
+ return {
575
+ allow: ['PATCH', 'DELETE'],
576
+ run: async (req, res) => {
577
+ if (req.method === 'DELETE') {
578
+ await uplinks.remove(id);
579
+ res.writeHead(204);
580
+ res.end();
581
+ return;
582
+ }
583
+ const body = await jsonObject(req, res);
584
+ if (body)
585
+ sendJson(res, 200, await uplinks.update(id, body));
586
+ },
587
+ };
588
+ }
589
+ if (s[3] === 'rotate')
590
+ return { allow: ['POST'], run: async (_req, res) => sendJson(res, 200, await uplinks.rotate(id)) };
591
+ if (s[3] === 'test')
592
+ return { allow: ['POST'], run: async (_req, res) => sendJson(res, 200, await uplinks.test(id)) };
593
+ return null;
594
+ }
595
+ if (s[1] === 'docking' && s.length <= 4) {
596
+ const docking = options.docking;
597
+ if (!docking)
598
+ return null;
599
+ if (s.length === 2)
600
+ return { allow: ['GET'], run: (_req, res) => sendJson(res, 200, docking.view()) };
601
+ const id = s[2] ?? '';
602
+ if (s.length === 3 && (id === 'code' || id === 'pair')) {
603
+ return {
604
+ allow: ['POST'],
605
+ run: async (req, res) => {
606
+ const body = await jsonObject(req, res);
607
+ if (body)
608
+ sendJson(res, 201, id === 'code' ? docking.createCode(body) : await docking.pair(body));
609
+ },
610
+ };
611
+ }
612
+ if (s.length === 3)
613
+ return { allow: ['DELETE'], run: async (_req, res) => sendJson(res, 200, await docking.undock(id)) };
614
+ if (s[3] !== 'handoff')
615
+ return null;
616
+ return {
617
+ allow: ['POST'],
618
+ run: async (req, res) => {
619
+ const body = await jsonObject(req, res);
620
+ if (body)
621
+ sendJson(res, 200, await docking.handOff(id, body));
622
+ },
623
+ };
624
+ }
625
+ if (s[1] === 'tasks' && s.length <= 3) {
626
+ const tasks = options.tasks;
627
+ if (!tasks)
628
+ return null;
629
+ const director = { kind: 'user' };
630
+ if (s.length === 2) {
631
+ return {
632
+ allow: ['GET', 'POST'],
633
+ run: async (req, res) => {
634
+ if (req.method === 'GET') {
635
+ sendJson(res, 200, tasks.list());
636
+ return;
637
+ }
638
+ const body = await jsonObject(req, res);
639
+ if (body)
640
+ sendJson(res, 201, await tasks.create(director, body));
641
+ },
642
+ };
643
+ }
644
+ const id = s[2] ?? '';
645
+ return {
646
+ allow: ['PATCH', 'DELETE'],
647
+ run: async (req, res) => {
648
+ if (req.method === 'DELETE') {
649
+ await tasks.remove(id);
650
+ res.writeHead(204);
651
+ res.end();
652
+ return;
653
+ }
654
+ const body = await jsonObject(req, res);
655
+ if (body)
656
+ sendJson(res, 200, await tasks.update(director, id, body));
657
+ },
658
+ };
659
+ }
660
+ if (s[1] === 'log' && s.length <= 3) {
661
+ const missionLog = options.missionLog;
662
+ if (!missionLog)
663
+ return null;
664
+ if (s.length === 2) {
665
+ return {
666
+ allow: ['GET', 'POST'],
667
+ run: async (req, res) => {
668
+ if (req.method === 'GET') {
669
+ sendJson(res, 200, missionLog.search(new URL(req.url ?? '/', 'http://localhost').searchParams.get('q') ?? ''));
670
+ return;
671
+ }
672
+ const body = await jsonObject(req, res);
673
+ if (body)
674
+ sendJson(res, 201, await missionLog.create('user', body));
675
+ },
676
+ };
677
+ }
678
+ const id = s[2] ?? '';
679
+ return {
680
+ allow: ['GET', 'PUT', 'DELETE'],
681
+ run: async (req, res) => {
682
+ if (req.method === 'GET') {
683
+ sendJson(res, 200, missionLog.get(id));
684
+ return;
685
+ }
686
+ if (req.method === 'DELETE') {
687
+ await missionLog.remove(id);
688
+ res.writeHead(204);
689
+ res.end();
690
+ return;
691
+ }
692
+ const body = await jsonObject(req, res);
693
+ if (body)
694
+ sendJson(res, 200, await missionLog.update(id, body, null));
695
+ },
696
+ };
697
+ }
698
+ if (s[1] === 'liveries' || s[1] === 'livery') {
699
+ const liveries = options.liveries;
700
+ if (!liveries)
701
+ return null;
702
+ if (s.length === 2 && s[1] === 'liveries')
703
+ return { allow: ['GET'], run: async (_req, res) => sendJson(res, 200, liveries.view()) };
704
+ if (s.length === 2) {
705
+ return {
706
+ allow: ['PUT'],
707
+ run: async (req, res) => {
708
+ const body = await jsonObject(req, res);
709
+ if (body)
710
+ sendJson(res, 200, await liveries.select(body));
711
+ },
712
+ };
713
+ }
714
+ if (s.length !== 3 || s[1] !== 'liveries')
715
+ return null;
716
+ if (s[2] === 'design') {
717
+ return {
718
+ allow: ['POST'],
719
+ run: async (req, res) => {
720
+ const body = await jsonObject(req, res);
721
+ if (body)
722
+ sendJson(res, 201, liveries.design(body));
723
+ },
724
+ };
725
+ }
726
+ return { allow: ['DELETE'], run: async (_req, res) => sendJson(res, 200, await liveries.remove(s[2] ?? '')) };
727
+ }
728
+ if (s[1] === 'relay' && s.length <= 4) {
729
+ const relay = options.relay;
730
+ if (!relay)
731
+ return null;
732
+ if (s.length === 2)
733
+ return { allow: ['GET'], run: async (_req, res) => sendJson(res, 200, relay.view()) };
734
+ const name = s[2] ?? '';
735
+ if (s.length === 4)
736
+ return s[3] === 'test' ? { allow: ['POST'], run: async (_req, res) => sendJson(res, 200, await relay.test(name)) } : null;
737
+ return {
738
+ allow: ['PUT', 'DELETE'],
739
+ run: async (req, res) => {
740
+ if (req.method === 'DELETE') {
741
+ sendJson(res, 200, await relay.remove(name));
742
+ return;
743
+ }
744
+ const body = await jsonObject(req, res);
745
+ if (body)
746
+ sendJson(res, 200, await (name === 'forward' ? relay.forward(body) : relay.set(name, body)));
747
+ },
748
+ };
749
+ }
750
+ if (s[1] === 'downlink' && s.length <= 3) {
751
+ const downlink = options.downlink;
752
+ if (!downlink)
753
+ return null;
754
+ if (s.length === 2)
755
+ return { allow: ['GET'], run: async (_req, res) => sendJson(res, 200, downlink.view()) };
756
+ if (s[2] === 'read-all')
757
+ return { allow: ['POST'], run: async (_req, res) => sendJson(res, 200, await downlink.readAll()) };
758
+ const action = s[2] === 'read' || s[2] === 'archive' ? s[2] : null;
759
+ if (action === null)
760
+ return null;
761
+ return {
762
+ allow: ['POST'],
763
+ run: async (req, res) => {
764
+ const body = await jsonObject(req, res);
765
+ if (body)
766
+ sendJson(res, 200, await downlink[action](body));
767
+ },
768
+ };
769
+ }
770
+ if (s[1] === 'poll' && s.length <= 3) {
771
+ const action = s[2];
772
+ if (s.length === 2) {
773
+ return {
774
+ allow: ['POST', 'DELETE'],
775
+ run: async (req, res) => {
776
+ if (req.method === 'DELETE') {
777
+ hub.clearPoll();
778
+ res.writeHead(204);
779
+ res.end();
780
+ return;
781
+ }
782
+ // the Director's Poll button may send no body: that is the default set
783
+ const body = hasBody(req) ? await jsonObject(req, res) : {};
784
+ if (!body)
785
+ return;
786
+ const parsed = parsePoll(body);
787
+ if (!parsed.ok)
788
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
789
+ else
790
+ sendJson(res, 201, hub.startPoll(parsed.value));
791
+ },
792
+ };
793
+ }
794
+ if (action === 'hold' || action === 'abort') {
795
+ return {
796
+ allow: ['POST'],
797
+ run: (_req, res) => sendJson(res, 200, action === 'hold' ? hub.holdPoll() : hub.abortPoll()),
798
+ };
799
+ }
800
+ return null;
801
+ }
802
+ if (s[1] !== 'agents')
803
+ return null;
804
+ if (s.length === 3) {
805
+ return {
806
+ allow: ['PATCH', 'DELETE'],
807
+ run: async (req, res) => {
808
+ const name = agentName(res, s[2]);
809
+ if (name === null)
810
+ return;
811
+ if (req.method === 'DELETE') {
812
+ await hub.remove(name);
813
+ res.writeHead(204);
814
+ res.end();
815
+ return;
816
+ }
817
+ const body = await jsonObject(req, res);
818
+ if (!body)
819
+ return;
820
+ const parsed = parseEdit(body);
821
+ if (!parsed.ok)
822
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
823
+ else
824
+ sendJson(res, 200, await hub.edit(name, parsed.value));
825
+ },
826
+ };
827
+ }
828
+ if (s.length === 4 && (s[3] === 'stop' || s[3] === 'restart')) {
829
+ return {
830
+ allow: ['POST'],
831
+ run: async (_req, res) => {
832
+ const name = agentName(res, s[2]);
833
+ if (name === null)
834
+ return;
835
+ sendJson(res, 200, await (s[3] === 'stop' ? hub.stop(name) : hub.restart(name)));
836
+ },
837
+ };
838
+ }
839
+ if (s.length === 4 && s[3] === 'resume') {
840
+ return {
841
+ allow: ['POST'],
842
+ run: (_req, res) => {
843
+ const name = agentName(res, s[2]);
844
+ if (name !== null)
845
+ sendJson(res, 200, hub.resume(name));
846
+ },
847
+ };
848
+ }
849
+ if (s.length === 4 && s[3] === 'answer') {
850
+ return {
851
+ allow: ['POST'],
852
+ run: async (req, res) => {
853
+ const name = agentName(res, s[2]);
854
+ if (name === null)
855
+ return;
856
+ const body = await jsonObject(req, res);
857
+ if (!body)
858
+ return;
859
+ const parsed = parseAnswer(body);
860
+ if (!parsed.ok)
861
+ sendApiError(res, 400, parsed.error, 'bad_request', parsed.field);
862
+ else
863
+ sendJson(res, 200, hub.answer(name, parsed.value));
864
+ },
865
+ };
866
+ }
867
+ return null;
868
+ };
869
+ const handleApi = async (req, res, segments) => {
870
+ if (!restAuthorized(req)) {
871
+ sendUnauthorized(res);
872
+ return;
873
+ }
874
+ if (!options.isReady()) {
875
+ sendApiError(res, 503, 'starting', 'unavailable');
876
+ return;
877
+ }
878
+ const route = matchApi(segments);
879
+ if (!route) {
880
+ sendNotFound(res);
881
+ return;
882
+ }
883
+ const method = req.method ?? 'GET';
884
+ if (!route.allow.includes(method)) {
885
+ sendMethodNotAllowed(res, route.allow.join(', '));
886
+ return;
887
+ }
888
+ if ((method === 'POST' || method === 'PATCH' || method === 'PUT') && hasBody(req) && !isJsonRequest(req)) {
889
+ sendApiError(res, 415, 'content type must be application/json', 'unsupported');
890
+ return;
891
+ }
892
+ try {
893
+ await route.run(req, res);
894
+ }
895
+ catch (e) {
896
+ sendHubError(res, e);
897
+ }
898
+ };
899
+ /* ---------------------------------------------------------------- static client (contract 3.7) */
900
+ const statOrNull = async (path) => {
901
+ try {
902
+ return await stat(path);
903
+ }
904
+ catch {
905
+ return null;
906
+ }
907
+ };
908
+ /**
909
+ * The descriptor is opened here and closed in `finally`, never left to a stream: a stream that pipeline() refuses because
910
+ * the client is already gone is never destroyed, so the descriptor it opened stays open for good, and enough of those end
911
+ * the process with EMFILE.
912
+ */
913
+ const sendFile = async (req, res, root, file, size) => {
914
+ const underAssets = file.startsWith(join(root, 'assets') + sep);
915
+ const head = {
916
+ 'Content-Type': MIME[extname(file).toLowerCase()] ?? 'application/octet-stream',
917
+ 'Content-Length': size,
918
+ 'Cache-Control': underAssets ? 'public, max-age=31536000, immutable' : 'no-cache',
919
+ };
920
+ if (req.method === 'HEAD') {
921
+ res.writeHead(200, head);
922
+ res.end();
923
+ return;
924
+ }
925
+ if (res.destroyed)
926
+ return;
927
+ const handle = await open(file, 'r');
928
+ try {
929
+ res.writeHead(200, head);
930
+ await pipeline(handle.createReadStream(), res);
931
+ }
932
+ catch (e) {
933
+ log.debug('static file stream failed', e);
934
+ res.destroy();
935
+ }
936
+ finally {
937
+ await handle.close();
938
+ }
939
+ };
940
+ const serveStatic = async (req, res, segments) => {
941
+ const method = req.method ?? 'GET';
942
+ if (method !== 'GET' && method !== 'HEAD') {
943
+ sendMethodNotAllowed(res, ALLOW_BY_KIND.static);
944
+ return;
945
+ }
946
+ if (staticRoot === null) {
947
+ sendText(res, 404, 'not found');
948
+ return;
949
+ }
950
+ const relative = segments.join('/');
951
+ const file = resolvePath(staticRoot, relative === '' ? 'index.html' : relative);
952
+ // shortcut: a symlink inside the static directory is followed; the directory is the client build, which holds none
953
+ if (!file.startsWith(staticRoot + sep)) {
954
+ sendText(res, 404, 'not found');
955
+ return;
956
+ }
957
+ const info = await statOrNull(file);
958
+ if (info?.isFile()) {
959
+ await sendFile(req, res, staticRoot, file, info.size);
960
+ return;
961
+ }
962
+ // a client route (no file extension, nothing there) gets the app; a directory or a missing asset is a 404
963
+ if (info === null && extname(segments[segments.length - 1] ?? '') === '') {
964
+ const index = join(staticRoot, 'index.html');
965
+ const indexInfo = await statOrNull(index);
966
+ if (indexInfo?.isFile()) {
967
+ await sendFile(req, res, staticRoot, index, indexInfo.size);
968
+ return;
969
+ }
970
+ }
971
+ sendText(res, 404, 'not found');
972
+ };
973
+ /**
974
+ * POST /uplink/:id: outside /api and the browser token. The sender proves itself with the uplink's secret (uplinks.ts), the
975
+ * Host and Origin checks of handleRequest ran before, and an unknown or disabled id is the same 404 as a path that is not there.
976
+ */
977
+ const handleUplink = async (req, res, segments) => {
978
+ const uplinks = options.uplinks;
979
+ const id = segments[1];
980
+ if (!uplinks || segments.length !== 2 || !id) {
981
+ sendNotFound(res);
982
+ return;
983
+ }
984
+ if (!options.isReady()) {
985
+ sendApiError(res, 503, 'starting', 'unavailable');
986
+ return;
987
+ }
988
+ if (req.method !== 'POST') {
989
+ sendMethodNotAllowed(res, ALLOW_BY_KIND.uplink);
990
+ return;
991
+ }
992
+ const body = await readBody(req, UPLINK_BODY_MAX_BYTES);
993
+ if (!body.ok) {
994
+ if (body.reason === 'too_large')
995
+ sendApiError(res, 413, 'request body too large', 'too_large');
996
+ else
997
+ res.destroy();
998
+ return;
999
+ }
1000
+ try {
1001
+ const done = uplinks.deliver(id, body.body, req.headers);
1002
+ // a ping or a challenge gets its answer with 200; a message that was made gets 202
1003
+ if ('answer' in done)
1004
+ sendJson(res, 200, done.answer);
1005
+ else
1006
+ sendJson(res, 202, done);
1007
+ }
1008
+ catch (e) {
1009
+ sendHubError(res, e);
1010
+ }
1011
+ };
1012
+ /**
1013
+ * /dock/<route>: another station's calls, outside /api and the browser token. They prove themselves with a signature
1014
+ * (docking.ts); the Host and Origin checks of handleRequest ran before.
1015
+ */
1016
+ const handleDock = async (req, res, segments) => {
1017
+ const docking = options.docking;
1018
+ const route = segments[1] ?? '';
1019
+ if (!docking || segments.length !== 2 || !Object.hasOwn(DOCK_ROUTES, route)) {
1020
+ sendNotFound(res);
1021
+ return;
1022
+ }
1023
+ if (!options.isReady()) {
1024
+ sendApiError(res, 503, 'starting', 'unavailable');
1025
+ return;
1026
+ }
1027
+ if (req.method !== DOCK_ROUTES[route]) {
1028
+ sendMethodNotAllowed(res, DOCK_ROUTES[route] ?? 'POST');
1029
+ return;
1030
+ }
1031
+ const body = await readBody(req, DOCK_BODY_MAX_BYTES);
1032
+ if (!body.ok) {
1033
+ if (body.reason === 'too_large')
1034
+ sendApiError(res, 413, 'request body too large', 'too_large');
1035
+ else
1036
+ res.destroy();
1037
+ return;
1038
+ }
1039
+ try {
1040
+ sendJson(res, 200, await docking.handle(route, req.method, req.url ?? '', req.headers, body.body));
1041
+ }
1042
+ catch (e) {
1043
+ sendHubError(res, e);
1044
+ }
1045
+ };
1046
+ /* ---------------------------------------------------------------- one HTTP request */
1047
+ const handleRequest = async (req, res) => {
1048
+ res.setHeader('X-Content-Type-Options', 'nosniff');
1049
+ res.setHeader('Referrer-Policy', 'no-referrer');
1050
+ res.setHeader('X-Frame-Options', 'DENY');
1051
+ // A Clean Room agent reaches the hooks and MCP by the host's name for containers: no other route may be reached by it.
1052
+ const viaContainer = !hostAllowed(req.headers.host) && hostName(req.headers.host ?? '') === CLEAN_ROOM_HOST;
1053
+ if (!viaContainer && !hostAllowed(req.headers.host)) {
1054
+ sendText(res, 403, 'forbidden host');
1055
+ return;
1056
+ }
1057
+ const segments = parseTarget(req.url);
1058
+ const kind = segments === null ? null : classify(segments);
1059
+ if (viaContainer && kind !== 'hook' && kind !== 'mcp') {
1060
+ sendText(res, 403, 'forbidden host');
1061
+ return;
1062
+ }
1063
+ if (segments === null || kind === null) {
1064
+ sendText(res, 404, 'not found');
1065
+ return;
1066
+ }
1067
+ if (kind !== 'static')
1068
+ res.setHeader('Cache-Control', 'no-store');
1069
+ const method = req.method ?? 'GET';
1070
+ const staticRead = kind === 'static' && (method === 'GET' || method === 'HEAD');
1071
+ if (!staticRead && !originAllowed(req, kind)) {
1072
+ sendText(res, 403, 'forbidden origin');
1073
+ return;
1074
+ }
1075
+ // a preflight carries no token and gets no CORS headers: nothing here answers it
1076
+ if (method === 'OPTIONS') {
1077
+ sendMethodNotAllowed(res, ALLOW_BY_KIND[kind]);
1078
+ return;
1079
+ }
1080
+ switch (kind) {
1081
+ case 'hook':
1082
+ if (segments.length === 3 && segments[1] && segments[2])
1083
+ await hookHandler(req, res, segments[1], segments[2]);
1084
+ else
1085
+ sendNotFound(res);
1086
+ return;
1087
+ case 'mcp':
1088
+ if (segments.length === 1)
1089
+ await mcpHandler(req, res);
1090
+ else
1091
+ sendNotFound(res);
1092
+ return;
1093
+ case 'ws':
1094
+ // a real WebSocket never gets here (it is an upgrade); this is a plain GET, a probe or a mistake
1095
+ if (!restAuthorized(req) && !wsAuthorized(req))
1096
+ sendUnauthorized(res);
1097
+ else if (!options.isReady())
1098
+ sendApiError(res, 503, 'starting', 'unavailable');
1099
+ else if (segments.length !== 1)
1100
+ sendNotFound(res);
1101
+ else if (method !== 'GET')
1102
+ sendMethodNotAllowed(res, ALLOW_BY_KIND.ws);
1103
+ else
1104
+ sendApiError(res, 400, 'this endpoint needs a WebSocket upgrade', 'bad_request');
1105
+ return;
1106
+ case 'uplink':
1107
+ await handleUplink(req, res, segments);
1108
+ return;
1109
+ case 'dock':
1110
+ await handleDock(req, res, segments);
1111
+ return;
1112
+ case 'api':
1113
+ await handleApi(req, res, segments);
1114
+ return;
1115
+ case 'static':
1116
+ await serveStatic(req, res, segments);
1117
+ return;
1118
+ }
1119
+ };
1120
+ const onRequest = (req, res) => {
1121
+ // a late write to a response whose socket is gone emits 'error' on it; without a listener that ends the process
1122
+ res.on('error', (e) => log.debug('response error', e));
1123
+ void handleRequest(req, res).catch((e) => {
1124
+ log.error('request failed', e);
1125
+ if (res.headersSent)
1126
+ res.destroy();
1127
+ else
1128
+ sendApiError(res, 500, 'internal error', 'internal');
1129
+ });
1130
+ };
1131
+ /* ---------------------------------------------------------------- WebSocket (contract 3.4) */
1132
+ const wss = new WebSocketServer({
1133
+ noServer: true,
1134
+ perMessageDeflate: false,
1135
+ maxPayload: WS_MAX_FRAME_BYTES,
1136
+ // the client offers the token as a second protocol; selecting only the real one keeps the secret out of the response
1137
+ handleProtocols: (protocols) => (protocols.has(WS_SUBPROTOCOL) ? WS_SUBPROTOCOL : false),
1138
+ });
1139
+ wss.on('error', (e) => log.error('websocket server error', e));
1140
+ const sendRaw = (client, data, binary) => {
1141
+ const { ws } = client;
1142
+ if (ws.readyState !== WebSocket.OPEN)
1143
+ return;
1144
+ if (ws.bufferedAmount > WS_MAX_BUFFERED_BYTES) {
1145
+ // the browser reconnects and gets a fresh snapshot, so dropping the slow reader loses nothing
1146
+ ws.close(WS_CLOSE_BACKPRESSURE, 'too slow');
1147
+ setTimeout(() => ws.terminate(), 2000).unref();
1148
+ return;
1149
+ }
1150
+ ws.send(data, { binary }, (err) => {
1151
+ if (err)
1152
+ log.debug('websocket send failed', err);
1153
+ });
1154
+ };
1155
+ const sendFrame = (client, frame) => sendRaw(client, JSON.stringify(frame), false);
1156
+ const sendError = (client, message, ref) => sendFrame(client, { t: 'error', message, ref });
1157
+ const sendOutput = (client, seq, chunk) => {
1158
+ const frame = Buffer.allocUnsafe(5 + chunk.length);
1159
+ frame[0] = WS_BINARY_OUTPUT;
1160
+ frame.writeUInt32BE(seq, 1);
1161
+ frame.set(chunk, 5);
1162
+ sendRaw(client, frame, true);
1163
+ };
1164
+ const releaseAttachment = (client) => {
1165
+ client.attachment?.detach();
1166
+ client.attachment = null;
1167
+ client.attached = null;
1168
+ };
1169
+ /** Makes this socket's size the pty's size, and tells every socket attached to that agent when it changed. */
1170
+ const takeSize = (agent, size) => {
1171
+ const before = terminals.info(agent);
1172
+ if (!before?.running || (before.cols === size.cols && before.rows === size.rows))
1173
+ return;
1174
+ terminals.resize(agent, size.cols, size.rows);
1175
+ const after = terminals.info(agent);
1176
+ if (!after || (after.cols === before.cols && after.rows === before.rows))
1177
+ return;
1178
+ for (const other of clients) {
1179
+ if (other.attached?.agent === agent)
1180
+ sendFrame(other, { t: 'size', agent, cols: after.cols, rows: after.rows });
1181
+ }
1182
+ };
1183
+ const onAttach = async (client, frame) => {
1184
+ const { seq, agent } = frame;
1185
+ if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 0 || seq > 0xffffffff || typeof agent !== 'string') {
1186
+ sendError(client, 'bad frame', 'attach');
1187
+ return;
1188
+ }
1189
+ if (!nameRe.test(agent) || !hub.views().some((v) => v.name === agent)) {
1190
+ sendError(client, 'unknown agent', 'attach');
1191
+ return;
1192
+ }
1193
+ const token = (client.attachToken += 1);
1194
+ releaseAttachment(client);
1195
+ const size = fitSize(frame.cols, frame.rows);
1196
+ if (size) {
1197
+ client.size = size;
1198
+ takeSize(agent, size);
1199
+ }
1200
+ const listener = (chunk) => {
1201
+ if (client.attachToken !== token)
1202
+ return;
1203
+ try {
1204
+ sendOutput(client, seq, chunk);
1205
+ }
1206
+ catch (e) {
1207
+ log.error('terminal output could not be sent', e);
1208
+ }
1209
+ };
1210
+ let attachment;
1211
+ try {
1212
+ attachment = await terminals.attach(agent, listener);
1213
+ }
1214
+ catch (e) {
1215
+ log.error('terminal attach failed', e);
1216
+ if (client.attachToken === token)
1217
+ sendError(client, 'could not attach', 'attach');
1218
+ return;
1219
+ }
1220
+ if (client.closed || client.attachToken !== token) {
1221
+ attachment.detach();
1222
+ return;
1223
+ }
1224
+ client.attachment = attachment;
1225
+ client.attached = { agent, seq };
1226
+ const snap = attachment.snapshot;
1227
+ sendFrame(client, {
1228
+ t: 'snapshot',
1229
+ seq,
1230
+ agent,
1231
+ generation: snap.generation,
1232
+ cols: snap.cols,
1233
+ rows: snap.rows,
1234
+ running: snap.running,
1235
+ data: snap.data,
1236
+ });
1237
+ attachment.start();
1238
+ };
1239
+ const onInput = (client, frame) => {
1240
+ const { agent, data, binary } = frame;
1241
+ if (typeof agent !== 'string' || typeof data !== 'string' || (binary !== undefined && typeof binary !== 'boolean')) {
1242
+ sendError(client, 'bad frame', 'input');
1243
+ return;
1244
+ }
1245
+ if (client.attached?.agent !== agent) {
1246
+ sendError(client, 'not attached to that agent', 'input');
1247
+ return;
1248
+ }
1249
+ if (!terminals.write(agent, binary === true ? Buffer.from(data, 'latin1') : data))
1250
+ return;
1251
+ let effect = 'none';
1252
+ try {
1253
+ effect = hub.onUserInput(agent, data);
1254
+ }
1255
+ catch (e) {
1256
+ log.error('hub.onUserInput failed', e);
1257
+ }
1258
+ // only a keystroke a person made owns the size: focus, mouse and terminal replies arrive as input too (contract 3.4)
1259
+ if (effect !== 'none' && client.size)
1260
+ takeSize(agent, client.size);
1261
+ };
1262
+ const onResize = (client, frame) => {
1263
+ const { agent } = frame;
1264
+ if (typeof agent !== 'string' || client.attached?.agent !== agent) {
1265
+ sendError(client, 'not attached to that agent', 'resize');
1266
+ return;
1267
+ }
1268
+ const size = fitSize(frame.cols, frame.rows);
1269
+ if (!size) {
1270
+ sendError(client, 'bad size', 'resize');
1271
+ return;
1272
+ }
1273
+ client.size = size;
1274
+ takeSize(agent, size);
1275
+ };
1276
+ const onMessage = async (client, data, isBinary) => {
1277
+ let frame = null;
1278
+ if (!isBinary) {
1279
+ try {
1280
+ frame = JSON.parse(rawToString(data));
1281
+ }
1282
+ catch {
1283
+ // falls through to the bad frame answer
1284
+ }
1285
+ }
1286
+ if (!isRecord(frame)) {
1287
+ sendError(client, 'bad frame', 'frame');
1288
+ return;
1289
+ }
1290
+ switch (frame.t) {
1291
+ case 'attach':
1292
+ await onAttach(client, frame);
1293
+ return;
1294
+ case 'detach':
1295
+ client.attachToken += 1;
1296
+ releaseAttachment(client);
1297
+ return;
1298
+ case 'input':
1299
+ onInput(client, frame);
1300
+ return;
1301
+ case 'resize':
1302
+ onResize(client, frame);
1303
+ return;
1304
+ default:
1305
+ sendError(client, 'bad frame', 'frame');
1306
+ }
1307
+ };
1308
+ const onConnection = (ws) => {
1309
+ ws.on('error', (e) => log.warn('websocket error', e));
1310
+ const client = { ws, alive: true, attached: null, attachment: null, attachToken: 0, size: null, closed: false };
1311
+ clients.add(client);
1312
+ ws.on('pong', () => {
1313
+ client.alive = true;
1314
+ });
1315
+ ws.on('message', (data, isBinary) => {
1316
+ void onMessage(client, data, isBinary).catch((e) => {
1317
+ log.error('websocket frame failed', e);
1318
+ sendError(client, 'internal error', 'frame');
1319
+ });
1320
+ });
1321
+ ws.on('close', () => {
1322
+ client.closed = true;
1323
+ client.attachToken += 1;
1324
+ clients.delete(client);
1325
+ try {
1326
+ releaseAttachment(client);
1327
+ }
1328
+ catch (e) {
1329
+ log.error('terminal detach failed', e);
1330
+ }
1331
+ });
1332
+ try {
1333
+ sendFrame(client, { t: 'state', state: snapshot() });
1334
+ }
1335
+ catch (e) {
1336
+ log.error('could not send the state snapshot', e);
1337
+ ws.terminate();
1338
+ }
1339
+ };
1340
+ const onUpgrade = (req, socket, head) => {
1341
+ // after 'upgrade' the raw socket has no error listener: a reset during the handshake would end the process
1342
+ socket.on('error', noop);
1343
+ try {
1344
+ // the order of contract 3.2: Host, Origin, token, ready; a path that is not /ws is a 404 like it is for a request
1345
+ const segments = parseTarget(req.url);
1346
+ if (!hostAllowed(req.headers.host)) {
1347
+ rejectUpgrade(socket, 403, 'text/plain', 'forbidden host');
1348
+ }
1349
+ else if (segments === null) {
1350
+ rejectUpgrade(socket, 404, 'text/plain', 'not found');
1351
+ }
1352
+ else if (!originAllowed(req, 'ws')) {
1353
+ rejectUpgrade(socket, 403, 'text/plain', 'forbidden origin');
1354
+ }
1355
+ else if (classify(segments) !== 'ws' || segments.length !== 1) {
1356
+ rejectUpgrade(socket, 404, 'text/plain', 'not found');
1357
+ }
1358
+ else if (req.method !== 'GET') {
1359
+ rejectUpgrade(socket, 405, 'text/plain', 'method not allowed', ['Allow: GET']);
1360
+ }
1361
+ else if (!wsAuthorized(req)) {
1362
+ rejectUpgrade(socket, 401, 'application/json', '{"error":"unauthorized","code":"unauthorized"}', ['WWW-Authenticate: Bearer']);
1363
+ }
1364
+ else if (!options.isReady()) {
1365
+ rejectUpgrade(socket, 503, 'application/json', '{"error":"starting","code":"unavailable"}');
1366
+ }
1367
+ else {
1368
+ socket.removeListener('error', noop);
1369
+ wss.handleUpgrade(req, socket, head, onConnection);
1370
+ }
1371
+ }
1372
+ catch (e) {
1373
+ log.error('upgrade failed', e);
1374
+ socket.on('error', noop);
1375
+ socket.destroy();
1376
+ }
1377
+ };
1378
+ /* ---------------------------------------------------------------- lifecycle */
1379
+ const createHttpServer = () => {
1380
+ const server = createServer(onRequest);
1381
+ server.on('upgrade', onUpgrade);
1382
+ return server;
1383
+ };
1384
+ const listenOn = (server, port, host) => new Promise((resolve, reject) => {
1385
+ server.once('error', reject);
1386
+ server.listen({ port, host }, () => {
1387
+ server.removeListener('error', reject);
1388
+ server.on('error', (e) => log.error('http server error', e));
1389
+ resolve();
1390
+ });
1391
+ });
1392
+ const closeHttp = (server) => new Promise((resolve) => {
1393
+ const force = setTimeout(() => server.closeAllConnections(), 1000);
1394
+ server.close(() => {
1395
+ clearTimeout(force);
1396
+ resolve();
1397
+ });
1398
+ server.closeIdleConnections();
1399
+ });
1400
+ const startListening = async () => {
1401
+ const primary = createHttpServer();
1402
+ servers.push(primary);
1403
+ await listenOn(primary, options.port, options.host);
1404
+ const address = primary.address();
1405
+ if (address === null || typeof address === 'string')
1406
+ throw new Error('the web server has no address');
1407
+ if (needsLoopbackTwin(options.host)) {
1408
+ const twin = createHttpServer();
1409
+ servers.push(twin);
1410
+ try {
1411
+ await listenOn(twin, address.port, '127.0.0.1');
1412
+ }
1413
+ catch (e) {
1414
+ await closeHttp(primary);
1415
+ throw e;
1416
+ }
1417
+ }
1418
+ pingTimer = setInterval(() => {
1419
+ for (const client of [...clients]) {
1420
+ try {
1421
+ if (!client.alive) {
1422
+ client.ws.terminate();
1423
+ continue;
1424
+ }
1425
+ client.alive = false;
1426
+ client.ws.ping();
1427
+ }
1428
+ catch (e) {
1429
+ log.debug('websocket ping failed', e);
1430
+ }
1431
+ }
1432
+ }, WS_PING_INTERVAL_MS);
1433
+ pingTimer.unref();
1434
+ return { host: address.address, port: address.port };
1435
+ };
1436
+ const waitClosed = (client) => new Promise((resolve) => {
1437
+ if (client.ws.readyState === WebSocket.CLOSED)
1438
+ resolve();
1439
+ else
1440
+ client.ws.once('close', () => resolve());
1441
+ });
1442
+ const closeAll = async () => {
1443
+ if (pingTimer)
1444
+ clearInterval(pingTimer);
1445
+ const open = [...clients];
1446
+ for (const client of open)
1447
+ client.ws.close(WS_CLOSE_GOING_AWAY, 'server shutting down');
1448
+ let giveUp;
1449
+ await Promise.race([
1450
+ Promise.all(open.map(waitClosed)),
1451
+ new Promise((resolve) => {
1452
+ giveUp = setTimeout(resolve, 1000);
1453
+ }),
1454
+ ]);
1455
+ clearTimeout(giveUp);
1456
+ for (const client of open)
1457
+ client.ws.terminate();
1458
+ await Promise.all(servers.map(closeHttp));
1459
+ wss.close();
1460
+ };
1461
+ return {
1462
+ listen: () => (started ??= startListening()),
1463
+ close: () => (closing ??= closeAll()),
1464
+ broadcast,
1465
+ };
1466
+ }