@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
@@ -2,12 +2,17 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RelayServer = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
5
6
  const node_http_1 = require("node:http");
7
+ const node_path_1 = require("node:path");
6
8
  const websocket_connection_1 = require("@celljs/rpc/lib/node/websocket/websocket-connection");
7
9
  const relay_blobs_1 = require("../common/relay-blobs");
8
10
  const relay_hub_1 = require("../common/relay-hub");
11
+ const relay_info_1 = require("../common/relay-info");
9
12
  const relay_protocol_1 = require("../common/relay-protocol");
10
13
  const relay_room_1 = require("../common/relay-room");
14
+ const relay_spot_1 = require("../common/relay-spot");
15
+ const relay_file_storage_1 = require("./relay-file-storage");
11
16
  const relay_viewer_1 = require("./relay-viewer");
12
17
  const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
13
18
  /** A copy of content in memory, deleted when it runs out. */
@@ -79,12 +84,45 @@ class RelayServer {
79
84
  this.options = options;
80
85
  this.rooms = new Map();
81
86
  this.blobs = new Map();
87
+ /** With `data`: the hash of the secret of each host id, kept across restarts. */
88
+ this.claims = new Map();
82
89
  this.hubs = new Map();
90
+ /** Spots of codes (RelaySpot): who is connected, nothing kept. */
91
+ this.spots = new Map();
92
+ /** Codes nobody opened, tried lately, by address (RelaySpotTries). */
93
+ this.spotTries = new Map();
94
+ /** The address each connection to a spot came from. */
95
+ this.spotAddresses = new WeakMap();
96
+ if (options.data) {
97
+ (0, node_fs_1.mkdirSync)(options.data, { recursive: true, mode: 0o700 });
98
+ try {
99
+ for (const [id, hash] of Object.entries(JSON.parse((0, node_fs_1.readFileSync)(this.claimsFile(), 'utf8')))) {
100
+ this.claims.set(id, hash);
101
+ }
102
+ }
103
+ catch (_a) {
104
+ // None yet.
105
+ }
106
+ // Copies and rooms with an alarm set again: one that ran out while the relay was off goes now.
107
+ for (const id of relay_file_storage_1.FileRelayStorage.ids((0, node_path_1.join)(options.data, 'blobs'))) {
108
+ this.blobCopy(id);
109
+ }
110
+ for (const id of relay_file_storage_1.FileRelayStorage.ids((0, node_path_1.join)(options.data, 'hubs'))) {
111
+ this.hubOf(id);
112
+ }
113
+ }
83
114
  }
84
115
  listen() {
85
116
  const server = (0, node_http_1.createServer)((request, response) => {
86
117
  var _a;
87
118
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split(/[?#]/)[0];
119
+ if (path === relay_info_1.RELAY_INFO_PATH) {
120
+ // Without a directory for its data, rooms and copies live in memory: gone when the relay restarts.
121
+ const info = relay_info_1.RelayInfoUtil.of(!!this.options.data);
122
+ response.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*', 'cache-control': 'no-store' });
123
+ response.end(JSON.stringify(info));
124
+ return;
125
+ }
88
126
  if (path.startsWith(relay_protocol_1.RELAY_BLOB_PATH)) {
89
127
  this.blob(path.slice(relay_protocol_1.RELAY_BLOB_PATH.length), request, response).catch(() => {
90
128
  // A request aborted or that failed: an unhandled rejection would end the relay.
@@ -125,15 +163,27 @@ class RelayServer {
125
163
  });
126
164
  }
127
165
  close() {
128
- var _a;
166
+ var _a, _b, _c, _d, _e;
129
167
  for (const { sockets } of this.hubs.values()) {
130
168
  for (const connection of sockets.keys()) {
131
169
  connection.close(1001, 'The relay is stopping.');
132
170
  }
133
171
  }
172
+ for (const { storage } of this.hubs.values()) {
173
+ (_b = (_a = storage).close) === null || _b === void 0 ? void 0 : _b.call(_a);
174
+ }
175
+ for (const { storage } of this.blobs.values()) {
176
+ (_d = (_c = storage).close) === null || _d === void 0 ? void 0 : _d.call(_c);
177
+ }
134
178
  this.hubs.clear();
179
+ for (const { sockets } of this.spots.values()) {
180
+ for (const connection of sockets.keys()) {
181
+ connection.close(1001, 'The relay is stopping.');
182
+ }
183
+ }
184
+ this.spots.clear();
135
185
  for (const room of this.rooms.values()) {
136
- (_a = room.host) === null || _a === void 0 ? void 0 : _a.close(1001, 'The relay is stopping.');
186
+ (_e = room.host) === null || _e === void 0 ? void 0 : _e.close(1001, 'The relay is stopping.');
137
187
  for (const client of room.clients.values()) {
138
188
  client.close(1001, 'The relay is stopping.');
139
189
  }
@@ -155,12 +205,7 @@ class RelayServer {
155
205
  return;
156
206
  }
157
207
  // Kept only while it holds a copy: requests for ids of no copy leave nothing behind.
158
- let copy = this.blobs.get(id);
159
- if (!copy) {
160
- const storage = new MemoryBlobStorage();
161
- copy = { blobs: new relay_blobs_1.RelayBlobs(storage), storage, pending: 0 };
162
- this.blobs.set(id, copy);
163
- }
208
+ const copy = this.blobCopy(id);
164
209
  const headers = new Headers();
165
210
  for (const [name, value] of Object.entries(request.headers)) {
166
211
  if (typeof value === 'string') {
@@ -183,6 +228,35 @@ class RelayServer {
183
228
  response.writeHead(answer.status, Object.fromEntries(answer.headers));
184
229
  response.end(Buffer.from(await answer.arrayBuffer()));
185
230
  }
231
+ blobCopy(id) {
232
+ let copy = this.blobs.get(id);
233
+ if (!copy) {
234
+ const data = this.options.data;
235
+ const made = { pending: 0 };
236
+ const storage = data
237
+ ? new relay_file_storage_1.FileRelayStorage((0, node_path_1.join)(data, 'blobs', id), () => {
238
+ var _a;
239
+ void ((_a = made.storage) === null || _a === void 0 ? void 0 : _a.deleteAll().then(() => this.blobs.get(id) === copy && this.blobs.delete(id)));
240
+ })
241
+ : new MemoryBlobStorage();
242
+ made.storage = storage;
243
+ made.blobs = new relay_blobs_1.RelayBlobs(storage);
244
+ copy = made;
245
+ this.blobs.set(id, copy);
246
+ }
247
+ return copy;
248
+ }
249
+ claimsFile() {
250
+ return (0, node_path_1.join)(this.options.data, 'hosts.json');
251
+ }
252
+ saveClaims() {
253
+ if (!this.options.data) {
254
+ return;
255
+ }
256
+ const file = this.claimsFile();
257
+ (0, node_fs_1.writeFileSync)(`${file}.tmp`, JSON.stringify(Object.fromEntries(this.claims)), { mode: 0o600 });
258
+ (0, node_fs_1.renameSync)(`${file}.tmp`, file);
259
+ }
186
260
  /** The body of a request, or undefined past `max` bytes: the rest is read and dropped. */
187
261
  static body(request, max) {
188
262
  return new Promise((resolve, reject) => {
@@ -206,7 +280,7 @@ class RelayServer {
206
280
  });
207
281
  }
208
282
  upgrade(request, socket, head) {
209
- var _a, _b;
283
+ var _a, _b, _c;
210
284
  const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://relay');
211
285
  const checked = websocket_connection_1.WebSocketConnection.check(request);
212
286
  if ('status' in checked) {
@@ -222,6 +296,22 @@ class RelayServer {
222
296
  this.openHub(id, websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, WEBSOCKET));
223
297
  return;
224
298
  }
299
+ if (url.pathname.startsWith(relay_spot_1.RELAY_SPOT_PATH)) {
300
+ const id = url.pathname.slice(relay_spot_1.RELAY_SPOT_PATH.length);
301
+ if (!relay_protocol_1.RELAY_ID.test(id)) {
302
+ websocket_connection_1.WebSocketConnection.refuse(socket, 404, 'Not found.');
303
+ return;
304
+ }
305
+ const address = relay_spot_1.RelaySpotTries.keyOf(request.socket.remoteAddress);
306
+ const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, WEBSOCKET);
307
+ const fails = relay_spot_1.RelaySpotTries.recent((_b = this.spotTries.get(address)) !== null && _b !== void 0 ? _b : [], Date.now());
308
+ if (relay_spot_1.RelaySpotTries.blocked(fails, Date.now())) {
309
+ connection.close(relay_spot_1.RelaySpotCloseCode.TRIES, 'Too many codes tried.');
310
+ return;
311
+ }
312
+ this.openSpot(id, connection, address);
313
+ return;
314
+ }
225
315
  const [path, id] = url.pathname.startsWith(relay_protocol_1.RELAY_HOST_PATH)
226
316
  ? [relay_protocol_1.RELAY_HOST_PATH, url.pathname.slice(relay_protocol_1.RELAY_HOST_PATH.length)]
227
317
  : [relay_protocol_1.RELAY_CONNECT_PATH, url.pathname.slice(relay_protocol_1.RELAY_CONNECT_PATH.length)];
@@ -231,17 +321,21 @@ class RelayServer {
231
321
  }
232
322
  const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, WEBSOCKET);
233
323
  if (path === relay_protocol_1.RELAY_HOST_PATH) {
234
- this.openHost(id, (_b = url.searchParams.get('secret')) !== null && _b !== void 0 ? _b : '', connection);
324
+ this.openHost(id, (_c = url.searchParams.get('secret')) !== null && _c !== void 0 ? _c : '', connection);
235
325
  }
236
326
  else {
237
327
  this.openClient(id, connection);
238
328
  }
239
329
  }
240
- /** The first host to come with an id keeps it, for as long as the relay runs. */
330
+ /** The first host to come with an id keeps it, for as long as the relay runs, or for good with `data`. */
241
331
  openHost(id, secret, connection) {
242
- var _a;
332
+ var _a, _b;
243
333
  const hash = (0, node_crypto_1.createHash)('sha256').update(secret).digest('base64url');
244
- const room = (_a = this.rooms.get(id)) !== null && _a !== void 0 ? _a : this.createRoom(id, hash);
334
+ if (secret.length >= 32 && !this.claims.has(id) && this.options.data) {
335
+ this.claims.set(id, hash);
336
+ this.saveClaims();
337
+ }
338
+ const room = (_a = this.rooms.get(id)) !== null && _a !== void 0 ? _a : this.createRoom(id, (_b = this.claims.get(id)) !== null && _b !== void 0 ? _b : hash);
245
339
  if (secret.length < 32 || !RelayServer.same(room.secretHash, hash)) {
246
340
  connection.close(relay_protocol_1.RelayCloseCode.REFUSED, 'Refused.');
247
341
  return;
@@ -277,31 +371,58 @@ class RelayServer {
277
371
  }
278
372
  });
279
373
  }
280
- /** A connection to the hub of a room (RelayHub), kept in memory for as long as the relay runs. */
281
- openHub(id, connection) {
282
- let hub = this.hubs.get(id);
283
- if (!hub) {
374
+ /** A connection to a spot of a code (RelaySpot): in memory, gone with the last one. */
375
+ openSpot(id, connection, address) {
376
+ let current = this.spots.get(id);
377
+ if (!current) {
284
378
  const sockets = new Map();
285
- const socketOf = (other) => {
286
- var _a;
287
- const state = (_a = sockets.get(other)) !== null && _a !== void 0 ? _a : {};
288
- return {
289
- key: other,
290
- get who() {
291
- return state.who;
292
- },
293
- set who(who) {
379
+ const socketOf = (other) => ({
380
+ key: other,
381
+ get who() {
382
+ var _a;
383
+ return (_a = sockets.get(other)) === null || _a === void 0 ? void 0 : _a.who;
384
+ },
385
+ set who(who) {
386
+ const state = sockets.get(other);
387
+ if (state) {
294
388
  state.who = who;
295
- },
296
- send: text => other.send(text),
297
- close: (code, reason) => other.close(code, reason),
298
- };
389
+ }
390
+ },
391
+ send: text => other.send(text),
392
+ close: (code, reason) => other.close(code, reason),
393
+ });
394
+ const missed = (socket) => {
395
+ var _a, _b;
396
+ const key = (_a = this.spotAddresses.get(socket.key)) !== null && _a !== void 0 ? _a : 'unknown';
397
+ const now = Date.now();
398
+ this.spotTries.set(key, [...relay_spot_1.RelaySpotTries.recent((_b = this.spotTries.get(key)) !== null && _b !== void 0 ? _b : [], now), now]);
399
+ for (const [other, fails] of this.spotTries) {
400
+ if (!relay_spot_1.RelaySpotTries.recent(fails, now).length) {
401
+ this.spotTries.delete(other);
402
+ }
403
+ }
299
404
  };
300
- const storage = new MemoryHubStorage();
301
- hub = { sockets, storage, hub: new relay_hub_1.RelayHub(storage, () => [...sockets.keys()].map(socketOf)) };
302
- this.hubs.set(id, hub);
405
+ current = { sockets, socketOf, spot: new relay_spot_1.RelaySpot(() => [...sockets.keys()].map(socketOf), Date.now, missed) };
406
+ this.spots.set(id, current);
303
407
  }
304
- const current = hub;
408
+ const { sockets, spot } = current;
409
+ sockets.set(connection, {});
410
+ this.spotAddresses.set(connection, address);
411
+ const socket = current.socketOf(connection);
412
+ connection.onMessage(text => spot.receive(socket, text));
413
+ connection.onClose(() => {
414
+ if (sockets.has(connection)) {
415
+ spot.closed(socket);
416
+ sockets.delete(connection);
417
+ }
418
+ if (sockets.size === 0 && this.spots.get(id) === current) {
419
+ this.spots.delete(id);
420
+ }
421
+ });
422
+ }
423
+ /** A connection to the hub of a room (RelayHub), kept in memory for as long as the relay runs. */
424
+ openHub(id, connection) {
425
+ const current = this.hubOf(id);
305
426
  const { sockets, hub: relay } = current;
306
427
  sockets.set(connection, {});
307
428
  let chain = Promise.resolve();
@@ -330,12 +451,47 @@ class RelayServer {
330
451
  sockets.delete(connection);
331
452
  }
332
453
  // Connections to ids of no room (refused, or the room closed) leave nothing behind.
333
- if (sockets.size === 0 && current.storage.empty && this.hubs.get(id) === current) {
334
- this.hubs.delete(id);
335
- }
454
+ this.dropHub(id, current);
336
455
  });
337
456
  });
338
457
  }
458
+ /** The hub of a room: in memory, or read from `data` when it was kept. */
459
+ hubOf(id) {
460
+ let hub = this.hubs.get(id);
461
+ if (!hub) {
462
+ const sockets = new Map();
463
+ const socketOf = (other) => {
464
+ var _a;
465
+ const state = (_a = sockets.get(other)) !== null && _a !== void 0 ? _a : {};
466
+ return {
467
+ key: other,
468
+ get who() {
469
+ return state.who;
470
+ },
471
+ set who(who) {
472
+ state.who = who;
473
+ },
474
+ send: text => other.send(text),
475
+ close: (code, reason) => other.close(code, reason),
476
+ };
477
+ };
478
+ const made = { sockets };
479
+ const storage = this.options.data
480
+ ? new relay_file_storage_1.FileRelayStorage((0, node_path_1.join)(this.options.data, 'hubs', id), () => { var _a; return void ((_a = made.hub) === null || _a === void 0 ? void 0 : _a.alarm().then(() => this.dropHub(id, made))); })
481
+ : new MemoryHubStorage();
482
+ made.storage = storage;
483
+ made.hub = new relay_hub_1.RelayHub(storage, () => [...sockets.keys()].map(socketOf));
484
+ hub = made;
485
+ this.hubs.set(id, hub);
486
+ }
487
+ return hub;
488
+ }
489
+ /** A room nobody holds any more, its storage empty: forgotten. */
490
+ dropHub(id, hub) {
491
+ if (hub && hub.sockets.size === 0 && hub.storage.empty && this.hubs.get(id) === hub) {
492
+ this.hubs.delete(id);
493
+ }
494
+ }
339
495
  createRoom(id, secretHash) {
340
496
  const room = {
341
497
  secretHash,
@@ -5,13 +5,21 @@ import type { RelayShareLink } from '../common/relay-share';
5
5
  export interface RelayDevice {
6
6
  id: string;
7
7
  name: string;
8
+ /** The relay it reaches this ta serve through; none: RelayConfig.url, as before devices kept theirs. */
9
+ relay?: string;
8
10
  /** base64url, 32 bytes: what the device and ta serve encrypt with. */
9
11
  key: string;
10
12
  createdAt: number;
13
+ /** One let in by the user, not the user's own device: the principal its calls are made as (docs/design/ta-team.md). */
14
+ member?: string;
15
+ /** No longer reaches this ta serve from then on: a link of invitation. */
16
+ expiresAt?: number;
11
17
  }
12
18
  /** A package handed on by a link: whoever has the link takes it from this ta serve while the share lasts. */
13
19
  export interface RelayShare {
14
20
  id: string;
21
+ /** The relay of its link; none: RelayConfig.url. */
22
+ relay?: string;
15
23
  /** base64url, 32 bytes. */
16
24
  key: string;
17
25
  /** The directory of the package. */
@@ -26,6 +34,8 @@ export interface RelayShare {
26
34
  */
27
35
  export interface RelayContentShare extends RelayContentHeader {
28
36
  id: string;
37
+ /** The relay of its link and its offline copy; none: RelayConfig.url. */
38
+ relay?: string;
29
39
  access: RelayContentAccess;
30
40
  /** base64url, 32 bytes: what the content is sealed with (with a password, derived from it and the key of the link). */
31
41
  key: string;
@@ -57,13 +67,18 @@ export interface RelayContentInput extends RelayContentHeader {
57
67
  /** None or 0: until stopped (not with `offline`, which is RELAY_BLOB_MAX_DAYS at most). */
58
68
  days?: number;
59
69
  offline?: boolean;
70
+ /** The relay of its link (relays.json's `share`); default the relay of the devices. */
71
+ relay?: string;
60
72
  /** For `people`: the Ta friends it is shared with, and this Ta's identity. */
61
73
  people?: RelayPublicIdentity[];
62
74
  identity?: RelayIdentity;
63
75
  }
64
- /** relay.json in the agent directory. Without devices, ta serve does not connect to the relay. */
76
+ /**
77
+ * relay.json in the agent directory: what this ta serve has on relays (its id there, the devices, the links), not which
78
+ * relay to use (relays.json). Without devices or links, ta serve connects to no relay.
79
+ */
65
80
  export interface RelayConfig {
66
- /** The relay, without a trailing slash. */
81
+ /** The relay of what names none of its own (made before each kept its relay), without a trailing slash. */
67
82
  url?: string;
68
83
  /** This ta serve at the relay: the id is public, the secret keeps another host from taking it. */
69
84
  host?: {
@@ -75,6 +90,8 @@ export interface RelayConfig {
75
90
  shares?: RelayShare[];
76
91
  /** Content shared; those past their time are dropped, with their bytes, when it is written. */
77
92
  contents?: RelayContentShare[];
93
+ /** `false`: ta serve lets the computer sleep while idle, also while a device uses it (KeepAwake in ta-host); kept only when false. */
94
+ keepAwake?: boolean;
78
95
  }
79
96
  /** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
80
97
  export declare class RelayStore {
@@ -83,7 +100,12 @@ export declare class RelayStore {
83
100
  constructor(agentDir: string);
84
101
  get file(): string;
85
102
  read(): RelayConfig;
86
- device(deviceId: string): RelayDevice | undefined;
103
+ /** A device paired, by its id: none once it expired. */
104
+ device(deviceId: string, now?: number): RelayDevice | undefined;
105
+ /** The relay of a device, a link or content shared: its own, else the one of relay.json, else the official one. */
106
+ static relayOf(item: {
107
+ relay?: string;
108
+ }, config: Pick<RelayConfig, 'url'>): string;
87
109
  /** A share still on, by its id. */
88
110
  share(shareId: string, now?: number): RelayShare | undefined;
89
111
  /** The shares still on. */
@@ -119,14 +141,20 @@ export declare class RelayStore {
119
141
  * A link of the package in `root`: the one of before while it lasts, else a new one for RELAY_SHARE_DAYS,
120
142
  * on the relay of the devices (the default one when there is none), which this ta serve then connects to.
121
143
  */
122
- shareRoot(root: string, name: string, now?: number): {
144
+ shareRoot(root: string, name: string, now?: number, relay?: string): {
123
145
  link: RelayShareLink;
124
146
  share: RelayShare;
125
147
  };
126
148
  /** Stops the shares of a package: their links no longer work. False when there were none. */
127
149
  unshareRoot(root: string): boolean;
128
- /** A new device for this relay; another relay than before unpairs the devices of the old one. */
129
- pair(relay: string, deviceName: string): RelayPairing;
150
+ /**
151
+ * A new device, through this relay; the devices of other relays stay on theirs, and this ta serve is connected to
152
+ * each relay that has one (docs/design/ta-relays.md). `member`: a device of one the user let in, not their own;
153
+ * `expiresAt`: it reaches this ta serve until then. Devices expired are dropped as a new one is added.
154
+ */
155
+ pair(relay: string, deviceName: string, options?: Pick<RelayDevice, 'member' | 'expiresAt'>): RelayPairing;
156
+ /** Whether ta serve keeps the computer awake for the devices (RelayConfig.keepAwake). */
157
+ setKeepAwake(on: boolean): void;
130
158
  /** False when there was no such device. */
131
159
  remove(deviceId: string): boolean;
132
160
  /** What the relay keeps of the host's secret. */
@@ -27,14 +27,21 @@ class RelayStore {
27
27
  devices: Array.isArray(config.devices) ? config.devices : [],
28
28
  shares: Array.isArray(config.shares) ? config.shares : [],
29
29
  contents: Array.isArray(config.contents) ? config.contents : [],
30
+ ...(config.keepAwake === false ? { keepAwake: false } : {}),
30
31
  };
31
32
  }
32
33
  catch (_a) {
33
34
  return { devices: [] };
34
35
  }
35
36
  }
36
- device(deviceId) {
37
- return this.read().devices.find(device => device.id === deviceId);
37
+ /** A device paired, by its id: none once it expired. */
38
+ device(deviceId, now = Date.now()) {
39
+ return this.read().devices.find(device => device.id === deviceId && !(device.expiresAt !== undefined && device.expiresAt <= now));
40
+ }
41
+ /** The relay of a device, a link or content shared: its own, else the one of relay.json, else the official one. */
42
+ static relayOf(item, config) {
43
+ var _a, _b;
44
+ return (_b = (_a = item.relay) !== null && _a !== void 0 ? _a : config.url) !== null && _b !== void 0 ? _b : relay_protocol_1.RELAY_DEFAULT_URL;
38
45
  }
39
46
  /** A share still on, by its id. */
40
47
  share(shareId, now = Date.now()) {
@@ -69,7 +76,7 @@ class RelayStore {
69
76
  * none), which this ta serve then connects to for any but `self`.
70
77
  */
71
78
  async addContent(input, now = Date.now()) {
72
- var _a, _b, _c;
79
+ var _a, _b, _c, _d, _e;
73
80
  const linkKey = (0, node_crypto_1.randomBytes)(32);
74
81
  const id = (0, node_crypto_1.randomBytes)(16).toString('base64url');
75
82
  const password = input.access === 'password' ? input.password : undefined;
@@ -81,8 +88,11 @@ class RelayStore {
81
88
  const days = input.offline ? Math.min(input.days || relay_protocol_1.RELAY_BLOB_MAX_DAYS, relay_protocol_1.RELAY_BLOB_MAX_DAYS) : input.days;
82
89
  const expiresAt = days ? now + days * 24 * 60 * 60 * 1000 : undefined;
83
90
  const offline = input.offline && input.access !== 'self' && input.access !== 'people';
91
+ const before = this.read();
92
+ const relay = ((_b = (_a = input.relay) !== null && _a !== void 0 ? _a : before.url) !== null && _b !== void 0 ? _b : relay_protocol_1.RELAY_DEFAULT_URL).replace(/\/+$/, '');
84
93
  const content = {
85
94
  id,
95
+ relay,
86
96
  kind: input.kind,
87
97
  title: input.title,
88
98
  createdAt: input.createdAt,
@@ -97,19 +107,18 @@ class RelayStore {
97
107
  };
98
108
  (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(this.contentFile(id)), { recursive: true, mode: 0o700 });
99
109
  (0, node_fs_1.writeFileSync)(this.contentFile(id), input.data, { mode: 0o600 });
100
- const before = this.read();
101
- const url = (_a = before.url) !== null && _a !== void 0 ? _a : relay_protocol_1.RELAY_DEFAULT_URL;
102
- const host = (_b = before.host) !== null && _b !== void 0 ? _b : { id: RelayStore.id(), secret: (0, node_crypto_1.randomBytes)(32).toString('base64url') };
103
- this.write({ ...before, url, host, contents: [...((_c = before.contents) !== null && _c !== void 0 ? _c : []), content] });
110
+ const url = (_c = before.url) !== null && _c !== void 0 ? _c : relay;
111
+ const host = (_d = before.host) !== null && _d !== void 0 ? _d : { id: RelayStore.id(), secret: (0, node_crypto_1.randomBytes)(32).toString('base64url') };
112
+ this.write({ ...before, url, host, contents: [...((_e = before.contents) !== null && _e !== void 0 ? _e : []), content] });
104
113
  return { content, link: this.contentLink(content, { url, host }) };
105
114
  }
106
115
  /** The link of content shared here. */
107
116
  contentLink(content, config = this.read()) {
108
117
  var _a;
109
- var _b, _c;
118
+ var _b;
110
119
  return {
111
- relay: (_b = config.url) !== null && _b !== void 0 ? _b : relay_protocol_1.RELAY_DEFAULT_URL,
112
- host: (_c = (_a = config.host) === null || _a === void 0 ? void 0 : _a.id) !== null && _c !== void 0 ? _c : '',
120
+ relay: RelayStore.relayOf(content, config),
121
+ host: (_b = (_a = config.host) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : '',
113
122
  share: content.id,
114
123
  key: content.linkKey,
115
124
  access: content.access,
@@ -158,16 +167,18 @@ class RelayStore {
158
167
  * A link of the package in `root`: the one of before while it lasts, else a new one for RELAY_SHARE_DAYS,
159
168
  * on the relay of the devices (the default one when there is none), which this ta serve then connects to.
160
169
  */
161
- shareRoot(root, name, now = Date.now()) {
162
- var _a, _b, _c;
170
+ shareRoot(root, name, now = Date.now(), relay) {
171
+ var _a, _b, _c, _d;
163
172
  const before = this.read();
164
- const url = (_a = before.url) !== null && _a !== void 0 ? _a : relay_protocol_1.RELAY_DEFAULT_URL;
165
- const host = (_b = before.host) !== null && _b !== void 0 ? _b : { id: id(), secret: (0, node_crypto_1.randomBytes)(32).toString('base64url') };
166
- const live = ((_c = before.shares) !== null && _c !== void 0 ? _c : []).filter(share => share.expiresAt > now);
167
- let share = live.find(candidate => candidate.root === root);
173
+ const wanted = ((_a = relay !== null && relay !== void 0 ? relay : before.url) !== null && _a !== void 0 ? _a : relay_protocol_1.RELAY_DEFAULT_URL).replace(/\/+$/, '');
174
+ const url = (_b = before.url) !== null && _b !== void 0 ? _b : wanted;
175
+ const host = (_c = before.host) !== null && _c !== void 0 ? _c : { id: id(), secret: (0, node_crypto_1.randomBytes)(32).toString('base64url') };
176
+ const live = ((_d = before.shares) !== null && _d !== void 0 ? _d : []).filter(share => share.expiresAt > now);
177
+ let share = live.find(candidate => candidate.root === root && RelayStore.relayOf(candidate, before) === wanted);
168
178
  if (!share) {
169
179
  share = {
170
180
  id: id(),
181
+ relay: wanted,
171
182
  key: (0, node_crypto_1.randomBytes)(32).toString('base64url'),
172
183
  root,
173
184
  name,
@@ -177,7 +188,7 @@ class RelayStore {
177
188
  live.push(share);
178
189
  }
179
190
  this.write({ ...before, url, host, shares: live });
180
- return { share, link: { relay: url, host: host.id, share: share.id, key: share.key, name } };
191
+ return { share, link: { relay: RelayStore.relayOf(share, { url }), host: host.id, share: share.id, key: share.key, name } };
181
192
  }
182
193
  /** Stops the shares of a package: their links no longer work. False when there were none. */
183
194
  unshareRoot(root) {
@@ -190,16 +201,37 @@ class RelayStore {
190
201
  this.write({ ...config, shares });
191
202
  return true;
192
203
  }
193
- /** A new device for this relay; another relay than before unpairs the devices of the old one. */
194
- pair(relay, deviceName) {
204
+ /**
205
+ * A new device, through this relay; the devices of other relays stay on theirs, and this ta serve is connected to
206
+ * each relay that has one (docs/design/ta-relays.md). `member`: a device of one the user let in, not their own;
207
+ * `expiresAt`: it reaches this ta serve until then. Devices expired are dropped as a new one is added.
208
+ */
209
+ pair(relay, deviceName, options = {}) {
210
+ var _a;
195
211
  const url = relay.replace(/\/+$/, '');
196
212
  const before = this.read();
197
- const config = before.url === url && before.host ? before : { url, host: { id: id(), secret: (0, node_crypto_1.randomBytes)(32).toString('base64url') }, devices: [], shares: [] };
198
- const device = { id: id(), name: deviceName, key: (0, node_crypto_1.randomBytes)(32).toString('base64url'), createdAt: Date.now() };
199
- config.devices.push(device);
213
+ const config = before.host
214
+ ? { ...before, url: (_a = before.url) !== null && _a !== void 0 ? _a : url }
215
+ : { ...before, url, host: { id: id(), secret: (0, node_crypto_1.randomBytes)(32).toString('base64url') } };
216
+ const now = Date.now();
217
+ const device = {
218
+ id: id(),
219
+ name: deviceName,
220
+ relay: url,
221
+ key: (0, node_crypto_1.randomBytes)(32).toString('base64url'),
222
+ createdAt: now,
223
+ ...(options.member ? { member: options.member } : {}),
224
+ ...(options.expiresAt !== undefined ? { expiresAt: options.expiresAt } : {}),
225
+ };
226
+ config.devices = [...config.devices.filter(one => one.expiresAt === undefined || one.expiresAt > now), device];
200
227
  this.write(config);
201
228
  return { relay: url, host: config.host.id, device: device.id, key: device.key, name: (0, node_os_1.hostname)() };
202
229
  }
230
+ /** Whether ta serve keeps the computer awake for the devices (RelayConfig.keepAwake). */
231
+ setKeepAwake(on) {
232
+ const { keepAwake: _keepAwake, ...config } = this.read();
233
+ this.write(on ? config : { ...config, keepAwake: false });
234
+ }
203
235
  /** False when there was no such device. */
204
236
  remove(deviceId) {
205
237
  const config = this.read();