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