@celljs/ta-relay 4.11.0 → 4.13.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 (86) hide show
  1. package/README.en.md +26 -1
  2. package/README.md +26 -1
  3. package/esm/common/index.d.ts +5 -0
  4. package/esm/common/index.js +5 -0
  5. package/esm/common/relay-faces.d.ts +32 -0
  6. package/esm/common/relay-faces.js +208 -0
  7. package/esm/common/relay-friends.d.ts +154 -0
  8. package/esm/common/relay-friends.js +482 -0
  9. package/esm/common/relay-hub-util.d.ts +9 -0
  10. package/esm/common/relay-hub-util.js +19 -2
  11. package/esm/common/relay-hubs-connection.d.ts +110 -0
  12. package/esm/common/relay-hubs-connection.js +508 -0
  13. package/esm/common/relay-hubs-protocol.d.ts +174 -0
  14. package/esm/common/relay-hubs-protocol.js +2 -0
  15. package/esm/common/relay-hubs.d.ts +68 -216
  16. package/esm/common/relay-hubs.js +303 -507
  17. package/esm/common/relay-identity.d.ts +2 -0
  18. package/esm/common/relay-info.d.ts +44 -0
  19. package/esm/common/relay-info.js +94 -0
  20. package/esm/common/relay-protocol.d.ts +7 -3
  21. package/esm/common/relay-protocol.js +7 -3
  22. package/esm/common/relay-room-chat.d.ts +36 -2
  23. package/esm/common/relay-room-chat.js +32 -7
  24. package/esm/common/relay-spot.d.ts +122 -0
  25. package/esm/common/relay-spot.js +179 -0
  26. package/esm/guest/guest-i18n.d.ts +5 -0
  27. package/esm/guest/guest-i18n.js +10 -0
  28. package/esm/guest/guest-style.d.ts +1 -1
  29. package/esm/guest/guest-style.js +11 -4
  30. package/esm/guest/guest.js +39 -18
  31. package/esm/node/index.d.ts +2 -0
  32. package/esm/node/index.js +2 -0
  33. package/esm/node/relay-file-storage.d.ts +32 -0
  34. package/esm/node/relay-file-storage.js +101 -0
  35. package/esm/node/relay-host.d.ts +63 -28
  36. package/esm/node/relay-host.js +145 -52
  37. package/esm/node/relay-hub-files.d.ts +1 -1
  38. package/esm/node/relay-server.d.ts +37 -3
  39. package/esm/node/relay-server.js +193 -37
  40. package/esm/node/relay-store.d.ts +34 -6
  41. package/esm/node/relay-store.js +54 -22
  42. package/esm/node/relays-file.d.ts +139 -0
  43. package/esm/node/relays-file.js +373 -0
  44. package/lib/common/index.d.ts +5 -0
  45. package/lib/common/index.js +5 -0
  46. package/lib/common/relay-faces.d.ts +33 -0
  47. package/lib/common/relay-faces.js +211 -0
  48. package/lib/common/relay-friends.d.ts +155 -0
  49. package/lib/common/relay-friends.js +486 -0
  50. package/lib/common/relay-hub-util.d.ts +9 -0
  51. package/lib/common/relay-hub-util.js +19 -2
  52. package/lib/common/relay-hubs-connection.d.ts +111 -0
  53. package/lib/common/relay-hubs-connection.js +513 -0
  54. package/lib/common/relay-hubs-protocol.d.ts +175 -0
  55. package/lib/common/relay-hubs-protocol.js +3 -0
  56. package/lib/common/relay-hubs.d.ts +68 -216
  57. package/lib/common/relay-hubs.js +311 -515
  58. package/lib/common/relay-identity.d.ts +2 -0
  59. package/lib/common/relay-info.d.ts +45 -0
  60. package/lib/common/relay-info.js +97 -0
  61. package/lib/common/relay-protocol.d.ts +7 -3
  62. package/lib/common/relay-protocol.js +8 -4
  63. package/lib/common/relay-room-chat.d.ts +36 -2
  64. package/lib/common/relay-room-chat.js +32 -7
  65. package/lib/common/relay-spot.d.ts +123 -0
  66. package/lib/common/relay-spot.js +183 -0
  67. package/lib/guest/guest-i18n.d.ts +5 -0
  68. package/lib/guest/guest-i18n.js +10 -0
  69. package/lib/guest/guest-style.d.ts +1 -1
  70. package/lib/guest/guest-style.js +11 -4
  71. package/lib/guest/guest.js +39 -18
  72. package/lib/node/index.d.ts +2 -0
  73. package/lib/node/index.js +2 -0
  74. package/lib/node/relay-file-storage.d.ts +33 -0
  75. package/lib/node/relay-file-storage.js +105 -0
  76. package/lib/node/relay-host.d.ts +63 -28
  77. package/lib/node/relay-host.js +146 -53
  78. package/lib/node/relay-hub-files.d.ts +1 -1
  79. package/lib/node/relay-server.d.ts +37 -3
  80. package/lib/node/relay-server.js +193 -37
  81. package/lib/node/relay-store.d.ts +34 -6
  82. package/lib/node/relay-store.js +54 -22
  83. package/lib/node/relays-file.d.ts +140 -0
  84. package/lib/node/relays-file.js +378 -0
  85. package/package.json +2 -2
  86. package/viewer/room.html +21 -14
@@ -1,52 +1,50 @@
1
- import { RelayHubCloseCode } from './relay-hub.js';
1
+ import { RELAY_FRIENDS_KIND, RelayFriends, RelayFriendsUtil } from './relay-friends.js';
2
2
  import { RelayHubUtil } from './relay-hub-util.js';
3
+ import { Live, OPEN, READY_MS, RelayHubsConnection } from './relay-hubs-connection.js';
3
4
  import { RelayIdentityUtil, RelayKeys } from './relay-identity.js';
4
- import { RelayPairingUtil } from './relay-pairing.js';
5
- import { RELAY_HUB_PATH, RELAY_PING, RELAY_PING_MS, RELAY_PONG, } from './relay-protocol.js';
6
- import { RELAY_CHAT_KEY } from './relay-room-chat.js';
7
- const MAX_RECONNECT_MS = 30000;
8
- const SKEW_MS = 5 * 60 * 1000;
5
+ import { RELAY_FRIENDS_MAX, RELAY_ROOM_MAX_MEMBERS } from './relay-protocol.js';
9
6
  const DAY_MS = 24 * 60 * 60 * 1000;
10
- const READY_MS = 15000;
11
- const MAX_FRIEND_ROOMS = 8;
12
- const OPEN = 1;
13
- /** A room as this Ta holds it while it runs: its connection and what it knows of the room. */
14
- class Live {
15
- constructor(record) {
16
- this.record = record;
17
- this.synced = false;
18
- this.online = new Set();
19
- this.state = new Map();
20
- /** Asks to join, with the invitation each came with. */
21
- this.asks = new Map();
22
- this.done = new Map();
23
- this.ready = [];
24
- this.attempts = 0;
25
- /** Connect again at once, whatever the close said. */
26
- this.retry = false;
27
- this.awaitingPong = false;
28
- /** Events are handled one after another: opening them is async. */
29
- this.chain = Promise.resolve();
30
- }
31
- }
32
7
  /**
33
8
  * The rooms of this Ta (docs/design/ta-link.md 3): its identity and friends, the rooms it made or asked to join,
34
9
  * and a connection to the hub of each while it runs, through which it sends, sets the shared state and hears
35
- * the others; every message signed by its member and sealed with the key of the room.
10
+ * the others; every message signed by its member and sealed with the key of the room. The friends are a room of
11
+ * their own (RelayFriends).
36
12
  */
37
- export class RelayHubs {
38
- constructor(options) {
39
- this.options = options;
40
- this.live = new Map();
41
- this.listeners = new Set();
42
- /** Asks the user was told of while this runs: those the owner finds waiting when it connects are told once. */
43
- this.told = new Set();
44
- this.stopped = true;
45
- this.nextId = 1;
13
+ export class RelayHubs extends RelayHubsConnection {
14
+ constructor() {
15
+ super(...arguments);
16
+ this.book = new RelayFriends({
17
+ identity: () => this.identity(),
18
+ list: () => this.list(),
19
+ ownerOf: room => { var _a; return (_a = this.live.get(room)) === null || _a === void 0 ? void 0 : _a.record.owner.id; },
20
+ memberOf: (room, member) => {
21
+ var _a, _b;
22
+ const found = (_b = (_a = this.live.get(room)) === null || _a === void 0 ? void 0 : _a.roster) === null || _b === void 0 ? void 0 : _b.members.find(each => each.member === member);
23
+ return found && RelayIdentityUtil.publicOf(found);
24
+ },
25
+ asksOf: room => { var _a; var _b; return [...((_b = (_a = this.live.get(room)) === null || _a === void 0 ? void 0 : _a.asks.values()) !== null && _b !== void 0 ? _b : [])].map(ask => ask.body); },
26
+ create: input => this.create(input),
27
+ invite: (room, options) => this.invite(room, options),
28
+ join: link => this.join(link),
29
+ answer: (room, ask, accept) => this.answer(room, ask, accept),
30
+ remove: (room, member) => this.remove(room, member),
31
+ leave: room => this.leave(room),
32
+ getState: (room, prefix) => this.getState(room, prefix),
33
+ setState: (room, key, value) => this.setState(room, key, value),
34
+ offer: (room, member, link) => this.sendBody(this.member(room), { friend: link }, member),
35
+ }, this.options.store, event => this.notify(event));
46
36
  }
47
37
  /** Connects to the rooms of rooms.json, and keeps connected. */
48
38
  start() {
49
39
  this.stopped = false;
40
+ if (!this.options.guest) {
41
+ const migrated = RelayFriendsUtil.migrate(this.readRooms(), this.options.store.read('friends'));
42
+ if (migrated) {
43
+ this.options.store.write('rooms', { rooms: migrated.records });
44
+ this.options.store.write('friends', migrated.book);
45
+ }
46
+ this.book.start();
47
+ }
50
48
  for (const record of this.readRooms()) {
51
49
  const live = new Live(record);
52
50
  this.live.set(record.id, live);
@@ -57,6 +55,7 @@ export class RelayHubs {
57
55
  }
58
56
  stop() {
59
57
  this.stopped = true;
58
+ this.book.stop();
60
59
  for (const live of this.live.values()) {
61
60
  this.disconnect(live);
62
61
  }
@@ -66,22 +65,6 @@ export class RelayHubs {
66
65
  this.listeners.add(listener);
67
66
  return () => this.listeners.delete(listener);
68
67
  }
69
- /** This Ta's identity, made the first time. */
70
- async identity() {
71
- var _a, _b;
72
- if (this.own) {
73
- return this.own;
74
- }
75
- const kept = this.options.store.read('identity');
76
- if (kept && (await RelayIdentityUtil.check(kept))) {
77
- this.own = kept;
78
- return kept;
79
- }
80
- const made = await RelayIdentityUtil.create(((_b = (_a = this.options).name) === null || _b === void 0 ? void 0 : _b.call(_a)) || 'Ta');
81
- this.options.store.write('identity', made);
82
- this.own = made;
83
- return made;
84
- }
85
68
  /** The name others see; the owners of rooms this Ta is in hear it. */
86
69
  async setName(name) {
87
70
  const trimmed = String(name).trim().slice(0, 40);
@@ -92,7 +75,8 @@ export class RelayHubs {
92
75
  this.options.store.write('identity', identity);
93
76
  this.own = identity;
94
77
  for (const live of this.live.values()) {
95
- if (live.record.status !== 'member') {
78
+ // A room joined with another identity keeps that one's name.
79
+ if (live.record.status !== 'member' || live.record.identity) {
96
80
  continue;
97
81
  }
98
82
  if (live.record.own) {
@@ -127,10 +111,11 @@ export class RelayHubs {
127
111
  const now = Date.now();
128
112
  const record = {
129
113
  id: RelayHubUtil.randomId(),
130
- relay: this.options.relay().replace(/\/+$/, ''),
114
+ relay: this.options.relay(typeof input.use === 'string' && input.use ? input.use : undefined).replace(/\/+$/, ''),
131
115
  kind,
132
116
  title,
133
117
  ...(input.view ? { view: String(input.view) } : {}),
118
+ ...(input.unlisted === true ? { unlisted: true } : {}),
134
119
  member: RelayHubUtil.randomId(),
135
120
  token: RelayHubUtil.randomKey(),
136
121
  key: RelayHubUtil.randomKey(),
@@ -160,7 +145,7 @@ export class RelayHubs {
160
145
  var _a;
161
146
  var _b, _c;
162
147
  const live = this.owned(roomId);
163
- const identity = await this.identity();
148
+ const identity = await this.identityOf(live);
164
149
  const linkOf = (invite) => ({
165
150
  link: RelayHubUtil.link({
166
151
  relay: live.record.relay,
@@ -196,10 +181,13 @@ export class RelayHubs {
196
181
  if (link.owner === identity.id) {
197
182
  throw new Error('This is a room of your own.');
198
183
  }
184
+ const friends = RelayFriendsUtil.isKind(link.kind);
199
185
  const record = {
200
186
  id: link.room,
201
187
  relay: link.relay,
202
- kind: '',
188
+ // A room of friends is known as one from its link: its Ta keeps it, whatever the owner says.
189
+ kind: friends ? RELAY_FRIENDS_KIND : '',
190
+ ...(friends ? { unlisted: true } : {}),
203
191
  title: link.title,
204
192
  member: RelayHubUtil.randomId(),
205
193
  token: RelayHubUtil.randomKey(),
@@ -224,6 +212,9 @@ export class RelayHubs {
224
212
  const friends = this.friendIds();
225
213
  const requests = [];
226
214
  for (const live of this.live.values()) {
215
+ if (this.isFriends(live)) {
216
+ continue;
217
+ }
227
218
  for (const ask of live.asks.values()) {
228
219
  requests.push(this.requestOf(live, ask.body, friends));
229
220
  }
@@ -232,6 +223,8 @@ export class RelayHubs {
232
223
  }
233
224
  /** The user's answer to one asking to join: admitted, it gets the key of the room and is in the roster. */
234
225
  async answer(roomId, askId, accept) {
226
+ var _a;
227
+ var _b;
235
228
  const live = this.owned(roomId);
236
229
  const asked = live.asks.get(askId);
237
230
  if (!asked) {
@@ -242,22 +235,23 @@ export class RelayHubs {
242
235
  this.request(live, { t: 'refuse', ask: askId });
243
236
  }
244
237
  else {
245
- const identity = await this.identity();
238
+ const identity = await this.identityOf(live);
246
239
  const body = {
247
240
  key: live.record.key,
248
241
  kind: live.record.kind,
249
242
  title: live.record.title,
250
243
  ...(live.record.view ? { view: live.record.view } : {}),
244
+ ...(live.record.unlisted ? { unlisted: true } : {}),
251
245
  };
252
246
  const ask = asked.body;
247
+ const most = this.isFriends(live) ? RELAY_FRIENDS_MAX + 1 : RELAY_ROOM_MAX_MEMBERS;
248
+ if (((_b = (_a = live.roster) === null || _a === void 0 ? void 0 : _a.members.length) !== null && _b !== void 0 ? _b : 0) >= most) {
249
+ throw new Error('The room is full.');
250
+ }
253
251
  const answer = await RelayHubUtil.sealAnswer(identity, live.record.id, ask, body, asked.invite);
254
252
  const member = { ...RelayIdentityUtil.publicOf(ask), member: ask.member, ...(ask.guest ? { guest: true } : {}), at: Date.now() };
255
253
  const roster = await this.nextRoster(live, members => [...members.filter(other => other.member !== ask.member), member]);
256
254
  this.request(live, { t: 'admit', ask: askId, answer, roster });
257
- // A guest of a browser is no Ta friend: its keys are of that browser alone.
258
- if (!member.guest) {
259
- this.meet(live.record.title, [member]);
260
- }
261
255
  }
262
256
  live.asks.delete(askId);
263
257
  this.emit({ type: 'rooms' });
@@ -312,7 +306,7 @@ export class RelayHubs {
312
306
  throw new Error('A key of 1 to 200 characters is needed.');
313
307
  }
314
308
  await this.ready(live);
315
- const identity = await this.identity();
309
+ const identity = await this.identityOf(live);
316
310
  const keys = live.keys;
317
311
  const d = await RelayHubUtil.seal(keys.seal, identity, live.record.member, { key: name, value: value !== null && value !== void 0 ? value : null });
318
312
  const k = await RelayHubUtil.keyId(keys, name);
@@ -348,14 +342,182 @@ export class RelayHubs {
348
342
  }
349
343
  return { ok: result.ok, version: result.v };
350
344
  }
345
+ /** What makes this Ta who it is in rooms, private keys and all (RelayIdentityBundle): for the user's own computers alone. */
346
+ async exportIdentity() {
347
+ return { identity: await this.identity(), rooms: [...this.live.values()].map(live => live.record), friends: this.book.chosen() };
348
+ }
349
+ /**
350
+ * Takes on the identity of the user's other computer, with its rooms and friends (a move, or the identity shared by
351
+ * sync). Another identity than this Ta's: each room this Ta is in keeps the identity it joined with
352
+ * (RelayRoomRecord.identity), new rooms are the other's. A room this Ta is in as another member is left as it is.
353
+ */
354
+ async importIdentity(bundle, options = {}) {
355
+ const incoming = bundle === null || bundle === void 0 ? void 0 : bundle.identity;
356
+ if (!RelayHubsUtil.isPrivate(incoming) || !(await RelayIdentityUtil.check(incoming))) {
357
+ throw new Error('Not an identity of Ta.');
358
+ }
359
+ const own = await this.identity();
360
+ const switched = incoming.id !== own.id;
361
+ if (switched) {
362
+ for (const live of this.live.values()) {
363
+ if (!live.record.identity) {
364
+ live.record = { ...live.record, identity: own };
365
+ }
366
+ }
367
+ }
368
+ const shared = options.shared || own.shared;
369
+ const next = { ...(switched ? incoming : own), ...(shared ? { shared: true } : {}) };
370
+ if (!shared) {
371
+ delete next.shared;
372
+ }
373
+ this.own = next;
374
+ this.options.store.write('identity', next);
375
+ let rooms = 0;
376
+ for (const record of Array.isArray(bundle.rooms) ? bundle.rooms : []) {
377
+ if (this.upsert(record)) {
378
+ rooms++;
379
+ }
380
+ }
381
+ const friends = this.book.merge(Array.isArray(bundle.friends) ? bundle.friends : []);
382
+ this.save();
383
+ this.emit({ type: 'rooms' });
384
+ return { switched, rooms, friends };
385
+ }
386
+ /** Whether the user's other computers are this Ta too (RelayIdentity.shared). */
387
+ async setShared(shared) {
388
+ const identity = { ...(await this.identity()) };
389
+ if (!!identity.shared === shared) {
390
+ return;
391
+ }
392
+ if (shared) {
393
+ identity.shared = true;
394
+ }
395
+ else {
396
+ delete identity.shared;
397
+ }
398
+ this.own = identity;
399
+ this.options.store.write('identity', identity);
400
+ }
401
+ /**
402
+ * A room as the user's other computer has it: added, or merged with this Ta's record of the same membership
403
+ * (RelayHubsUtil.merge), connected or not as its status says. False when nothing changed, or this Ta is in the room
404
+ * as another member.
405
+ */
406
+ upsert(record) {
407
+ if (!RelayHubsUtil.isRecord(record)) {
408
+ return false;
409
+ }
410
+ const live = this.live.get(record.id);
411
+ if (!live) {
412
+ const added = new Live({ ...record });
413
+ this.live.set(record.id, added);
414
+ if (record.status === 'member' || record.status === 'waiting') {
415
+ this.connect(added);
416
+ }
417
+ this.save();
418
+ this.emit({ type: 'rooms' });
419
+ return true;
420
+ }
421
+ if (live.record.member !== record.member) {
422
+ return false;
423
+ }
424
+ const merged = RelayHubsUtil.merge(live.record, record);
425
+ if (JSON.stringify(merged) === JSON.stringify(live.record)) {
426
+ return false;
427
+ }
428
+ const was = live.record.status;
429
+ live.record = merged;
430
+ if (merged.status !== 'member' && merged.status !== 'waiting') {
431
+ this.disconnect(live);
432
+ }
433
+ else if (was !== merged.status || !live.socket) {
434
+ this.disconnect(live);
435
+ this.connect(live);
436
+ }
437
+ this.save();
438
+ this.emit({ type: 'rooms' });
439
+ return true;
440
+ }
441
+ /** A room the user's other computer left or forgot: forgotten here, without a word to the relay (that computer said it). */
442
+ forget(roomId, member) {
443
+ const live = this.live.get(roomId);
444
+ if (!live || live.record.member !== member) {
445
+ return false;
446
+ }
447
+ this.disconnect(live);
448
+ this.live.delete(roomId);
449
+ this.save();
450
+ this.emit({ type: 'rooms' });
451
+ return true;
452
+ }
453
+ /** Friends of the user's other computer, with those of this Ta. */
454
+ mergeFriends(friends) {
455
+ return this.book.merge(friends);
456
+ }
457
+ /** The friends, with their keys: each in the room of the other (shares to friends are sealed for them). */
351
458
  friends() {
352
- return this.readFriends().sort((a, b) => b.seenAt - a.seenAt);
459
+ return this.book.friends();
460
+ }
461
+ /** The friends and those being added, for the pages. */
462
+ listFriends() {
463
+ return this.book.list();
464
+ }
465
+ /** The room of friends of this Ta, made the first time: other features keep there what they give friends. */
466
+ friendRoom() {
467
+ return this.book.room();
468
+ }
469
+ /** The link (and code) that asks to be the user's friend; with `renew`, a new one, the one before no longer working. */
470
+ friendLink(renew = false) {
471
+ return this.book.link(renew);
472
+ }
473
+ /** Asks the one of a link to be friends, on the user's word. */
474
+ addFriend(link) {
475
+ return this.book.add(link);
353
476
  }
477
+ /** Asks a member of a room the user is in to be friends. */
478
+ offerFriend(roomId, member) {
479
+ return this.book.offer(roomId, member);
480
+ }
481
+ friendRequests() {
482
+ return this.book.requests();
483
+ }
484
+ /** The user's answer to one asking to be friends. */
485
+ answerFriend(id, accept) {
486
+ return this.book.answer(id, accept);
487
+ }
488
+ /** No longer friends, on both sides. */
354
489
  removeFriend(id) {
355
- const friends = this.readFriends();
356
- const left = friends.filter(friend => friend.id !== id);
357
- this.options.store.write('friends', { friends: left });
358
- return left.length !== friends.length;
490
+ return this.book.remove(id);
491
+ }
492
+ isFriends(live) {
493
+ return live.record.own && live.record.kind === RELAY_FRIENDS_KIND;
494
+ }
495
+ friendIds() {
496
+ return this.book.ids();
497
+ }
498
+ heardAsk(live, ask) {
499
+ if (this.isFriends(live)) {
500
+ this.book.asked(ask);
501
+ }
502
+ else {
503
+ super.heardAsk(live, ask);
504
+ }
505
+ }
506
+ heardMembers(members) {
507
+ if (!this.options.guest) {
508
+ this.book.heard(members);
509
+ }
510
+ }
511
+ offered(live, from, link) {
512
+ if (!this.options.guest) {
513
+ this.book.offered(from, link, live.record.title);
514
+ }
515
+ }
516
+ /** What changes the friends: rooms coming and going, members, the links friends leave to join back. */
517
+ after(event) {
518
+ if (!this.options.guest && (event.type === 'rooms' || (event.type === 'state' && event.key.startsWith('back:')))) {
519
+ this.book.changed();
520
+ }
359
521
  }
360
522
  owned(roomId) {
361
523
  const live = this.member(roomId);
@@ -389,6 +551,8 @@ export class RelayHubs {
389
551
  kind: record.kind,
390
552
  title: record.title,
391
553
  ...(record.view ? { view: record.view } : {}),
554
+ ...(record.unlisted ? { unlisted: true } : {}),
555
+ relay: record.relay,
392
556
  owner: record.own,
393
557
  ownerName: record.owner.name,
394
558
  status: record.status,
@@ -399,446 +563,78 @@ export class RelayHubs {
399
563
  ...(record.joinedAt ? { joinedAt: record.joinedAt } : {}),
400
564
  };
401
565
  }
402
- requestOf(live, ask, friends) {
403
- return {
404
- room: live.record.id,
405
- title: live.record.title,
406
- ask: ask.member,
407
- id: ask.id,
408
- name: ask.name,
409
- friend: friends.has(ask.id),
410
- ...(ask.guest ? { guest: true } : {}),
411
- at: ask.at,
412
- };
413
- }
414
- /** Resolves once the room is connected and has its state; rejects after a while. */
415
- ready(live) {
416
- var _a;
417
- if (((_a = live.socket) === null || _a === void 0 ? void 0 : _a.readyState) === OPEN && live.synced) {
418
- return Promise.resolve();
419
- }
420
- return new Promise((resolve, reject) => {
421
- const timer = setTimeout(() => reject(new Error('The room cannot be reached now.')), READY_MS);
422
- live.ready.push(() => {
423
- clearTimeout(timer);
424
- resolve();
425
- });
426
- });
427
- }
428
- request(live, request) {
429
- var _a;
430
- if (((_a = live.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== OPEN) {
431
- throw new Error('The room cannot be reached now.');
432
- }
433
- live.socket.send(JSON.stringify(request));
434
- }
435
- async sendBody(live, body, to) {
436
- await this.ready(live);
437
- const identity = await this.identity();
438
- const d = await RelayHubUtil.seal(live.keys.seal, identity, live.record.member, body);
439
- this.request(live, { t: 'send', d, ...(to ? { to } : {}) });
440
- }
441
- /** The roster with `change` made, its version one more, signed by the owner. */
442
- async nextRoster(live, change) {
443
- var _a, _b;
444
- var _c, _d;
445
- const identity = await this.identity();
446
- const body = { v: ((_c = (_a = live.roster) === null || _a === void 0 ? void 0 : _a.v) !== null && _c !== void 0 ? _c : 0) + 1, members: change((_d = (_b = live.roster) === null || _b === void 0 ? void 0 : _b.members) !== null && _d !== void 0 ? _d : []) };
447
- const d = await RelayHubUtil.seal(live.keys.seal, identity, live.record.member, body);
448
- live.roster = body;
449
- return { v: body.v, d };
450
- }
451
- async writeRoster(live, change) {
452
- await this.ready(live);
453
- this.request(live, { t: 'roster', roster: await this.nextRoster(live, change) });
454
- }
455
- connect(live) {
456
- if (this.stopped) {
457
- return;
458
- }
459
- const { record } = live;
460
- const socket = new WebSocket(RelayPairingUtil.websocketUrl(record.relay, RELAY_HUB_PATH + record.id));
461
- live.socket = socket;
462
- live.synced = false;
463
- socket.onopen = () => {
464
- var _a;
465
- live.attempts = 0;
466
- void this.hello(live, socket);
467
- live.pingTimer = setInterval(() => {
468
- if (live.awaitingPong) {
469
- socket.close(4408, 'The relay did not answer.');
470
- return;
471
- }
472
- live.awaitingPong = true;
473
- socket.send(RELAY_PING);
474
- }, (_a = this.options.pingMs) !== null && _a !== void 0 ? _a : RELAY_PING_MS);
475
- };
476
- socket.onmessage = message => {
477
- const text = String(message.data);
478
- if (text === RELAY_PONG) {
479
- live.awaitingPong = false;
480
- return;
481
- }
482
- live.chain = live.chain.then(() => this.receive(live, text)).catch(() => undefined);
483
- };
484
- socket.onerror = () => undefined;
485
- socket.onclose = event => {
486
- if (live.socket !== socket) {
487
- return;
488
- }
489
- clearInterval(live.pingTimer);
490
- live.socket = undefined;
491
- live.synced = false;
492
- live.awaitingPong = false;
493
- live.online.clear();
494
- void live.chain.then(() => this.closed(live, event.code));
566
+ }
567
+ /** How far a membership has come: one computer heard it end, it ended for both. */
568
+ const STATUS_RANK = { waiting: 0, member: 1, refused: 2, gone: 3 };
569
+ export var RelayHubsUtil;
570
+ (function (RelayHubsUtil) {
571
+ function isPrivate(identity) {
572
+ const value = identity;
573
+ return (!!value &&
574
+ typeof value.id === 'string' &&
575
+ typeof value.name === 'string' &&
576
+ typeof value.sign === 'string' &&
577
+ typeof value.box === 'string' &&
578
+ !!value.signKey &&
579
+ typeof value.signKey === 'object' &&
580
+ !!value.boxKey &&
581
+ typeof value.boxKey === 'object');
582
+ }
583
+ RelayHubsUtil.isPrivate = isPrivate;
584
+ function isRecord(record) {
585
+ const value = record;
586
+ return (!!value &&
587
+ typeof value.id === 'string' &&
588
+ typeof value.relay === 'string' &&
589
+ typeof value.member === 'string' &&
590
+ typeof value.token === 'string' &&
591
+ typeof value.status === 'string' &&
592
+ value.status in STATUS_RANK &&
593
+ !!value.owner &&
594
+ typeof value.owner.id === 'string' &&
595
+ (value.identity === undefined || isPrivate(value.identity)));
596
+ }
597
+ RelayHubsUtil.isRecord = isRecord;
598
+ /**
599
+ * Two records of one membership, as two computers of the user hold it: the further status (one heard it end), the
600
+ * key and the owner's keys once either has them, the invitations of both, made once either made it.
601
+ */
602
+ function merge(local, other) {
603
+ var _a, _b, _c, _d, _e, _f;
604
+ const ahead = STATUS_RANK[other.status] > STATUS_RANK[local.status] ? other : local;
605
+ const behind = ahead === local ? other : local;
606
+ const invites = [...((_a = local.invites) !== null && _a !== void 0 ? _a : []), ...((_b = other.invites) !== null && _b !== void 0 ? _b : [])]
607
+ .filter((invite, index, all) => all.findIndex(each => each.secret === invite.secret) === index)
608
+ .sort((a, b) => a.expiresAt - b.expiresAt)
609
+ .slice(-3);
610
+ const merged = {
611
+ ...behind,
612
+ ...ahead,
613
+ kind: ahead.kind || behind.kind,
614
+ owner: ahead.owner.sign ? ahead.owner : behind.owner.sign ? behind.owner : ahead.owner,
615
+ createdAt: Math.min(local.createdAt, other.createdAt),
495
616
  };
496
- }
497
- async hello(live, socket) {
498
- var _a;
499
- const { record } = live;
500
- let request;
501
- if (record.status === 'waiting') {
502
- request =
503
- record.asked || !record.invite
504
- ? { t: 'wait', ask: record.member, token: record.token }
505
- : {
506
- t: 'ask',
507
- ask: record.member,
508
- token: record.token,
509
- proof: await RelayHubUtil.inviteProof(record.invite),
510
- d: await RelayHubUtil.sealAsk(record.invite, await this.identity(), record.member, Date.now(), !!this.options.guest),
511
- };
617
+ const key = (_c = ahead.key) !== null && _c !== void 0 ? _c : behind.key;
618
+ const joinedAt = Math.max((_d = local.joinedAt) !== null && _d !== void 0 ? _d : 0, (_e = other.joinedAt) !== null && _e !== void 0 ? _e : 0);
619
+ const identity = (_f = local.identity) !== null && _f !== void 0 ? _f : other.identity;
620
+ delete merged.key;
621
+ delete merged.invites;
622
+ delete merged.joinedAt;
623
+ delete merged.identity;
624
+ delete merged.made;
625
+ if (merged.status !== 'waiting') {
626
+ delete merged.invite;
627
+ delete merged.asked;
512
628
  }
513
- else {
514
- (_a = live.keys) !== null && _a !== void 0 ? _a : (live.keys = await RelayHubUtil.keys(record.key));
515
- request = { t: record.own && !record.made ? 'create' : 'auth', member: record.member, token: record.token };
516
- }
517
- if (socket.readyState === OPEN) {
518
- socket.send(JSON.stringify(request));
519
- }
520
- }
521
- closed(live, code) {
522
- var _a;
523
- for (const resolve of live.done.values()) {
524
- resolve({ ok: false, v: 0, error: 'gone' });
525
- }
526
- live.done.clear();
527
- const { record } = live;
528
- this.emit({ type: 'rooms' });
529
- if (this.stopped || this.live.get(record.id) !== live) {
530
- return;
531
- }
532
- if ((code === RelayHubCloseCode.ANSWERED || live.retry) && (record.status === 'member' || record.status === 'waiting')) {
533
- live.retry = false;
534
- this.connect(live);
535
- return;
536
- }
537
- if (code === RelayHubCloseCode.REFUSED || code === RelayHubCloseCode.GONE || code === RelayHubCloseCode.REMOVED || code === RelayHubCloseCode.INVALID) {
538
- return;
539
- }
540
- if (record.status !== 'member' && record.status !== 'waiting') {
541
- return;
542
- }
543
- const delay = Math.min(((_a = this.options.reconnectDelayMs) !== null && _a !== void 0 ? _a : 1000) * 2 ** live.attempts, MAX_RECONNECT_MS);
544
- live.attempts++;
545
- clearTimeout(live.timer);
546
- live.timer = setTimeout(() => this.connect(live), delay);
547
- }
548
- disconnect(live) {
549
- clearTimeout(live.timer);
550
- clearInterval(live.pingTimer);
551
- const socket = live.socket;
552
- live.socket = undefined;
553
- socket === null || socket === void 0 ? void 0 : socket.close(1000, 'Bye.');
554
- }
555
- async receive(live, text) {
556
- var _a;
557
- var _b;
558
- let event;
559
- try {
560
- event = JSON.parse(text);
561
- }
562
- catch (_c) {
563
- return;
564
- }
565
- const { record } = live;
566
- switch (event.t) {
567
- case 'welcome': {
568
- if (record.own && !record.made) {
569
- record.made = true;
570
- this.save();
571
- }
572
- live.online = new Set(event.online);
573
- live.asks.clear();
574
- if (event.roster) {
575
- await this.readRoster(live, event.roster.d);
576
- }
577
- for (const ask of (_b = event.asks) !== null && _b !== void 0 ? _b : []) {
578
- await this.asked(live, ask.d, false);
579
- }
580
- return;
581
- }
582
- case 'entries':
583
- for (const entry of event.entries) {
584
- await this.readEntry(live, entry, false);
585
- }
586
- return;
587
- case 'synced':
588
- live.synced = true;
589
- for (const resolve of live.ready.splice(0)) {
590
- resolve();
591
- }
592
- this.emit({ type: 'rooms' });
593
- return;
594
- case 'state':
595
- await this.readEntry(live, event.entry, true);
596
- return;
597
- case 'msg':
598
- await this.readMessage(live, event.from, event.d);
599
- return;
600
- case 'done':
601
- (_a = live.done.get(event.id)) === null || _a === void 0 ? void 0 : _a({ ok: event.ok, v: event.v, error: event.error });
602
- live.done.delete(event.id);
603
- return;
604
- case 'presence':
605
- if (event.online) {
606
- live.online.add(event.member);
607
- }
608
- else {
609
- live.online.delete(event.member);
610
- }
611
- this.emit({ type: 'rooms' });
612
- return;
613
- case 'roster':
614
- await this.readRoster(live, event.roster.d);
615
- this.emit({ type: 'rooms' });
616
- return;
617
- case 'asked':
618
- await this.asked(live, event.ask.d, true);
619
- return;
620
- case 'left':
621
- live.online.delete(event.member);
622
- if (record.own) {
623
- await this.writeRoster(live, members => members.filter(member => member.member !== event.member)).catch(() => undefined);
624
- }
625
- this.emit({ type: 'rooms' });
626
- return;
627
- case 'waiting':
628
- if (!record.asked) {
629
- record.asked = true;
630
- this.save();
631
- }
632
- this.emit({ type: 'rooms' });
633
- return;
634
- case 'admitted':
635
- await this.admitted(live, event.answer);
636
- return;
637
- case 'refused':
638
- this.setStatus(live, 'refused');
639
- return;
640
- case 'error':
641
- this.failed(live, event.code);
642
- return;
643
- }
644
- }
645
- failed(live, code) {
646
- const { record } = live;
647
- if (code === 'gone') {
648
- this.setStatus(live, 'gone', record.status === 'waiting' ? 'invite' : 'closed');
649
- }
650
- else if (code === 'auth' && record.status === 'member') {
651
- this.setStatus(live, 'gone', 'removed');
652
- }
653
- else if (code === 'invite' || (code === 'exists' && record.status === 'waiting')) {
654
- this.setStatus(live, 'gone', 'invite');
655
- }
656
- else if (code === 'exists' && record.own && !record.made) {
657
- // Made before, its first answer not heard: it is this Ta's, to connect to as a member.
658
- record.made = true;
659
- live.retry = true;
660
- this.save();
661
- }
662
- }
663
- setStatus(live, status, reason) {
664
- live.record = { ...live.record, status, ...(reason ? { reason } : {}) };
665
- if (status !== 'member' && status !== 'waiting') {
666
- delete live.record.key;
667
- delete live.record.invite;
668
- this.disconnect(live);
669
- }
670
- this.save();
671
- this.emit({ type: 'rooms' });
672
- }
673
- async admitted(live, answer) {
674
- const { record } = live;
675
- const opened = record.invite
676
- ? await RelayHubUtil.openAnswer(await this.identity(), record.id, record.member, record.owner.id, answer, record.invite)
677
- : undefined;
678
- if (!opened) {
679
- // Not signed by the owner the link named: whoever answered, it is not that room.
680
- this.setStatus(live, 'gone', 'invite');
681
- return;
682
- }
683
- live.record = {
684
- ...record,
685
- key: opened.body.key,
686
- kind: String(opened.body.kind),
687
- title: String(opened.body.title).slice(0, 80),
688
- ...(opened.body.view ? { view: String(opened.body.view) } : {}),
689
- owner: opened.owner,
690
- status: 'member',
691
- joinedAt: Date.now(),
629
+ return {
630
+ ...merged,
631
+ ...(key && (merged.status === 'member' || merged.status === 'waiting') ? { key } : {}),
632
+ ...(invites.length ? { invites } : {}),
633
+ ...(local.made || other.made ? { made: true } : {}),
634
+ ...(joinedAt ? { joinedAt } : {}),
635
+ ...(identity ? { identity } : {}),
692
636
  };
693
- delete live.record.invite;
694
- delete live.record.asked;
695
- live.keys = await RelayHubUtil.keys(opened.body.key);
696
- this.save();
697
- this.emit({ type: 'rooms' });
698
637
  }
699
- /** An ask to join: told as a request the first time this Ta hears it; `fresh` when it came now, not with the welcome. */
700
- async asked(live, sealed, fresh) {
701
- var _a;
702
- for (const invite of [...((_a = live.record.invites) !== null && _a !== void 0 ? _a : [])].reverse()) {
703
- const ask = await RelayHubUtil.openAsk(invite.secret, sealed);
704
- if (ask) {
705
- live.asks.set(ask.member, { body: ask, invite: invite.secret });
706
- if (fresh || !this.told.has(ask.member)) {
707
- this.told.add(ask.member);
708
- this.emit({ type: 'request', request: this.requestOf(live, ask, this.friendIds()) });
709
- this.emit({ type: 'rooms' });
710
- }
711
- return;
712
- }
713
- }
714
- }
715
- async readRoster(live, sealed) {
716
- var _a;
717
- const owner = live.record.owner;
718
- const keys = (_a = live.keys) !== null && _a !== void 0 ? _a : (live.record.key ? await RelayHubUtil.keys(live.record.key) : undefined);
719
- if (!keys || !owner.sign) {
720
- return;
721
- }
722
- live.keys = keys;
723
- // Signed by the owner alone: its member id is in the roster it signs.
724
- let ownerMember;
725
- const signed = await RelayHubUtil.open(keys.seal, sealed, member => {
726
- ownerMember = member;
727
- return owner.sign;
728
- });
729
- if (!signed || !Array.isArray(signed.b.members) || (live.roster && signed.b.v < live.roster.v)) {
730
- return;
731
- }
732
- const members = signed.b.members.filter(member => member && typeof member.member === 'string');
733
- if (!members.some(member => member.owner && member.member === ownerMember && member.id === owner.id)) {
734
- return;
735
- }
736
- live.roster = { v: signed.b.v, members };
737
- const own = (await this.identity()).id;
738
- this.meet(live.record.title, members.filter(member => member.id !== own && !member.guest));
739
- if (!members.some(member => member.member === live.record.member) && !live.record.own && live.record.status === 'member') {
740
- this.setStatus(live, 'gone', 'removed');
741
- }
742
- }
743
- guestOf(live, member) {
744
- var _a, _b;
745
- return !!((_b = (_a = live.roster) === null || _a === void 0 ? void 0 : _a.members.find(other => other.member === member)) === null || _b === void 0 ? void 0 : _b.guest);
746
- }
747
- signOf(live) {
748
- return member => { var _a, _b; return (_b = (_a = live.roster) === null || _a === void 0 ? void 0 : _a.members.find(other => other.member === member)) === null || _b === void 0 ? void 0 : _b.sign; };
749
- }
750
- async readEntry(live, entry, tell) {
751
- var _a, _b;
752
- if (!live.keys) {
753
- return;
754
- }
755
- const signed = await RelayHubUtil.open(live.keys.seal, entry.d, this.signOf(live));
756
- if (!signed || signed.m !== entry.by || typeof signed.b.key !== 'string' || (await RelayHubUtil.keyId(live.keys, signed.b.key)) !== entry.k) {
757
- return;
758
- }
759
- const before = live.state.get(signed.b.key);
760
- if (before && before.version >= entry.v) {
761
- return;
762
- }
763
- if (this.guestOf(live, entry.by) && !signed.b.key.startsWith(RELAY_CHAT_KEY)) {
764
- // A guest only chats: what else it set is not taken, its version kept, so that setting it again goes on that.
765
- live.state.set(signed.b.key, { value: (_a = before === null || before === void 0 ? void 0 : before.value) !== null && _a !== void 0 ? _a : null, version: entry.v, by: (_b = before === null || before === void 0 ? void 0 : before.by) !== null && _b !== void 0 ? _b : entry.by });
766
- return;
767
- }
768
- live.state.set(signed.b.key, { value: signed.b.value, version: entry.v, by: entry.by });
769
- if (tell) {
770
- this.emit({ type: 'state', room: live.record.id, key: signed.b.key, value: signed.b.value, version: entry.v, by: entry.by });
771
- }
772
- }
773
- async readMessage(live, from, sealed) {
774
- var _a;
775
- var _b;
776
- if (!live.keys) {
777
- return;
778
- }
779
- const signed = await RelayHubUtil.open(live.keys.seal, sealed, this.signOf(live), { skewMs: SKEW_MS });
780
- if (!signed || signed.m !== from) {
781
- return;
782
- }
783
- const sender = (_a = live.roster) === null || _a === void 0 ? void 0 : _a.members.find(member => member.member === from);
784
- if ((sender === null || sender === void 0 ? void 0 : sender.guest) && typeof signed.b.name !== 'string') {
785
- // A guest only chats, in the state: the messages of games are not its.
786
- return;
787
- }
788
- if (typeof signed.b.name === 'string') {
789
- if (live.record.own && sender) {
790
- const name = signed.b.name.trim().slice(0, 40);
791
- await this.writeRoster(live, members => members.map(member => (member.member === from ? { ...member, name } : member))).catch(() => undefined);
792
- }
793
- return;
794
- }
795
- this.emit({ type: 'message', room: live.record.id, from, name: (_b = sender === null || sender === void 0 ? void 0 : sender.name) !== null && _b !== void 0 ? _b : '', data: signed.b.d });
796
- }
797
- /** Those of a room are friends: kept with their keys and the rooms shared. */
798
- meet(title, members) {
799
- if (!members.length) {
800
- return;
801
- }
802
- const friends = this.readFriends();
803
- const now = Date.now();
804
- for (const member of members) {
805
- const known = friends.find(friend => friend.id === member.id);
806
- if (known) {
807
- known.name = member.name;
808
- known.seenAt = now;
809
- known.rooms = [...known.rooms.filter(room => room !== title), title].slice(-MAX_FRIEND_ROOMS);
810
- }
811
- else {
812
- friends.push({ ...RelayIdentityUtil.publicOf(member), rooms: [title], metAt: now, seenAt: now });
813
- }
814
- }
815
- this.options.store.write('friends', { friends });
816
- }
817
- friendIds() {
818
- return new Set(this.readFriends().map(friend => friend.id));
819
- }
820
- readFriends() {
821
- var _a;
822
- const friends = (_a = this.options.store.read('friends')) === null || _a === void 0 ? void 0 : _a.friends;
823
- return Array.isArray(friends) ? friends : [];
824
- }
825
- readRooms() {
826
- var _a;
827
- const rooms = (_a = this.options.store.read('rooms')) === null || _a === void 0 ? void 0 : _a.rooms;
828
- return Array.isArray(rooms) ? rooms : [];
829
- }
830
- save() {
831
- this.options.store.write('rooms', { rooms: [...this.live.values()].map(live => live.record) });
832
- }
833
- emit(event) {
834
- for (const listener of this.listeners) {
835
- try {
836
- listener(event);
837
- }
838
- catch (_a) {
839
- // A listener's failure is its own.
840
- }
841
- }
842
- }
843
- }
638
+ RelayHubsUtil.merge = merge;
639
+ })(RelayHubsUtil || (RelayHubsUtil = {}));
844
640
  //# sourceMappingURL=relay-hubs.js.map