hopwire 0.1.8 → 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.
Files changed (41) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/redact.js +38 -0
  3. package/dist/bin.js +5 -1
  4. package/dist/cli.js +237 -10
  5. package/dist/commands/connect.js +23 -7
  6. package/dist/commands/doctor.js +63 -3
  7. package/dist/commands/http.js +25 -4
  8. package/dist/commands/init.js +355 -0
  9. package/dist/commands/up.js +22 -3
  10. package/dist/commands/watch.js +54 -9
  11. package/dist/config-template.js +80 -0
  12. package/dist/config.js +65 -5
  13. package/dist/control-plane-client.js +70 -0
  14. package/dist/inspector/assets/index-CIOfyIbK.js +5 -0
  15. package/dist/inspector/assets/index-Du4-DCNN.css +2 -0
  16. package/dist/inspector/index.html +2 -2
  17. package/dist/inspector-api.js +145 -0
  18. package/dist/interceptor.js +19 -4
  19. package/dist/log-follow.js +473 -0
  20. package/dist/log.js +178 -11
  21. package/dist/main.js +1 -0
  22. package/dist/mcp/logs.js +46 -0
  23. package/dist/mcp/tools.js +136 -3
  24. package/dist/output.js +67 -1
  25. package/dist/p2p.js +249 -24
  26. package/dist/prompt.js +63 -0
  27. package/dist/relay.js +545 -0
  28. package/dist/serve.js +62 -2
  29. package/node_modules/@hopwire/protocol/dist/constants.d.ts +10 -0
  30. package/node_modules/@hopwire/protocol/dist/constants.js +10 -0
  31. package/node_modules/@hopwire/protocol/dist/index.d.ts +2 -0
  32. package/node_modules/@hopwire/protocol/dist/index.js +2 -0
  33. package/node_modules/@hopwire/protocol/dist/inspector.d.ts +18 -0
  34. package/node_modules/@hopwire/protocol/dist/log-entries.d.ts +72 -0
  35. package/node_modules/@hopwire/protocol/dist/log-entries.js +147 -0
  36. package/node_modules/@hopwire/protocol/dist/relay.d.ts +81 -0
  37. package/node_modules/@hopwire/protocol/dist/relay.js +102 -0
  38. package/node_modules/@hopwire/protocol/dist/ws-messages.d.ts +2 -1
  39. package/package.json +2 -1
  40. package/dist/inspector/assets/index-D3yNjmSA.js +0 -2
  41. package/dist/inspector/assets/index-XotF7D1X.css +0 -2
package/dist/relay.js ADDED
@@ -0,0 +1,545 @@
1
+ import { Duplex } from 'node:stream';
2
+ import NoiseSecretStream, {} from '@hyperswarm/secret-stream';
3
+ import { WebSocket } from 'ws';
4
+ import { RECONNECT_BACKOFF_MS, RELAY_ACCEPT_PATH, RELAY_BACKPRESSURE_BYTES, RELAY_CHUNK_BYTES, RELAY_CLOSE, RELAY_DIAL_PATH, RELAY_DIAL_TIMEOUT_MS, RELAY_FRAME, RELAY_LISTEN_PATH, RELAY_MESSAGE_MAX_BYTES, decodeRelayControl, } from '@hopwire/protocol';
5
+ import { HopwireError, TemporaryError } from './errors.js';
6
+ import { proxiedConnection, proxyFor, throughProxy } from './outbound-proxy.js';
7
+ /**
8
+ * The relay for strict networks (`--relay`, spec phase 12, decision 136). When no direct P2P connection comes about
9
+ * (both sides behind a symmetric NAT, or a network that blocks UDP), both CLIs open a WebSocket on 443 to the edge,
10
+ * which pairs them within one organisation and passes the bytes on. Over that pipe they run the Noise handshake of the
11
+ * DHT path (@hyperswarm/secret-stream, the same key pairs), so the edge passes on bytes it cannot read, and whoever
12
+ * gets in is decided by the sharer on the peer's public key, as on the DHT path.
13
+ *
14
+ * This is the only module that opens a relay socket. It is loaded only for --relay, which needs --team: without it
15
+ * private mode never contacts the edge.
16
+ */
17
+ /** How long the edge may take to answer the upgrade request. */
18
+ const HANDSHAKE_TIMEOUT_MS = 15_000;
19
+ /** How long the Noise handshake over a pipe may take. */
20
+ const NOISE_TIMEOUT_MS = 15_000;
21
+ /** How often a listen socket pings the edge; two pings without a pong and it is given up. */
22
+ const PING_INTERVAL_MS = 30_000;
23
+ /** How long before the token of a listen socket runs out the socket is replaced with one of a new token. */
24
+ const RENEW_BEFORE_MS = 60_000;
25
+ /** The relay of one run: its access and the tokens all its sockets share. */
26
+ export function relaySetup(option, peerKey) {
27
+ const access = { ...option, peerKey };
28
+ return { access, tokens: new RelayTokens(access) };
29
+ }
30
+ /** Why a relay socket did not become what it was opened for. `code` is for messages; see relayProblem. */
31
+ export class RelayError extends Error {
32
+ code;
33
+ detail;
34
+ constructor(code, detail = '') {
35
+ super(`The relay did not connect (${code}${detail === '' ? '' : `: ${detail}`})`);
36
+ this.code = code;
37
+ this.detail = detail;
38
+ }
39
+ }
40
+ /** Tokens for the relay sockets: fetched from the control plane, used until shortly before they run out. */
41
+ export class RelayTokens {
42
+ access;
43
+ current = null;
44
+ fetching = null;
45
+ constructor(access) {
46
+ this.access = access;
47
+ }
48
+ /** A token that still counts for at least a minute; fetched anew otherwise. */
49
+ async get(signal) {
50
+ if (this.current !== null && this.current.validUntil - Date.now() > RENEW_BEFORE_MS) {
51
+ return this.current;
52
+ }
53
+ this.fetching ??= this.access.tokens
54
+ .relayToken(this.access.peerKey, signal)
55
+ .then((answer) => {
56
+ this.current = { token: answer.token, validUntil: Date.now() + answer.expiresInMs };
57
+ return this.current;
58
+ })
59
+ .finally(() => {
60
+ this.fetching = null;
61
+ });
62
+ return this.fetching;
63
+ }
64
+ /** The edge refused the token: the next socket fetches a new one. */
65
+ drop() {
66
+ this.current = null;
67
+ }
68
+ }
69
+ /**
70
+ * A relay socket as the raw stream of a Noise stream: binary messages of the pipe, each with a first byte that says
71
+ * what it is (RELAY_FRAME). Stream bytes go both ways with backpressure (the socket stops being read while the
72
+ * reader is full); datagrams (the flow control of hopwire connect) go next to them; the end of one direction is a
73
+ * message of its own, since a WebSocket cannot be half closed.
74
+ */
75
+ class RelayDuplex extends Duplex {
76
+ ws;
77
+ localEnded = false;
78
+ remoteEnded = false;
79
+ constructor(ws) {
80
+ super({ allowHalfOpen: true });
81
+ this.ws = ws;
82
+ ws.on('message', (data, isBinary) => this.receive(data, isBinary));
83
+ ws.once('close', (code, reason) => {
84
+ if (this.destroyed) {
85
+ return;
86
+ }
87
+ if (this.remoteEnded && (this.localEnded || code === 1000)) {
88
+ this.destroy();
89
+ return;
90
+ }
91
+ this.destroy(new RelayError(closeError(code), reason.toString()));
92
+ });
93
+ ws.on('error', () => { });
94
+ }
95
+ /** A datagram next to the stream; dropped when the socket is not open or has a lot waiting (it is unreliable). */
96
+ trySend(message) {
97
+ if (this.ws.readyState === WebSocket.OPEN && this.ws.bufferedAmount < RELAY_BACKPRESSURE_BYTES) {
98
+ this.ws.send(frame(RELAY_FRAME.datagram, message), { binary: true });
99
+ }
100
+ }
101
+ send(message) {
102
+ this.trySend(message);
103
+ return true;
104
+ }
105
+ _read() {
106
+ if (this.ws.isPaused) {
107
+ this.ws.resume();
108
+ }
109
+ }
110
+ _write(chunk, _encoding, callback) {
111
+ if (this.ws.readyState !== WebSocket.OPEN) {
112
+ callback(new RelayError('closed'));
113
+ return;
114
+ }
115
+ // Pieces the edge takes whole; the callback waits for the last, so the writer feels the socket's pace
116
+ for (let offset = 0; offset < chunk.length; offset += RELAY_CHUNK_BYTES) {
117
+ const last = offset + RELAY_CHUNK_BYTES >= chunk.length;
118
+ this.ws.send(frame(RELAY_FRAME.data, chunk.subarray(offset, offset + RELAY_CHUNK_BYTES)), { binary: true }, last ? (error) => callback(error ?? null) : undefined);
119
+ }
120
+ if (chunk.length === 0) {
121
+ callback();
122
+ }
123
+ }
124
+ _final(callback) {
125
+ this.localEnded = true;
126
+ if (this.ws.readyState !== WebSocket.OPEN) {
127
+ callback();
128
+ return;
129
+ }
130
+ this.ws.send(frame(RELAY_FRAME.end, new Uint8Array(0)), { binary: true }, () => {
131
+ callback();
132
+ this.closeWhenBothEnded();
133
+ });
134
+ }
135
+ _destroy(error, callback) {
136
+ if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
137
+ this.ws.close(error === null ? 1000 : 1001);
138
+ }
139
+ callback(error);
140
+ }
141
+ receive(data, isBinary) {
142
+ const message = toBuffer(data);
143
+ if (!isBinary || message.length === 0) {
144
+ this.destroy(new RelayError('closed', 'unexpected message'));
145
+ return;
146
+ }
147
+ const kind = message[0];
148
+ const body = message.subarray(1);
149
+ if (kind === RELAY_FRAME.data) {
150
+ if (!this.push(body)) {
151
+ this.ws.pause();
152
+ }
153
+ }
154
+ else if (kind === RELAY_FRAME.datagram) {
155
+ this.emit('message', body);
156
+ }
157
+ else if (kind === RELAY_FRAME.end) {
158
+ this.remoteEnded = true;
159
+ this.push(null);
160
+ this.closeWhenBothEnded();
161
+ }
162
+ }
163
+ closeWhenBothEnded() {
164
+ if (this.localEnded && this.remoteEnded && this.ws.readyState === WebSocket.OPEN) {
165
+ this.ws.close(1000);
166
+ }
167
+ }
168
+ }
169
+ /** Opens a relay socket at the edge; rejects with a RelayError when it is refused or cannot be reached. */
170
+ async function openSocket(access, tokens, pathAndQuery, signal) {
171
+ for (let attempt = 0;; attempt++) {
172
+ signal?.throwIfAborted();
173
+ const { token } = await tokens.get(signal);
174
+ const url = new URL(pathAndQuery, access.edgeUrl);
175
+ const proxy = proxyFor(url);
176
+ const options = {
177
+ headers: { authorization: `Bearer ${token}` },
178
+ handshakeTimeout: HANDSHAKE_TIMEOUT_MS,
179
+ maxPayload: RELAY_MESSAGE_MAX_BYTES,
180
+ perMessageDeflate: false,
181
+ ...(proxy === null
182
+ ? {}
183
+ : { createConnection: proxiedConnection(proxy, url) }),
184
+ };
185
+ const ws = new WebSocket(url, options);
186
+ ws.on('error', () => { });
187
+ const outcome = await new Promise((resolve) => {
188
+ const abort = () => {
189
+ ws.terminate();
190
+ resolve(new RelayError('closed', 'stopped'));
191
+ };
192
+ signal?.addEventListener('abort', abort, { once: true });
193
+ const done = (value) => {
194
+ signal?.removeEventListener('abort', abort);
195
+ resolve(value);
196
+ };
197
+ ws.once('open', () => done(ws));
198
+ ws.once('unexpected-response', (_request, response) => {
199
+ response.resume();
200
+ ws.terminate();
201
+ done(new RelayError('refused', String(response.statusCode ?? 0)));
202
+ });
203
+ ws.once('error', (error) => done(new RelayError('unreachable', `${error.code ?? error.message}${throughProxy(proxy)}`.replace(/^ /, ''))));
204
+ });
205
+ if (outcome instanceof WebSocket) {
206
+ return outcome;
207
+ }
208
+ signal?.throwIfAborted();
209
+ // A token the edge did not take (it expired on the way, the clocks differ): once more with a new one
210
+ if (outcome.code === 'refused' && outcome.detail === '401' && attempt === 0) {
211
+ tokens.drop();
212
+ continue;
213
+ }
214
+ throw outcome;
215
+ }
216
+ }
217
+ /** Runs the Noise handshake over a relay socket; resolves with the stream once it is open. */
218
+ async function secure(ws, isInitiator, keyPair) {
219
+ const stream = new NoiseSecretStream(isInitiator, new RelayDuplex(ws), { keyPair });
220
+ stream.on('error', () => { });
221
+ let timer;
222
+ const opened = await Promise.race([
223
+ stream.opened,
224
+ new Promise((resolve) => {
225
+ timer = setTimeout(() => resolve(false), NOISE_TIMEOUT_MS);
226
+ }),
227
+ ]);
228
+ clearTimeout(timer);
229
+ if (!opened) {
230
+ stream.destroy();
231
+ throw new RelayError('handshake');
232
+ }
233
+ return stream;
234
+ }
235
+ /**
236
+ * Dials a topic through the relay: resolves with an end-to-end encrypted stream to the machine that listens on it,
237
+ * or rejects with a RelayError (nobody listens, a limit, the edge cannot be reached).
238
+ */
239
+ export async function dialRelay(options) {
240
+ const ws = await openSocket(options.access, options.tokens, `${RELAY_DIAL_PATH}?target=${options.target}`, options.signal);
241
+ try {
242
+ await new Promise((resolve, reject) => {
243
+ const timer = setTimeout(() => {
244
+ ws.terminate();
245
+ reject(new RelayError('dial_timeout'));
246
+ }, RELAY_DIAL_TIMEOUT_MS + 5_000);
247
+ const onMessage = (data, isBinary) => {
248
+ clearTimeout(timer);
249
+ ws.off('close', onClose);
250
+ if (isBinary || safeControl(toBuffer(data).toString())?.type !== 'paired') {
251
+ ws.terminate();
252
+ reject(new RelayError('closed', 'unexpected message'));
253
+ return;
254
+ }
255
+ resolve();
256
+ };
257
+ const onClose = (code, reason) => {
258
+ clearTimeout(timer);
259
+ ws.off('message', onMessage);
260
+ reject(new RelayError(closeError(code), reason.toString()));
261
+ };
262
+ ws.once('message', onMessage);
263
+ ws.once('close', onClose);
264
+ });
265
+ const stream = await secure(ws, true, options.keyPair);
266
+ if (options.remotePublicKey !== null && !stream.remotePublicKey.equals(options.remotePublicKey)) {
267
+ // Someone of the organisation listened on the topic, but it is not the machine that was asked for
268
+ stream.destroy();
269
+ throw new RelayError('wrong_peer');
270
+ }
271
+ return stream;
272
+ }
273
+ catch (error) {
274
+ ws.terminate();
275
+ throw error;
276
+ }
277
+ }
278
+ /**
279
+ * The sharer's side: keeps a listen socket open at the edge for its topics, replaces it with one of a new token
280
+ * before the token runs out, and comes back with the backoff of the edge bridge when it is lost. Every dial the edge
281
+ * reports is answered with an accept socket and a Noise handshake as the responder.
282
+ *
283
+ * Resolves once the first socket is open; a first socket that cannot be opened is no error: the tunnel runs on
284
+ * direct P2P and the listener keeps trying.
285
+ */
286
+ export async function startRelayListener(options) {
287
+ const { access, tokens, topics } = options;
288
+ const query = [...topics.keys()].map((topic) => `topic=${topic}`).join('&');
289
+ const streams = new Set();
290
+ let closed = false;
291
+ let current = null;
292
+ let relayedOnce = false;
293
+ let ready = false;
294
+ /** Events wait until the start is over, so the lines of the start come first; its outcome is `problem` */
295
+ let started = false;
296
+ let problem = null;
297
+ let backoff = RECONNECT_BACKOFF_MS.initial;
298
+ let retry;
299
+ let renew;
300
+ let end = () => { };
301
+ const ended = new Promise((resolve) => {
302
+ end = resolve;
303
+ });
304
+ const answer = async (dial, topic) => {
305
+ const answering = topics.get(topic);
306
+ if (answering === undefined || closed) {
307
+ return;
308
+ }
309
+ try {
310
+ const ws = await openSocket(access, tokens, `${RELAY_ACCEPT_PATH}?dial=${dial}`);
311
+ if (closed) {
312
+ ws.terminate();
313
+ return;
314
+ }
315
+ const stream = await secure(ws, false, answering.keyPair);
316
+ if (closed) {
317
+ stream.destroy();
318
+ return;
319
+ }
320
+ streams.add(stream);
321
+ stream.once('close', () => streams.delete(stream));
322
+ if (!relayedOnce) {
323
+ relayedOnce = true;
324
+ options.onEvent?.({ type: 'relayed' });
325
+ }
326
+ answering.onStream(stream);
327
+ }
328
+ catch {
329
+ // The dialer hears of it from the edge; nothing to say here
330
+ }
331
+ };
332
+ const watch = (ws, validUntil) => {
333
+ let missed = 0;
334
+ const pinger = setInterval(() => {
335
+ if (missed >= 2) {
336
+ ws.terminate();
337
+ return;
338
+ }
339
+ missed += 1;
340
+ ws.ping();
341
+ }, PING_INTERVAL_MS);
342
+ pinger.unref();
343
+ ws.on('pong', () => {
344
+ missed = 0;
345
+ });
346
+ ws.on('message', (data, isBinary) => {
347
+ const control = isBinary ? null : safeControl(toBuffer(data).toString());
348
+ if (control?.type === 'dial') {
349
+ void answer(control.dial, control.topic);
350
+ }
351
+ });
352
+ ws.once('close', (code) => {
353
+ clearInterval(pinger);
354
+ if (ws !== current || closed) {
355
+ return;
356
+ }
357
+ current = null;
358
+ clearTimeout(renew);
359
+ if (ready) {
360
+ ready = false;
361
+ options.onEvent?.({ type: 'lost', problem: `the connection to the edge closed (${code})` });
362
+ }
363
+ schedule();
364
+ });
365
+ clearTimeout(renew);
366
+ // A new socket with a new token before this one's runs out; the old one goes once the new one is open
367
+ renew = setTimeout(() => void connect(true), Math.max(30_000, validUntil - Date.now() - RENEW_BEFORE_MS));
368
+ renew.unref();
369
+ };
370
+ const connect = async (replacing) => {
371
+ if (closed) {
372
+ return;
373
+ }
374
+ try {
375
+ const ws = await openSocket(access, tokens, `${RELAY_LISTEN_PATH}?${query}`, options.signal);
376
+ if (closed) {
377
+ ws.close(1000);
378
+ return;
379
+ }
380
+ const previous = current;
381
+ current = ws;
382
+ backoff = RECONNECT_BACKOFF_MS.initial;
383
+ watch(ws, (await tokens.get()).validUntil);
384
+ previous?.close(1000);
385
+ if (!ready) {
386
+ ready = true;
387
+ if (started) {
388
+ options.onEvent?.({ type: 'ready' });
389
+ }
390
+ }
391
+ }
392
+ catch (error) {
393
+ if (closed || options.signal?.aborted === true) {
394
+ return;
395
+ }
396
+ if (error instanceof HopwireError && !(error instanceof TemporaryError)) {
397
+ // The control plane refuses relay tokens for good: the relay is off for this run
398
+ closed = true;
399
+ current?.close(1000);
400
+ end(error);
401
+ return;
402
+ }
403
+ if (replacing && current !== null) {
404
+ // The old socket still counts until its token runs out; the edge closes it then
405
+ renew = setTimeout(() => void connect(true), 10_000);
406
+ renew.unref();
407
+ return;
408
+ }
409
+ if (!replacing || current === null) {
410
+ if (started) {
411
+ if (ready) {
412
+ ready = false;
413
+ options.onEvent?.({ type: 'lost', problem: relayProblem(error) });
414
+ }
415
+ }
416
+ else {
417
+ problem = relayProblem(error);
418
+ }
419
+ schedule();
420
+ }
421
+ }
422
+ };
423
+ const schedule = () => {
424
+ if (closed) {
425
+ return;
426
+ }
427
+ clearTimeout(retry);
428
+ const wait = backoff * (0.5 + Math.random() / 2);
429
+ backoff = Math.min(backoff * 2, RECONNECT_BACKOFF_MS.max);
430
+ retry = setTimeout(() => void connect(false), wait);
431
+ };
432
+ await connect(false);
433
+ started = true;
434
+ return {
435
+ problem: ready ? null : problem,
436
+ ended,
437
+ async close() {
438
+ closed = true;
439
+ clearTimeout(retry);
440
+ clearTimeout(renew);
441
+ current?.close(1000);
442
+ for (const stream of streams) {
443
+ stream.destroy();
444
+ }
445
+ },
446
+ };
447
+ }
448
+ /** One sentence about what went wrong with the relay, for a line of output. */
449
+ export function relayProblem(error) {
450
+ if (error instanceof HopwireError) {
451
+ return error.message;
452
+ }
453
+ if (!(error instanceof RelayError)) {
454
+ return 'the relay failed';
455
+ }
456
+ switch (error.code) {
457
+ case 'unreachable':
458
+ return `the edge cannot be reached (${error.detail})`;
459
+ case 'refused':
460
+ return `the edge refused the relay socket (${error.detail})`;
461
+ case 'no_listener':
462
+ return 'the teammate is not reachable through the relay: its tunnel runs without --relay, is not running, or belongs to another organisation';
463
+ case 'dial_timeout':
464
+ return 'the teammate did not answer through the relay in time';
465
+ case 'limit':
466
+ return error.detail === 'relay_bytes'
467
+ ? 'your organisation has used up the relayed data of the day; the relay works again from 00:00 UTC'
468
+ : 'your organisation has as many relayed connections open as it may';
469
+ case 'handshake':
470
+ return 'the end-to-end handshake through the relay failed';
471
+ case 'wrong_peer':
472
+ return 'the machine that answered through the relay is not the one with that key';
473
+ case 'closed':
474
+ return 'the relay connection closed';
475
+ }
476
+ }
477
+ /** Whether the relay refused because of a limit of the organisation (4029): said on a Limit line. */
478
+ export function isRelayLimit(error) {
479
+ return error instanceof RelayError && error.code === 'limit';
480
+ }
481
+ function closeError(code) {
482
+ switch (code) {
483
+ case RELAY_CLOSE.noListener:
484
+ return 'no_listener';
485
+ case RELAY_CLOSE.dialTimeout:
486
+ return 'dial_timeout';
487
+ case RELAY_CLOSE.limit:
488
+ return 'limit';
489
+ default:
490
+ return 'closed';
491
+ }
492
+ }
493
+ function safeControl(text) {
494
+ try {
495
+ return decodeRelayControl(text);
496
+ }
497
+ catch {
498
+ return null;
499
+ }
500
+ }
501
+ function frame(kind, body) {
502
+ const message = Buffer.allocUnsafe(body.length + 1);
503
+ message[0] = kind;
504
+ message.set(body, 1);
505
+ return message;
506
+ }
507
+ function toBuffer(data) {
508
+ if (Array.isArray(data)) {
509
+ return Buffer.concat(data);
510
+ }
511
+ return data instanceof ArrayBuffer ? Buffer.from(data) : data;
512
+ }
513
+ /**
514
+ * `hopwire doctor --network`: whether the relay of the edge answers from this network, through the proxy public mode
515
+ * would use. Sends a listen request without a token: the edge answers 401 and learns nothing but the address.
516
+ */
517
+ export async function probeRelay(edgeUrl) {
518
+ const url = new URL(`${RELAY_LISTEN_PATH}?topic=${'0'.repeat(64)}`, edgeUrl);
519
+ const proxy = proxyFor(url);
520
+ const ws = new WebSocket(url, {
521
+ handshakeTimeout: HANDSHAKE_TIMEOUT_MS,
522
+ perMessageDeflate: false,
523
+ ...(proxy === null
524
+ ? {}
525
+ : { createConnection: proxiedConnection(proxy, url) }),
526
+ });
527
+ ws.on('error', () => { });
528
+ return new Promise((resolve) => {
529
+ ws.once('unexpected-response', (_request, response) => {
530
+ response.resume();
531
+ ws.terminate();
532
+ resolve(response.statusCode === 401
533
+ ? { reachable: true }
534
+ : {
535
+ reachable: false,
536
+ problem: `the edge answered ${response.statusCode ?? 0} on the relay path; it may run an older version`,
537
+ });
538
+ });
539
+ ws.once('open', () => {
540
+ ws.terminate();
541
+ resolve({ reachable: false, problem: 'the edge took the relay socket without a token' });
542
+ });
543
+ ws.once('error', (error) => resolve({ reachable: false, problem: `${error.code ?? error.message}${throughProxy(proxy)}` }));
544
+ });
545
+ }
package/dist/serve.js CHANGED
@@ -3,10 +3,11 @@ import { fileURLToPath } from 'node:url';
3
3
  import { HopwireError, errorCode, listenError } from './errors.js';
4
4
  import { loadOrCreateIdentity } from './identity.js';
5
5
  import { startAgentSocket } from './agent-socket.js';
6
- import { createInspectorApi } from './inspector-api.js';
6
+ import { createInspectorApi, withLocalLogs } from './inspector-api.js';
7
7
  import { startInspectorServer } from './inspector-server.js';
8
8
  import { createInterceptor } from './interceptor.js';
9
9
  import { openOwnLog } from './data-dir-holder.js';
10
+ import { InFlightExchanges, followLogFile } from './log-follow.js';
10
11
  import { createProxyServer } from './proxy-server.js';
11
12
  import { Supervisor } from './supervisor.js';
12
13
  /**
@@ -37,14 +38,29 @@ export async function startServing(options) {
37
38
  // Waits for the exchanges that were answered and are still being appended
38
39
  return log.close();
39
40
  });
41
+ // Log entries that are not shared go into a core of their own, opened only when a file is followed
42
+ let localLogs = null;
43
+ if (options.services.some((service) => (service.logs?.length ?? 0) > 0)) {
44
+ const local = await log.openLocalLogs();
45
+ localLogs = local;
46
+ supervisor.add('store', () => local.close());
47
+ }
48
+ const shareLogs = options.share && options.shareLogs === true;
40
49
  const interceptors = new Map();
50
+ const inFlight = new Map();
41
51
  const services = [];
42
52
  for (const service of options.services) {
43
53
  proceed();
54
+ const tracked = (service.logs?.length ?? 0) > 0 ? new InFlightExchanges() : undefined;
55
+ if (tracked !== undefined) {
56
+ inFlight.set(service.name, tracked);
57
+ }
44
58
  const interceptor = createInterceptor({
45
59
  target: service.target,
46
60
  serviceName: service.name,
47
61
  log,
62
+ inFlight: tracked,
63
+ logRequestId: options.logRequestId === true && tracked !== undefined,
48
64
  allowAgents: options.share && options.allowAgents === true,
49
65
  captureWebSocketMessages: options.captureWebSocketMessages ?? true,
50
66
  onExchange: options.onExchange,
@@ -68,12 +84,41 @@ export async function startServing(options) {
68
84
  url: `http://127.0.0.1:${port}`,
69
85
  subdomain: service.public?.subdomain ?? null,
70
86
  publicUrl: null,
87
+ customDomains: [],
71
88
  usage: null,
72
89
  });
73
90
  }
91
+ const logs = [];
92
+ for (const service of options.services) {
93
+ const tracked = inFlight.get(service.name);
94
+ const target = shareLogs ? log : localLogs;
95
+ if (tracked === undefined || target === null) {
96
+ continue;
97
+ }
98
+ for (const file of service.logs ?? []) {
99
+ proceed();
100
+ const follower = await followLogFile({
101
+ ...file,
102
+ serviceName: service.name,
103
+ inFlight: tracked,
104
+ append: (block) => target.append(block),
105
+ agents: shareLogs && options.allowAgents === true,
106
+ onNotice: (line) => options.onLogNotice?.(service.name, line),
107
+ onLogError: () => {
108
+ if (!storeClosing) {
109
+ options.onLogError(service.name);
110
+ }
111
+ },
112
+ });
113
+ // Stopped with the servers: its last batch is written before the store closes
114
+ supervisor.add('servers', () => follower.stop());
115
+ logs.push({ serviceName: service.name, name: file.name, path: file.path, waiting: follower.waiting });
116
+ }
117
+ }
74
118
  const endings = [];
75
119
  let peerKey = null;
76
120
  let team = null;
121
+ let relay = null;
77
122
  if (options.share) {
78
123
  proceed();
79
124
  const identity = await loadOrCreateIdentity(options.dataDir);
@@ -93,6 +138,12 @@ export async function startServing(options) {
93
138
  team = { organisation: keys.organisation, keys: keys.size };
94
139
  endings.push(keys.ended);
95
140
  }
141
+ let relaySetup;
142
+ if (options.relay !== undefined) {
143
+ // Loaded only here: without --relay nothing opens a relay socket
144
+ const relayModule = await import('./relay.js');
145
+ relaySetup = relayModule.relaySetup(options.relay, identity.publicKey.toString('hex'));
146
+ }
96
147
  // Loaded only here: without sharing no DHT node and no swarm exist
97
148
  const { startSharing } = await import('./p2p.js');
98
149
  const sharing = await startSharing({
@@ -103,9 +154,14 @@ export async function startServing(options) {
103
154
  admission,
104
155
  bootstrap: options.bootstrap,
105
156
  signal: options.signal,
157
+ relay: relaySetup,
158
+ onRelayEvent: options.onRelayEvent,
106
159
  });
107
160
  supervisor.add('p2p', () => sharing.close());
108
161
  peerKey = sharing.peerKey;
162
+ if (options.relay !== undefined) {
163
+ relay = { edgeUrl: options.relay.edgeUrl, problem: sharing.relayProblem };
164
+ }
109
165
  }
110
166
  // The connections to the edge are closed side by side: each waits for the edge to confirm, and an edge that
111
167
  // no longer answers must not cost that wait once per service
@@ -134,6 +190,8 @@ export async function startServing(options) {
134
190
  proceed();
135
191
  token = issued.token;
136
192
  subdomain = issued.subdomain;
193
+ // Named once, at the start: a renewal that changes the set does not reprint the line
194
+ served.customDomains = issued.domains;
137
195
  renewToken = async () => (await connectTokens.connectToken(issued.subdomain)).token;
138
196
  }
139
197
  if (token === undefined || subdomain === null) {
@@ -178,7 +236,7 @@ export async function startServing(options) {
178
236
  proceed();
179
237
  // One API for both listeners: the same streams, the same replays
180
238
  const api = createInspectorApi({
181
- sources: [{ origin: 'own', log }],
239
+ sources: [{ origin: 'own', log: withLocalLogs(log, localLogs) }],
182
240
  status: () => status,
183
241
  // A replay goes to the local target of the exchange's service
184
242
  replayThrough: (exchange) => interceptors.get(exchange.serviceName) ?? null,
@@ -216,6 +274,7 @@ export async function startServing(options) {
216
274
  proceed();
217
275
  return {
218
276
  services,
277
+ logs,
219
278
  inspectorUrl,
220
279
  agentSocket,
221
280
  agentProblem,
@@ -223,6 +282,7 @@ export async function startServing(options) {
223
282
  logLength: log.length,
224
283
  peerKey,
225
284
  team,
285
+ relay,
226
286
  ended: endings.length > 0 ? Promise.race(endings) : new Promise(() => { }),
227
287
  close: supervisor.close,
228
288
  };