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/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
@@ -74,6 +74,7 @@ export async function startServing(options) {
74
74
  const endings = [];
75
75
  let peerKey = null;
76
76
  let team = null;
77
+ let relay = null;
77
78
  if (options.share) {
78
79
  proceed();
79
80
  const identity = await loadOrCreateIdentity(options.dataDir);
@@ -93,6 +94,12 @@ export async function startServing(options) {
93
94
  team = { organisation: keys.organisation, keys: keys.size };
94
95
  endings.push(keys.ended);
95
96
  }
97
+ let relaySetup;
98
+ if (options.relay !== undefined) {
99
+ // Loaded only here: without --relay nothing opens a relay socket
100
+ const relayModule = await import('./relay.js');
101
+ relaySetup = relayModule.relaySetup(options.relay, identity.publicKey.toString('hex'));
102
+ }
96
103
  // Loaded only here: without sharing no DHT node and no swarm exist
97
104
  const { startSharing } = await import('./p2p.js');
98
105
  const sharing = await startSharing({
@@ -103,9 +110,14 @@ export async function startServing(options) {
103
110
  admission,
104
111
  bootstrap: options.bootstrap,
105
112
  signal: options.signal,
113
+ relay: relaySetup,
114
+ onRelayEvent: options.onRelayEvent,
106
115
  });
107
116
  supervisor.add('p2p', () => sharing.close());
108
117
  peerKey = sharing.peerKey;
118
+ if (options.relay !== undefined) {
119
+ relay = { edgeUrl: options.relay.edgeUrl, problem: sharing.relayProblem };
120
+ }
109
121
  }
110
122
  // The connections to the edge are closed side by side: each waits for the edge to confirm, and an edge that
111
123
  // no longer answers must not cost that wait once per service
@@ -223,6 +235,7 @@ export async function startServing(options) {
223
235
  logLength: log.length,
224
236
  peerKey,
225
237
  team,
238
+ relay,
226
239
  ended: endings.length > 0 ? Promise.race(endings) : new Promise(() => { }),
227
240
  close: supervisor.close,
228
241
  };
@@ -6,6 +6,7 @@ export * from './headers.js';
6
6
  export * from './inspector.js';
7
7
  export * from './p2p.js';
8
8
  export * from './plan.js';
9
+ export * from './relay.js';
9
10
  export * from './subdomain.js';
10
11
  export * from './websocket.js';
11
12
  export * from './ws-messages.js';
@@ -6,6 +6,7 @@ export * from './headers.js';
6
6
  export * from './inspector.js';
7
7
  export * from './p2p.js';
8
8
  export * from './plan.js';
9
+ export * from './relay.js';
9
10
  export * from './subdomain.js';
10
11
  export * from './websocket.js';
11
12
  export * from './ws-messages.js';
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The relay for strict networks (spec phase 12, decision 136): with --relay on the Team plan, private mode goes
3
+ * through the edge when no direct connection comes about. Both CLIs open a WebSocket to the edge; the edge pairs a
4
+ * dial with a listener of the same organisation and pipes the bytes. Over the pipe both CLIs run the same Noise
5
+ * handshake as on the DHT path, so the edge passes on bytes it cannot read.
6
+ *
7
+ * - The sharer keeps a listen socket (RELAY_LISTEN_PATH) open for its topics: the public key of its machine (what
8
+ * `hopwire connect` dials) and the discovery key of its traffic log (what `hopwire watch` dials).
9
+ * - A peer opens a dial socket (RELAY_DIAL_PATH?target=<topic>). The edge tells the listener (a dial message), the
10
+ * listener opens an accept socket (RELAY_ACCEPT_PATH?dial=<id>), and the edge tells the dialer it is paired. From
11
+ * then on every binary message of one side is the next binary message of the other.
12
+ * - Every socket carries a relay token of the control plane (Authorization: Bearer), audience RELAY_TOKEN_AUDIENCE.
13
+ */
14
+ /** The sharer's socket: `?topic=<hex>` once per topic. */
15
+ export declare const RELAY_LISTEN_PATH = "/_hopwire/relay/listen";
16
+ /** A peer's socket: `?target=<hex>`, the topic it wants to reach. */
17
+ export declare const RELAY_DIAL_PATH = "/_hopwire/relay/dial";
18
+ /** The sharer's answer to one dial: `?dial=<id>`, the id of the dial message. */
19
+ export declare const RELAY_ACCEPT_PATH = "/_hopwire/relay/accept";
20
+ /** Audience (`aud`) of a relay token; the edge takes it only on the relay paths, and nowhere else takes it. */
21
+ export declare const RELAY_TOKEN_AUDIENCE = "hopwire-relay";
22
+ /** Topics one listen socket may name: the machine key and the discovery key of the log, with room to spare. */
23
+ export declare const RELAY_MAX_TOPICS = 4;
24
+ /** How long the edge holds a dial for the listener to accept it. */
25
+ export declare const RELAY_DIAL_TIMEOUT_MS = 10000;
26
+ /** A pipe without a byte in either direction for this long is closed. */
27
+ export declare const RELAY_IDLE_TIMEOUT_MS: number;
28
+ /** Bytes waiting to go out on one side of a pipe above which the edge stops reading the other side. */
29
+ export declare const RELAY_BACKPRESSURE_BYTES: number;
30
+ /** Largest binary message on a relay socket; the CLI sends at most RELAY_CHUNK_BYTES of data in one. */
31
+ export declare const RELAY_MESSAGE_MAX_BYTES: number;
32
+ export declare const RELAY_CHUNK_BYTES: number;
33
+ /** Pipes one organisation may have open at once, unless the edge is configured otherwise (RELAY_PIPES_PER_ORG). */
34
+ export declare const RELAY_PIPES_PER_ORG_DEFAULT = 20;
35
+ /** Relayed bytes per organisation and UTC day on the Team plan, unless configured otherwise (provisional). */
36
+ export declare const RELAY_BYTES_PER_DAY_DEFAULT = 20000000000;
37
+ /** Close codes of relay sockets. */
38
+ export declare const RELAY_CLOSE: {
39
+ /** The token of a listener expired; the CLI comes back with a new one */
40
+ readonly tokenExpired: 4001;
41
+ /** A pipe had no byte for RELAY_IDLE_TIMEOUT_MS */
42
+ readonly idle: 4009;
43
+ /** A limit of the organisation: open pipes or relayed bytes of the day; the reason names which */
44
+ readonly limit: 4029;
45
+ /** Nobody of the organisation listens on the topic of a dial */
46
+ readonly noListener: 4404;
47
+ /** The listener did not accept a dial in time */
48
+ readonly dialTimeout: 4408;
49
+ };
50
+ /** The reasons of a RELAY_CLOSE.limit close. */
51
+ export declare const RELAY_LIMIT_REASONS: readonly ["relay_pipes", "relay_bytes"];
52
+ export type RelayLimitReason = (typeof RELAY_LIMIT_REASONS)[number];
53
+ /**
54
+ * A text message of the edge on a relay socket: `dial` on a listen socket (a peer wants a topic; answer with an
55
+ * accept socket for `dial`), `paired` on a dial socket (from here on the socket is the pipe).
56
+ */
57
+ export type RelayControlMessage = {
58
+ type: 'dial';
59
+ dial: string;
60
+ topic: string;
61
+ } | {
62
+ type: 'paired';
63
+ };
64
+ export declare function isRelayDialId(value: string): boolean;
65
+ /** A topic as the relay takes it: a public key or discovery key as 64 hexadecimal characters, lower case. */
66
+ export declare function isRelayTopic(value: string): boolean;
67
+ export declare function encodeRelayControl(message: RelayControlMessage): string;
68
+ /** Reads a control message of the edge. Throws ProtocolError for anything else. */
69
+ export declare function decodeRelayControl(text: string): RelayControlMessage;
70
+ /**
71
+ * The first byte of every binary message between two CLIs on a pipe. The edge never looks at it: it passes whole
72
+ * messages on.
73
+ */
74
+ export declare const RELAY_FRAME: {
75
+ /** The rest is bytes of the encrypted stream */
76
+ readonly data: 0;
77
+ /** The rest is one encrypted datagram next to the stream (the flow control of hopwire connect) */
78
+ readonly datagram: 1;
79
+ /** The sender will send no more stream bytes */
80
+ readonly end: 2;
81
+ };