@celljs/ta-relay 4.9.1 → 4.11.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 (118) hide show
  1. package/README.en.md +29 -2
  2. package/README.md +29 -2
  3. package/esm/common/index.d.ts +10 -0
  4. package/esm/common/index.js +10 -0
  5. package/esm/common/relay-blobs.d.ts +54 -0
  6. package/esm/common/relay-blobs.js +153 -0
  7. package/esm/common/relay-card.d.ts +23 -0
  8. package/esm/common/relay-card.js +30 -0
  9. package/esm/common/relay-cipher.d.ts +15 -0
  10. package/esm/common/relay-cipher.js +62 -2
  11. package/esm/common/relay-content.d.ts +104 -0
  12. package/esm/common/relay-content.js +316 -0
  13. package/esm/common/relay-conversation.d.ts +59 -0
  14. package/esm/common/relay-conversation.js +9 -0
  15. package/esm/common/relay-files.d.ts +108 -0
  16. package/esm/common/relay-files.js +170 -0
  17. package/esm/common/relay-hub-util.d.ts +91 -0
  18. package/esm/common/relay-hub-util.js +164 -0
  19. package/esm/common/relay-hub.d.ts +125 -0
  20. package/esm/common/relay-hub.js +438 -0
  21. package/esm/common/relay-hubs.d.ts +271 -0
  22. package/esm/common/relay-hubs.js +844 -0
  23. package/esm/common/relay-identity.d.ts +46 -0
  24. package/esm/common/relay-identity.js +126 -0
  25. package/esm/common/relay-protocol.d.ts +217 -2
  26. package/esm/common/relay-protocol.js +53 -0
  27. package/esm/common/relay-room-chat.d.ts +80 -0
  28. package/esm/common/relay-room-chat.js +152 -0
  29. package/esm/common/relay-socket.d.ts +8 -0
  30. package/esm/common/relay-socket.js +33 -4
  31. package/esm/guest/guest-i18n.d.ts +47 -0
  32. package/esm/guest/guest-i18n.js +97 -0
  33. package/esm/guest/guest-style.d.ts +1 -0
  34. package/esm/guest/guest-style.js +78 -0
  35. package/esm/guest/guest.d.ts +1 -0
  36. package/esm/guest/guest.js +371 -0
  37. package/esm/node/index.d.ts +3 -0
  38. package/esm/node/index.js +3 -0
  39. package/esm/node/relay-files-host.d.ts +27 -0
  40. package/esm/node/relay-files-host.js +130 -0
  41. package/esm/node/relay-host.d.ts +35 -2
  42. package/esm/node/relay-host.js +150 -13
  43. package/esm/node/relay-hub-files.d.ts +12 -0
  44. package/esm/node/relay-hub-files.js +39 -0
  45. package/esm/node/relay-server.d.ts +46 -1
  46. package/esm/node/relay-server.js +227 -1
  47. package/esm/node/relay-store.d.ts +72 -0
  48. package/esm/node/relay-store.js +123 -2
  49. package/esm/node/relay-viewer.d.ts +7 -0
  50. package/esm/node/relay-viewer.js +33 -0
  51. package/esm/viewer/viewer-i18n.d.ts +56 -0
  52. package/esm/viewer/viewer-i18n.js +117 -0
  53. package/esm/viewer/viewer-markdown.d.ts +7 -0
  54. package/esm/viewer/viewer-markdown.js +198 -0
  55. package/esm/viewer/viewer-style.d.ts +1 -0
  56. package/esm/viewer/viewer-style.js +72 -0
  57. package/esm/viewer/viewer.d.ts +8 -0
  58. package/esm/viewer/viewer.js +378 -0
  59. package/lib/common/index.d.ts +10 -0
  60. package/lib/common/index.js +10 -0
  61. package/lib/common/relay-blobs.d.ts +55 -0
  62. package/lib/common/relay-blobs.js +157 -0
  63. package/lib/common/relay-card.d.ts +24 -0
  64. package/lib/common/relay-card.js +33 -0
  65. package/lib/common/relay-cipher.d.ts +15 -0
  66. package/lib/common/relay-cipher.js +63 -3
  67. package/lib/common/relay-content.d.ts +105 -0
  68. package/lib/common/relay-content.js +320 -0
  69. package/lib/common/relay-conversation.d.ts +60 -0
  70. package/lib/common/relay-conversation.js +12 -0
  71. package/lib/common/relay-files.d.ts +109 -0
  72. package/lib/common/relay-files.js +174 -0
  73. package/lib/common/relay-hub-util.d.ts +92 -0
  74. package/lib/common/relay-hub-util.js +167 -0
  75. package/lib/common/relay-hub.d.ts +126 -0
  76. package/lib/common/relay-hub.js +442 -0
  77. package/lib/common/relay-hubs.d.ts +272 -0
  78. package/lib/common/relay-hubs.js +848 -0
  79. package/lib/common/relay-identity.d.ts +47 -0
  80. package/lib/common/relay-identity.js +129 -0
  81. package/lib/common/relay-protocol.d.ts +217 -2
  82. package/lib/common/relay-protocol.js +54 -1
  83. package/lib/common/relay-room-chat.d.ts +81 -0
  84. package/lib/common/relay-room-chat.js +156 -0
  85. package/lib/common/relay-socket.d.ts +8 -0
  86. package/lib/common/relay-socket.js +32 -3
  87. package/lib/guest/guest-i18n.d.ts +48 -0
  88. package/lib/guest/guest-i18n.js +100 -0
  89. package/lib/guest/guest-style.d.ts +2 -0
  90. package/lib/guest/guest-style.js +81 -0
  91. package/lib/guest/guest.d.ts +2 -0
  92. package/lib/guest/guest.js +373 -0
  93. package/lib/node/index.d.ts +3 -0
  94. package/lib/node/index.js +3 -0
  95. package/lib/node/relay-files-host.d.ts +28 -0
  96. package/lib/node/relay-files-host.js +134 -0
  97. package/lib/node/relay-host.d.ts +35 -2
  98. package/lib/node/relay-host.js +149 -12
  99. package/lib/node/relay-hub-files.d.ts +13 -0
  100. package/lib/node/relay-hub-files.js +43 -0
  101. package/lib/node/relay-server.d.ts +46 -1
  102. package/lib/node/relay-server.js +226 -0
  103. package/lib/node/relay-store.d.ts +72 -0
  104. package/lib/node/relay-store.js +121 -0
  105. package/lib/node/relay-viewer.d.ts +8 -0
  106. package/lib/node/relay-viewer.js +32 -0
  107. package/lib/viewer/viewer-i18n.d.ts +57 -0
  108. package/lib/viewer/viewer-i18n.js +120 -0
  109. package/lib/viewer/viewer-markdown.d.ts +8 -0
  110. package/lib/viewer/viewer-markdown.js +201 -0
  111. package/lib/viewer/viewer-style.d.ts +2 -0
  112. package/lib/viewer/viewer-style.js +75 -0
  113. package/lib/viewer/viewer.d.ts +9 -0
  114. package/lib/viewer/viewer.js +381 -0
  115. package/package.json +5 -4
  116. package/viewer/frame.html +1 -0
  117. package/viewer/page.html +80 -0
  118. package/viewer/room.html +87 -0
@@ -1,33 +1,85 @@
1
1
  import { RelayBytes } from '../common/relay-bytes.js';
2
- import { RelayCipher } from '../common/relay-cipher.js';
2
+ import { RelayCipher, RelayDeflate } from '../common/relay-cipher.js';
3
+ import { RelayFilesUtil } from '../common/relay-files.js';
3
4
  import { RelayPairingUtil } from '../common/relay-pairing.js';
4
5
  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';
6
+ import { RelayFilesHost } from './relay-files-host.js';
7
+ /** Wrong keys (passwords) for a share before it is refused a while, and for how long. */
8
+ const MAX_WRONG_KEYS = 10;
9
+ const WRONG_KEY_WINDOW_MS = 10 * 60 * 1000;
5
10
  const MAX_RECONNECT_DELAY_MS = 30000;
6
11
  const HELLO_TIMEOUT_MS = 10000;
7
- /** A device on a channel: the handshake, then its connection to ta serve. */
12
+ /**
13
+ * A device on a channel: the handshake, then its connection to ta serve — or, for a channel that asked
14
+ * for files (RelayFiles, RelayFilesHost), the file it asks for. What a channel is, it says in its first
15
+ * sealed message; until then nothing of ta serve is opened for it.
16
+ */
8
17
  class RelayChannel {
9
18
  constructor(id, host, options) {
10
19
  this.id = id;
11
20
  this.host = host;
12
21
  this.options = options;
13
22
  this.early = [];
23
+ /** Agreed in the hello of a viewer of content, set once it proved. */
24
+ this.compress = false;
14
25
  this.timer = setTimeout(() => this.close(), HELLO_TIMEOUT_MS);
15
26
  }
16
27
  async receive(text) {
17
- var _a;
28
+ var _a, _b;
18
29
  if (!this.cipher) {
19
30
  await this.hello(text);
20
31
  return;
21
32
  }
33
+ if (this.content && this.candidates) {
34
+ // Whose key it is, the proof says: the relay and the others do not learn who looks.
35
+ const content = this.content;
36
+ for (const candidate of this.candidates) {
37
+ const opened = await candidate.open(text).catch(() => undefined);
38
+ if (opened !== undefined) {
39
+ this.cipher = candidate;
40
+ this.candidates = undefined;
41
+ await this.proven(candidate, content, opened);
42
+ return;
43
+ }
44
+ }
45
+ this.candidates = undefined;
46
+ this.wrongKey(content);
47
+ this.close();
48
+ return;
49
+ }
22
50
  let data;
23
51
  try {
24
52
  data = await this.cipher.open(text);
25
53
  }
26
- catch (_b) {
54
+ catch (_c) {
55
+ if (this.content) {
56
+ this.wrongKey(this.content);
57
+ }
27
58
  this.close();
28
59
  return;
29
60
  }
30
- if (((_a = this.local) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
61
+ if (this.content) {
62
+ await this.proven(this.cipher, this.content, data);
63
+ return;
64
+ }
65
+ if (this.mode === 'share' || this.mode === 'content') {
66
+ // A link hands on what it shares and nothing else: what its holder sends never opens ta serve's socket or files.
67
+ return;
68
+ }
69
+ if (!this.mode) {
70
+ this.mode = RelayFilesUtil.isHello(data) ? 'files' : 'rpc';
71
+ if (this.mode === 'files') {
72
+ this.files = new RelayFilesHost({ localUrl: this.options.localUrl, send: frame => this.sendFrame(frame) });
73
+ }
74
+ else {
75
+ this.connectLocal(this.cipher);
76
+ }
77
+ }
78
+ if (this.mode === 'files') {
79
+ await ((_a = this.files) === null || _a === void 0 ? void 0 : _a.receive(data));
80
+ return;
81
+ }
82
+ if (((_b = this.local) === null || _b === void 0 ? void 0 : _b.readyState) === WebSocket.OPEN) {
31
83
  this.local.send(data);
32
84
  }
33
85
  else {
@@ -36,24 +88,38 @@ class RelayChannel {
36
88
  }
37
89
  /** From the relay: the device is gone. */
38
90
  closed() {
39
- var _a;
91
+ var _a, _b;
40
92
  clearTimeout(this.timer);
41
- (_a = this.local) === null || _a === void 0 ? void 0 : _a.close();
93
+ clearTimeout(this.proofTimer);
94
+ (_a = this.files) === null || _a === void 0 ? void 0 : _a.close();
95
+ (_b = this.local) === null || _b === void 0 ? void 0 : _b.close();
42
96
  }
43
- async hello(text) {
97
+ /** A frame of the files of the workspace, sealed as the rest. */
98
+ sendFrame(frame) {
44
99
  var _a;
100
+ (_a = this.cipher) === null || _a === void 0 ? void 0 : _a.seal(JSON.stringify(frame)).then(sealed => this.host.send({ t: 'data', ch: this.id, d: sealed }));
101
+ }
102
+ async hello(text) {
103
+ var _a, _b, _c;
45
104
  let hello;
46
105
  try {
47
106
  hello = JSON.parse(text);
48
107
  }
49
- catch (_b) {
108
+ catch (_d) {
50
109
  this.close();
51
110
  return;
52
111
  }
53
112
  const valid = hello.t === 'hello' && hello.v === 1 && typeof hello.nonce === 'string';
54
113
  const device = valid ? this.options.store.device(hello.device) : undefined;
55
114
  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;
115
+ const content = valid && !device && !share && this.options.shareContent ? this.options.store.content(hello.device) : undefined;
116
+ if (content && this.host.blocked(content.id)) {
117
+ this.answer({ t: 'refused', reason: 'busy' });
118
+ this.close();
119
+ return;
120
+ }
121
+ const people = (content === null || content === void 0 ? void 0 : content.access) === 'people' ? ((_a = content.people) !== null && _a !== void 0 ? _a : []).map(person => person.key) : undefined;
122
+ const key = (_c = (_b = device === null || device === void 0 ? void 0 : device.key) !== null && _b !== void 0 ? _b : share === null || share === void 0 ? void 0 : share.key) !== null && _c !== void 0 ? _c : ((content === null || content === void 0 ? void 0 : content.access) === 'self' ? undefined : people ? people[0] : content === null || content === void 0 ? void 0 : content.key);
57
123
  if (!key) {
58
124
  this.answer({ t: 'refused', reason: 'This device is not paired.' });
59
125
  this.close();
@@ -63,13 +129,70 @@ class RelayChannel {
63
129
  const nonce = RelayBytes.random(16);
64
130
  const cipher = await RelayCipher.derive(RelayBytes.fromBase64(key), RelayBytes.fromBase64(hello.nonce), nonce, 'host');
65
131
  this.cipher = cipher;
66
- this.answer({ t: 'ready', nonce: RelayBytes.toBase64(nonce), proof: await cipher.seal(RELAY_PROOF) });
132
+ if (people) {
133
+ this.candidates = [
134
+ cipher,
135
+ ...(await Promise.all(people.slice(1).map(other => RelayCipher.derive(RelayBytes.fromBase64(other), RelayBytes.fromBase64(hello.nonce), nonce, 'host')))),
136
+ ];
137
+ }
138
+ if (share) {
139
+ this.mode = 'share';
140
+ }
141
+ const compress = hello.z === 1 && RelayDeflate.supported();
142
+ if (content) {
143
+ // The viewer proves first: what this side seals would let one with the link but not the password try passwords offline.
144
+ this.content = content;
145
+ this.compress = compress;
146
+ // A viewer that never proves would hold one of the places of the devices.
147
+ this.proofTimer = setTimeout(() => this.close(), HELLO_TIMEOUT_MS);
148
+ this.answer({ t: 'ready', nonce: RelayBytes.toBase64(nonce), ...(compress ? { z: 1 } : {}) });
149
+ return;
150
+ }
151
+ const proof = await cipher.seal(RELAY_PROOF);
152
+ // The messages after the proof, both ways: the device sets it once it opened the proof.
153
+ cipher.compress = compress;
154
+ this.answer({ t: 'ready', nonce: RelayBytes.toBase64(nonce), proof, ...(compress ? { z: 1 } : {}) });
67
155
  if (share) {
68
156
  await this.sendShare(cipher, share);
69
157
  }
158
+ }
159
+ /** The first sealed message of a viewer of content: its proof, then the content; a wrong one is counted, and refused. */
160
+ async proven(cipher, content, data) {
161
+ this.content = undefined;
162
+ clearTimeout(this.proofTimer);
163
+ if (data !== RELAY_PROOF) {
164
+ this.wrongKey(content);
165
+ this.close();
166
+ return;
167
+ }
168
+ cipher.compress = this.compress;
169
+ this.mode = 'content';
170
+ const send = async (message) => this.host.send({ t: 'data', ch: this.id, d: await cipher.seal(JSON.stringify(message)) });
171
+ const bytes = this.options.store.content(content.id) ? this.options.store.contentData(content) : undefined;
172
+ if (!bytes) {
173
+ await send({ t: 'error', message: 'This link no longer works: the share was stopped or ran out.' });
174
+ }
70
175
  else {
71
- this.connectLocal(cipher);
176
+ await send({
177
+ t: 'content',
178
+ kind: content.kind,
179
+ title: content.title,
180
+ size: bytes.length,
181
+ createdAt: content.createdAt,
182
+ ...(content.type ? { type: content.type } : {}),
183
+ });
184
+ for (let at = 0; at < bytes.length; at += RELAY_SHARE_CHUNK_BYTES) {
185
+ await send({ t: 'chunk', d: RelayBytes.toBase64(bytes.subarray(at, at + RELAY_SHARE_CHUNK_BYTES)) });
186
+ }
187
+ await send({ t: 'end' });
72
188
  }
189
+ this.close();
190
+ }
191
+ /** The key did not open: told in the clear (the viewer cannot open what is sealed), and counted. */
192
+ wrongKey(content) {
193
+ this.content = undefined;
194
+ this.answer({ t: 'refused', reason: 'key' });
195
+ this.host.wrongKey(content.id);
73
196
  }
74
197
  /** 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
198
  async sendShare(cipher, share) {
@@ -108,6 +231,7 @@ class RelayChannel {
108
231
  }
109
232
  close() {
110
233
  clearTimeout(this.timer);
234
+ clearTimeout(this.proofTimer);
111
235
  this.host.closeChannel(this.id);
112
236
  }
113
237
  }
@@ -122,6 +246,18 @@ export class RelayHost {
122
246
  this.stopped = false;
123
247
  this.attempts = 0;
124
248
  this.channels = new Map();
249
+ /** Wrong keys of each share of content, of late. */
250
+ this.wrong = new Map();
251
+ }
252
+ /** @internal Whether a share of content had too many wrong keys of late. */
253
+ blocked(contentId, now = Date.now()) {
254
+ const wrong = this.wrong.get(contentId);
255
+ return !!wrong && now - wrong.since < WRONG_KEY_WINDOW_MS && wrong.count >= MAX_WRONG_KEYS;
256
+ }
257
+ /** @internal */
258
+ wrongKey(contentId, now = Date.now()) {
259
+ const wrong = this.wrong.get(contentId);
260
+ this.wrong.set(contentId, wrong && now - wrong.since < WRONG_KEY_WINDOW_MS ? { count: wrong.count + 1, since: wrong.since } : { count: 1, since: now });
125
261
  }
126
262
  /** Whether the connection to the relay is open. */
127
263
  get online() {
@@ -136,7 +272,8 @@ export class RelayHost {
136
272
  /** relay.json may have changed: connect if it now has devices, or leave if it has none. */
137
273
  refresh() {
138
274
  const { url, host, devices } = this.options.store.read();
139
- const shared = !!this.options.sharePackage && this.options.store.shares().length > 0;
275
+ const shared = (!!this.options.sharePackage && this.options.store.shares().length > 0) ||
276
+ (!!this.options.shareContent && this.options.store.contents().some(content => content.access !== 'self'));
140
277
  const wanted = !this.stopped && url !== undefined && host !== undefined && (devices.length > 0 || shared);
141
278
  if (!wanted) {
142
279
  this.disconnect();
@@ -0,0 +1,12 @@
1
+ import type { RelayHubsStore, RelayHubsStoreName } from '../common/relay-hubs.js';
2
+ /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
3
+ export declare class RelayHubFiles implements RelayHubsStore {
4
+ readonly agentDir: string;
5
+ constructor(agentDir: string);
6
+ file(name: RelayHubsStoreName): string;
7
+ read<T>(name: RelayHubsStoreName): T | undefined;
8
+ /** Written whole, then renamed over the file, readable by the user alone: it holds keys. */
9
+ write(name: RelayHubsStoreName, value: unknown): void;
10
+ /** The name of a new identity: the user's on this system. */
11
+ static userName(): string;
12
+ }
@@ -0,0 +1,39 @@
1
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { userInfo } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
5
+ export class RelayHubFiles {
6
+ constructor(agentDir) {
7
+ this.agentDir = agentDir;
8
+ }
9
+ file(name) {
10
+ return join(this.agentDir, `${name}.json`);
11
+ }
12
+ read(name) {
13
+ try {
14
+ return JSON.parse(readFileSync(this.file(name), 'utf8'));
15
+ }
16
+ catch (_a) {
17
+ return undefined;
18
+ }
19
+ }
20
+ /** Written whole, then renamed over the file, readable by the user alone: it holds keys. */
21
+ write(name, value) {
22
+ const file = this.file(name);
23
+ mkdirSync(dirname(file), { recursive: true });
24
+ const temporary = `${file}.${process.pid}.tmp`;
25
+ writeFileSync(temporary, `${JSON.stringify(value, undefined, 2)}\n`, { mode: 0o600 });
26
+ chmodSync(temporary, 0o600);
27
+ renameSync(temporary, file);
28
+ }
29
+ /** The name of a new identity: the user's on this system. */
30
+ static userName() {
31
+ try {
32
+ return userInfo().username || 'Ta';
33
+ }
34
+ catch (_a) {
35
+ return 'Ta';
36
+ }
37
+ }
38
+ }
39
+ //# sourceMappingURL=relay-hub-files.js.map
@@ -1,6 +1,8 @@
1
- import { type IncomingMessage, type Server } from 'node:http';
1
+ import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
2
  import type { Duplex } from 'node:stream';
3
3
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
4
+ import { type RelayBlobStorage, RelayBlobs } from '../common/relay-blobs.js';
5
+ import { RelayHub, type RelayHubStorage, type RelayHubWho } from '../common/relay-hub.js';
4
6
  import { RelayRoom } from '../common/relay-room.js';
5
7
  export interface RelayServerOptions {
6
8
  host?: string;
@@ -12,6 +14,37 @@ interface Room {
12
14
  clients: Map<string, WebSocketConnection>;
13
15
  relay: RelayRoom;
14
16
  }
17
+ /** A copy of content in memory, deleted when it runs out. */
18
+ declare class MemoryBlobStorage implements RelayBlobStorage {
19
+ protected readonly values: Map<string, unknown>;
20
+ protected timer?: ReturnType<typeof setTimeout>;
21
+ get<T>(key: string): Promise<T | undefined>;
22
+ put(key: string, value: unknown): Promise<void>;
23
+ deleteAll(): Promise<void>;
24
+ /** No copy is kept: nothing of it need stay in the relay's memory. */
25
+ get empty(): boolean;
26
+ setAlarm(at: number): Promise<void>;
27
+ }
28
+ /** A room in memory, as a Durable Object keeps it. */
29
+ declare class MemoryHubStorage implements RelayHubStorage {
30
+ protected readonly values: Map<string, unknown>;
31
+ get<T>(key: string): Promise<T | undefined>;
32
+ put(key: string, value: unknown): Promise<void>;
33
+ delete(key: string): Promise<boolean>;
34
+ list<T>(options: {
35
+ prefix: string;
36
+ }): Promise<Map<string, T>>;
37
+ deleteAll(): Promise<void>;
38
+ /** No room was made, or it was closed. */
39
+ get empty(): boolean;
40
+ }
41
+ interface Hub {
42
+ hub: RelayHub;
43
+ storage: MemoryHubStorage;
44
+ sockets: Map<WebSocketConnection, {
45
+ who?: RelayHubWho;
46
+ }>;
47
+ }
15
48
  /**
16
49
  * `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
17
50
  * and keeps the hash of each host's secret in memory, for as long as it runs.
@@ -19,14 +52,26 @@ interface Room {
19
52
  export declare class RelayServer {
20
53
  protected readonly options: RelayServerOptions;
21
54
  protected readonly rooms: Map<string, Room>;
55
+ protected readonly blobs: Map<string, {
56
+ blobs: RelayBlobs;
57
+ storage: MemoryBlobStorage;
58
+ pending: number;
59
+ }>;
60
+ protected readonly hubs: Map<string, Hub>;
22
61
  protected server?: Server;
23
62
  constructor(options?: RelayServerOptions);
24
63
  listen(): Promise<string>;
25
64
  close(): Promise<void>;
65
+ /** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
66
+ protected blob(id: string, request: IncomingMessage, response: ServerResponse): Promise<void>;
67
+ /** The body of a request, or undefined past `max` bytes: the rest is read and dropped. */
68
+ protected static body(request: IncomingMessage, max: number): Promise<Buffer<ArrayBuffer> | undefined>;
26
69
  protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void;
27
70
  /** The first host to come with an id keeps it, for as long as the relay runs. */
28
71
  protected openHost(id: string, secret: string, connection: WebSocketConnection): void;
29
72
  protected openClient(id: string, connection: WebSocketConnection): void;
73
+ /** A connection to the hub of a room (RelayHub), kept in memory for as long as the relay runs. */
74
+ protected openHub(id: string, connection: WebSocketConnection): void;
30
75
  protected createRoom(id: string, secretHash: string): Room;
31
76
  protected static same(a: string, b: string): boolean;
32
77
  }
@@ -1,9 +1,71 @@
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, RELAY_SHARE_PAGE, RELAY_SHARE_PATH, RelayCloseCode, } from '../common/relay-protocol.js';
4
+ import { RelayBlobs } from '../common/relay-blobs.js';
5
+ import { RelayHub } from '../common/relay-hub.js';
6
+ import { RELAY_BLOB_PATH, RELAY_CONNECT_PATH, RELAY_CONTENT_PATH, RELAY_FRAME_HEADER_CSP, RELAY_FRAME_PATH, RELAY_HOST_PATH, RELAY_HUB_PATH, RELAY_ID, RELAY_PAIR_PAGE, RELAY_PAIR_PATH, RELAY_ROOM_PATH, RELAY_SHARE_PAGE, RELAY_SHARE_PATH, RELAY_VIEWER_HEADERS, RelayCloseCode, } from '../common/relay-protocol.js';
5
7
  import { RelayRoom } from '../common/relay-room.js';
8
+ import { RelayViewer } from './relay-viewer.js';
6
9
  const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
10
+ /** A copy of content in memory, deleted when it runs out. */
11
+ class MemoryBlobStorage {
12
+ constructor() {
13
+ this.values = new Map();
14
+ }
15
+ async get(key) {
16
+ return this.values.get(key);
17
+ }
18
+ async put(key, value) {
19
+ this.values.set(key, value);
20
+ }
21
+ async deleteAll() {
22
+ this.values.clear();
23
+ clearTimeout(this.timer);
24
+ }
25
+ /** No copy is kept: nothing of it need stay in the relay's memory. */
26
+ get empty() {
27
+ return this.values.size === 0;
28
+ }
29
+ async setAlarm(at) {
30
+ var _a, _b;
31
+ clearTimeout(this.timer);
32
+ // Past the 24 days of a timer, it is found run out on the next read.
33
+ this.timer = setTimeout(() => this.values.clear(), Math.min(Math.max(at - Date.now(), 0), 2 ** 31 - 1));
34
+ (_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
35
+ }
36
+ }
37
+ /** A room in memory, as a Durable Object keeps it. */
38
+ class MemoryHubStorage {
39
+ constructor() {
40
+ this.values = new Map();
41
+ }
42
+ async get(key) {
43
+ const value = this.values.get(key);
44
+ return value === undefined ? undefined : structuredClone(value);
45
+ }
46
+ async put(key, value) {
47
+ this.values.set(key, structuredClone(value));
48
+ }
49
+ async delete(key) {
50
+ return this.values.delete(key);
51
+ }
52
+ async list(options) {
53
+ const found = new Map();
54
+ for (const [key, value] of [...this.values].sort(([a], [b]) => a.localeCompare(b))) {
55
+ if (key.startsWith(options.prefix)) {
56
+ found.set(key, structuredClone(value));
57
+ }
58
+ }
59
+ return found;
60
+ }
61
+ async deleteAll() {
62
+ this.values.clear();
63
+ }
64
+ /** No room was made, or it was closed. */
65
+ get empty() {
66
+ return this.values.size === 0;
67
+ }
68
+ }
7
69
  const peer = (connection) => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
8
70
  /**
9
71
  * `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
@@ -13,11 +75,37 @@ export class RelayServer {
13
75
  constructor(options = {}) {
14
76
  this.options = options;
15
77
  this.rooms = new Map();
78
+ this.blobs = new Map();
79
+ this.hubs = new Map();
16
80
  }
17
81
  listen() {
18
82
  const server = createServer((request, response) => {
19
83
  var _a;
20
84
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split(/[?#]/)[0];
85
+ if (path.startsWith(RELAY_BLOB_PATH)) {
86
+ this.blob(path.slice(RELAY_BLOB_PATH.length), request, response).catch(() => {
87
+ // A request aborted or that failed: an unhandled rejection would end the relay.
88
+ if (!response.headersSent) {
89
+ response.writeHead(400);
90
+ }
91
+ response.end();
92
+ });
93
+ return;
94
+ }
95
+ if (path === RELAY_ROOM_PATH) {
96
+ response.writeHead(200, { ...RELAY_VIEWER_HEADERS, 'x-frame-options': 'DENY' });
97
+ response.end(RelayViewer.room());
98
+ return;
99
+ }
100
+ if (path === RELAY_CONTENT_PATH || path === RELAY_FRAME_PATH) {
101
+ const frame = path === RELAY_FRAME_PATH;
102
+ response.writeHead(200, {
103
+ ...RELAY_VIEWER_HEADERS,
104
+ ...(frame ? { 'content-security-policy': RELAY_FRAME_HEADER_CSP } : { 'x-frame-options': 'DENY' }),
105
+ });
106
+ response.end(frame ? RelayViewer.frame() : RelayViewer.page());
107
+ return;
108
+ }
21
109
  const page = path === RELAY_PAIR_PATH ? RELAY_PAIR_PAGE : path === RELAY_SHARE_PATH ? RELAY_SHARE_PAGE : undefined;
22
110
  response.writeHead(200, { 'content-type': page ? 'text/html; charset=utf-8' : 'text/plain' });
23
111
  response.end(page !== null && page !== void 0 ? page : 'Ta relay\n');
@@ -35,6 +123,12 @@ export class RelayServer {
35
123
  }
36
124
  close() {
37
125
  var _a;
126
+ for (const { sockets } of this.hubs.values()) {
127
+ for (const connection of sockets.keys()) {
128
+ connection.close(1001, 'The relay is stopping.');
129
+ }
130
+ }
131
+ this.hubs.clear();
38
132
  for (const room of this.rooms.values()) {
39
133
  (_a = room.host) === null || _a === void 0 ? void 0 : _a.close(1001, 'The relay is stopping.');
40
134
  for (const client of room.clients.values()) {
@@ -44,6 +138,70 @@ export class RelayServer {
44
138
  this.rooms.clear();
45
139
  return new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
46
140
  }
141
+ /** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
142
+ async blob(id, request, response) {
143
+ var _a;
144
+ if (!RELAY_ID.test(id)) {
145
+ response.writeHead(404).end();
146
+ return;
147
+ }
148
+ const read = await RelayServer.body(request, RelayBlobs.MAX_BYTES);
149
+ if (!read) {
150
+ // Refused before it is all in memory, whatever its content-length said.
151
+ response.writeHead(413, { connection: 'close' }).end('Too large.\n');
152
+ return;
153
+ }
154
+ // Kept only while it holds a copy: requests for ids of no copy leave nothing behind.
155
+ let copy = this.blobs.get(id);
156
+ if (!copy) {
157
+ const storage = new MemoryBlobStorage();
158
+ copy = { blobs: new RelayBlobs(storage), storage, pending: 0 };
159
+ this.blobs.set(id, copy);
160
+ }
161
+ const headers = new Headers();
162
+ for (const [name, value] of Object.entries(request.headers)) {
163
+ if (typeof value === 'string') {
164
+ headers.set(name, value);
165
+ }
166
+ }
167
+ const method = (_a = request.method) !== null && _a !== void 0 ? _a : 'GET';
168
+ const body = read.length && method !== 'GET' && method !== 'HEAD' ? read : undefined;
169
+ copy.pending++;
170
+ let answer;
171
+ try {
172
+ answer = await copy.blobs.handle(new Request(`http://relay${request.url}`, { method, headers, body }));
173
+ }
174
+ finally {
175
+ copy.pending--;
176
+ if (copy.pending === 0 && copy.storage.empty && this.blobs.get(id) === copy) {
177
+ this.blobs.delete(id);
178
+ }
179
+ }
180
+ response.writeHead(answer.status, Object.fromEntries(answer.headers));
181
+ response.end(Buffer.from(await answer.arrayBuffer()));
182
+ }
183
+ /** The body of a request, or undefined past `max` bytes: the rest is read and dropped. */
184
+ static body(request, max) {
185
+ return new Promise((resolve, reject) => {
186
+ const chunks = [];
187
+ let size = 0;
188
+ request.on('data', (chunk) => {
189
+ if (size < 0) {
190
+ return;
191
+ }
192
+ size += chunk.length;
193
+ if (size > max) {
194
+ size = -1;
195
+ chunks.length = 0;
196
+ resolve(undefined);
197
+ return;
198
+ }
199
+ chunks.push(chunk);
200
+ });
201
+ request.on('end', () => size >= 0 && resolve(Buffer.concat(chunks)));
202
+ request.on('error', reject);
203
+ });
204
+ }
47
205
  upgrade(request, socket, head) {
48
206
  var _a, _b;
49
207
  const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://relay');
@@ -52,6 +210,15 @@ export class RelayServer {
52
210
  WebSocketConnection.refuse(socket, checked.status, checked.message);
53
211
  return;
54
212
  }
213
+ if (url.pathname.startsWith(RELAY_HUB_PATH)) {
214
+ const id = url.pathname.slice(RELAY_HUB_PATH.length);
215
+ if (!RELAY_ID.test(id)) {
216
+ WebSocketConnection.refuse(socket, 404, 'Not found.');
217
+ return;
218
+ }
219
+ this.openHub(id, WebSocketConnection.open(socket, checked.key, head, WEBSOCKET));
220
+ return;
221
+ }
55
222
  const [path, id] = url.pathname.startsWith(RELAY_HOST_PATH)
56
223
  ? [RELAY_HOST_PATH, url.pathname.slice(RELAY_HOST_PATH.length)]
57
224
  : [RELAY_CONNECT_PATH, url.pathname.slice(RELAY_CONNECT_PATH.length)];
@@ -107,6 +274,65 @@ export class RelayServer {
107
274
  }
108
275
  });
109
276
  }
277
+ /** A connection to the hub of a room (RelayHub), kept in memory for as long as the relay runs. */
278
+ openHub(id, connection) {
279
+ let hub = this.hubs.get(id);
280
+ if (!hub) {
281
+ const sockets = new Map();
282
+ const socketOf = (other) => {
283
+ var _a;
284
+ const state = (_a = sockets.get(other)) !== null && _a !== void 0 ? _a : {};
285
+ return {
286
+ key: other,
287
+ get who() {
288
+ return state.who;
289
+ },
290
+ set who(who) {
291
+ state.who = who;
292
+ },
293
+ send: text => other.send(text),
294
+ close: (code, reason) => other.close(code, reason),
295
+ };
296
+ };
297
+ const storage = new MemoryHubStorage();
298
+ hub = { sockets, storage, hub: new RelayHub(storage, () => [...sockets.keys()].map(socketOf)) };
299
+ this.hubs.set(id, hub);
300
+ }
301
+ const current = hub;
302
+ const { sockets, hub: relay } = current;
303
+ sockets.set(connection, {});
304
+ let chain = Promise.resolve();
305
+ const socket = {
306
+ key: connection,
307
+ get who() {
308
+ var _a;
309
+ return (_a = sockets.get(connection)) === null || _a === void 0 ? void 0 : _a.who;
310
+ },
311
+ set who(who) {
312
+ const state = sockets.get(connection);
313
+ if (state) {
314
+ state.who = who;
315
+ }
316
+ },
317
+ send: text => connection.send(text),
318
+ close: (code, reason) => connection.close(code, reason),
319
+ };
320
+ connection.onMessage(text => {
321
+ chain = chain.then(() => relay.receive(socket, text)).catch(() => undefined);
322
+ });
323
+ connection.onClose(() => {
324
+ void chain.then(() => {
325
+ if (sockets.has(connection)) {
326
+ relay.closed(socket);
327
+ sockets.delete(connection);
328
+ }
329
+ // Connections to ids of no room (refused, or the room closed) leave nothing behind.
330
+ if (sockets.size === 0 && current.storage.empty && this.hubs.get(id) === current) {
331
+ this.hubs.delete(id);
332
+ }
333
+ });
334
+ });
335
+ }
110
336
  createRoom(id, secretHash) {
111
337
  const room = {
112
338
  secretHash,