@celljs/ta-relay 0.0.0-stage → 4.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -2
- package/esm/common/index.d.ts +6 -0
- package/esm/common/index.js +7 -0
- package/esm/common/index.js.map +1 -0
- package/esm/common/relay-bytes.d.ts +8 -0
- package/esm/common/relay-bytes.js +40 -0
- package/esm/common/relay-bytes.js.map +1 -0
- package/esm/common/relay-cipher.d.ts +22 -0
- package/esm/common/relay-cipher.js +55 -0
- package/esm/common/relay-cipher.js.map +1 -0
- package/esm/common/relay-pairing.d.ts +18 -0
- package/esm/common/relay-pairing.js +35 -0
- package/esm/common/relay-pairing.js.map +1 -0
- package/esm/common/relay-protocol.d.ts +56 -0
- package/esm/common/relay-protocol.js +29 -0
- package/esm/common/relay-protocol.js.map +1 -0
- package/esm/common/relay-room.d.ts +31 -0
- package/esm/common/relay-room.js +63 -0
- package/esm/common/relay-room.js.map +1 -0
- package/esm/common/relay-socket.d.ts +38 -0
- package/esm/common/relay-socket.js +98 -0
- package/esm/common/relay-socket.js.map +1 -0
- package/esm/node/index.d.ts +4 -0
- package/esm/node/index.js +5 -0
- package/esm/node/index.js.map +1 -0
- package/esm/node/relay-host.d.ts +61 -0
- package/esm/node/relay-host.js +208 -0
- package/esm/node/relay-host.js.map +1 -0
- package/esm/node/relay-server.d.ts +33 -0
- package/esm/node/relay-server.js +127 -0
- package/esm/node/relay-server.js.map +1 -0
- package/esm/node/relay-store.d.ts +35 -0
- package/esm/node/relay-store.js +59 -0
- package/esm/node/relay-store.js.map +1 -0
- package/esm/package.json +3 -0
- package/lib/common/index.d.ts +7 -0
- package/lib/common/index.d.ts.map +1 -0
- package/lib/common/index.js +23 -0
- package/lib/common/index.js.map +1 -0
- package/lib/common/relay-bytes.d.ts +9 -0
- package/lib/common/relay-bytes.d.ts.map +1 -0
- package/lib/common/relay-bytes.js +43 -0
- package/lib/common/relay-bytes.js.map +1 -0
- package/lib/common/relay-cipher.d.ts +23 -0
- package/lib/common/relay-cipher.d.ts.map +1 -0
- package/lib/common/relay-cipher.js +59 -0
- package/lib/common/relay-cipher.js.map +1 -0
- package/lib/common/relay-cipher.spec.d.ts +2 -0
- package/lib/common/relay-cipher.spec.d.ts.map +1 -0
- package/lib/common/relay-cipher.spec.js +43 -0
- package/lib/common/relay-cipher.spec.js.map +1 -0
- package/lib/common/relay-pairing.d.ts +19 -0
- package/lib/common/relay-pairing.d.ts.map +1 -0
- package/lib/common/relay-pairing.js +38 -0
- package/lib/common/relay-pairing.js.map +1 -0
- package/lib/common/relay-pairing.spec.d.ts +2 -0
- package/lib/common/relay-pairing.spec.d.ts.map +1 -0
- package/lib/common/relay-pairing.spec.js +25 -0
- package/lib/common/relay-pairing.spec.js.map +1 -0
- package/lib/common/relay-protocol.d.ts +57 -0
- package/lib/common/relay-protocol.d.ts.map +1 -0
- package/lib/common/relay-protocol.js +32 -0
- package/lib/common/relay-protocol.js.map +1 -0
- package/lib/common/relay-room.d.ts +32 -0
- package/lib/common/relay-room.d.ts.map +1 -0
- package/lib/common/relay-room.js +67 -0
- package/lib/common/relay-room.js.map +1 -0
- package/lib/common/relay-socket.d.ts +39 -0
- package/lib/common/relay-socket.d.ts.map +1 -0
- package/lib/common/relay-socket.js +102 -0
- package/lib/common/relay-socket.js.map +1 -0
- package/lib/node/index.d.ts +5 -0
- package/lib/node/index.d.ts.map +1 -0
- package/lib/node/index.js +21 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/relay-host.d.ts +62 -0
- package/lib/node/relay-host.d.ts.map +1 -0
- package/lib/node/relay-host.js +212 -0
- package/lib/node/relay-host.js.map +1 -0
- package/lib/node/relay-server.d.ts +34 -0
- package/lib/node/relay-server.d.ts.map +1 -0
- package/lib/node/relay-server.js +131 -0
- package/lib/node/relay-server.js.map +1 -0
- package/lib/node/relay-store.d.ts +36 -0
- package/lib/node/relay-store.d.ts.map +1 -0
- package/lib/node/relay-store.js +63 -0
- package/lib/node/relay-store.js.map +1 -0
- package/lib/node/relay.spec.d.ts +2 -0
- package/lib/node/relay.spec.d.ts.map +1 -0
- package/lib/node/relay.spec.js +141 -0
- package/lib/node/relay.spec.js.map +1 -0
- package/package.json +58 -4
- package/src/common/index.ts +6 -0
- package/src/common/relay-bytes.ts +37 -0
- package/src/common/relay-cipher.spec.ts +45 -0
- package/src/common/relay-cipher.ts +74 -0
- package/src/common/relay-pairing.spec.ts +26 -0
- package/src/common/relay-pairing.ts +46 -0
- package/src/common/relay-protocol.ts +50 -0
- package/src/common/relay-room.ts +79 -0
- package/src/common/relay-socket.ts +106 -0
- package/src/node/index.ts +4 -0
- package/src/node/relay-host.ts +230 -0
- package/src/node/relay-server.ts +143 -0
- package/src/node/relay-store.ts +84 -0
- package/src/node/relay.spec.ts +151 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { RelayCloseCode, type RelayHostMessage } from './relay-protocol';
|
|
2
|
+
|
|
3
|
+
/** One end of a WebSocket at the relay. */
|
|
4
|
+
export interface RelayPeer {
|
|
5
|
+
send(text: string): void;
|
|
6
|
+
close(code: number, reason: string): void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Where the room finds its connections: kept in memory, or in a Durable Object that sleeps between messages. */
|
|
10
|
+
export interface RelayPeers {
|
|
11
|
+
host(): RelayPeer | undefined;
|
|
12
|
+
client(channel: string): RelayPeer | undefined;
|
|
13
|
+
clients(): RelayPeer[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Devices at once on one host. */
|
|
17
|
+
export const RELAY_MAX_CLIENTS = 16;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The relay's whole job for one host: pass what a device sends to the host on the device's channel, and
|
|
21
|
+
* what the host sends on a channel to that device. It holds no state of its own, so that it runs the same
|
|
22
|
+
* in `ta relay` and in a Durable Object.
|
|
23
|
+
*/
|
|
24
|
+
export class RelayRoom {
|
|
25
|
+
constructor(protected readonly peers: RelayPeers) {}
|
|
26
|
+
|
|
27
|
+
/** False when the device cannot stay: the host is away or has too many devices; close it with the code. */
|
|
28
|
+
clientOpened(channel: string): RelayCloseCode | undefined {
|
|
29
|
+
const host = this.peers.host();
|
|
30
|
+
if (!host) {
|
|
31
|
+
return RelayCloseCode.HOST_OFFLINE;
|
|
32
|
+
}
|
|
33
|
+
if (this.peers.clients().length > RELAY_MAX_CLIENTS) {
|
|
34
|
+
return RelayCloseCode.FULL;
|
|
35
|
+
}
|
|
36
|
+
this.toHost(host, { t: 'open', ch: channel });
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
fromClient(channel: string, text: string): void {
|
|
41
|
+
const host = this.peers.host();
|
|
42
|
+
if (host) {
|
|
43
|
+
this.toHost(host, { t: 'data', ch: channel, d: text });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
clientClosed(channel: string): void {
|
|
48
|
+
const host = this.peers.host();
|
|
49
|
+
if (host) {
|
|
50
|
+
this.toHost(host, { t: 'close', ch: channel });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What the host sends that is not a message of the protocol is dropped. */
|
|
55
|
+
fromHost(text: string): void {
|
|
56
|
+
let message: RelayHostMessage;
|
|
57
|
+
try {
|
|
58
|
+
message = JSON.parse(text);
|
|
59
|
+
} catch {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const client = typeof message.ch === 'string' ? this.peers.client(message.ch) : undefined;
|
|
63
|
+
if (message.t === 'data' && typeof message.d === 'string') {
|
|
64
|
+
client?.send(message.d);
|
|
65
|
+
} else if (message.t === 'close') {
|
|
66
|
+
client?.close(RelayCloseCode.CLOSED_BY_HOST, 'Closed by the host.');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
hostClosed(): void {
|
|
71
|
+
for (const client of this.peers.clients()) {
|
|
72
|
+
client.close(RelayCloseCode.HOST_OFFLINE, 'The host went offline.');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
protected toHost(host: RelayPeer, message: RelayHostMessage): void {
|
|
77
|
+
host.send(JSON.stringify(message));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { RelayBytes } from './relay-bytes';
|
|
2
|
+
import { RelayCipher } from './relay-cipher';
|
|
3
|
+
import { type RelayPairing, RelayPairingUtil } from './relay-pairing';
|
|
4
|
+
import { RELAY_CONNECT_PATH, RELAY_PROOF, type RelayHello, type RelayWelcome } from './relay-protocol';
|
|
5
|
+
|
|
6
|
+
const CONNECTING = 0;
|
|
7
|
+
const OPEN = 1;
|
|
8
|
+
const CLOSING = 2;
|
|
9
|
+
const CLOSED = 3;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A WebSocket to ta serve through a relay, for a paired device: it says hello, checks that the host has
|
|
13
|
+
* the device's key, and then seals and opens every message. It behaves as much like a WebSocket as
|
|
14
|
+
* TaConnection needs: `readyState`, `send`, `close` and the four handlers.
|
|
15
|
+
*/
|
|
16
|
+
export class RelaySocket {
|
|
17
|
+
static readonly CONNECTING = CONNECTING;
|
|
18
|
+
static readonly OPEN = OPEN;
|
|
19
|
+
static readonly CLOSING = CLOSING;
|
|
20
|
+
static readonly CLOSED = CLOSED;
|
|
21
|
+
/** The close code when the host does not know the device, or does not show its key. */
|
|
22
|
+
static readonly REFUSED = 4403;
|
|
23
|
+
|
|
24
|
+
onopen: (() => void) | null = null;
|
|
25
|
+
onmessage: ((message: { data: string }) => void) | null = null;
|
|
26
|
+
onclose: ((event: { code: number; reason: string }) => void) | null = null;
|
|
27
|
+
onerror: ((event: unknown) => void) | null = null;
|
|
28
|
+
|
|
29
|
+
protected state = CONNECTING;
|
|
30
|
+
protected code?: number;
|
|
31
|
+
protected cipher?: RelayCipher;
|
|
32
|
+
protected readonly socket: WebSocket;
|
|
33
|
+
protected readonly nonce = RelayBytes.random(16);
|
|
34
|
+
|
|
35
|
+
constructor(protected readonly pairing: RelayPairing) {
|
|
36
|
+
this.socket = new WebSocket(RelayPairingUtil.websocketUrl(pairing.relay, RELAY_CONNECT_PATH + pairing.host));
|
|
37
|
+
this.socket.onopen = () => {
|
|
38
|
+
const hello: RelayHello = { t: 'hello', v: 1, device: pairing.device, nonce: RelayBytes.toBase64(this.nonce) };
|
|
39
|
+
this.socket.send(JSON.stringify(hello));
|
|
40
|
+
};
|
|
41
|
+
this.socket.onmessage = message => void this.receive(String(message.data));
|
|
42
|
+
this.socket.onerror = event => this.onerror?.(event);
|
|
43
|
+
this.socket.onclose = event => this.finish(event.code, event.reason);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
get readyState(): number {
|
|
47
|
+
return this.state;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Why it closed, once it has. */
|
|
51
|
+
get closeCode(): number | undefined {
|
|
52
|
+
return this.code;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
send(text: string): void {
|
|
56
|
+
if (this.state !== OPEN || !this.cipher) {
|
|
57
|
+
throw new Error('The connection is not open.');
|
|
58
|
+
}
|
|
59
|
+
this.cipher.seal(text).then(frame => this.socket.readyState === OPEN && this.socket.send(frame));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
close(code = 1000, reason = ''): void {
|
|
63
|
+
if (this.state === CLOSED) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
this.state = CLOSING;
|
|
67
|
+
this.socket.close(code, reason);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
protected async receive(text: string): Promise<void> {
|
|
71
|
+
if (this.cipher) {
|
|
72
|
+
try {
|
|
73
|
+
const data = await this.cipher.open(text);
|
|
74
|
+
this.onmessage?.({ data });
|
|
75
|
+
} catch {
|
|
76
|
+
this.close(4400, 'A message did not open.');
|
|
77
|
+
}
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const welcome = JSON.parse(text) as RelayWelcome;
|
|
82
|
+
if (welcome.t !== 'ready') {
|
|
83
|
+
throw new Error(welcome.reason);
|
|
84
|
+
}
|
|
85
|
+
const cipher = await RelayCipher.derive(RelayBytes.fromBase64(this.pairing.key), this.nonce, RelayBytes.fromBase64(welcome.nonce), 'client');
|
|
86
|
+
if ((await cipher.open(welcome.proof)) !== RELAY_PROOF) {
|
|
87
|
+
throw new Error('The host did not show the key.');
|
|
88
|
+
}
|
|
89
|
+
this.cipher = cipher;
|
|
90
|
+
this.state = OPEN;
|
|
91
|
+
this.onopen?.();
|
|
92
|
+
} catch {
|
|
93
|
+
// A host without the key is not this device's host, whoever answered.
|
|
94
|
+
this.close(RelaySocket.REFUSED, 'The host refused this device.');
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
protected finish(code: number, reason: string): void {
|
|
99
|
+
if (this.state === CLOSED) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
this.state = CLOSED;
|
|
103
|
+
this.code = code;
|
|
104
|
+
this.onclose?.({ code, reason });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { RelayBytes } from '../common/relay-bytes';
|
|
2
|
+
import { RelayCipher } from '../common/relay-cipher';
|
|
3
|
+
import { RelayPairingUtil } from '../common/relay-pairing';
|
|
4
|
+
import { RELAY_HOST_PATH, RELAY_PROOF, RelayCloseCode, type RelayHello, type RelayHostMessage, type RelayWelcome } from '../common/relay-protocol';
|
|
5
|
+
import type { RelayStore } from './relay-store';
|
|
6
|
+
|
|
7
|
+
export interface RelayHostOptions {
|
|
8
|
+
store: RelayStore;
|
|
9
|
+
/** The WebSocket of this ta serve, with its token: every device gets a connection to it of its own. */
|
|
10
|
+
localUrl: string;
|
|
11
|
+
/** First wait before reconnecting to the relay; it doubles up to 30 seconds. */
|
|
12
|
+
reconnectDelayMs?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const MAX_RECONNECT_DELAY_MS = 30000;
|
|
16
|
+
const HELLO_TIMEOUT_MS = 10000;
|
|
17
|
+
|
|
18
|
+
/** A device on a channel: the handshake, then its connection to ta serve. */
|
|
19
|
+
class RelayChannel {
|
|
20
|
+
protected cipher?: RelayCipher;
|
|
21
|
+
protected local?: WebSocket;
|
|
22
|
+
protected readonly early: string[] = [];
|
|
23
|
+
protected readonly timer = setTimeout(() => this.close(), HELLO_TIMEOUT_MS);
|
|
24
|
+
|
|
25
|
+
constructor(
|
|
26
|
+
readonly id: string,
|
|
27
|
+
protected readonly host: RelayHost,
|
|
28
|
+
protected readonly options: RelayHostOptions,
|
|
29
|
+
) {}
|
|
30
|
+
|
|
31
|
+
async receive(text: string): Promise<void> {
|
|
32
|
+
if (!this.cipher) {
|
|
33
|
+
await this.hello(text);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
let data: string;
|
|
37
|
+
try {
|
|
38
|
+
data = await this.cipher.open(text);
|
|
39
|
+
} catch {
|
|
40
|
+
this.close();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (this.local?.readyState === WebSocket.OPEN) {
|
|
44
|
+
this.local.send(data);
|
|
45
|
+
} else {
|
|
46
|
+
this.early.push(data);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** From the relay: the device is gone. */
|
|
51
|
+
closed(): void {
|
|
52
|
+
clearTimeout(this.timer);
|
|
53
|
+
this.local?.close();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
protected async hello(text: string): Promise<void> {
|
|
57
|
+
let hello: RelayHello;
|
|
58
|
+
try {
|
|
59
|
+
hello = JSON.parse(text);
|
|
60
|
+
} catch {
|
|
61
|
+
this.close();
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const device = hello.t === 'hello' && hello.v === 1 ? this.options.store.device(hello.device) : undefined;
|
|
65
|
+
if (!device || typeof hello.nonce !== 'string') {
|
|
66
|
+
this.answer({ t: 'refused', reason: 'This device is not paired.' });
|
|
67
|
+
this.close();
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
clearTimeout(this.timer);
|
|
71
|
+
const nonce = RelayBytes.random(16);
|
|
72
|
+
const cipher = await RelayCipher.derive(RelayBytes.fromBase64(device.key), RelayBytes.fromBase64(hello.nonce), nonce, 'host');
|
|
73
|
+
this.cipher = cipher;
|
|
74
|
+
this.answer({ t: 'ready', nonce: RelayBytes.toBase64(nonce), proof: await cipher.seal(RELAY_PROOF) });
|
|
75
|
+
this.connectLocal(cipher);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
protected connectLocal(cipher: RelayCipher): void {
|
|
79
|
+
const local = new WebSocket(this.options.localUrl);
|
|
80
|
+
this.local = local;
|
|
81
|
+
local.onopen = () => {
|
|
82
|
+
for (const data of this.early.splice(0)) {
|
|
83
|
+
local.send(data);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
local.onmessage = message => {
|
|
87
|
+
cipher.seal(String(message.data)).then(frame => this.host.send({ t: 'data', ch: this.id, d: frame }));
|
|
88
|
+
};
|
|
89
|
+
local.onclose = () => this.close();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
protected answer(welcome: RelayWelcome): void {
|
|
93
|
+
this.host.send({ t: 'data', ch: this.id, d: JSON.stringify(welcome) });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
protected close(): void {
|
|
97
|
+
clearTimeout(this.timer);
|
|
98
|
+
this.host.closeChannel(this.id);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* ta serve at the relay: one WebSocket out to it, over which the paired devices come in, each on a
|
|
104
|
+
* channel of its own. A device that knows its key gets a connection to ta serve; nothing else does, and
|
|
105
|
+
* the relay sees only what the two seal.
|
|
106
|
+
*/
|
|
107
|
+
export class RelayHost {
|
|
108
|
+
protected socket?: WebSocket;
|
|
109
|
+
/** Where {@link socket} goes: WebSocket.url is normalised. */
|
|
110
|
+
protected target?: string;
|
|
111
|
+
protected stopped = false;
|
|
112
|
+
protected attempts = 0;
|
|
113
|
+
protected timer?: ReturnType<typeof setTimeout>;
|
|
114
|
+
protected readonly channels = new Map<string, RelayChannel>();
|
|
115
|
+
|
|
116
|
+
constructor(protected readonly options: RelayHostOptions) {}
|
|
117
|
+
|
|
118
|
+
/** Whether the connection to the relay is open. */
|
|
119
|
+
get online(): boolean {
|
|
120
|
+
return this.socket?.readyState === WebSocket.OPEN;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Connects when relay.json has a relay and a device, and keeps connected; checks again on {@link refresh}. */
|
|
124
|
+
start(): void {
|
|
125
|
+
this.stopped = false;
|
|
126
|
+
this.refresh();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** relay.json may have changed: connect if it now has devices, or leave if it has none. */
|
|
130
|
+
refresh(): void {
|
|
131
|
+
const { url, host, devices } = this.options.store.read();
|
|
132
|
+
const wanted = !this.stopped && url !== undefined && host !== undefined && devices.length > 0;
|
|
133
|
+
if (!wanted) {
|
|
134
|
+
this.disconnect();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const target = `${RelayPairingUtil.websocketUrl(url, RELAY_HOST_PATH + host.id)}?secret=${encodeURIComponent(host.secret)}`;
|
|
138
|
+
if (this.socket && this.target === target && this.socket.readyState <= WebSocket.OPEN) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
this.disconnect();
|
|
142
|
+
this.connect(target);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
stop(): void {
|
|
146
|
+
this.stopped = true;
|
|
147
|
+
this.disconnect();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** @internal */
|
|
151
|
+
send(message: RelayHostMessage): void {
|
|
152
|
+
if (this.socket?.readyState === WebSocket.OPEN) {
|
|
153
|
+
this.socket.send(JSON.stringify(message));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** @internal */
|
|
158
|
+
closeChannel(id: string): void {
|
|
159
|
+
const channel = this.channels.get(id);
|
|
160
|
+
if (channel) {
|
|
161
|
+
this.channels.delete(id);
|
|
162
|
+
channel.closed();
|
|
163
|
+
this.send({ t: 'close', ch: id });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
protected connect(target: string): void {
|
|
168
|
+
const socket = new WebSocket(target);
|
|
169
|
+
this.socket = socket;
|
|
170
|
+
this.target = target;
|
|
171
|
+
socket.onopen = () => {
|
|
172
|
+
this.attempts = 0;
|
|
173
|
+
};
|
|
174
|
+
socket.onmessage = message => this.receive(String(message.data));
|
|
175
|
+
socket.onclose = event => {
|
|
176
|
+
if (this.socket !== socket) {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
this.socket = undefined;
|
|
180
|
+
this.closeChannels();
|
|
181
|
+
// Another host has this id: trying again would not change that.
|
|
182
|
+
if (event.code !== RelayCloseCode.REFUSED && event.code !== RelayCloseCode.REPLACED) {
|
|
183
|
+
this.scheduleReconnect();
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
// A failed connection also closes it.
|
|
187
|
+
socket.onerror = () => undefined;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
protected receive(text: string): void {
|
|
191
|
+
let message: RelayHostMessage;
|
|
192
|
+
try {
|
|
193
|
+
message = JSON.parse(text);
|
|
194
|
+
} catch {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (message.t === 'open') {
|
|
198
|
+
this.channels.set(message.ch, new RelayChannel(message.ch, this, this.options));
|
|
199
|
+
} else if (message.t === 'data') {
|
|
200
|
+
void this.channels.get(message.ch)?.receive(message.d);
|
|
201
|
+
} else if (message.t === 'close') {
|
|
202
|
+
this.channels.get(message.ch)?.closed();
|
|
203
|
+
this.channels.delete(message.ch);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
protected scheduleReconnect(): void {
|
|
208
|
+
if (this.stopped) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const delay = Math.min((this.options.reconnectDelayMs ?? 500) * 2 ** this.attempts++, MAX_RECONNECT_DELAY_MS);
|
|
212
|
+
clearTimeout(this.timer);
|
|
213
|
+
this.timer = setTimeout(() => this.refresh(), delay);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
protected disconnect(): void {
|
|
217
|
+
clearTimeout(this.timer);
|
|
218
|
+
const socket = this.socket;
|
|
219
|
+
this.socket = undefined;
|
|
220
|
+
this.closeChannels();
|
|
221
|
+
socket?.close();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
protected closeChannels(): void {
|
|
225
|
+
for (const channel of this.channels.values()) {
|
|
226
|
+
channel.closed();
|
|
227
|
+
}
|
|
228
|
+
this.channels.clear();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { createServer, type IncomingMessage, type Server } from 'node:http';
|
|
3
|
+
import type { AddressInfo } from 'node:net';
|
|
4
|
+
import type { Duplex } from 'node:stream';
|
|
5
|
+
import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
6
|
+
import { RELAY_CONNECT_PATH, RELAY_HOST_PATH, RELAY_ID, RELAY_PAIR_PAGE, RELAY_PAIR_PATH, RelayCloseCode } from '../common/relay-protocol';
|
|
7
|
+
import { type RelayPeer, RelayRoom } from '../common/relay-room';
|
|
8
|
+
|
|
9
|
+
export interface RelayServerOptions {
|
|
10
|
+
host?: string;
|
|
11
|
+
port?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
|
|
15
|
+
|
|
16
|
+
interface Room {
|
|
17
|
+
secretHash: string;
|
|
18
|
+
host?: WebSocketConnection;
|
|
19
|
+
clients: Map<string, WebSocketConnection>;
|
|
20
|
+
relay: RelayRoom;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const peer = (connection: WebSocketConnection): RelayPeer => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
|
|
27
|
+
* and keeps the hash of each host's secret in memory, for as long as it runs.
|
|
28
|
+
*/
|
|
29
|
+
export class RelayServer {
|
|
30
|
+
protected readonly rooms = new Map<string, Room>();
|
|
31
|
+
protected server?: Server;
|
|
32
|
+
|
|
33
|
+
constructor(protected readonly options: RelayServerOptions = {}) {}
|
|
34
|
+
|
|
35
|
+
listen(): Promise<string> {
|
|
36
|
+
const server = createServer((request, response) => {
|
|
37
|
+
const page = (request.url ?? '/').split(/[?#]/)[0] === RELAY_PAIR_PATH;
|
|
38
|
+
response.writeHead(200, { 'content-type': page ? 'text/html; charset=utf-8' : 'text/plain' });
|
|
39
|
+
response.end(page ? RELAY_PAIR_PAGE : 'Ta relay\n');
|
|
40
|
+
});
|
|
41
|
+
server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
|
|
42
|
+
this.server = server;
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
server.once('error', reject);
|
|
45
|
+
server.listen(this.options.port ?? 0, this.options.host ?? '127.0.0.1', () => {
|
|
46
|
+
const { address, port } = server.address() as AddressInfo;
|
|
47
|
+
resolve(`http://${address.includes(':') ? `[${address}]` : address}:${port}`);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
close(): Promise<void> {
|
|
53
|
+
for (const room of this.rooms.values()) {
|
|
54
|
+
room.host?.close(1001, 'The relay is stopping.');
|
|
55
|
+
for (const client of room.clients.values()) {
|
|
56
|
+
client.close(1001, 'The relay is stopping.');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
this.rooms.clear();
|
|
60
|
+
return new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {
|
|
64
|
+
const url = new URL(request.url ?? '/', 'http://relay');
|
|
65
|
+
const checked = WebSocketConnection.check(request);
|
|
66
|
+
if ('status' in checked) {
|
|
67
|
+
WebSocketConnection.refuse(socket, checked.status, checked.message);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const [path, id] = url.pathname.startsWith(RELAY_HOST_PATH)
|
|
71
|
+
? [RELAY_HOST_PATH, url.pathname.slice(RELAY_HOST_PATH.length)]
|
|
72
|
+
: [RELAY_CONNECT_PATH, url.pathname.slice(RELAY_CONNECT_PATH.length)];
|
|
73
|
+
if (!url.pathname.startsWith(path) || !RELAY_ID.test(id)) {
|
|
74
|
+
WebSocketConnection.refuse(socket, 404, 'Not found.');
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const connection = WebSocketConnection.open(socket, checked.key, head, WEBSOCKET);
|
|
78
|
+
if (path === RELAY_HOST_PATH) {
|
|
79
|
+
this.openHost(id, url.searchParams.get('secret') ?? '', connection);
|
|
80
|
+
} else {
|
|
81
|
+
this.openClient(id, connection);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The first host to come with an id keeps it, for as long as the relay runs. */
|
|
86
|
+
protected openHost(id: string, secret: string, connection: WebSocketConnection): void {
|
|
87
|
+
const hash = createHash('sha256').update(secret).digest('base64url');
|
|
88
|
+
const room = this.rooms.get(id) ?? this.createRoom(id, hash);
|
|
89
|
+
if (secret.length < 32 || !RelayServer.same(room.secretHash, hash)) {
|
|
90
|
+
connection.close(RelayCloseCode.REFUSED, 'Refused.');
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
room.host?.close(RelayCloseCode.REPLACED, 'The host connected again.');
|
|
94
|
+
room.host = connection;
|
|
95
|
+
connection.onMessage(text => room.relay.fromHost(text));
|
|
96
|
+
connection.onClose(() => {
|
|
97
|
+
if (room.host === connection) {
|
|
98
|
+
room.host = undefined;
|
|
99
|
+
room.relay.hostClosed();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
protected openClient(id: string, connection: WebSocketConnection): void {
|
|
105
|
+
const room = this.rooms.get(id);
|
|
106
|
+
const channel = randomBytes(9).toString('base64url');
|
|
107
|
+
room?.clients.set(channel, connection);
|
|
108
|
+
const refused = room ? room.relay.clientOpened(channel) : RelayCloseCode.HOST_OFFLINE;
|
|
109
|
+
if (!room || refused !== undefined) {
|
|
110
|
+
room?.clients.delete(channel);
|
|
111
|
+
connection.close(refused ?? RelayCloseCode.HOST_OFFLINE, 'The host is not available.');
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
connection.onMessage(text => room.relay.fromClient(channel, text));
|
|
115
|
+
connection.onClose(() => {
|
|
116
|
+
if (room.clients.delete(channel)) {
|
|
117
|
+
room.relay.clientClosed(channel);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
protected createRoom(id: string, secretHash: string): Room {
|
|
123
|
+
const room: Room = {
|
|
124
|
+
secretHash,
|
|
125
|
+
clients: new Map(),
|
|
126
|
+
relay: new RelayRoom({
|
|
127
|
+
host: () => (room.host ? peer(room.host) : undefined),
|
|
128
|
+
client: channel => {
|
|
129
|
+
const client = room.clients.get(channel);
|
|
130
|
+
return client ? peer(client) : undefined;
|
|
131
|
+
},
|
|
132
|
+
clients: () => [...room.clients.values()].map(peer),
|
|
133
|
+
}),
|
|
134
|
+
};
|
|
135
|
+
this.rooms.set(id, room);
|
|
136
|
+
return room;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
protected static same(a: string, b: string): boolean {
|
|
140
|
+
const [left, right] = [Buffer.from(a), Buffer.from(b)];
|
|
141
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { hostname } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import type { RelayPairing } from '../common/relay-pairing';
|
|
6
|
+
|
|
7
|
+
export interface RelayDevice {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
/** base64url, 32 bytes: what the device and ta serve encrypt with. */
|
|
11
|
+
key: string;
|
|
12
|
+
createdAt: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** relay.json in the agent directory. Without devices, ta serve does not connect to the relay. */
|
|
16
|
+
export interface RelayConfig {
|
|
17
|
+
/** The relay, without a trailing slash. */
|
|
18
|
+
url?: string;
|
|
19
|
+
/** This ta serve at the relay: the id is public, the secret keeps another host from taking it. */
|
|
20
|
+
host?: { id: string; secret: string };
|
|
21
|
+
devices: RelayDevice[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const id = () => randomBytes(16).toString('base64url');
|
|
25
|
+
|
|
26
|
+
/** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
|
|
27
|
+
export class RelayStore {
|
|
28
|
+
static readonly FILE = 'relay.json';
|
|
29
|
+
|
|
30
|
+
constructor(protected readonly agentDir: string) {}
|
|
31
|
+
|
|
32
|
+
get file(): string {
|
|
33
|
+
return join(this.agentDir, RelayStore.FILE);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
read(): RelayConfig {
|
|
37
|
+
try {
|
|
38
|
+
const config = JSON.parse(readFileSync(this.file, 'utf8')) as RelayConfig;
|
|
39
|
+
return { url: config.url, host: config.host, devices: Array.isArray(config.devices) ? config.devices : [] };
|
|
40
|
+
} catch {
|
|
41
|
+
return { devices: [] };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
device(deviceId: string): RelayDevice | undefined {
|
|
46
|
+
return this.read().devices.find(device => device.id === deviceId);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A new device for this relay; another relay than before unpairs the devices of the old one. */
|
|
50
|
+
pair(relay: string, deviceName: string): RelayPairing {
|
|
51
|
+
const url = relay.replace(/\/+$/, '');
|
|
52
|
+
const before = this.read();
|
|
53
|
+
const config: RelayConfig =
|
|
54
|
+
before.url === url && before.host ? before : { url, host: { id: id(), secret: randomBytes(32).toString('base64url') }, devices: [] };
|
|
55
|
+
const device: RelayDevice = { id: id(), name: deviceName, key: randomBytes(32).toString('base64url'), createdAt: Date.now() };
|
|
56
|
+
config.devices.push(device);
|
|
57
|
+
this.write(config);
|
|
58
|
+
return { relay: url, host: (config.host as { id: string }).id, device: device.id, key: device.key, name: hostname() };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** False when there was no such device. */
|
|
62
|
+
remove(deviceId: string): boolean {
|
|
63
|
+
const config = this.read();
|
|
64
|
+
const devices = config.devices.filter(device => device.id !== deviceId);
|
|
65
|
+
if (devices.length === config.devices.length) {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
this.write({ ...config, devices });
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** What the relay keeps of the host's secret. */
|
|
73
|
+
static secretHash(secret: string): string {
|
|
74
|
+
return createHash('sha256').update(secret).digest('base64url');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
protected write(config: RelayConfig): void {
|
|
78
|
+
mkdirSync(dirname(this.file), { recursive: true });
|
|
79
|
+
const temporary = `${this.file}.${process.pid}.tmp`;
|
|
80
|
+
writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
81
|
+
chmodSync(temporary, 0o600);
|
|
82
|
+
renameSync(temporary, this.file);
|
|
83
|
+
}
|
|
84
|
+
}
|