hopwire 0.1.8 → 0.1.9

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/dist/p2p.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import HyperDHT, {} from 'hyperdht';
2
2
  import Hyperswarm from 'hyperswarm';
3
3
  import { P2P_PREFACE_MAX_BYTES, decodeP2pPreface, decodeP2pPrefaceReply, encodeP2pPreface, encodeP2pPrefaceReply, } from '@hopwire/protocol';
4
+ import { RECONNECT_BACKOFF_MS } from '@hopwire/protocol';
5
+ import { HopwireError } from './errors.js';
4
6
  import { deriveKeyPair } from './identity.js';
5
7
  import { LineError, readLine, toNodeDuplex } from './p2p-stream.js';
6
8
  import { createProxyServer } from './proxy-server.js';
@@ -32,6 +34,8 @@ const REQUEST_TIMEOUT_MS = 300_000;
32
34
  */
33
35
  const MAX_STREAMS = 64;
34
36
  const MAX_STREAMS_PER_PEER = 16;
37
+ /** Keeps a relayed replication from being taken for idle by the edge while the log has nothing new. */
38
+ const RELAY_KEEPALIVE_MS = 30_000;
35
39
  /**
36
40
  * `--share`: answers `hopwire connect` on the identity key (p2pConnect) and
37
41
  * announces the traffic log for `hopwire watch` (logReplication). With an
@@ -164,9 +168,8 @@ export async function startSharing(options) {
164
168
  }, (stream) => {
165
169
  void accept(stream);
166
170
  });
167
- // The identity key answers `hopwire connect`, and one DHT node cannot listen twice on the same key
168
- const swarm = new Hyperswarm({ keyPair: deriveKeyPair(identity, 'replication'), dht, firewall: refuses });
169
- swarm.on('connection', (connection) => {
171
+ /** A watcher's connection, direct or relayed: replicated once its key is let in */
172
+ const replicateTo = (connection) => {
170
173
  connection.on('error', () => { });
171
174
  if (refuses(connection.remotePublicKey)) {
172
175
  connection.destroy();
@@ -188,8 +191,15 @@ export async function startSharing(options) {
188
191
  track(peer, connection);
189
192
  log.replicate(connection);
190
193
  });
191
- });
194
+ };
195
+ // The identity key answers `hopwire connect`, and one DHT node cannot listen twice on the same key
196
+ const replicationKeyPair = deriveKeyPair(identity, 'replication');
197
+ const swarm = new Hyperswarm({ keyPair: replicationKeyPair, dht, firewall: refuses });
198
+ swarm.on('connection', replicateTo);
199
+ let relay = null;
200
+ let relayProblem = null;
192
201
  const close = async () => {
202
+ await relay?.close();
193
203
  for (const socket of sockets) {
194
204
  socket.destroy();
195
205
  }
@@ -200,12 +210,55 @@ export async function startSharing(options) {
200
210
  try {
201
211
  await unlessAborted(server.listen(identity), options.signal);
202
212
  await unlessAborted(swarm.join(log.discoveryKey, { server: true, client: false }).flushed(), options.signal);
213
+ if (options.relay !== undefined) {
214
+ // Loaded only here: without --relay nothing opens a relay socket
215
+ const { startRelayListener } = await import('./relay.js');
216
+ const listener = await startRelayListener({
217
+ ...options.relay,
218
+ topics: new Map([
219
+ [
220
+ identity.publicKey.toString('hex'),
221
+ {
222
+ keyPair: identity,
223
+ // Who gets in is decided here, on the key of the Noise handshake, as on the DHT path
224
+ onStream: (stream) => {
225
+ stream.on('error', () => { });
226
+ const peer = stream.remotePublicKey.toString('hex');
227
+ void (async () => {
228
+ if (refuses(stream.remotePublicKey) ||
229
+ (admission !== null && !(await admission.admits(peer)))) {
230
+ stream.destroy();
231
+ return;
232
+ }
233
+ await accept(stream);
234
+ })();
235
+ },
236
+ },
237
+ ],
238
+ [
239
+ log.discoveryKey.toString('hex'),
240
+ {
241
+ keyPair: replicationKeyPair,
242
+ onStream: (stream) => {
243
+ keepAlive(stream);
244
+ replicateTo(stream);
245
+ },
246
+ },
247
+ ],
248
+ ]),
249
+ onEvent: options.onRelayEvent,
250
+ signal: options.signal,
251
+ });
252
+ relay = listener;
253
+ relayProblem = listener.problem;
254
+ void listener.ended.then((error) => options.onRelayEvent?.({ type: 'off', problem: error.message }));
255
+ }
203
256
  }
204
257
  catch (error) {
205
258
  await close().catch(() => { });
206
259
  throw error;
207
260
  }
208
- return { peerKey: identity.publicKey.toString('hex'), close };
261
+ return { peerKey: identity.publicKey.toString('hex'), relayProblem, close };
209
262
  }
210
263
  /**
211
264
  * Keeps a teammate's stream from staying open without doing anything: it is destroyed when it has no request in
@@ -253,14 +306,26 @@ export function selectService(names, requested) {
253
306
  }
254
307
  return names.includes(requested) ? { name: requested } : { error: 'unknown_service' };
255
308
  }
256
- /** A stream to the peer could not be opened or was not accepted. `code` is a HyperDHT error code, a preface error code or `timeout`. */
309
+ /**
310
+ * A stream to the peer could not be opened or was not accepted. `code` is a HyperDHT error code, a preface error
311
+ * code, `timeout`, or `relay` when neither the direct path nor the relay worked (`problem` then says why the relay
312
+ * did not).
313
+ */
257
314
  export class PeerConnectError extends Error {
258
315
  code;
259
- constructor(code) {
316
+ problem;
317
+ limit;
318
+ constructor(code, problem = null,
319
+ /** The relay refused because of a limit of the organisation (relayed bytes of the day, open pipes) */
320
+ limit = false) {
260
321
  super(`No stream to the peer (${code})`);
261
322
  this.code = code;
323
+ this.problem = problem;
324
+ this.limit = limit;
262
325
  }
263
326
  }
327
+ /** Answers of the sharer itself: the stream reached it, so another path would get the same answer. */
328
+ const SHARER_ANSWERS = ['unknown_service', 'service_required', 'bad_preface', 'busy'];
264
329
  /** How long `probeNetwork` waits for the DHT. */
265
330
  const PROBE_TIMEOUT_MS = 15_000;
266
331
  /**
@@ -301,30 +366,90 @@ export async function probeNetwork(options) {
301
366
  await dht.destroy({ force: true }).catch(() => { });
302
367
  }
303
368
  }
304
- /** The connecting side of p2pConnect: every call of `open` is one HyperDHT stream to the peer key. */
369
+ /**
370
+ * The connecting side of p2pConnect: every call of `open` is one stream to the peer key, end-to-end encrypted. Direct
371
+ * over HyperDHT first; with --relay, once that fails, through the relay of the edge, and from then on through the
372
+ * relay (each new direct attempt would cost seconds), back to direct only when the relay fails.
373
+ */
305
374
  export function createPeerConnector(options) {
306
375
  const dht = new HyperDHT({ bootstrap: options.bootstrap });
307
376
  const peerKey = Buffer.from(options.peerKey, 'hex');
308
377
  const preface = encodeP2pPreface(options.service);
309
378
  const sockets = new Set();
379
+ let throughRelay = false;
380
+ /** Sends the preface on a stream and waits for the sharer's answer. */
381
+ const offer = async (stream) => {
382
+ const socket = toNodeDuplex(stream);
383
+ sockets.add(socket);
384
+ socket.once('close', () => sockets.delete(socket));
385
+ try {
386
+ socket.write(preface);
387
+ const reply = decodeP2pPrefaceReply(await readLine(socket, P2P_PREFACE_MAX_BYTES, CONNECT_TIMEOUT_MS));
388
+ if ('error' in reply) {
389
+ throw new PeerConnectError(reply.error);
390
+ }
391
+ return socket;
392
+ }
393
+ catch (error) {
394
+ socket.destroy();
395
+ throw error instanceof PeerConnectError ? error : new PeerConnectError(failureCode(error));
396
+ }
397
+ };
398
+ const direct = () => offer(dht.connect(peerKey, { keyPair: options.identity }));
399
+ const relayed = async (relay) => {
400
+ const { dialRelay, isRelayLimit, relayProblem } = await import('./relay.js');
401
+ let stream;
402
+ try {
403
+ stream = await dialRelay({
404
+ ...relay,
405
+ target: options.peerKey,
406
+ keyPair: options.identity,
407
+ // Anyone of the organisation could listen on the key; only the machine with it is taken
408
+ remotePublicKey: peerKey,
409
+ });
410
+ }
411
+ catch (error) {
412
+ throw new PeerConnectError('relay', relayProblem(error), isRelayLimit(error));
413
+ }
414
+ return offer(stream);
415
+ };
310
416
  return {
311
417
  async open() {
312
- const socket = toNodeDuplex(dht.connect(peerKey, { keyPair: options.identity }));
313
- sockets.add(socket);
314
- socket.once('close', () => sockets.delete(socket));
315
- try {
316
- socket.write(preface);
317
- const reply = decodeP2pPrefaceReply(await readLine(socket, P2P_PREFACE_MAX_BYTES, CONNECT_TIMEOUT_MS));
318
- if ('error' in reply) {
319
- throw new PeerConnectError(reply.error);
418
+ const relay = options.relay;
419
+ if (relay !== undefined && throughRelay) {
420
+ try {
421
+ return await relayed(relay);
320
422
  }
321
- return socket;
423
+ catch (error) {
424
+ if (error instanceof PeerConnectError && SHARER_ANSWERS.includes(error.code)) {
425
+ throw error;
426
+ }
427
+ // The relay failed: the direct path may work again. When it does not, the relay's reason is the one
428
+ // that tells the user something (a limit, a teammate who stopped sharing)
429
+ throughRelay = false;
430
+ try {
431
+ return await direct();
432
+ }
433
+ catch {
434
+ throw error;
435
+ }
436
+ }
437
+ }
438
+ try {
439
+ return await direct();
322
440
  }
323
441
  catch (error) {
324
- socket.destroy();
325
- throw error instanceof PeerConnectError ? error : new PeerConnectError(failureCode(error));
442
+ if (relay === undefined ||
443
+ !(error instanceof PeerConnectError) ||
444
+ SHARER_ANSWERS.includes(error.code)) {
445
+ throw error;
446
+ }
447
+ const socket = await relayed(relay);
448
+ throughRelay = true;
449
+ return socket;
326
450
  }
327
451
  },
452
+ relayed: () => throughRelay,
328
453
  async close() {
329
454
  for (const socket of sockets) {
330
455
  socket.destroy();
@@ -343,12 +468,19 @@ function failureCode(error) {
343
468
  // An answer that is not a preface reply
344
469
  return 'bad_reply';
345
470
  }
346
- /** Nobody announces the log (`not_found`), or its sharer was found but no connection came about (`no_connection`). */
471
+ /**
472
+ * Nobody announces the log (`not_found`), or its sharer was found but no connection came about (`no_connection`).
473
+ * With --relay, `relayProblem` says why the relay did not help either.
474
+ */
347
475
  export class JoinError extends Error {
348
476
  code;
349
- constructor(code) {
477
+ relayProblem;
478
+ relayLimit;
479
+ constructor(code, relayProblem = null, relayLimit = false) {
350
480
  super(`The log could not be joined (${code})`);
351
481
  this.code = code;
482
+ this.relayProblem = relayProblem;
483
+ this.relayLimit = relayLimit;
352
484
  }
353
485
  }
354
486
  /**
@@ -356,6 +488,10 @@ export class JoinError extends Error {
356
488
  * connects to whoever announces it and replicates it over every connection.
357
489
  * Resolves once a first connection is open; rejects with JoinError when there
358
490
  * is none after the lookup. Later the swarm reconnects by itself.
491
+ *
492
+ * With --relay a lookup without a connection is followed by a dial of the discovery key through the relay. The
493
+ * relayed connection is kept: when it is lost and no direct one is open, it is dialled again with a backoff, while
494
+ * the swarm goes on looking for a direct one.
359
495
  */
360
496
  export async function joinLog(options) {
361
497
  const swarm = new Hyperswarm({ keyPair: options.identity, bootstrap: options.bootstrap });
@@ -380,10 +516,99 @@ export async function joinLog(options) {
380
516
  finally {
381
517
  clearTimeout(timer);
382
518
  }
383
- if (swarm.connections.size === 0) {
384
- const found = swarm.stats.connects.client.attempted > 0;
519
+ if (swarm.connections.size > 0) {
520
+ return { connected: () => swarm.connections.size > 0, relayed: false, close: () => swarm.destroy() };
521
+ }
522
+ const found = swarm.stats.connects.client.attempted > 0;
523
+ const relay = options.relay;
524
+ if (relay === undefined) {
385
525
  await swarm.destroy();
386
526
  throw new JoinError(found ? 'no_connection' : 'not_found');
387
527
  }
388
- return { connected: () => swarm.connections.size > 0, close: () => swarm.destroy() };
528
+ // Loaded only here: without --relay nothing opens a relay socket
529
+ const { dialRelay, isRelayLimit, relayProblem } = await import('./relay.js');
530
+ const target = options.log.discoveryKey.toString('hex');
531
+ const dial = async () => {
532
+ const stream = await dialRelay({
533
+ ...relay,
534
+ target,
535
+ keyPair: options.identity,
536
+ // Whoever answers on the discovery key: what it sends is checked against the log key by Hypercore, and
537
+ // only a machine that knows the log key can take part in its replication
538
+ remotePublicKey: null,
539
+ signal: options.signal,
540
+ });
541
+ stream.on('error', () => { });
542
+ keepAlive(stream);
543
+ options.log.replicate(stream);
544
+ return stream;
545
+ };
546
+ let current;
547
+ try {
548
+ current = await dial();
549
+ }
550
+ catch (error) {
551
+ await swarm.destroy();
552
+ if (error instanceof HopwireError) {
553
+ throw error;
554
+ }
555
+ throw new JoinError(found ? 'no_connection' : 'not_found', relayProblem(error), isRelayLimit(error));
556
+ }
557
+ let closed = false;
558
+ let retry;
559
+ let backoff = RECONNECT_BACKOFF_MS.initial;
560
+ /** The problem of the relay that was said last; null while it works */
561
+ let said = null;
562
+ const keep = (stream) => {
563
+ current = stream;
564
+ stream.once('close', () => {
565
+ if (closed) {
566
+ return;
567
+ }
568
+ const again = () => {
569
+ retry = setTimeout(() => {
570
+ if (closed) {
571
+ return;
572
+ }
573
+ if (swarm.connections.size > 0) {
574
+ // A direct connection came about meanwhile; the relay is tried again when it is lost
575
+ backoff = RECONNECT_BACKOFF_MS.initial;
576
+ again();
577
+ return;
578
+ }
579
+ dial().then((next) => {
580
+ backoff = RECONNECT_BACKOFF_MS.initial;
581
+ said = null;
582
+ keep(next);
583
+ }, (error) => {
584
+ // Said once per problem, not on every attempt of the backoff
585
+ const problem = relayProblem(error);
586
+ if (problem !== said) {
587
+ said = problem;
588
+ options.onRelayLost?.(problem, isRelayLimit(error));
589
+ }
590
+ again();
591
+ });
592
+ }, backoff * (0.5 + Math.random() / 2));
593
+ backoff = Math.min(backoff * 2, RECONNECT_BACKOFF_MS.max);
594
+ };
595
+ again();
596
+ });
597
+ };
598
+ keep(current);
599
+ return {
600
+ connected: () => swarm.connections.size > 0 || !current.destroyed,
601
+ relayed: true,
602
+ close: async () => {
603
+ closed = true;
604
+ clearTimeout(retry);
605
+ current.destroy();
606
+ await swarm.destroy();
607
+ },
608
+ };
609
+ }
610
+ /** An empty message now and then, so the edge does not close a relayed replication while the log has nothing new. */
611
+ function keepAlive(stream) {
612
+ const secret = stream;
613
+ secret.setKeepAlive?.(RELAY_KEEPALIVE_MS);
389
614
  }
package/dist/prompt.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { HopwireError } from './errors.js';
2
2
  const CTRL_C = '\u0003';
3
3
  const CTRL_D = '\u0004';
4
+ const ESCAPE = '\u001b';
4
5
  const BACKSPACE = new Set(['\u007f', '\b']);
5
6
  /**
6
7
  * Asks a question on the terminal and reads the answer without showing it: nothing that is typed or pasted is
@@ -60,3 +61,65 @@ export function promptHidden(question, input, output, signal) {
60
61
  signal?.addEventListener('abort', onAbort, { once: true });
61
62
  });
62
63
  }
64
+ /**
65
+ * Asks a question on the terminal and reads one line, shown as it is typed (hopwire init). Enter ends the answer;
66
+ * Backspace takes back a character; an arrow or another key that sends an escape sequence is ignored. Ctrl-C and
67
+ * Ctrl-D cancel, as in `promptHidden`, and so does the signal. Without a terminal the returned promise rejects.
68
+ */
69
+ export function promptLine(question, input, output, signal) {
70
+ if (input.isTTY !== true || input.setRawMode === undefined) {
71
+ return Promise.reject(new HopwireError('There is no terminal to ask on.'));
72
+ }
73
+ if (signal?.aborted) {
74
+ return Promise.reject(signal.reason instanceof Error ? signal.reason : new Error('The question was stopped'));
75
+ }
76
+ const setRawMode = input.setRawMode.bind(input);
77
+ return new Promise((resolve, reject) => {
78
+ // Characters, not UTF-16 units: Backspace takes back what was typed as one
79
+ const answer = [];
80
+ const finish = (settle) => {
81
+ input.off('data', onData);
82
+ signal?.removeEventListener('abort', onAbort);
83
+ setRawMode(false);
84
+ input.pause();
85
+ output.write('\n');
86
+ settle();
87
+ };
88
+ const onAbort = () => {
89
+ finish(() => reject(signal?.reason instanceof Error ? signal.reason : new Error('The question was stopped')));
90
+ };
91
+ const onData = (chunk) => {
92
+ for (const character of chunk) {
93
+ if (character === '\r' || character === '\n') {
94
+ finish(() => resolve(answer.join('')));
95
+ return;
96
+ }
97
+ if (character === CTRL_C || character === CTRL_D) {
98
+ finish(() => reject(new HopwireError('Cancelled; nothing was written.')));
99
+ return;
100
+ }
101
+ if (character === ESCAPE) {
102
+ // An arrow or function key: the rest of the chunk is its sequence
103
+ return;
104
+ }
105
+ if (BACKSPACE.has(character)) {
106
+ if (answer.pop() !== undefined) {
107
+ output.write('\b \b');
108
+ }
109
+ }
110
+ else if (character >= ' ') {
111
+ answer.push(character);
112
+ output.write(character);
113
+ }
114
+ }
115
+ };
116
+ input.setEncoding('utf8');
117
+ // Raw mode, as for promptHidden: Ctrl-C and Ctrl-D arrive as characters, so a cancelled question ends the
118
+ // same way on every terminal; the answer is echoed here
119
+ setRawMode(true);
120
+ output.write(question);
121
+ input.resume();
122
+ input.on('data', onData);
123
+ signal?.addEventListener('abort', onAbort, { once: true });
124
+ });
125
+ }