@celljs/ta-relay 4.10.0 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.en.md +13 -1
  2. package/README.md +13 -1
  3. package/esm/common/index.d.ts +11 -0
  4. package/esm/common/index.js +11 -0
  5. package/esm/common/relay-blobs.d.ts +54 -0
  6. package/esm/common/relay-blobs.js +153 -0
  7. package/esm/common/relay-card.d.ts +23 -0
  8. package/esm/common/relay-card.js +30 -0
  9. package/esm/common/relay-content.d.ts +104 -0
  10. package/esm/common/relay-content.js +316 -0
  11. package/esm/common/relay-conversation.d.ts +59 -0
  12. package/esm/common/relay-conversation.js +9 -0
  13. package/esm/common/relay-faces.d.ts +32 -0
  14. package/esm/common/relay-faces.js +208 -0
  15. package/esm/common/relay-hub-util.d.ts +91 -0
  16. package/esm/common/relay-hub-util.js +164 -0
  17. package/esm/common/relay-hub.d.ts +125 -0
  18. package/esm/common/relay-hub.js +438 -0
  19. package/esm/common/relay-hubs-connection.d.ts +98 -0
  20. package/esm/common/relay-hubs-connection.js +505 -0
  21. package/esm/common/relay-hubs-protocol.d.ts +130 -0
  22. package/esm/common/relay-hubs-protocol.js +2 -0
  23. package/esm/common/relay-hubs.d.ts +61 -0
  24. package/esm/common/relay-hubs.js +351 -0
  25. package/esm/common/relay-identity.d.ts +46 -0
  26. package/esm/common/relay-identity.js +126 -0
  27. package/esm/common/relay-protocol.d.ts +211 -2
  28. package/esm/common/relay-protocol.js +53 -0
  29. package/esm/common/relay-room-chat.d.ts +109 -0
  30. package/esm/common/relay-room-chat.js +176 -0
  31. package/esm/common/relay-socket.d.ts +8 -0
  32. package/esm/common/relay-socket.js +23 -2
  33. package/esm/guest/guest-i18n.d.ts +50 -0
  34. package/esm/guest/guest-i18n.js +103 -0
  35. package/esm/guest/guest-style.d.ts +1 -0
  36. package/esm/guest/guest-style.js +85 -0
  37. package/esm/guest/guest.d.ts +1 -0
  38. package/esm/guest/guest.js +384 -0
  39. package/esm/node/index.d.ts +2 -0
  40. package/esm/node/index.js +2 -0
  41. package/esm/node/relay-host.d.ts +25 -3
  42. package/esm/node/relay-host.js +115 -4
  43. package/esm/node/relay-hub-files.d.ts +12 -0
  44. package/esm/node/relay-hub-files.js +39 -0
  45. package/esm/node/relay-server.d.ts +46 -1
  46. package/esm/node/relay-server.js +227 -1
  47. package/esm/node/relay-store.d.ts +72 -0
  48. package/esm/node/relay-store.js +123 -2
  49. package/esm/node/relay-viewer.d.ts +7 -0
  50. package/esm/node/relay-viewer.js +33 -0
  51. package/esm/viewer/viewer-i18n.d.ts +56 -0
  52. package/esm/viewer/viewer-i18n.js +117 -0
  53. package/esm/viewer/viewer-markdown.d.ts +7 -0
  54. package/esm/viewer/viewer-markdown.js +198 -0
  55. package/esm/viewer/viewer-style.d.ts +1 -0
  56. package/esm/viewer/viewer-style.js +72 -0
  57. package/esm/viewer/viewer.d.ts +8 -0
  58. package/esm/viewer/viewer.js +378 -0
  59. package/lib/common/index.d.ts +11 -0
  60. package/lib/common/index.js +11 -0
  61. package/lib/common/relay-blobs.d.ts +55 -0
  62. package/lib/common/relay-blobs.js +157 -0
  63. package/lib/common/relay-card.d.ts +24 -0
  64. package/lib/common/relay-card.js +33 -0
  65. package/lib/common/relay-content.d.ts +105 -0
  66. package/lib/common/relay-content.js +320 -0
  67. package/lib/common/relay-conversation.d.ts +60 -0
  68. package/lib/common/relay-conversation.js +12 -0
  69. package/lib/common/relay-faces.d.ts +33 -0
  70. package/lib/common/relay-faces.js +211 -0
  71. package/lib/common/relay-hub-util.d.ts +92 -0
  72. package/lib/common/relay-hub-util.js +167 -0
  73. package/lib/common/relay-hub.d.ts +126 -0
  74. package/lib/common/relay-hub.js +442 -0
  75. package/lib/common/relay-hubs-connection.d.ts +99 -0
  76. package/lib/common/relay-hubs-connection.js +510 -0
  77. package/lib/common/relay-hubs-protocol.d.ts +131 -0
  78. package/lib/common/relay-hubs-protocol.js +3 -0
  79. package/lib/common/relay-hubs.d.ts +62 -0
  80. package/lib/common/relay-hubs.js +355 -0
  81. package/lib/common/relay-identity.d.ts +47 -0
  82. package/lib/common/relay-identity.js +129 -0
  83. package/lib/common/relay-protocol.d.ts +211 -2
  84. package/lib/common/relay-protocol.js +54 -1
  85. package/lib/common/relay-room-chat.d.ts +110 -0
  86. package/lib/common/relay-room-chat.js +180 -0
  87. package/lib/common/relay-socket.d.ts +8 -0
  88. package/lib/common/relay-socket.js +23 -2
  89. package/lib/guest/guest-i18n.d.ts +51 -0
  90. package/lib/guest/guest-i18n.js +106 -0
  91. package/lib/guest/guest-style.d.ts +2 -0
  92. package/lib/guest/guest-style.js +88 -0
  93. package/lib/guest/guest.d.ts +2 -0
  94. package/lib/guest/guest.js +386 -0
  95. package/lib/node/index.d.ts +2 -0
  96. package/lib/node/index.js +2 -0
  97. package/lib/node/relay-host.d.ts +25 -3
  98. package/lib/node/relay-host.js +115 -4
  99. package/lib/node/relay-hub-files.d.ts +13 -0
  100. package/lib/node/relay-hub-files.js +43 -0
  101. package/lib/node/relay-server.d.ts +46 -1
  102. package/lib/node/relay-server.js +226 -0
  103. package/lib/node/relay-store.d.ts +72 -0
  104. package/lib/node/relay-store.js +121 -0
  105. package/lib/node/relay-viewer.d.ts +8 -0
  106. package/lib/node/relay-viewer.js +32 -0
  107. package/lib/viewer/viewer-i18n.d.ts +57 -0
  108. package/lib/viewer/viewer-i18n.js +120 -0
  109. package/lib/viewer/viewer-markdown.d.ts +8 -0
  110. package/lib/viewer/viewer-markdown.js +201 -0
  111. package/lib/viewer/viewer-style.d.ts +2 -0
  112. package/lib/viewer/viewer-style.js +75 -0
  113. package/lib/viewer/viewer.d.ts +9 -0
  114. package/lib/viewer/viewer.js +381 -0
  115. package/package.json +5 -4
  116. package/viewer/frame.html +1 -0
  117. package/viewer/page.html +80 -0
  118. package/viewer/room.html +94 -0
@@ -0,0 +1,13 @@
1
+ import type { RelayHubsStore, RelayHubsStoreName } from '../common/relay-hubs-protocol';
2
+ /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
3
+ export declare class RelayHubFiles implements RelayHubsStore {
4
+ readonly agentDir: string;
5
+ constructor(agentDir: string);
6
+ file(name: RelayHubsStoreName): string;
7
+ read<T>(name: RelayHubsStoreName): T | undefined;
8
+ /** Written whole, then renamed over the file, readable by the user alone: it holds keys. */
9
+ write(name: RelayHubsStoreName, value: unknown): void;
10
+ /** The name of a new identity: the user's on this system. */
11
+ static userName(): string;
12
+ }
13
+ //# sourceMappingURL=relay-hub-files.d.ts.map
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelayHubFiles = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_os_1 = require("node:os");
6
+ const node_path_1 = require("node:path");
7
+ /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
8
+ class RelayHubFiles {
9
+ constructor(agentDir) {
10
+ this.agentDir = agentDir;
11
+ }
12
+ file(name) {
13
+ return (0, node_path_1.join)(this.agentDir, `${name}.json`);
14
+ }
15
+ read(name) {
16
+ try {
17
+ return JSON.parse((0, node_fs_1.readFileSync)(this.file(name), 'utf8'));
18
+ }
19
+ catch (_a) {
20
+ return undefined;
21
+ }
22
+ }
23
+ /** Written whole, then renamed over the file, readable by the user alone: it holds keys. */
24
+ write(name, value) {
25
+ const file = this.file(name);
26
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(file), { recursive: true });
27
+ const temporary = `${file}.${process.pid}.tmp`;
28
+ (0, node_fs_1.writeFileSync)(temporary, `${JSON.stringify(value, undefined, 2)}\n`, { mode: 0o600 });
29
+ (0, node_fs_1.chmodSync)(temporary, 0o600);
30
+ (0, node_fs_1.renameSync)(temporary, file);
31
+ }
32
+ /** The name of a new identity: the user's on this system. */
33
+ static userName() {
34
+ try {
35
+ return (0, node_os_1.userInfo)().username || 'Ta';
36
+ }
37
+ catch (_a) {
38
+ return 'Ta';
39
+ }
40
+ }
41
+ }
42
+ exports.RelayHubFiles = RelayHubFiles;
43
+ //# sourceMappingURL=relay-hub-files.js.map
@@ -1,6 +1,8 @@
1
- import { type IncomingMessage, type Server } from 'node:http';
1
+ import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
2
  import type { Duplex } from 'node:stream';
3
3
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
4
+ import { type RelayBlobStorage, RelayBlobs } from '../common/relay-blobs';
5
+ import { RelayHub, type RelayHubStorage, type RelayHubWho } from '../common/relay-hub';
4
6
  import { RelayRoom } from '../common/relay-room';
5
7
  export interface RelayServerOptions {
6
8
  host?: string;
@@ -12,6 +14,37 @@ interface Room {
12
14
  clients: Map<string, WebSocketConnection>;
13
15
  relay: RelayRoom;
14
16
  }
17
+ /** A copy of content in memory, deleted when it runs out. */
18
+ declare class MemoryBlobStorage implements RelayBlobStorage {
19
+ protected readonly values: Map<string, unknown>;
20
+ protected timer?: ReturnType<typeof setTimeout>;
21
+ get<T>(key: string): Promise<T | undefined>;
22
+ put(key: string, value: unknown): Promise<void>;
23
+ deleteAll(): Promise<void>;
24
+ /** No copy is kept: nothing of it need stay in the relay's memory. */
25
+ get empty(): boolean;
26
+ setAlarm(at: number): Promise<void>;
27
+ }
28
+ /** A room in memory, as a Durable Object keeps it. */
29
+ declare class MemoryHubStorage implements RelayHubStorage {
30
+ protected readonly values: Map<string, unknown>;
31
+ get<T>(key: string): Promise<T | undefined>;
32
+ put(key: string, value: unknown): Promise<void>;
33
+ delete(key: string): Promise<boolean>;
34
+ list<T>(options: {
35
+ prefix: string;
36
+ }): Promise<Map<string, T>>;
37
+ deleteAll(): Promise<void>;
38
+ /** No room was made, or it was closed. */
39
+ get empty(): boolean;
40
+ }
41
+ interface Hub {
42
+ hub: RelayHub;
43
+ storage: MemoryHubStorage;
44
+ sockets: Map<WebSocketConnection, {
45
+ who?: RelayHubWho;
46
+ }>;
47
+ }
15
48
  /**
16
49
  * `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
17
50
  * and keeps the hash of each host's secret in memory, for as long as it runs.
@@ -19,14 +52,26 @@ interface Room {
19
52
  export declare class RelayServer {
20
53
  protected readonly options: RelayServerOptions;
21
54
  protected readonly rooms: Map<string, Room>;
55
+ protected readonly blobs: Map<string, {
56
+ blobs: RelayBlobs;
57
+ storage: MemoryBlobStorage;
58
+ pending: number;
59
+ }>;
60
+ protected readonly hubs: Map<string, Hub>;
22
61
  protected server?: Server;
23
62
  constructor(options?: RelayServerOptions);
24
63
  listen(): Promise<string>;
25
64
  close(): Promise<void>;
65
+ /** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
66
+ protected blob(id: string, request: IncomingMessage, response: ServerResponse): Promise<void>;
67
+ /** The body of a request, or undefined past `max` bytes: the rest is read and dropped. */
68
+ protected static body(request: IncomingMessage, max: number): Promise<Buffer<ArrayBuffer> | undefined>;
26
69
  protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void;
27
70
  /** The first host to come with an id keeps it, for as long as the relay runs. */
28
71
  protected openHost(id: string, secret: string, connection: WebSocketConnection): void;
29
72
  protected openClient(id: string, connection: WebSocketConnection): void;
73
+ /** A connection to the hub of a room (RelayHub), kept in memory for as long as the relay runs. */
74
+ protected openHub(id: string, connection: WebSocketConnection): void;
30
75
  protected createRoom(id: string, secretHash: string): Room;
31
76
  protected static same(a: string, b: string): boolean;
32
77
  }
@@ -4,9 +4,71 @@ exports.RelayServer = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const node_http_1 = require("node:http");
6
6
  const websocket_connection_1 = require("@celljs/rpc/lib/node/websocket/websocket-connection");
7
+ const relay_blobs_1 = require("../common/relay-blobs");
8
+ const relay_hub_1 = require("../common/relay-hub");
7
9
  const relay_protocol_1 = require("../common/relay-protocol");
8
10
  const relay_room_1 = require("../common/relay-room");
11
+ const relay_viewer_1 = require("./relay-viewer");
9
12
  const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
13
+ /** A copy of content in memory, deleted when it runs out. */
14
+ class MemoryBlobStorage {
15
+ constructor() {
16
+ this.values = new Map();
17
+ }
18
+ async get(key) {
19
+ return this.values.get(key);
20
+ }
21
+ async put(key, value) {
22
+ this.values.set(key, value);
23
+ }
24
+ async deleteAll() {
25
+ this.values.clear();
26
+ clearTimeout(this.timer);
27
+ }
28
+ /** No copy is kept: nothing of it need stay in the relay's memory. */
29
+ get empty() {
30
+ return this.values.size === 0;
31
+ }
32
+ async setAlarm(at) {
33
+ var _a, _b;
34
+ clearTimeout(this.timer);
35
+ // Past the 24 days of a timer, it is found run out on the next read.
36
+ this.timer = setTimeout(() => this.values.clear(), Math.min(Math.max(at - Date.now(), 0), 2 ** 31 - 1));
37
+ (_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
38
+ }
39
+ }
40
+ /** A room in memory, as a Durable Object keeps it. */
41
+ class MemoryHubStorage {
42
+ constructor() {
43
+ this.values = new Map();
44
+ }
45
+ async get(key) {
46
+ const value = this.values.get(key);
47
+ return value === undefined ? undefined : structuredClone(value);
48
+ }
49
+ async put(key, value) {
50
+ this.values.set(key, structuredClone(value));
51
+ }
52
+ async delete(key) {
53
+ return this.values.delete(key);
54
+ }
55
+ async list(options) {
56
+ const found = new Map();
57
+ for (const [key, value] of [...this.values].sort(([a], [b]) => a.localeCompare(b))) {
58
+ if (key.startsWith(options.prefix)) {
59
+ found.set(key, structuredClone(value));
60
+ }
61
+ }
62
+ return found;
63
+ }
64
+ async deleteAll() {
65
+ this.values.clear();
66
+ }
67
+ /** No room was made, or it was closed. */
68
+ get empty() {
69
+ return this.values.size === 0;
70
+ }
71
+ }
10
72
  const peer = (connection) => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
11
73
  /**
12
74
  * `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
@@ -16,11 +78,37 @@ class RelayServer {
16
78
  constructor(options = {}) {
17
79
  this.options = options;
18
80
  this.rooms = new Map();
81
+ this.blobs = new Map();
82
+ this.hubs = new Map();
19
83
  }
20
84
  listen() {
21
85
  const server = (0, node_http_1.createServer)((request, response) => {
22
86
  var _a;
23
87
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split(/[?#]/)[0];
88
+ if (path.startsWith(relay_protocol_1.RELAY_BLOB_PATH)) {
89
+ this.blob(path.slice(relay_protocol_1.RELAY_BLOB_PATH.length), request, response).catch(() => {
90
+ // A request aborted or that failed: an unhandled rejection would end the relay.
91
+ if (!response.headersSent) {
92
+ response.writeHead(400);
93
+ }
94
+ response.end();
95
+ });
96
+ return;
97
+ }
98
+ if (path === relay_protocol_1.RELAY_ROOM_PATH) {
99
+ response.writeHead(200, { ...relay_protocol_1.RELAY_VIEWER_HEADERS, 'x-frame-options': 'DENY' });
100
+ response.end(relay_viewer_1.RelayViewer.room());
101
+ return;
102
+ }
103
+ if (path === relay_protocol_1.RELAY_CONTENT_PATH || path === relay_protocol_1.RELAY_FRAME_PATH) {
104
+ const frame = path === relay_protocol_1.RELAY_FRAME_PATH;
105
+ response.writeHead(200, {
106
+ ...relay_protocol_1.RELAY_VIEWER_HEADERS,
107
+ ...(frame ? { 'content-security-policy': relay_protocol_1.RELAY_FRAME_HEADER_CSP } : { 'x-frame-options': 'DENY' }),
108
+ });
109
+ response.end(frame ? relay_viewer_1.RelayViewer.frame() : relay_viewer_1.RelayViewer.page());
110
+ return;
111
+ }
24
112
  const page = path === relay_protocol_1.RELAY_PAIR_PATH ? relay_protocol_1.RELAY_PAIR_PAGE : path === relay_protocol_1.RELAY_SHARE_PATH ? relay_protocol_1.RELAY_SHARE_PAGE : undefined;
25
113
  response.writeHead(200, { 'content-type': page ? 'text/html; charset=utf-8' : 'text/plain' });
26
114
  response.end(page !== null && page !== void 0 ? page : 'Ta relay\n');
@@ -38,6 +126,12 @@ class RelayServer {
38
126
  }
39
127
  close() {
40
128
  var _a;
129
+ for (const { sockets } of this.hubs.values()) {
130
+ for (const connection of sockets.keys()) {
131
+ connection.close(1001, 'The relay is stopping.');
132
+ }
133
+ }
134
+ this.hubs.clear();
41
135
  for (const room of this.rooms.values()) {
42
136
  (_a = room.host) === null || _a === void 0 ? void 0 : _a.close(1001, 'The relay is stopping.');
43
137
  for (const client of room.clients.values()) {
@@ -47,6 +141,70 @@ class RelayServer {
47
141
  this.rooms.clear();
48
142
  return new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
49
143
  }
144
+ /** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
145
+ async blob(id, request, response) {
146
+ var _a;
147
+ if (!relay_protocol_1.RELAY_ID.test(id)) {
148
+ response.writeHead(404).end();
149
+ return;
150
+ }
151
+ const read = await RelayServer.body(request, relay_blobs_1.RelayBlobs.MAX_BYTES);
152
+ if (!read) {
153
+ // Refused before it is all in memory, whatever its content-length said.
154
+ response.writeHead(413, { connection: 'close' }).end('Too large.\n');
155
+ return;
156
+ }
157
+ // 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
+ }
164
+ const headers = new Headers();
165
+ for (const [name, value] of Object.entries(request.headers)) {
166
+ if (typeof value === 'string') {
167
+ headers.set(name, value);
168
+ }
169
+ }
170
+ const method = (_a = request.method) !== null && _a !== void 0 ? _a : 'GET';
171
+ const body = read.length && method !== 'GET' && method !== 'HEAD' ? read : undefined;
172
+ copy.pending++;
173
+ let answer;
174
+ try {
175
+ answer = await copy.blobs.handle(new Request(`http://relay${request.url}`, { method, headers, body }));
176
+ }
177
+ finally {
178
+ copy.pending--;
179
+ if (copy.pending === 0 && copy.storage.empty && this.blobs.get(id) === copy) {
180
+ this.blobs.delete(id);
181
+ }
182
+ }
183
+ response.writeHead(answer.status, Object.fromEntries(answer.headers));
184
+ response.end(Buffer.from(await answer.arrayBuffer()));
185
+ }
186
+ /** The body of a request, or undefined past `max` bytes: the rest is read and dropped. */
187
+ static body(request, max) {
188
+ return new Promise((resolve, reject) => {
189
+ const chunks = [];
190
+ let size = 0;
191
+ request.on('data', (chunk) => {
192
+ if (size < 0) {
193
+ return;
194
+ }
195
+ size += chunk.length;
196
+ if (size > max) {
197
+ size = -1;
198
+ chunks.length = 0;
199
+ resolve(undefined);
200
+ return;
201
+ }
202
+ chunks.push(chunk);
203
+ });
204
+ request.on('end', () => size >= 0 && resolve(Buffer.concat(chunks)));
205
+ request.on('error', reject);
206
+ });
207
+ }
50
208
  upgrade(request, socket, head) {
51
209
  var _a, _b;
52
210
  const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://relay');
@@ -55,6 +213,15 @@ class RelayServer {
55
213
  websocket_connection_1.WebSocketConnection.refuse(socket, checked.status, checked.message);
56
214
  return;
57
215
  }
216
+ if (url.pathname.startsWith(relay_protocol_1.RELAY_HUB_PATH)) {
217
+ const id = url.pathname.slice(relay_protocol_1.RELAY_HUB_PATH.length);
218
+ if (!relay_protocol_1.RELAY_ID.test(id)) {
219
+ websocket_connection_1.WebSocketConnection.refuse(socket, 404, 'Not found.');
220
+ return;
221
+ }
222
+ this.openHub(id, websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, WEBSOCKET));
223
+ return;
224
+ }
58
225
  const [path, id] = url.pathname.startsWith(relay_protocol_1.RELAY_HOST_PATH)
59
226
  ? [relay_protocol_1.RELAY_HOST_PATH, url.pathname.slice(relay_protocol_1.RELAY_HOST_PATH.length)]
60
227
  : [relay_protocol_1.RELAY_CONNECT_PATH, url.pathname.slice(relay_protocol_1.RELAY_CONNECT_PATH.length)];
@@ -110,6 +277,65 @@ class RelayServer {
110
277
  }
111
278
  });
112
279
  }
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) {
284
+ 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) {
294
+ state.who = who;
295
+ },
296
+ send: text => other.send(text),
297
+ close: (code, reason) => other.close(code, reason),
298
+ };
299
+ };
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);
303
+ }
304
+ const current = hub;
305
+ const { sockets, hub: relay } = current;
306
+ sockets.set(connection, {});
307
+ let chain = Promise.resolve();
308
+ const socket = {
309
+ key: connection,
310
+ get who() {
311
+ var _a;
312
+ return (_a = sockets.get(connection)) === null || _a === void 0 ? void 0 : _a.who;
313
+ },
314
+ set who(who) {
315
+ const state = sockets.get(connection);
316
+ if (state) {
317
+ state.who = who;
318
+ }
319
+ },
320
+ send: text => connection.send(text),
321
+ close: (code, reason) => connection.close(code, reason),
322
+ };
323
+ connection.onMessage(text => {
324
+ chain = chain.then(() => relay.receive(socket, text)).catch(() => undefined);
325
+ });
326
+ connection.onClose(() => {
327
+ void chain.then(() => {
328
+ if (sockets.has(connection)) {
329
+ relay.closed(socket);
330
+ sockets.delete(connection);
331
+ }
332
+ // 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
+ }
336
+ });
337
+ });
338
+ }
113
339
  createRoom(id, secretHash) {
114
340
  const room = {
115
341
  secretHash,
@@ -1,3 +1,5 @@
1
+ import { type RelayContentAccess, type RelayContentHeader, type RelayContentLink } from '../common/relay-content';
2
+ import { type RelayIdentity, type RelayPublicIdentity } from '../common/relay-identity';
1
3
  import type { RelayPairing } from '../common/relay-pairing';
2
4
  import type { RelayShareLink } from '../common/relay-share';
3
5
  export interface RelayDevice {
@@ -18,6 +20,47 @@ export interface RelayShare {
18
20
  createdAt: number;
19
21
  expiresAt: number;
20
22
  }
23
+ /**
24
+ * Content shared by a link (docs/design/ta-link.md): a conversation, a page, a file, as it was when shared. Its
25
+ * bytes are in `shares/<id>` of the agent directory; this ta serve hands them to whoever opens the link.
26
+ */
27
+ export interface RelayContentShare extends RelayContentHeader {
28
+ id: string;
29
+ access: RelayContentAccess;
30
+ /** base64url, 32 bytes: what the content is sealed with (with a password, derived from it and the key of the link). */
31
+ key: string;
32
+ /** base64url, 32 bytes: the key of the link, for the link again; none for `self`. */
33
+ linkKey?: string;
34
+ size: number;
35
+ /** None: until stopped. */
36
+ expiresAt?: number;
37
+ /** A copy kept on the relay, sealed: the token that writes and deletes it there, and when it runs out. */
38
+ offline?: {
39
+ token: string;
40
+ expiresAt: number;
41
+ };
42
+ /** For `people`: the Ta friends it is shared with, each with the key made with it (RelayContentUtil.peopleKey). */
43
+ people?: {
44
+ id: string;
45
+ name: string;
46
+ key: string;
47
+ }[];
48
+ /** For `people`: this Ta's identity, which the link names. */
49
+ owner?: string;
50
+ }
51
+ /** What a share of content is made of (RelayStore.addContent). */
52
+ export interface RelayContentInput extends RelayContentHeader {
53
+ data: Uint8Array;
54
+ access: RelayContentAccess;
55
+ /** For `password`. */
56
+ password?: string;
57
+ /** None or 0: until stopped (not with `offline`, which is RELAY_BLOB_MAX_DAYS at most). */
58
+ days?: number;
59
+ offline?: boolean;
60
+ /** For `people`: the Ta friends it is shared with, and this Ta's identity. */
61
+ people?: RelayPublicIdentity[];
62
+ identity?: RelayIdentity;
63
+ }
21
64
  /** relay.json in the agent directory. Without devices, ta serve does not connect to the relay. */
22
65
  export interface RelayConfig {
23
66
  /** The relay, without a trailing slash. */
@@ -30,6 +73,8 @@ export interface RelayConfig {
30
73
  devices: RelayDevice[];
31
74
  /** Packages handed on; those past their time are dropped when it is written. */
32
75
  shares?: RelayShare[];
76
+ /** Content shared; those past their time are dropped, with their bytes, when it is written. */
77
+ contents?: RelayContentShare[];
33
78
  }
34
79
  /** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
35
80
  export declare class RelayStore {
@@ -43,6 +88,33 @@ export declare class RelayStore {
43
88
  share(shareId: string, now?: number): RelayShare | undefined;
44
89
  /** The shares still on. */
45
90
  shares(now?: number): RelayShare[];
91
+ /** Content shared, still on, by its id. */
92
+ content(contentId: string, now?: number): RelayContentShare | undefined;
93
+ /** Content shared, still on, the latest first. */
94
+ contents(now?: number): RelayContentShare[];
95
+ /** The bytes of content shared; undefined when they are gone. */
96
+ contentData(content: RelayContentShare): Uint8Array | undefined;
97
+ /**
98
+ * Shares content: its bytes kept here, a link for it on the relay of the devices (the default one when there is
99
+ * none), which this ta serve then connects to for any but `self`.
100
+ */
101
+ addContent(input: RelayContentInput, now?: number): Promise<{
102
+ content: RelayContentShare;
103
+ link: RelayContentLink;
104
+ }>;
105
+ /** The link of content shared here. */
106
+ contentLink(content: RelayContentShare, config?: Pick<RelayConfig, 'url' | 'host'>): RelayContentLink;
107
+ /** Stops a share of content: its link no longer works, its bytes are deleted. The share, if there was one. */
108
+ removeContent(contentId: string): RelayContentShare | undefined;
109
+ /** The key of each Ta friend content is shared with, made with this Ta's identity for this share. */
110
+ protected static people(input: RelayContentInput, id: string): Promise<{
111
+ id: string;
112
+ name: string;
113
+ key: string;
114
+ }[]>;
115
+ protected contentFile(contentId: string): string;
116
+ protected static live(content: RelayContentShare, now: number): boolean;
117
+ protected static id(): string;
46
118
  /**
47
119
  * A link of the package in `root`: the one of before while it lasts, else a new one for RELAY_SHARE_DAYS,
48
120
  * on the relay of the devices (the default one when there is none), which this ta serve then connects to.
@@ -5,6 +5,9 @@ const node_crypto_1 = require("node:crypto");
5
5
  const node_fs_1 = require("node:fs");
6
6
  const node_os_1 = require("node:os");
7
7
  const node_path_1 = require("node:path");
8
+ const relay_bytes_1 = require("../common/relay-bytes");
9
+ const relay_content_1 = require("../common/relay-content");
10
+ const relay_identity_1 = require("../common/relay-identity");
8
11
  const relay_protocol_1 = require("../common/relay-protocol");
9
12
  const id = () => (0, node_crypto_1.randomBytes)(16).toString('base64url');
10
13
  /** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
@@ -23,6 +26,7 @@ class RelayStore {
23
26
  host: config.host,
24
27
  devices: Array.isArray(config.devices) ? config.devices : [],
25
28
  shares: Array.isArray(config.shares) ? config.shares : [],
29
+ contents: Array.isArray(config.contents) ? config.contents : [],
26
30
  };
27
31
  }
28
32
  catch (_a) {
@@ -42,6 +46,114 @@ class RelayStore {
42
46
  var _a;
43
47
  return ((_a = this.read().shares) !== null && _a !== void 0 ? _a : []).filter(share => share.expiresAt > now);
44
48
  }
49
+ /** Content shared, still on, by its id. */
50
+ content(contentId, now = Date.now()) {
51
+ return this.contents(now).find(content => content.id === contentId);
52
+ }
53
+ /** Content shared, still on, the latest first. */
54
+ contents(now = Date.now()) {
55
+ var _a;
56
+ return ((_a = this.read().contents) !== null && _a !== void 0 ? _a : []).filter(content => RelayStore.live(content, now)).sort((a, b) => b.createdAt - a.createdAt);
57
+ }
58
+ /** The bytes of content shared; undefined when they are gone. */
59
+ contentData(content) {
60
+ try {
61
+ return new Uint8Array((0, node_fs_1.readFileSync)(this.contentFile(content.id)));
62
+ }
63
+ catch (_a) {
64
+ return undefined;
65
+ }
66
+ }
67
+ /**
68
+ * Shares content: its bytes kept here, a link for it on the relay of the devices (the default one when there is
69
+ * none), which this ta serve then connects to for any but `self`.
70
+ */
71
+ async addContent(input, now = Date.now()) {
72
+ var _a, _b, _c;
73
+ const linkKey = (0, node_crypto_1.randomBytes)(32);
74
+ const id = (0, node_crypto_1.randomBytes)(16).toString('base64url');
75
+ const password = input.access === 'password' ? input.password : undefined;
76
+ if (input.access === 'password' && !password) {
77
+ throw new Error('A share with a password needs the password.');
78
+ }
79
+ const people = input.access === 'people' ? await RelayStore.people(input, id) : undefined;
80
+ const key = await relay_content_1.RelayContentUtil.contentKey(new Uint8Array(linkKey), id, password);
81
+ 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
+ const expiresAt = days ? now + days * 24 * 60 * 60 * 1000 : undefined;
83
+ const offline = input.offline && input.access !== 'self' && input.access !== 'people';
84
+ const content = {
85
+ id,
86
+ kind: input.kind,
87
+ title: input.title,
88
+ createdAt: input.createdAt,
89
+ ...(input.type ? { type: input.type } : {}),
90
+ access: input.access,
91
+ key: relay_bytes_1.RelayBytes.toBase64(key),
92
+ ...(input.access === 'self' || people ? {} : { linkKey: linkKey.toString('base64url') }),
93
+ ...(people && input.identity ? { people, owner: input.identity.id } : {}),
94
+ size: input.data.length,
95
+ ...(expiresAt ? { expiresAt } : {}),
96
+ ...(offline && expiresAt ? { offline: { token: (0, node_crypto_1.randomBytes)(32).toString('base64url'), expiresAt } } : {}),
97
+ };
98
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(this.contentFile(id)), { recursive: true, mode: 0o700 });
99
+ (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] });
104
+ return { content, link: this.contentLink(content, { url, host }) };
105
+ }
106
+ /** The link of content shared here. */
107
+ contentLink(content, config = this.read()) {
108
+ var _a;
109
+ var _b, _c;
110
+ 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 : '',
113
+ share: content.id,
114
+ key: content.linkKey,
115
+ access: content.access,
116
+ ...(content.owner ? { owner: content.owner } : {}),
117
+ offline: !!content.offline,
118
+ kind: content.kind,
119
+ };
120
+ }
121
+ /** Stops a share of content: its link no longer works, its bytes are deleted. The share, if there was one. */
122
+ removeContent(contentId) {
123
+ var _a, _b;
124
+ const config = this.read();
125
+ const content = (_a = config.contents) === null || _a === void 0 ? void 0 : _a.find(candidate => candidate.id === contentId);
126
+ if (!content) {
127
+ return undefined;
128
+ }
129
+ this.write({ ...config, contents: (_b = config.contents) === null || _b === void 0 ? void 0 : _b.filter(candidate => candidate.id !== contentId) });
130
+ (0, node_fs_1.rmSync)(this.contentFile(contentId), { force: true });
131
+ return content;
132
+ }
133
+ /** The key of each Ta friend content is shared with, made with this Ta's identity for this share. */
134
+ static async people(input, id) {
135
+ var _a;
136
+ const { identity } = input;
137
+ const people = (_a = input.people) !== null && _a !== void 0 ? _a : [];
138
+ if (!identity || people.length === 0) {
139
+ throw new Error('A share with Ta friends needs them, and this Ta.');
140
+ }
141
+ return Promise.all(people.map(async (person) => {
142
+ if (!(await relay_identity_1.RelayIdentityUtil.check(person))) {
143
+ throw new Error(`${person.name} is not a Ta friend whose keys check.`);
144
+ }
145
+ return { id: person.id, name: person.name, key: relay_bytes_1.RelayBytes.toBase64(await relay_content_1.RelayContentUtil.peopleKey(identity, person.box, id)) };
146
+ }));
147
+ }
148
+ contentFile(contentId) {
149
+ return (0, node_path_1.join)(this.agentDir, 'shares', contentId);
150
+ }
151
+ static live(content, now) {
152
+ return content.expiresAt === undefined || content.expiresAt > now;
153
+ }
154
+ static id() {
155
+ return id();
156
+ }
45
157
  /**
46
158
  * A link of the package in `root`: the one of before while it lasts, else a new one for RELAY_SHARE_DAYS,
47
159
  * on the relay of the devices (the default one when there is none), which this ta serve then connects to.
@@ -103,6 +215,15 @@ class RelayStore {
103
215
  return (0, node_crypto_1.createHash)('sha256').update(secret).digest('base64url');
104
216
  }
105
217
  write(config) {
218
+ var _a;
219
+ var _b;
220
+ const now = Date.now();
221
+ for (const content of (_b = config.contents) !== null && _b !== void 0 ? _b : []) {
222
+ if (!RelayStore.live(content, now)) {
223
+ (0, node_fs_1.rmSync)(this.contentFile(content.id), { force: true });
224
+ }
225
+ }
226
+ config = { ...config, contents: (_a = config.contents) === null || _a === void 0 ? void 0 : _a.filter(content => RelayStore.live(content, now)) };
106
227
  (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(this.file), { recursive: true });
107
228
  const temporary = `${this.file}.${process.pid}.tmp`;
108
229
  (0, node_fs_1.writeFileSync)(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
@@ -0,0 +1,8 @@
1
+ /** The viewer of the relay as `ta relay` serves it: the pages scripts/build-viewer.ts built, next to lib/. */
2
+ export declare namespace RelayViewer {
3
+ /** The page of guests of rooms: a link that invites, opened in a browser. */
4
+ function room(): string;
5
+ function page(): string;
6
+ function frame(): string;
7
+ }
8
+ //# sourceMappingURL=relay-viewer.d.ts.map