@celljs/ta-relay 4.7.0 → 4.9.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 (96) hide show
  1. package/README.en.md +8 -3
  2. package/README.md +8 -3
  3. package/esm/common/index.d.ts +2 -0
  4. package/esm/common/index.js +2 -0
  5. package/esm/common/qr-code.d.ts +42 -0
  6. package/esm/common/qr-code.js +366 -0
  7. package/esm/common/relay-protocol.d.ts +42 -1
  8. package/esm/common/relay-protocol.js +26 -0
  9. package/esm/common/relay-room.d.ts +1 -0
  10. package/esm/common/relay-room.js +13 -2
  11. package/esm/common/relay-share.d.ts +31 -0
  12. package/esm/common/relay-share.js +117 -0
  13. package/esm/common/relay-socket.d.ts +18 -1
  14. package/esm/common/relay-socket.js +43 -5
  15. package/esm/node/relay-host.d.ts +18 -3
  16. package/esm/node/relay-host.js +82 -8
  17. package/esm/node/relay-server.js +10 -6
  18. package/esm/node/relay-store.d.ts +29 -1
  19. package/esm/node/relay-store.js +54 -2
  20. package/lib/common/index.d.ts +2 -0
  21. package/lib/common/index.js +2 -0
  22. package/lib/common/qr-code.d.ts +43 -0
  23. package/lib/common/qr-code.js +370 -0
  24. package/lib/common/relay-protocol.d.ts +42 -1
  25. package/lib/common/relay-protocol.js +27 -1
  26. package/lib/common/relay-room.d.ts +1 -0
  27. package/lib/common/relay-room.js +12 -1
  28. package/lib/common/relay-share.d.ts +32 -0
  29. package/lib/common/relay-share.js +120 -0
  30. package/lib/common/relay-socket.d.ts +18 -1
  31. package/lib/common/relay-socket.js +42 -4
  32. package/lib/node/relay-host.d.ts +18 -3
  33. package/lib/node/relay-host.js +81 -7
  34. package/lib/node/relay-server.js +9 -5
  35. package/lib/node/relay-store.d.ts +29 -1
  36. package/lib/node/relay-store.js +54 -2
  37. package/package.json +4 -3
  38. package/esm/common/index.js.map +0 -1
  39. package/esm/common/relay-bytes.js.map +0 -1
  40. package/esm/common/relay-cipher.js.map +0 -1
  41. package/esm/common/relay-pairing.js.map +0 -1
  42. package/esm/common/relay-protocol.js.map +0 -1
  43. package/esm/common/relay-room.js.map +0 -1
  44. package/esm/common/relay-socket.js.map +0 -1
  45. package/esm/node/index.js.map +0 -1
  46. package/esm/node/relay-host.js.map +0 -1
  47. package/esm/node/relay-server.js.map +0 -1
  48. package/esm/node/relay-store.js.map +0 -1
  49. package/lib/common/index.d.ts.map +0 -1
  50. package/lib/common/index.js.map +0 -1
  51. package/lib/common/relay-bytes.d.ts.map +0 -1
  52. package/lib/common/relay-bytes.js.map +0 -1
  53. package/lib/common/relay-cipher.d.ts.map +0 -1
  54. package/lib/common/relay-cipher.js.map +0 -1
  55. package/lib/common/relay-cipher.spec.d.ts +0 -2
  56. package/lib/common/relay-cipher.spec.d.ts.map +0 -1
  57. package/lib/common/relay-cipher.spec.js +0 -43
  58. package/lib/common/relay-cipher.spec.js.map +0 -1
  59. package/lib/common/relay-pairing.d.ts.map +0 -1
  60. package/lib/common/relay-pairing.js.map +0 -1
  61. package/lib/common/relay-pairing.spec.d.ts +0 -2
  62. package/lib/common/relay-pairing.spec.d.ts.map +0 -1
  63. package/lib/common/relay-pairing.spec.js +0 -25
  64. package/lib/common/relay-pairing.spec.js.map +0 -1
  65. package/lib/common/relay-protocol.d.ts.map +0 -1
  66. package/lib/common/relay-protocol.js.map +0 -1
  67. package/lib/common/relay-room.d.ts.map +0 -1
  68. package/lib/common/relay-room.js.map +0 -1
  69. package/lib/common/relay-socket.d.ts.map +0 -1
  70. package/lib/common/relay-socket.js.map +0 -1
  71. package/lib/node/index.d.ts.map +0 -1
  72. package/lib/node/index.js.map +0 -1
  73. package/lib/node/relay-host.d.ts.map +0 -1
  74. package/lib/node/relay-host.js.map +0 -1
  75. package/lib/node/relay-server.d.ts.map +0 -1
  76. package/lib/node/relay-server.js.map +0 -1
  77. package/lib/node/relay-store.d.ts.map +0 -1
  78. package/lib/node/relay-store.js.map +0 -1
  79. package/lib/node/relay.spec.d.ts +0 -2
  80. package/lib/node/relay.spec.d.ts.map +0 -1
  81. package/lib/node/relay.spec.js +0 -141
  82. package/lib/node/relay.spec.js.map +0 -1
  83. package/src/common/index.ts +0 -6
  84. package/src/common/relay-bytes.ts +0 -37
  85. package/src/common/relay-cipher.spec.ts +0 -45
  86. package/src/common/relay-cipher.ts +0 -74
  87. package/src/common/relay-pairing.spec.ts +0 -26
  88. package/src/common/relay-pairing.ts +0 -46
  89. package/src/common/relay-protocol.ts +0 -50
  90. package/src/common/relay-room.ts +0 -79
  91. package/src/common/relay-socket.ts +0 -106
  92. package/src/node/index.ts +0 -4
  93. package/src/node/relay-host.ts +0 -230
  94. package/src/node/relay-server.ts +0 -143
  95. package/src/node/relay-store.ts +0 -84
  96. package/src/node/relay.spec.ts +0 -151
@@ -0,0 +1,31 @@
1
+ /** What another computer needs to take a package from the host that shared it, through the relay. */
2
+ export interface RelayShareLink {
3
+ relay: string;
4
+ host: string;
5
+ /** The id of the share, as a device's on the relay. */
6
+ share: string;
7
+ /** base64url, 32 bytes. */
8
+ key: string;
9
+ /** The name of its package, to show before it is fetched. */
10
+ name?: string;
11
+ }
12
+ export interface RelayShareOptions {
13
+ maxBytes?: number;
14
+ /** For all of it. Default 60 seconds. */
15
+ timeoutMs?: number;
16
+ }
17
+ export declare namespace RelayShareUtil {
18
+ /** `https://<relay>/share#v=1&h=<host>&s=<share>&k=<key>&n=<name>`: the key in the fragment, which is not sent to the relay. */
19
+ function link(share: RelayShareLink): string;
20
+ function is(text: string): boolean;
21
+ /** Throws on what is not a link of {@link link}. */
22
+ function parse(text: string): RelayShareLink;
23
+ /**
24
+ * The package of a link, from the computer that shared it, end to end through the relay: that computer
25
+ * must be running Ta. Rejects past the size limit, the time limit, or when the share is gone.
26
+ */
27
+ function fetch(text: string, options?: RelayShareOptions): Promise<{
28
+ name: string;
29
+ data: Uint8Array;
30
+ }>;
31
+ }
@@ -0,0 +1,117 @@
1
+ import { RelayBytes } from './relay-bytes.js';
2
+ import { RELAY_ID, RELAY_SHARE_MAX_BYTES, RELAY_SHARE_PATH } from './relay-protocol.js';
3
+ import { RelaySocket } from './relay-socket.js';
4
+ export var RelayShareUtil;
5
+ (function (RelayShareUtil) {
6
+ /** `https://<relay>/share#v=1&h=<host>&s=<share>&k=<key>&n=<name>`: the key in the fragment, which is not sent to the relay. */
7
+ function link(share) {
8
+ const fragment = new URLSearchParams({ v: '1', h: share.host, s: share.share, k: share.key });
9
+ if (share.name) {
10
+ fragment.set('n', share.name);
11
+ }
12
+ return `${share.relay}${RELAY_SHARE_PATH}#${fragment}`;
13
+ }
14
+ RelayShareUtil.link = link;
15
+ function is(text) {
16
+ try {
17
+ parse(text);
18
+ return true;
19
+ }
20
+ catch (_a) {
21
+ return false;
22
+ }
23
+ }
24
+ RelayShareUtil.is = is;
25
+ /** Throws on what is not a link of {@link link}. */
26
+ function parse(text) {
27
+ var _a;
28
+ const url = new URL(text.trim());
29
+ const fragment = new URLSearchParams(url.hash.slice(1));
30
+ const [host, share, key] = ['h', 's', 'k'].map(name => { var _a; return (_a = fragment.get(name)) !== null && _a !== void 0 ? _a : ''; });
31
+ if (!/^https?:$/.test(url.protocol) ||
32
+ url.pathname !== RELAY_SHARE_PATH ||
33
+ fragment.get('v') !== '1' ||
34
+ !RELAY_ID.test(host) ||
35
+ !RELAY_ID.test(share) ||
36
+ !/^[A-Za-z0-9_-]{43}$/.test(key)) {
37
+ throw new Error('Not a link of an extension of Ta.');
38
+ }
39
+ return { relay: url.origin, host, share, key, name: (_a = fragment.get('n')) !== null && _a !== void 0 ? _a : undefined };
40
+ }
41
+ RelayShareUtil.parse = parse;
42
+ /**
43
+ * The package of a link, from the computer that shared it, end to end through the relay: that computer
44
+ * must be running Ta. Rejects past the size limit, the time limit, or when the share is gone.
45
+ */
46
+ function fetch(text, options = {}) {
47
+ var _a;
48
+ const share = parse(text);
49
+ const max = (_a = options.maxBytes) !== null && _a !== void 0 ? _a : RELAY_SHARE_MAX_BYTES;
50
+ const pairing = { relay: share.relay, host: share.host, device: share.share, key: share.key };
51
+ return new Promise((resolve, reject) => {
52
+ var _a;
53
+ const socket = new RelaySocket(pairing);
54
+ const chunks = [];
55
+ let received = 0;
56
+ let expected;
57
+ let done = false;
58
+ const finish = (error, result) => {
59
+ if (done) {
60
+ return;
61
+ }
62
+ done = true;
63
+ clearTimeout(timer);
64
+ socket.onclose = null;
65
+ socket.close();
66
+ if (error) {
67
+ reject(error);
68
+ }
69
+ else if (result) {
70
+ resolve(result);
71
+ }
72
+ };
73
+ const timer = setTimeout(() => finish(new Error('The computer that shared it took too long to send it.')), (_a = options.timeoutMs) !== null && _a !== void 0 ? _a : 60000);
74
+ socket.onmessage = ({ data }) => {
75
+ let message;
76
+ try {
77
+ message = JSON.parse(data);
78
+ }
79
+ catch (_a) {
80
+ finish(new Error('The computer that shared it sent what is not a package.'));
81
+ return;
82
+ }
83
+ if (message.t === 'error') {
84
+ finish(new Error(message.message));
85
+ }
86
+ else if (message.t === 'package') {
87
+ if (!(message.size > 0) || message.size > max) {
88
+ finish(new Error(`The package is larger than ${Math.round(max / 1024 / 1024)} MB.`));
89
+ return;
90
+ }
91
+ expected = { name: String(message.name), size: message.size };
92
+ }
93
+ else if (message.t === 'chunk' && expected) {
94
+ const bytes = RelayBytes.fromBase64(message.d);
95
+ received += bytes.length;
96
+ if (received > expected.size) {
97
+ finish(new Error('The package is larger than it said.'));
98
+ return;
99
+ }
100
+ chunks.push(bytes);
101
+ }
102
+ else if (message.t === 'end' && expected) {
103
+ if (received !== expected.size) {
104
+ finish(new Error('The package came short.'));
105
+ return;
106
+ }
107
+ finish(undefined, { name: expected.name, data: RelayBytes.concat(...chunks) });
108
+ }
109
+ };
110
+ socket.onclose = ({ code }) => finish(new Error(code === RelaySocket.REFUSED
111
+ ? 'This link no longer works: the share was stopped or ran out.'
112
+ : 'The computer that shared it is not running Ta, or cannot be reached.'));
113
+ });
114
+ }
115
+ RelayShareUtil.fetch = fetch;
116
+ })(RelayShareUtil || (RelayShareUtil = {}));
117
+ //# sourceMappingURL=relay-share.js.map
@@ -1,5 +1,11 @@
1
1
  import { RelayCipher } from './relay-cipher.js';
2
2
  import { type RelayPairing } from './relay-pairing.js';
3
+ export interface RelaySocketOptions {
4
+ /** Default RELAY_PING_MS. */
5
+ pingMs?: number;
6
+ /** Default 15 seconds. */
7
+ helloMs?: number;
8
+ }
3
9
  /**
4
10
  * A WebSocket to ta serve through a relay, for a paired device: it says hello, checks that the host has
5
11
  * the device's key, and then seals and opens every message. It behaves as much like a WebSocket as
@@ -27,12 +33,23 @@ export declare class RelaySocket {
27
33
  protected cipher?: RelayCipher;
28
34
  protected readonly socket: WebSocket;
29
35
  protected readonly nonce: Uint8Array<ArrayBufferLike>;
30
- constructor(pairing: RelayPairing);
36
+ protected readonly helloTimer: ReturnType<typeof setTimeout>;
37
+ protected pingTimer?: ReturnType<typeof setInterval>;
38
+ /** Whether the relay answers pings: one of before does not, and is not given up for that. */
39
+ protected ponged: boolean;
40
+ protected awaitingPong: boolean;
41
+ /** Messages are opened one after another, in order, and a close waits for them: a host may send several at once, then close. */
42
+ protected receiving: Promise<void>;
43
+ constructor(pairing: RelayPairing, options?: RelaySocketOptions);
31
44
  get readyState(): number;
32
45
  /** Why it closed, once it has. */
33
46
  get closeCode(): number | undefined;
34
47
  send(text: string): void;
35
48
  close(code?: number, reason?: string): void;
36
49
  protected receive(text: string): Promise<void>;
50
+ /** The relay stopped answering: the connection is gone without a word, and closing it would wait for one. */
51
+ protected ping(): void;
52
+ /** Closed at once, rather than once the close is answered. */
53
+ protected drop(code: number, reason: string): void;
37
54
  protected finish(code: number, reason: string): void;
38
55
  }
@@ -1,18 +1,21 @@
1
1
  import { RelayBytes } from './relay-bytes.js';
2
2
  import { RelayCipher } from './relay-cipher.js';
3
3
  import { RelayPairingUtil } from './relay-pairing.js';
4
- import { RELAY_CONNECT_PATH, RELAY_PROOF } from './relay-protocol.js';
4
+ import { RELAY_CONNECT_PATH, RELAY_PING, RELAY_PING_MS, RELAY_PONG, RELAY_PROOF, RelayCloseCode } from './relay-protocol.js';
5
5
  const CONNECTING = 0;
6
6
  const OPEN = 1;
7
7
  const CLOSING = 2;
8
8
  const CLOSED = 3;
9
+ /** How long the host has to answer the hello: the relay may still take a host that is gone for there. */
10
+ const HELLO_MS = 15000;
9
11
  /**
10
12
  * A WebSocket to ta serve through a relay, for a paired device: it says hello, checks that the host has
11
13
  * the device's key, and then seals and opens every message. It behaves as much like a WebSocket as
12
14
  * TaConnection needs: `readyState`, `send`, `close` and the four handlers.
13
15
  */
14
16
  export class RelaySocket {
15
- constructor(pairing) {
17
+ constructor(pairing, options = {}) {
18
+ var _a;
16
19
  this.pairing = pairing;
17
20
  this.onopen = null;
18
21
  this.onmessage = null;
@@ -20,14 +23,30 @@ export class RelaySocket {
20
23
  this.onerror = null;
21
24
  this.state = CONNECTING;
22
25
  this.nonce = RelayBytes.random(16);
26
+ /** Whether the relay answers pings: one of before does not, and is not given up for that. */
27
+ this.ponged = false;
28
+ this.awaitingPong = false;
29
+ /** Messages are opened one after another, in order, and a close waits for them: a host may send several at once, then close. */
30
+ this.receiving = Promise.resolve();
23
31
  this.socket = new WebSocket(RelayPairingUtil.websocketUrl(pairing.relay, RELAY_CONNECT_PATH + pairing.host));
32
+ this.helloTimer = setTimeout(() => this.drop(RelayCloseCode.TIMEOUT, 'The host did not answer.'), (_a = options.helloMs) !== null && _a !== void 0 ? _a : HELLO_MS);
24
33
  this.socket.onopen = () => {
34
+ var _a;
25
35
  const hello = { t: 'hello', v: 1, device: pairing.device, nonce: RelayBytes.toBase64(this.nonce) };
26
36
  this.socket.send(JSON.stringify(hello));
37
+ this.pingTimer = setInterval(() => this.ping(), (_a = options.pingMs) !== null && _a !== void 0 ? _a : RELAY_PING_MS);
38
+ };
39
+ this.socket.onmessage = message => {
40
+ const text = String(message.data);
41
+ if (text === RELAY_PONG) {
42
+ this.ponged = true;
43
+ this.awaitingPong = false;
44
+ return;
45
+ }
46
+ this.receiving = this.receiving.then(() => this.receive(text));
27
47
  };
28
- this.socket.onmessage = message => void this.receive(String(message.data));
29
48
  this.socket.onerror = event => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, event); };
30
- this.socket.onclose = event => this.finish(event.code, event.reason);
49
+ this.socket.onclose = event => void this.receiving.then(() => this.finish(event.code, event.reason));
31
50
  }
32
51
  get readyState() {
33
52
  return this.state;
@@ -71,19 +90,38 @@ export class RelaySocket {
71
90
  throw new Error('The host did not show the key.');
72
91
  }
73
92
  this.cipher = cipher;
93
+ clearTimeout(this.helloTimer);
74
94
  this.state = OPEN;
75
95
  (_b = this.onopen) === null || _b === void 0 ? void 0 : _b.call(this);
76
96
  }
77
97
  catch (_d) {
78
98
  // A host without the key is not this device's host, whoever answered.
79
- this.close(RelaySocket.REFUSED, 'The host refused this device.');
99
+ this.drop(RelaySocket.REFUSED, 'The host refused this device.');
100
+ }
101
+ }
102
+ /** The relay stopped answering: the connection is gone without a word, and closing it would wait for one. */
103
+ ping() {
104
+ if (this.awaitingPong && this.ponged) {
105
+ this.drop(RelayCloseCode.TIMEOUT, 'The relay did not answer.');
106
+ return;
80
107
  }
108
+ this.awaitingPong = true;
109
+ if (this.socket.readyState === OPEN) {
110
+ this.socket.send(RELAY_PING);
111
+ }
112
+ }
113
+ /** Closed at once, rather than once the close is answered. */
114
+ drop(code, reason) {
115
+ this.close(code, reason);
116
+ this.finish(code, reason);
81
117
  }
82
118
  finish(code, reason) {
83
119
  var _a;
84
120
  if (this.state === CLOSED) {
85
121
  return;
86
122
  }
123
+ clearTimeout(this.helloTimer);
124
+ clearInterval(this.pingTimer);
87
125
  this.state = CLOSED;
88
126
  this.code = code;
89
127
  (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this, { code, reason });
@@ -1,12 +1,16 @@
1
1
  import { RelayCipher } from '../common/relay-cipher.js';
2
- import { type RelayHostMessage, type RelayWelcome } from '../common/relay-protocol.js';
3
- import type { RelayStore } from './relay-store.js';
2
+ import { RELAY_PING, type RelayHostMessage, type RelayWelcome } from '../common/relay-protocol.js';
3
+ import type { RelayShare, RelayStore } from './relay-store.js';
4
4
  export interface RelayHostOptions {
5
5
  store: RelayStore;
6
6
  /** The WebSocket of this ta serve, with its token: every device gets a connection to it of its own. */
7
7
  localUrl: string;
8
8
  /** First wait before reconnecting to the relay; it doubles up to 30 seconds. */
9
9
  reconnectDelayMs?: number;
10
+ /** Between the pings of the heartbeat. Default RELAY_PING_MS. */
11
+ pingMs?: number;
12
+ /** The bytes of a package handed on (a share of the store), for one who has its link; without it, shares are refused. */
13
+ sharePackage?(share: RelayShare): Promise<Uint8Array>;
10
14
  }
11
15
  /** A device on a channel: the handshake, then its connection to ta serve. */
12
16
  declare class RelayChannel {
@@ -22,6 +26,8 @@ declare class RelayChannel {
22
26
  /** From the relay: the device is gone. */
23
27
  closed(): void;
24
28
  protected hello(text: string): Promise<void>;
29
+ /** A package handed on: what it is, its bytes in chunks, the end; then the channel closes. It never reaches ta serve's socket. */
30
+ protected sendShare(cipher: RelayCipher, share: RelayShare): Promise<void>;
25
31
  protected connectLocal(cipher: RelayCipher): void;
26
32
  protected answer(welcome: RelayWelcome): void;
27
33
  protected close(): void;
@@ -39,6 +45,7 @@ export declare class RelayHost {
39
45
  protected stopped: boolean;
40
46
  protected attempts: number;
41
47
  protected timer?: ReturnType<typeof setTimeout>;
48
+ protected pingTimer?: ReturnType<typeof setInterval>;
42
49
  protected readonly channels: Map<string, RelayChannel>;
43
50
  constructor(options: RelayHostOptions);
44
51
  /** Whether the connection to the relay is open. */
@@ -49,10 +56,18 @@ export declare class RelayHost {
49
56
  refresh(): void;
50
57
  stop(): void;
51
58
  /** @internal */
52
- send(message: RelayHostMessage): void;
59
+ send(message: RelayHostMessage | typeof RELAY_PING): void;
53
60
  /** @internal */
54
61
  closeChannel(id: string): void;
55
62
  protected connect(target: string): void;
63
+ /**
64
+ * The heartbeat of the connection to the relay. Without it a connection gone without a word (through
65
+ * a proxy, a network that changed, a computer that slept) would look open for good, its devices told
66
+ * the host is offline until ta serve started again. It is made again when the relay stops answering,
67
+ * or when the timer was late by much (the computer slept). A relay of before, which never answers, is
68
+ * not given up for that.
69
+ */
70
+ protected beat(socket: WebSocket): void;
56
71
  protected receive(text: string): void;
57
72
  protected scheduleReconnect(): void;
58
73
  protected disconnect(): void;
@@ -1,7 +1,7 @@
1
1
  import { RelayBytes } from '../common/relay-bytes.js';
2
2
  import { RelayCipher } from '../common/relay-cipher.js';
3
3
  import { RelayPairingUtil } from '../common/relay-pairing.js';
4
- import { RELAY_HOST_PATH, RELAY_PROOF, RelayCloseCode } from '../common/relay-protocol.js';
4
+ import { RELAY_HOST_PATH, RELAY_PING, RELAY_PING_MS, RELAY_PONG, RELAY_PROOF, RELAY_SHARE_CHUNK_BYTES, RELAY_SHARE_MAX_BYTES, RelayCloseCode, } from '../common/relay-protocol.js';
5
5
  const MAX_RECONNECT_DELAY_MS = 30000;
6
6
  const HELLO_TIMEOUT_MS = 10000;
7
7
  /** A device on a channel: the handshake, then its connection to ta serve. */
@@ -41,26 +41,54 @@ class RelayChannel {
41
41
  (_a = this.local) === null || _a === void 0 ? void 0 : _a.close();
42
42
  }
43
43
  async hello(text) {
44
+ var _a;
44
45
  let hello;
45
46
  try {
46
47
  hello = JSON.parse(text);
47
48
  }
48
- catch (_a) {
49
+ catch (_b) {
49
50
  this.close();
50
51
  return;
51
52
  }
52
- const device = hello.t === 'hello' && hello.v === 1 ? this.options.store.device(hello.device) : undefined;
53
- if (!device || typeof hello.nonce !== 'string') {
53
+ const valid = hello.t === 'hello' && hello.v === 1 && typeof hello.nonce === 'string';
54
+ const device = valid ? this.options.store.device(hello.device) : undefined;
55
+ const share = valid && !device && this.options.sharePackage ? this.options.store.share(hello.device) : undefined;
56
+ const key = (_a = device === null || device === void 0 ? void 0 : device.key) !== null && _a !== void 0 ? _a : share === null || share === void 0 ? void 0 : share.key;
57
+ if (!key) {
54
58
  this.answer({ t: 'refused', reason: 'This device is not paired.' });
55
59
  this.close();
56
60
  return;
57
61
  }
58
62
  clearTimeout(this.timer);
59
63
  const nonce = RelayBytes.random(16);
60
- const cipher = await RelayCipher.derive(RelayBytes.fromBase64(device.key), RelayBytes.fromBase64(hello.nonce), nonce, 'host');
64
+ const cipher = await RelayCipher.derive(RelayBytes.fromBase64(key), RelayBytes.fromBase64(hello.nonce), nonce, 'host');
61
65
  this.cipher = cipher;
62
66
  this.answer({ t: 'ready', nonce: RelayBytes.toBase64(nonce), proof: await cipher.seal(RELAY_PROOF) });
63
- this.connectLocal(cipher);
67
+ if (share) {
68
+ await this.sendShare(cipher, share);
69
+ }
70
+ else {
71
+ this.connectLocal(cipher);
72
+ }
73
+ }
74
+ /** A package handed on: what it is, its bytes in chunks, the end; then the channel closes. It never reaches ta serve's socket. */
75
+ async sendShare(cipher, share) {
76
+ const send = async (message) => this.host.send({ t: 'data', ch: this.id, d: await cipher.seal(JSON.stringify(message)) });
77
+ try {
78
+ const data = await this.options.sharePackage(share);
79
+ if (data.length > RELAY_SHARE_MAX_BYTES) {
80
+ throw new Error(`${share.name} is larger than ${RELAY_SHARE_MAX_BYTES / 1024 / 1024} MB, too large to hand on by a link.`);
81
+ }
82
+ await send({ t: 'package', name: share.name, size: data.length });
83
+ for (let at = 0; at < data.length; at += RELAY_SHARE_CHUNK_BYTES) {
84
+ await send({ t: 'chunk', d: RelayBytes.toBase64(data.subarray(at, at + RELAY_SHARE_CHUNK_BYTES)) });
85
+ }
86
+ await send({ t: 'end' });
87
+ }
88
+ catch (error) {
89
+ await send({ t: 'error', message: error instanceof Error ? error.message : String(error) });
90
+ }
91
+ this.close();
64
92
  }
65
93
  connectLocal(cipher) {
66
94
  const local = new WebSocket(this.options.localUrl);
@@ -108,7 +136,8 @@ export class RelayHost {
108
136
  /** relay.json may have changed: connect if it now has devices, or leave if it has none. */
109
137
  refresh() {
110
138
  const { url, host, devices } = this.options.store.read();
111
- const wanted = !this.stopped && url !== undefined && host !== undefined && devices.length > 0;
139
+ const shared = !!this.options.sharePackage && this.options.store.shares().length > 0;
140
+ const wanted = !this.stopped && url !== undefined && host !== undefined && (devices.length > 0 || shared);
112
141
  if (!wanted) {
113
142
  this.disconnect();
114
143
  return;
@@ -128,7 +157,7 @@ export class RelayHost {
128
157
  send(message) {
129
158
  var _a;
130
159
  if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
131
- this.socket.send(JSON.stringify(message));
160
+ this.socket.send(typeof message === 'string' ? message : JSON.stringify(message));
132
161
  }
133
162
  }
134
163
  /** @internal */
@@ -146,6 +175,7 @@ export class RelayHost {
146
175
  this.target = target;
147
176
  socket.onopen = () => {
148
177
  this.attempts = 0;
178
+ this.beat(socket);
149
179
  };
150
180
  socket.onmessage = message => this.receive(String(message.data));
151
181
  socket.onclose = event => {
@@ -153,6 +183,7 @@ export class RelayHost {
153
183
  return;
154
184
  }
155
185
  this.socket = undefined;
186
+ clearInterval(this.pingTimer);
156
187
  this.closeChannels();
157
188
  // Another host has this id: trying again would not change that.
158
189
  if (event.code !== RelayCloseCode.REFUSED && event.code !== RelayCloseCode.REPLACED) {
@@ -162,8 +193,50 @@ export class RelayHost {
162
193
  // A failed connection also closes it.
163
194
  socket.onerror = () => undefined;
164
195
  }
196
+ /**
197
+ * The heartbeat of the connection to the relay. Without it a connection gone without a word (through
198
+ * a proxy, a network that changed, a computer that slept) would look open for good, its devices told
199
+ * the host is offline until ta serve started again. It is made again when the relay stops answering,
200
+ * or when the timer was late by much (the computer slept). A relay of before, which never answers, is
201
+ * not given up for that.
202
+ */
203
+ beat(socket) {
204
+ var _a, _b;
205
+ var _c;
206
+ const every = (_c = this.options.pingMs) !== null && _c !== void 0 ? _c : RELAY_PING_MS;
207
+ let last = Date.now();
208
+ let ponged = false;
209
+ let awaiting = false;
210
+ const pongs = (message) => {
211
+ if (message.data === RELAY_PONG) {
212
+ ponged = true;
213
+ awaiting = false;
214
+ }
215
+ };
216
+ socket.addEventListener('message', pongs);
217
+ clearInterval(this.pingTimer);
218
+ this.pingTimer = setInterval(() => {
219
+ const now = Date.now();
220
+ const slept = now - last > every * 2;
221
+ last = now;
222
+ if (this.socket !== socket) {
223
+ return;
224
+ }
225
+ if (slept || (awaiting && ponged)) {
226
+ this.disconnect();
227
+ this.refresh();
228
+ return;
229
+ }
230
+ awaiting = true;
231
+ this.send(RELAY_PING);
232
+ }, every);
233
+ (_b = (_a = this.pingTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
234
+ }
165
235
  receive(text) {
166
236
  var _a, _b;
237
+ if (text === RELAY_PONG) {
238
+ return;
239
+ }
167
240
  let message;
168
241
  try {
169
242
  message = JSON.parse(text);
@@ -193,6 +266,7 @@ export class RelayHost {
193
266
  }
194
267
  disconnect() {
195
268
  clearTimeout(this.timer);
269
+ clearInterval(this.pingTimer);
196
270
  const socket = this.socket;
197
271
  this.socket = undefined;
198
272
  this.closeChannels();
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { createServer } from 'node:http';
3
3
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
4
- import { RELAY_CONNECT_PATH, RELAY_HOST_PATH, RELAY_ID, RELAY_PAIR_PAGE, RELAY_PAIR_PATH, RelayCloseCode } from '../common/relay-protocol.js';
4
+ import { RELAY_CONNECT_PATH, RELAY_HOST_PATH, RELAY_ID, RELAY_PAIR_PAGE, RELAY_PAIR_PATH, RELAY_SHARE_PAGE, RELAY_SHARE_PATH, RelayCloseCode, } from '../common/relay-protocol.js';
5
5
  import { RelayRoom } from '../common/relay-room.js';
6
6
  const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
7
7
  const peer = (connection) => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
@@ -17,9 +17,10 @@ export class RelayServer {
17
17
  listen() {
18
18
  const server = createServer((request, response) => {
19
19
  var _a;
20
- const page = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split(/[?#]/)[0] === RELAY_PAIR_PATH;
20
+ const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split(/[?#]/)[0];
21
+ const page = path === RELAY_PAIR_PATH ? RELAY_PAIR_PAGE : path === RELAY_SHARE_PATH ? RELAY_SHARE_PAGE : undefined;
21
22
  response.writeHead(200, { 'content-type': page ? 'text/html; charset=utf-8' : 'text/plain' });
22
- response.end(page ? RELAY_PAIR_PAGE : 'Ta relay\n');
23
+ response.end(page !== null && page !== void 0 ? page : 'Ta relay\n');
23
24
  });
24
25
  server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
25
26
  this.server = server;
@@ -69,14 +70,17 @@ export class RelayServer {
69
70
  /** The first host to come with an id keeps it, for as long as the relay runs. */
70
71
  openHost(id, secret, connection) {
71
72
  var _a;
72
- var _b;
73
73
  const hash = createHash('sha256').update(secret).digest('base64url');
74
- const room = (_b = this.rooms.get(id)) !== null && _b !== void 0 ? _b : this.createRoom(id, hash);
74
+ const room = (_a = this.rooms.get(id)) !== null && _a !== void 0 ? _a : this.createRoom(id, hash);
75
75
  if (secret.length < 32 || !RelayServer.same(room.secretHash, hash)) {
76
76
  connection.close(RelayCloseCode.REFUSED, 'Refused.');
77
77
  return;
78
78
  }
79
- (_a = room.host) === null || _a === void 0 ? void 0 : _a.close(RelayCloseCode.REPLACED, 'The host connected again.');
79
+ if (room.host) {
80
+ // The devices came over the connection before, whose channels went with it.
81
+ room.host.close(RelayCloseCode.REPLACED, 'The host connected again.');
82
+ room.relay.hostClosed();
83
+ }
80
84
  room.host = connection;
81
85
  connection.onMessage(text => room.relay.fromHost(text));
82
86
  connection.onClose(() => {
@@ -1,4 +1,5 @@
1
1
  import type { RelayPairing } from '../common/relay-pairing.js';
2
+ import type { RelayShareLink } from '../common/relay-share.js';
2
3
  export interface RelayDevice {
3
4
  id: string;
4
5
  name: string;
@@ -6,6 +7,17 @@ export interface RelayDevice {
6
7
  key: string;
7
8
  createdAt: number;
8
9
  }
10
+ /** A package handed on by a link: whoever has the link takes it from this ta serve while the share lasts. */
11
+ export interface RelayShare {
12
+ id: string;
13
+ /** base64url, 32 bytes. */
14
+ key: string;
15
+ /** The directory of the package. */
16
+ root: string;
17
+ name: string;
18
+ createdAt: number;
19
+ expiresAt: number;
20
+ }
9
21
  /** relay.json in the agent directory. Without devices, ta serve does not connect to the relay. */
10
22
  export interface RelayConfig {
11
23
  /** The relay, without a trailing slash. */
@@ -16,6 +28,8 @@ export interface RelayConfig {
16
28
  secret: string;
17
29
  };
18
30
  devices: RelayDevice[];
31
+ /** Packages handed on; those past their time are dropped when it is written. */
32
+ shares?: RelayShare[];
19
33
  }
20
34
  /** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
21
35
  export declare class RelayStore {
@@ -25,11 +39,25 @@ export declare class RelayStore {
25
39
  get file(): string;
26
40
  read(): RelayConfig;
27
41
  device(deviceId: string): RelayDevice | undefined;
42
+ /** A share still on, by its id. */
43
+ share(shareId: string, now?: number): RelayShare | undefined;
44
+ /** The shares still on. */
45
+ shares(now?: number): RelayShare[];
46
+ /**
47
+ * A link of the package in `root`: the one of before while it lasts, else a new one for RELAY_SHARE_DAYS,
48
+ * on the relay of the devices (the default one when there is none), which this ta serve then connects to.
49
+ */
50
+ shareRoot(root: string, name: string, now?: number): {
51
+ link: RelayShareLink;
52
+ share: RelayShare;
53
+ };
54
+ /** Stops the shares of a package: their links no longer work. False when there were none. */
55
+ unshareRoot(root: string): boolean;
28
56
  /** A new device for this relay; another relay than before unpairs the devices of the old one. */
29
57
  pair(relay: string, deviceName: string): RelayPairing;
30
58
  /** False when there was no such device. */
31
59
  remove(deviceId: string): boolean;
32
60
  /** What the relay keeps of the host's secret. */
33
61
  static secretHash(secret: string): string;
34
- protected write(config: RelayConfig): void;
62
+ write(config: RelayConfig): void;
35
63
  }