@celljs/ta-relay 4.8.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
@@ -1,230 +0,0 @@
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
- }
@@ -1,143 +0,0 @@
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
- }
@@ -1,84 +0,0 @@
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
- }
@@ -1,151 +0,0 @@
1
- import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
2
- import { type ChildProcess, spawn } from 'node:child_process';
3
- import { mkdtempSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
6
- import { RelayPairingUtil } from '../common/relay-pairing';
7
- import { RelayCloseCode } from '../common/relay-protocol';
8
- import { RelaySocket } from '../common/relay-socket';
9
- import { RelayHost } from './relay-host';
10
- import { RelayStore } from './relay-store';
11
-
12
- /** In Node.js: the HTTP server of Bun before 1.4 cannot answer WebSocket upgrades. Prints what reached the host side. */
13
- function startRelay(port = 0): Promise<{ child: ChildProcess; url: string; seen: string[] }> {
14
- const script = `const { RelayServer } = require(${JSON.stringify(join(__dirname, 'relay-server.js'))});
15
- const { RelayRoom } = require(${JSON.stringify(join(__dirname, '../common/relay-room.js'))});
16
- const fromClient = RelayRoom.prototype.fromClient;
17
- RelayRoom.prototype.fromClient = function (channel, text) { console.error('SEEN ' + text); return fromClient.call(this, channel, text); };
18
- new RelayServer({ port: ${port} }).listen().then(url => console.log(url));`;
19
- const child = spawn('node', ['-e', script], { stdio: ['ignore', 'pipe', 'pipe'] });
20
- const seen: string[] = [];
21
- child.stderr?.on('data', data => seen.push(String(data)));
22
- return new Promise(resolve => child.stdout?.once('data', data => resolve({ child, url: String(data).trim(), seen })));
23
- }
24
-
25
- /** Stands in for ta serve: answers every message with what it got, to connections with the token. */
26
- function startLocal() {
27
- return Bun.serve({
28
- port: 0,
29
- hostname: '127.0.0.1',
30
- fetch: (request, server) =>
31
- new URL(request.url).searchParams.get('token') === 'local-token' && server.upgrade(request) ? undefined : new Response('no', { status: 401 }),
32
- websocket: {
33
- message: (socket, message) => {
34
- socket.send(`echo ${message}`);
35
- },
36
- },
37
- });
38
- }
39
-
40
- function open(socket: RelaySocket): Promise<{ code: number } | undefined> {
41
- return new Promise(resolve => {
42
- socket.onopen = () => resolve(undefined);
43
- socket.onclose = event => resolve({ code: event.code });
44
- });
45
- }
46
-
47
- function next(socket: RelaySocket): Promise<string> {
48
- return new Promise(resolve => {
49
- socket.onmessage = message => resolve(message.data);
50
- });
51
- }
52
-
53
- describe('the relay', () => {
54
- let relay: Awaited<ReturnType<typeof startRelay>>;
55
- const local = startLocal();
56
- const store = new RelayStore(mkdtempSync(join(tmpdir(), 'ta-relay-')));
57
- let host: RelayHost;
58
-
59
- beforeAll(async () => {
60
- relay = await startRelay();
61
- host = new RelayHost({ store, localUrl: `ws://127.0.0.1:${local.port}/?token=local-token`, reconnectDelayMs: 20 });
62
- });
63
-
64
- afterAll(() => {
65
- host.stop();
66
- local.stop(true);
67
- relay.child.kill();
68
- });
69
-
70
- const online = async () => {
71
- host.refresh();
72
- while (!host.online) {
73
- await Bun.sleep(10);
74
- }
75
- };
76
-
77
- it('does not connect ta serve before a device is paired', () => {
78
- host.start();
79
- expect(host.online).toBe(false);
80
- });
81
-
82
- it('takes a paired device to ta serve, and the relay sees only what is sealed', async () => {
83
- const pairing = store.pair(relay.url, 'phone');
84
- await online();
85
- const socket = new RelaySocket(RelayPairingUtil.parse(RelayPairingUtil.link(pairing)));
86
- expect(await open(socket)).toBeUndefined();
87
- const answer = next(socket);
88
- socket.send('a secret question');
89
- expect(await answer).toBe('echo a secret question');
90
- const seen = relay.seen.join('');
91
- expect(seen).toContain('SEEN');
92
- expect(seen).not.toContain('secret');
93
- socket.close();
94
- });
95
-
96
- it('refuses a device that is not paired, or no longer', async () => {
97
- const pairing = store.pair(relay.url, 'tablet');
98
- const stranger = new RelaySocket({ ...pairing, device: 'x'.repeat(22) });
99
- expect((await open(stranger))?.code).toBe(4403);
100
- store.remove(pairing.device);
101
- const removed = new RelaySocket(pairing);
102
- expect((await open(removed))?.code).toBe(4403);
103
- });
104
-
105
- it('refuses a device whose key is wrong', async () => {
106
- const pairing = store.pair(relay.url, 'laptop');
107
- const forged = new RelaySocket({ ...pairing, key: store.pair(relay.url, 'other').key });
108
- expect((await open(forged))?.code).toBe(4403);
109
- });
110
-
111
- it('tells a device when its host is offline', async () => {
112
- const pairing = store.pair(relay.url, 'watch');
113
- const socket = new RelaySocket({ ...pairing, host: 'n'.repeat(22) });
114
- expect((await open(socket))?.code).toBe(RelayCloseCode.HOST_OFFLINE);
115
- });
116
-
117
- it('does not let another host take the id', async () => {
118
- const { host: id } = store.read();
119
- const thief = new WebSocket(`${RelayPairingUtil.websocketUrl(relay.url, '/v1/host/')}${id?.id}?secret=${'w'.repeat(43)}`);
120
- const code = await new Promise<number>(resolve => {
121
- thief.onclose = event => resolve(event.code);
122
- });
123
- expect(code).toBe(RelayCloseCode.REFUSED);
124
- expect(host.online).toBe(true);
125
- });
126
-
127
- it('comes back when the relay does', async () => {
128
- const port = Number(new URL(relay.url).port);
129
- relay.child.kill();
130
- await new Promise(resolve => relay.child.once('exit', resolve));
131
- while (host.online) {
132
- await Bun.sleep(10);
133
- }
134
- relay = await startRelay(port);
135
- while (!host.online) {
136
- await Bun.sleep(10);
137
- }
138
- const pairing = store.pair(relay.url, 'again');
139
- const socket = new RelaySocket(pairing);
140
- expect(await open(socket)).toBeUndefined();
141
- socket.close();
142
- });
143
-
144
- it('leaves the relay when the last device is removed', async () => {
145
- for (const device of store.read().devices) {
146
- store.remove(device.id);
147
- }
148
- host.refresh();
149
- expect(host.online).toBe(false);
150
- });
151
- });