@celljs/ta-relay 4.10.0 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.en.md +13 -1
  2. package/README.md +13 -1
  3. package/esm/common/index.d.ts +9 -0
  4. package/esm/common/index.js +9 -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-hub-util.d.ts +91 -0
  14. package/esm/common/relay-hub-util.js +164 -0
  15. package/esm/common/relay-hub.d.ts +125 -0
  16. package/esm/common/relay-hub.js +438 -0
  17. package/esm/common/relay-hubs.d.ts +271 -0
  18. package/esm/common/relay-hubs.js +844 -0
  19. package/esm/common/relay-identity.d.ts +46 -0
  20. package/esm/common/relay-identity.js +126 -0
  21. package/esm/common/relay-protocol.d.ts +211 -2
  22. package/esm/common/relay-protocol.js +53 -0
  23. package/esm/common/relay-room-chat.d.ts +80 -0
  24. package/esm/common/relay-room-chat.js +152 -0
  25. package/esm/common/relay-socket.d.ts +8 -0
  26. package/esm/common/relay-socket.js +23 -2
  27. package/esm/guest/guest-i18n.d.ts +47 -0
  28. package/esm/guest/guest-i18n.js +97 -0
  29. package/esm/guest/guest-style.d.ts +1 -0
  30. package/esm/guest/guest-style.js +78 -0
  31. package/esm/guest/guest.d.ts +1 -0
  32. package/esm/guest/guest.js +371 -0
  33. package/esm/node/index.d.ts +2 -0
  34. package/esm/node/index.js +2 -0
  35. package/esm/node/relay-host.d.ts +25 -3
  36. package/esm/node/relay-host.js +115 -4
  37. package/esm/node/relay-hub-files.d.ts +12 -0
  38. package/esm/node/relay-hub-files.js +39 -0
  39. package/esm/node/relay-server.d.ts +46 -1
  40. package/esm/node/relay-server.js +227 -1
  41. package/esm/node/relay-store.d.ts +72 -0
  42. package/esm/node/relay-store.js +123 -2
  43. package/esm/node/relay-viewer.d.ts +7 -0
  44. package/esm/node/relay-viewer.js +33 -0
  45. package/esm/viewer/viewer-i18n.d.ts +56 -0
  46. package/esm/viewer/viewer-i18n.js +117 -0
  47. package/esm/viewer/viewer-markdown.d.ts +7 -0
  48. package/esm/viewer/viewer-markdown.js +198 -0
  49. package/esm/viewer/viewer-style.d.ts +1 -0
  50. package/esm/viewer/viewer-style.js +72 -0
  51. package/esm/viewer/viewer.d.ts +8 -0
  52. package/esm/viewer/viewer.js +378 -0
  53. package/lib/common/index.d.ts +9 -0
  54. package/lib/common/index.js +9 -0
  55. package/lib/common/relay-blobs.d.ts +55 -0
  56. package/lib/common/relay-blobs.js +157 -0
  57. package/lib/common/relay-card.d.ts +24 -0
  58. package/lib/common/relay-card.js +33 -0
  59. package/lib/common/relay-content.d.ts +105 -0
  60. package/lib/common/relay-content.js +320 -0
  61. package/lib/common/relay-conversation.d.ts +60 -0
  62. package/lib/common/relay-conversation.js +12 -0
  63. package/lib/common/relay-hub-util.d.ts +92 -0
  64. package/lib/common/relay-hub-util.js +167 -0
  65. package/lib/common/relay-hub.d.ts +126 -0
  66. package/lib/common/relay-hub.js +442 -0
  67. package/lib/common/relay-hubs.d.ts +272 -0
  68. package/lib/common/relay-hubs.js +848 -0
  69. package/lib/common/relay-identity.d.ts +47 -0
  70. package/lib/common/relay-identity.js +129 -0
  71. package/lib/common/relay-protocol.d.ts +211 -2
  72. package/lib/common/relay-protocol.js +54 -1
  73. package/lib/common/relay-room-chat.d.ts +81 -0
  74. package/lib/common/relay-room-chat.js +156 -0
  75. package/lib/common/relay-socket.d.ts +8 -0
  76. package/lib/common/relay-socket.js +23 -2
  77. package/lib/guest/guest-i18n.d.ts +48 -0
  78. package/lib/guest/guest-i18n.js +100 -0
  79. package/lib/guest/guest-style.d.ts +2 -0
  80. package/lib/guest/guest-style.js +81 -0
  81. package/lib/guest/guest.d.ts +2 -0
  82. package/lib/guest/guest.js +373 -0
  83. package/lib/node/index.d.ts +2 -0
  84. package/lib/node/index.js +2 -0
  85. package/lib/node/relay-host.d.ts +25 -3
  86. package/lib/node/relay-host.js +115 -4
  87. package/lib/node/relay-hub-files.d.ts +13 -0
  88. package/lib/node/relay-hub-files.js +43 -0
  89. package/lib/node/relay-server.d.ts +46 -1
  90. package/lib/node/relay-server.js +226 -0
  91. package/lib/node/relay-store.d.ts +72 -0
  92. package/lib/node/relay-store.js +121 -0
  93. package/lib/node/relay-viewer.d.ts +8 -0
  94. package/lib/node/relay-viewer.js +32 -0
  95. package/lib/viewer/viewer-i18n.d.ts +57 -0
  96. package/lib/viewer/viewer-i18n.js +120 -0
  97. package/lib/viewer/viewer-markdown.d.ts +8 -0
  98. package/lib/viewer/viewer-markdown.js +201 -0
  99. package/lib/viewer/viewer-style.d.ts +2 -0
  100. package/lib/viewer/viewer-style.js +75 -0
  101. package/lib/viewer/viewer.d.ts +9 -0
  102. package/lib/viewer/viewer.js +381 -0
  103. package/package.json +5 -4
  104. package/viewer/frame.html +1 -0
  105. package/viewer/page.html +80 -0
  106. package/viewer/room.html +87 -0
@@ -0,0 +1,371 @@
1
+ import { RelayHubUtil } from '../common/relay-hub-util.js';
2
+ import { RelayHubs } from '../common/relay-hubs.js';
3
+ import { RelayRoomChat } from '../common/relay-room-chat.js';
4
+ import { ViewerMarkdown } from '../viewer/viewer-markdown.js';
5
+ import { GuestI18n } from './guest-i18n.js';
6
+ import { GUEST_STYLE } from './guest-style.js';
7
+ /*
8
+ * The page a link inviting into a room opens in a browser (docs/design/ta-link.md 3.8): one without Ta asks to join
9
+ * as a guest, and once its owner lets it in, chats there. The keys are this browser's, kept for the relay's origin
10
+ * alone; the relay serves this page and never sees what is said.
11
+ */
12
+ const { t } = GuestI18n;
13
+ const el = ViewerMarkdown.el;
14
+ const NAMED = 'ta-guest:named';
15
+ /** A new run after this long without a word of the same member; a line with the time after a longer pause. */
16
+ const RUN_MS = 5 * 60 * 1000;
17
+ const PAUSE_MS = 15 * 60 * 1000;
18
+ /** What a guest keeps: the storage of this browser, for the origin of the relay alone. */
19
+ class BrowserStore {
20
+ read(name) {
21
+ try {
22
+ const text = localStorage.getItem(`ta-guest:${name}`);
23
+ return text ? JSON.parse(text) : undefined;
24
+ }
25
+ catch (_a) {
26
+ return undefined;
27
+ }
28
+ }
29
+ write(name, value) {
30
+ try {
31
+ localStorage.setItem(`ta-guest:${name}`, JSON.stringify(value));
32
+ }
33
+ catch (_a) {
34
+ // A browser that keeps nothing (a private window that is full): this visit alone.
35
+ }
36
+ }
37
+ }
38
+ function div(className, ...children) {
39
+ const node = el('div');
40
+ node.className = className;
41
+ node.append(...children);
42
+ return node;
43
+ }
44
+ function tint(id) {
45
+ let hash = 0;
46
+ for (const char of id) {
47
+ hash = (hash * 31 + char.charCodeAt(0)) | 0;
48
+ }
49
+ return Math.abs(hash) % 6;
50
+ }
51
+ function face(id, name, size, online) {
52
+ var _a;
53
+ var _b;
54
+ const node = el('span', (_b = (_a = Array.from(name.trim())[0]) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== null && _b !== void 0 ? _b : '?');
55
+ node.className = `face t${tint(id)}`;
56
+ node.style.cssText = `width:${size}px;height:${size}px;font-size:${Math.round(size * 0.42)}px`;
57
+ if (online !== undefined) {
58
+ const dot = el('i');
59
+ dot.className = online ? 'on' : '';
60
+ node.append(dot);
61
+ }
62
+ return node;
63
+ }
64
+ function button(className, text, onClick) {
65
+ const node = el('button', text);
66
+ node.type = 'button';
67
+ node.className = className;
68
+ node.addEventListener('click', onClick);
69
+ return node;
70
+ }
71
+ /** The page: who asks, waits, and chats, as the room the link names is for this browser. */
72
+ class GuestPage {
73
+ constructor(link) {
74
+ this.link = link;
75
+ this.hubs = new RelayHubs({
76
+ store: new BrowserStore(),
77
+ relay: () => location.origin,
78
+ guest: true,
79
+ name: () => (GuestI18n.chinese ? '访客' : 'Guest'),
80
+ });
81
+ this.screen = '';
82
+ this.stuck = true;
83
+ this.connected = false;
84
+ }
85
+ start() {
86
+ this.hubs.onEvent(event => {
87
+ var _a;
88
+ if (event.type === 'state' && event.room === this.link.room) {
89
+ (_a = this.chat) === null || _a === void 0 ? void 0 : _a.heard(event.key, event);
90
+ }
91
+ else if (event.type === 'rooms') {
92
+ this.update();
93
+ }
94
+ });
95
+ this.hubs.start();
96
+ this.update();
97
+ }
98
+ room() {
99
+ return this.hubs.room(this.link.room);
100
+ }
101
+ /** Shows what holds now: a screen of its own for each status, the chat kept as the room changes. */
102
+ update() {
103
+ var _a;
104
+ var _b;
105
+ const room = this.room();
106
+ const screen = !room ? 'join' : room.status === 'gone' ? `gone:${(_b = room.reason) !== null && _b !== void 0 ? _b : 'closed'}` : room.status;
107
+ if (screen === this.screen && room) {
108
+ if (room.status === 'member') {
109
+ this.refresh(room);
110
+ }
111
+ return;
112
+ }
113
+ this.screen = screen;
114
+ (_a = this.sheet) === null || _a === void 0 ? void 0 : _a.remove();
115
+ this.sheet = undefined;
116
+ if (!room) {
117
+ this.join();
118
+ }
119
+ else if (room.status === 'waiting') {
120
+ this.waiting();
121
+ }
122
+ else if (room.status === 'member') {
123
+ this.chatScreen(room);
124
+ }
125
+ else {
126
+ this.out(room);
127
+ }
128
+ }
129
+ frame(...children) {
130
+ const app = div('app', ...children);
131
+ document.body.replaceChildren(app);
132
+ return app;
133
+ }
134
+ top() {
135
+ const logo = el('span', 'Ta');
136
+ logo.className = 'logo';
137
+ const heading = div('heading', Object.assign(el('b'), { textContent: t('title') }));
138
+ return div('top', logo, heading);
139
+ }
140
+ join(error) {
141
+ document.title = t('title');
142
+ const field = el('input');
143
+ field.className = 'text';
144
+ field.placeholder = t('namePlaceholder');
145
+ field.maxLength = 40;
146
+ field.enterKeyHint = 'go';
147
+ if (localStorage.getItem(NAMED)) {
148
+ void this.hubs.identity().then(identity => {
149
+ field.value || (field.value = identity.name);
150
+ });
151
+ }
152
+ const label = el('label');
153
+ label.className = 'field';
154
+ label.append(t('name'), field);
155
+ const ask = button('primary', t('join'), () => void submit());
156
+ const shown = error ? [Object.assign(el('p', error), { className: 'error' })] : [];
157
+ const submit = async () => {
158
+ const name = field.value.trim();
159
+ if (!name) {
160
+ field.focus();
161
+ return;
162
+ }
163
+ ask.disabled = true;
164
+ ask.textContent = t('joining');
165
+ try {
166
+ await this.hubs.setName(name);
167
+ localStorage.setItem(NAMED, '1');
168
+ await this.hubs.join(location.href);
169
+ this.update();
170
+ }
171
+ catch (failure) {
172
+ this.screen = '';
173
+ this.join(failure instanceof Error && /own/.test(failure.message) ? t('own') : String(failure instanceof Error ? failure.message : failure));
174
+ }
175
+ };
176
+ field.addEventListener('keydown', event => {
177
+ if (event.key === 'Enter' && !event.isComposing) {
178
+ void submit();
179
+ }
180
+ });
181
+ this.frame(this.top(), div('center', Object.assign(face(this.link.owner, this.link.by || '?', 56), { className: `face card-face t${tint(this.link.owner)}` }), Object.assign(el('p', t('invited', { by: this.link.by || '…' })), { className: 'lead' }), Object.assign(el('h1', this.link.title || t('title')), { className: 'room-name' }), Object.assign(el('p', t('joinHint')), { className: 'hint' }), label, ...shown, ask, Object.assign(el('p', t('keep')), { className: 'small' }), Object.assign(el('p', t('haveTa')), { className: 'small' })));
182
+ }
183
+ waiting() {
184
+ this.frame(this.top(), div('center', Object.assign(el('div'), { className: 'spin' }), Object.assign(el('h1', t('waiting', { by: this.link.by || '…' })), { className: 'room-name' }), Object.assign(el('p', t('waitingHint')), { className: 'hint' }), button('plain', t('cancel'), () => void this.hubs.leave(this.link.room).then(() => this.update()))));
185
+ }
186
+ out(room) {
187
+ const text = room.status === 'refused'
188
+ ? t('refused', { by: room.ownerName || this.link.by })
189
+ : room.reason === 'removed'
190
+ ? t('removed')
191
+ : room.reason === 'invite'
192
+ ? t('inviteGone')
193
+ : t('closed');
194
+ this.frame(this.top(), div('center', Object.assign(el('h1', text), { className: 'room-name' }), button('plain', t('again'), () => void this.hubs.leave(this.link.room).then(() => this.update()))));
195
+ }
196
+ chatScreen(room) {
197
+ document.title = room.title;
198
+ this.chat = new RelayRoomChat(this.hubs, room.id);
199
+ this.chat.subscribe(() => this.draw());
200
+ this.connected = room.connected;
201
+ void this.chat.load().catch(() => undefined);
202
+ const heading = div('heading');
203
+ this.heading = heading;
204
+ const more = button('icon', '⋯', () => this.members());
205
+ more.setAttribute('aria-label', t('members'));
206
+ const top = div('top', heading, more);
207
+ const list = div('list');
208
+ list.addEventListener('scroll', () => {
209
+ this.stuck = list.scrollHeight - list.scrollTop - list.clientHeight < 48;
210
+ });
211
+ this.list = list;
212
+ const field = el('textarea');
213
+ field.rows = 1;
214
+ field.placeholder = t('placeholder');
215
+ field.enterKeyHint = 'send';
216
+ const send = button('primary', t('send'), () => void say());
217
+ const fit = () => {
218
+ field.style.height = 'auto';
219
+ field.style.height = `${Math.min(field.scrollHeight + 2, 160)}px`;
220
+ };
221
+ const say = async () => {
222
+ var _a;
223
+ const text = field.value.trim();
224
+ const self = (_a = this.room()) === null || _a === void 0 ? void 0 : _a.members.find(member => member.self);
225
+ if (!text || !self || !this.chat) {
226
+ return;
227
+ }
228
+ field.value = '';
229
+ fit();
230
+ this.stuck = true;
231
+ try {
232
+ await this.chat.say(text, self);
233
+ }
234
+ catch (failure) {
235
+ field.value || (field.value = text);
236
+ fit();
237
+ const note = Object.assign(el('p', t('failed', { reason: failure instanceof Error ? failure.message : String(failure) })), {
238
+ className: 'failed',
239
+ });
240
+ list.append(note);
241
+ setTimeout(() => note.remove(), 4000);
242
+ }
243
+ };
244
+ field.addEventListener('input', fit);
245
+ field.addEventListener('keydown', event => {
246
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
247
+ event.preventDefault();
248
+ void say();
249
+ }
250
+ });
251
+ const banner = room.view ? [div('banner', t('game'))] : [];
252
+ this.frame(top, ...banner, list, div('box', field, send), div('foot', t('secure')));
253
+ this.refresh(room);
254
+ this.draw();
255
+ }
256
+ /** The head of the chat, and the members if shown, as the room changed (who is online, the roster). */
257
+ refresh(room) {
258
+ var _a, _b;
259
+ if (room.connected && !this.connected) {
260
+ // Connected again: what was said meanwhile.
261
+ void ((_a = this.chat) === null || _a === void 0 ? void 0 : _a.load().catch(() => undefined));
262
+ }
263
+ this.connected = room.connected;
264
+ const title = el('b', room.title);
265
+ title.append(Object.assign(el('span', `(${room.members.length})`)));
266
+ const online = room.members.filter(member => member.online && !member.self).length;
267
+ const sub = el('small', !room.connected ? t('connecting') : online ? t('online', { n: online }) : t('nobody'));
268
+ sub.className = room.connected && online ? '' : 'quiet';
269
+ (_b = this.heading) === null || _b === void 0 ? void 0 : _b.replaceChildren(title, sub);
270
+ if (this.sheet) {
271
+ this.members();
272
+ }
273
+ }
274
+ draw() {
275
+ var _a;
276
+ const list = this.list;
277
+ const room = this.room();
278
+ if (!list || !room || !this.chat) {
279
+ return;
280
+ }
281
+ const lines = this.chat.lines;
282
+ const self = (_a = room.members.find(member => member.self)) === null || _a === void 0 ? void 0 : _a.member;
283
+ const nameOf = (line) => { var _a; var _b; return (_b = (_a = room.members.find(member => member.member === line.from)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : line.name; };
284
+ const nodes = [];
285
+ if (!lines.length) {
286
+ nodes.push(div('empty', t('empty')));
287
+ }
288
+ lines.forEach((line, index) => {
289
+ var _a;
290
+ const before = lines[index - 1];
291
+ const separator = !before || line.at - before.at > PAUSE_MS;
292
+ const first = separator || before.from !== line.from || line.at - before.at > RUN_MS;
293
+ if (separator) {
294
+ nodes.push(div('when', GuestI18n.time(line.at)));
295
+ }
296
+ const bubble = div('bubble', ViewerMarkdown.render(line.text));
297
+ bubble.title = GuestI18n.time(line.at);
298
+ if (line.from === self) {
299
+ nodes.push(div('mine', bubble));
300
+ return;
301
+ }
302
+ const other = room.members.find(member => member.member === line.from);
303
+ const col = div('col', ...(first ? [div('who', nameOf(line))] : []), bubble);
304
+ nodes.push(div(`msg${first ? ' first' : ''}`, div('slot', ...(first ? [face((_a = other === null || other === void 0 ? void 0 : other.id) !== null && _a !== void 0 ? _a : line.from, nameOf(line), 32)] : [])), col));
305
+ });
306
+ list.replaceChildren(...nodes);
307
+ if (this.stuck) {
308
+ list.scrollTop = list.scrollHeight;
309
+ }
310
+ }
311
+ /** The members, over the chat: who is online, and the user's name and way out. */
312
+ members() {
313
+ var _a;
314
+ const room = this.room();
315
+ if (!room) {
316
+ return;
317
+ }
318
+ const panel = div('panel', Object.assign(el('h3', `${t('members')} (${room.members.length})`)));
319
+ for (const member of room.members) {
320
+ const tags = [member.self ? t('you') : '', member.owner ? t('owner') : '', member.guest ? t('guest') : ''].filter(Boolean);
321
+ const name = div('nm', member.name, ...tags.map(tag => Object.assign(el('span', tag), { className: 'tag' })));
322
+ const status = Object.assign(el('span', member.online ? t('onlineNow') : ''), { className: 'st on' });
323
+ panel.append(div('member', face(member.id, member.name, 32, member.online), name, status));
324
+ }
325
+ panel.append(div('sep'), button('row', t('rename'), () => {
326
+ var _a, _b;
327
+ var _c;
328
+ const name = (_b = prompt(t('name'), (_c = (_a = room.members.find(member => member.self)) === null || _a === void 0 ? void 0 : _a.name) !== null && _c !== void 0 ? _c : '')) === null || _b === void 0 ? void 0 : _b.trim();
329
+ if (name) {
330
+ void this.hubs.setName(name).then(() => this.update());
331
+ }
332
+ }), button('row danger', t('leave'), () => {
333
+ if (confirm(t('leaveAsk', { title: room.title }))) {
334
+ void this.hubs.leave(room.id).then(() => this.update());
335
+ }
336
+ }), button('row', t('close'), () => this.closeSheet()));
337
+ const sheet = div('sheet', panel);
338
+ sheet.addEventListener('click', event => {
339
+ if (event.target === sheet) {
340
+ this.closeSheet();
341
+ }
342
+ });
343
+ (_a = this.sheet) === null || _a === void 0 ? void 0 : _a.replaceWith(sheet);
344
+ if (!this.sheet) {
345
+ document.body.append(sheet);
346
+ }
347
+ this.sheet = sheet;
348
+ }
349
+ closeSheet() {
350
+ var _a;
351
+ (_a = this.sheet) === null || _a === void 0 ? void 0 : _a.remove();
352
+ this.sheet = undefined;
353
+ }
354
+ }
355
+ function main() {
356
+ const style = el('style', GUEST_STYLE);
357
+ document.head.append(style);
358
+ let link;
359
+ try {
360
+ link = RelayHubUtil.parse(location.href);
361
+ }
362
+ catch (_a) {
363
+ const logo = Object.assign(el('span', 'Ta'), { className: 'logo' });
364
+ document.body.replaceChildren(div('app', div('top', logo), div('center', Object.assign(el('p', t('invalid')), { className: 'hint' }))));
365
+ return;
366
+ }
367
+ new GuestPage(link).start();
368
+ }
369
+ addEventListener('hashchange', () => location.reload());
370
+ main();
371
+ //# sourceMappingURL=guest.js.map
@@ -1,5 +1,7 @@
1
1
  export * from '../common/index.js';
2
2
  export * from './relay-files-host.js';
3
3
  export * from './relay-host.js';
4
+ export * from './relay-hub-files.js';
4
5
  export * from './relay-server.js';
5
6
  export * from './relay-store.js';
7
+ export * from './relay-viewer.js';
package/esm/node/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export * from '../common/index.js';
2
2
  export * from './relay-files-host.js';
3
3
  export * from './relay-host.js';
4
+ export * from './relay-hub-files.js';
4
5
  export * from './relay-server.js';
5
6
  export * from './relay-store.js';
7
+ export * from './relay-viewer.js';
6
8
  //# sourceMappingURL=index.js.map
@@ -2,7 +2,7 @@ import { RelayCipher } from '../common/relay-cipher.js';
2
2
  import { type RelayFilesFrame } from '../common/relay-files.js';
3
3
  import { RELAY_PING, type RelayHostMessage, type RelayWelcome } from '../common/relay-protocol.js';
4
4
  import { RelayFilesHost } from './relay-files-host.js';
5
- import type { RelayShare, RelayStore } from './relay-store.js';
5
+ import type { RelayContentShare, RelayShare, RelayStore } from './relay-store.js';
6
6
  export interface RelayHostOptions {
7
7
  store: RelayStore;
8
8
  /** The WebSocket of this ta serve, with its token: every device gets a connection to it of its own. */
@@ -13,6 +13,8 @@ export interface RelayHostOptions {
13
13
  pingMs?: number;
14
14
  /** The bytes of a package handed on (a share of the store), for one who has its link; without it, shares are refused. */
15
15
  sharePackage?(share: RelayShare): Promise<Uint8Array>;
16
+ /** Hands on the content shared in the store (RelayStore.contents) to whoever has its link; without it, such links are refused. */
17
+ shareContent?: boolean;
16
18
  }
17
19
  /**
18
20
  * A device on a channel: the handshake, then its connection to ta serve — or, for a channel that asked
@@ -25,10 +27,17 @@ declare class RelayChannel {
25
27
  protected readonly options: RelayHostOptions;
26
28
  protected cipher?: RelayCipher;
27
29
  protected local?: WebSocket;
28
- /** What this channel does, once its first sealed message said it. */
29
- protected mode?: 'rpc' | 'files';
30
+ /** What this channel does, once its first sealed message said it; `share` from the handshake, for a link of a package. */
31
+ protected mode?: 'rpc' | 'files' | 'share' | 'content';
32
+ /** Content shared, until the viewer proved it has its key (RelayContentUtil). */
33
+ protected content?: RelayContentShare;
34
+ /** Content shared with Ta friends: a cipher with the key of each, till the proof of one opens. */
35
+ protected candidates?: RelayCipher[];
30
36
  protected files?: RelayFilesHost;
31
37
  protected readonly early: string[];
38
+ /** Agreed in the hello of a viewer of content, set once it proved. */
39
+ protected compress: boolean;
40
+ protected proofTimer?: ReturnType<typeof setTimeout>;
32
41
  protected readonly timer: NodeJS.Timeout;
33
42
  constructor(id: string, host: RelayHost, options: RelayHostOptions);
34
43
  receive(text: string): Promise<void>;
@@ -37,6 +46,10 @@ declare class RelayChannel {
37
46
  /** A frame of the files of the workspace, sealed as the rest. */
38
47
  protected sendFrame(frame: RelayFilesFrame): void;
39
48
  protected hello(text: string): Promise<void>;
49
+ /** The first sealed message of a viewer of content: its proof, then the content; a wrong one is counted, and refused. */
50
+ protected proven(cipher: RelayCipher, content: RelayContentShare, data: string): Promise<void>;
51
+ /** The key did not open: told in the clear (the viewer cannot open what is sealed), and counted. */
52
+ protected wrongKey(content: RelayContentShare): void;
40
53
  /** A package handed on: what it is, its bytes in chunks, the end; then the channel closes. It never reaches ta serve's socket. */
41
54
  protected sendShare(cipher: RelayCipher, share: RelayShare): Promise<void>;
42
55
  protected connectLocal(cipher: RelayCipher): void;
@@ -58,7 +71,16 @@ export declare class RelayHost {
58
71
  protected timer?: ReturnType<typeof setTimeout>;
59
72
  protected pingTimer?: ReturnType<typeof setInterval>;
60
73
  protected readonly channels: Map<string, RelayChannel>;
74
+ /** Wrong keys of each share of content, of late. */
75
+ protected readonly wrong: Map<string, {
76
+ count: number;
77
+ since: number;
78
+ }>;
61
79
  constructor(options: RelayHostOptions);
80
+ /** @internal Whether a share of content had too many wrong keys of late. */
81
+ blocked(contentId: string, now?: number): boolean;
82
+ /** @internal */
83
+ wrongKey(contentId: string, now?: number): void;
62
84
  /** Whether the connection to the relay is open. */
63
85
  get online(): boolean;
64
86
  /** Connects when relay.json has a relay and a device, and keeps connected; checks again on {@link refresh}. */
@@ -4,6 +4,9 @@ import { RelayFilesUtil } from '../common/relay-files.js';
4
4
  import { RelayPairingUtil } from '../common/relay-pairing.js';
5
5
  import { RELAY_HOST_PATH, RELAY_PING, RELAY_PING_MS, RELAY_PONG, RELAY_PROOF, RELAY_SHARE_CHUNK_BYTES, RELAY_SHARE_MAX_BYTES, RelayCloseCode, } from '../common/relay-protocol.js';
6
6
  import { RelayFilesHost } from './relay-files-host.js';
7
+ /** Wrong keys (passwords) for a share before it is refused a while, and for how long. */
8
+ const MAX_WRONG_KEYS = 10;
9
+ const WRONG_KEY_WINDOW_MS = 10 * 60 * 1000;
7
10
  const MAX_RECONNECT_DELAY_MS = 30000;
8
11
  const HELLO_TIMEOUT_MS = 10000;
9
12
  /**
@@ -17,6 +20,8 @@ class RelayChannel {
17
20
  this.host = host;
18
21
  this.options = options;
19
22
  this.early = [];
23
+ /** Agreed in the hello of a viewer of content, set once it proved. */
24
+ this.compress = false;
20
25
  this.timer = setTimeout(() => this.close(), HELLO_TIMEOUT_MS);
21
26
  }
22
27
  async receive(text) {
@@ -25,14 +30,42 @@ class RelayChannel {
25
30
  await this.hello(text);
26
31
  return;
27
32
  }
33
+ if (this.content && this.candidates) {
34
+ // Whose key it is, the proof says: the relay and the others do not learn who looks.
35
+ const content = this.content;
36
+ for (const candidate of this.candidates) {
37
+ const opened = await candidate.open(text).catch(() => undefined);
38
+ if (opened !== undefined) {
39
+ this.cipher = candidate;
40
+ this.candidates = undefined;
41
+ await this.proven(candidate, content, opened);
42
+ return;
43
+ }
44
+ }
45
+ this.candidates = undefined;
46
+ this.wrongKey(content);
47
+ this.close();
48
+ return;
49
+ }
28
50
  let data;
29
51
  try {
30
52
  data = await this.cipher.open(text);
31
53
  }
32
54
  catch (_c) {
55
+ if (this.content) {
56
+ this.wrongKey(this.content);
57
+ }
33
58
  this.close();
34
59
  return;
35
60
  }
61
+ if (this.content) {
62
+ await this.proven(this.cipher, this.content, data);
63
+ return;
64
+ }
65
+ if (this.mode === 'share' || this.mode === 'content') {
66
+ // A link hands on what it shares and nothing else: what its holder sends never opens ta serve's socket or files.
67
+ return;
68
+ }
36
69
  if (!this.mode) {
37
70
  this.mode = RelayFilesUtil.isHello(data) ? 'files' : 'rpc';
38
71
  if (this.mode === 'files') {
@@ -57,6 +90,7 @@ class RelayChannel {
57
90
  closed() {
58
91
  var _a, _b;
59
92
  clearTimeout(this.timer);
93
+ clearTimeout(this.proofTimer);
60
94
  (_a = this.files) === null || _a === void 0 ? void 0 : _a.close();
61
95
  (_b = this.local) === null || _b === void 0 ? void 0 : _b.close();
62
96
  }
@@ -66,19 +100,26 @@ class RelayChannel {
66
100
  (_a = this.cipher) === null || _a === void 0 ? void 0 : _a.seal(JSON.stringify(frame)).then(sealed => this.host.send({ t: 'data', ch: this.id, d: sealed }));
67
101
  }
68
102
  async hello(text) {
69
- var _a;
103
+ var _a, _b, _c;
70
104
  let hello;
71
105
  try {
72
106
  hello = JSON.parse(text);
73
107
  }
74
- catch (_b) {
108
+ catch (_d) {
75
109
  this.close();
76
110
  return;
77
111
  }
78
112
  const valid = hello.t === 'hello' && hello.v === 1 && typeof hello.nonce === 'string';
79
113
  const device = valid ? this.options.store.device(hello.device) : undefined;
80
114
  const share = valid && !device && this.options.sharePackage ? this.options.store.share(hello.device) : undefined;
81
- const key = (_a = device === null || device === void 0 ? void 0 : device.key) !== null && _a !== void 0 ? _a : share === null || share === void 0 ? void 0 : share.key;
115
+ const content = valid && !device && !share && this.options.shareContent ? this.options.store.content(hello.device) : undefined;
116
+ if (content && this.host.blocked(content.id)) {
117
+ this.answer({ t: 'refused', reason: 'busy' });
118
+ this.close();
119
+ return;
120
+ }
121
+ const people = (content === null || content === void 0 ? void 0 : content.access) === 'people' ? ((_a = content.people) !== null && _a !== void 0 ? _a : []).map(person => person.key) : undefined;
122
+ const key = (_c = (_b = device === null || device === void 0 ? void 0 : device.key) !== null && _b !== void 0 ? _b : share === null || share === void 0 ? void 0 : share.key) !== null && _c !== void 0 ? _c : ((content === null || content === void 0 ? void 0 : content.access) === 'self' ? undefined : people ? people[0] : content === null || content === void 0 ? void 0 : content.key);
82
123
  if (!key) {
83
124
  this.answer({ t: 'refused', reason: 'This device is not paired.' });
84
125
  this.close();
@@ -88,7 +129,25 @@ class RelayChannel {
88
129
  const nonce = RelayBytes.random(16);
89
130
  const cipher = await RelayCipher.derive(RelayBytes.fromBase64(key), RelayBytes.fromBase64(hello.nonce), nonce, 'host');
90
131
  this.cipher = cipher;
132
+ if (people) {
133
+ this.candidates = [
134
+ cipher,
135
+ ...(await Promise.all(people.slice(1).map(other => RelayCipher.derive(RelayBytes.fromBase64(other), RelayBytes.fromBase64(hello.nonce), nonce, 'host')))),
136
+ ];
137
+ }
138
+ if (share) {
139
+ this.mode = 'share';
140
+ }
91
141
  const compress = hello.z === 1 && RelayDeflate.supported();
142
+ if (content) {
143
+ // The viewer proves first: what this side seals would let one with the link but not the password try passwords offline.
144
+ this.content = content;
145
+ this.compress = compress;
146
+ // A viewer that never proves would hold one of the places of the devices.
147
+ this.proofTimer = setTimeout(() => this.close(), HELLO_TIMEOUT_MS);
148
+ this.answer({ t: 'ready', nonce: RelayBytes.toBase64(nonce), ...(compress ? { z: 1 } : {}) });
149
+ return;
150
+ }
92
151
  const proof = await cipher.seal(RELAY_PROOF);
93
152
  // The messages after the proof, both ways: the device sets it once it opened the proof.
94
153
  cipher.compress = compress;
@@ -97,6 +156,44 @@ class RelayChannel {
97
156
  await this.sendShare(cipher, share);
98
157
  }
99
158
  }
159
+ /** The first sealed message of a viewer of content: its proof, then the content; a wrong one is counted, and refused. */
160
+ async proven(cipher, content, data) {
161
+ this.content = undefined;
162
+ clearTimeout(this.proofTimer);
163
+ if (data !== RELAY_PROOF) {
164
+ this.wrongKey(content);
165
+ this.close();
166
+ return;
167
+ }
168
+ cipher.compress = this.compress;
169
+ this.mode = 'content';
170
+ const send = async (message) => this.host.send({ t: 'data', ch: this.id, d: await cipher.seal(JSON.stringify(message)) });
171
+ const bytes = this.options.store.content(content.id) ? this.options.store.contentData(content) : undefined;
172
+ if (!bytes) {
173
+ await send({ t: 'error', message: 'This link no longer works: the share was stopped or ran out.' });
174
+ }
175
+ else {
176
+ await send({
177
+ t: 'content',
178
+ kind: content.kind,
179
+ title: content.title,
180
+ size: bytes.length,
181
+ createdAt: content.createdAt,
182
+ ...(content.type ? { type: content.type } : {}),
183
+ });
184
+ for (let at = 0; at < bytes.length; at += RELAY_SHARE_CHUNK_BYTES) {
185
+ await send({ t: 'chunk', d: RelayBytes.toBase64(bytes.subarray(at, at + RELAY_SHARE_CHUNK_BYTES)) });
186
+ }
187
+ await send({ t: 'end' });
188
+ }
189
+ this.close();
190
+ }
191
+ /** The key did not open: told in the clear (the viewer cannot open what is sealed), and counted. */
192
+ wrongKey(content) {
193
+ this.content = undefined;
194
+ this.answer({ t: 'refused', reason: 'key' });
195
+ this.host.wrongKey(content.id);
196
+ }
100
197
  /** A package handed on: what it is, its bytes in chunks, the end; then the channel closes. It never reaches ta serve's socket. */
101
198
  async sendShare(cipher, share) {
102
199
  const send = async (message) => this.host.send({ t: 'data', ch: this.id, d: await cipher.seal(JSON.stringify(message)) });
@@ -134,6 +231,7 @@ class RelayChannel {
134
231
  }
135
232
  close() {
136
233
  clearTimeout(this.timer);
234
+ clearTimeout(this.proofTimer);
137
235
  this.host.closeChannel(this.id);
138
236
  }
139
237
  }
@@ -148,6 +246,18 @@ export class RelayHost {
148
246
  this.stopped = false;
149
247
  this.attempts = 0;
150
248
  this.channels = new Map();
249
+ /** Wrong keys of each share of content, of late. */
250
+ this.wrong = new Map();
251
+ }
252
+ /** @internal Whether a share of content had too many wrong keys of late. */
253
+ blocked(contentId, now = Date.now()) {
254
+ const wrong = this.wrong.get(contentId);
255
+ return !!wrong && now - wrong.since < WRONG_KEY_WINDOW_MS && wrong.count >= MAX_WRONG_KEYS;
256
+ }
257
+ /** @internal */
258
+ wrongKey(contentId, now = Date.now()) {
259
+ const wrong = this.wrong.get(contentId);
260
+ this.wrong.set(contentId, wrong && now - wrong.since < WRONG_KEY_WINDOW_MS ? { count: wrong.count + 1, since: wrong.since } : { count: 1, since: now });
151
261
  }
152
262
  /** Whether the connection to the relay is open. */
153
263
  get online() {
@@ -162,7 +272,8 @@ export class RelayHost {
162
272
  /** relay.json may have changed: connect if it now has devices, or leave if it has none. */
163
273
  refresh() {
164
274
  const { url, host, devices } = this.options.store.read();
165
- const shared = !!this.options.sharePackage && this.options.store.shares().length > 0;
275
+ const shared = (!!this.options.sharePackage && this.options.store.shares().length > 0) ||
276
+ (!!this.options.shareContent && this.options.store.contents().some(content => content.access !== 'self'));
166
277
  const wanted = !this.stopped && url !== undefined && host !== undefined && (devices.length > 0 || shared);
167
278
  if (!wanted) {
168
279
  this.disconnect();
@@ -0,0 +1,12 @@
1
+ import type { RelayHubsStore, RelayHubsStoreName } from '../common/relay-hubs.js';
2
+ /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
3
+ export declare class RelayHubFiles implements RelayHubsStore {
4
+ readonly agentDir: string;
5
+ constructor(agentDir: string);
6
+ file(name: RelayHubsStoreName): string;
7
+ read<T>(name: RelayHubsStoreName): T | undefined;
8
+ /** Written whole, then renamed over the file, readable by the user alone: it holds keys. */
9
+ write(name: RelayHubsStoreName, value: unknown): void;
10
+ /** The name of a new identity: the user's on this system. */
11
+ static userName(): string;
12
+ }