@celljs/ta-relay 4.12.0 → 4.13.1

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