@celljs/ta-relay 4.9.1 → 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 (118) hide show
  1. package/README.en.md +29 -2
  2. package/README.md +29 -2
  3. package/esm/common/index.d.ts +10 -0
  4. package/esm/common/index.js +10 -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-cipher.d.ts +15 -0
  10. package/esm/common/relay-cipher.js +62 -2
  11. package/esm/common/relay-content.d.ts +104 -0
  12. package/esm/common/relay-content.js +316 -0
  13. package/esm/common/relay-conversation.d.ts +59 -0
  14. package/esm/common/relay-conversation.js +9 -0
  15. package/esm/common/relay-files.d.ts +108 -0
  16. package/esm/common/relay-files.js +170 -0
  17. package/esm/common/relay-hub-util.d.ts +91 -0
  18. package/esm/common/relay-hub-util.js +164 -0
  19. package/esm/common/relay-hub.d.ts +125 -0
  20. package/esm/common/relay-hub.js +438 -0
  21. package/esm/common/relay-hubs.d.ts +271 -0
  22. package/esm/common/relay-hubs.js +844 -0
  23. package/esm/common/relay-identity.d.ts +46 -0
  24. package/esm/common/relay-identity.js +126 -0
  25. package/esm/common/relay-protocol.d.ts +217 -2
  26. package/esm/common/relay-protocol.js +53 -0
  27. package/esm/common/relay-room-chat.d.ts +80 -0
  28. package/esm/common/relay-room-chat.js +152 -0
  29. package/esm/common/relay-socket.d.ts +8 -0
  30. package/esm/common/relay-socket.js +33 -4
  31. package/esm/guest/guest-i18n.d.ts +47 -0
  32. package/esm/guest/guest-i18n.js +97 -0
  33. package/esm/guest/guest-style.d.ts +1 -0
  34. package/esm/guest/guest-style.js +78 -0
  35. package/esm/guest/guest.d.ts +1 -0
  36. package/esm/guest/guest.js +371 -0
  37. package/esm/node/index.d.ts +3 -0
  38. package/esm/node/index.js +3 -0
  39. package/esm/node/relay-files-host.d.ts +27 -0
  40. package/esm/node/relay-files-host.js +130 -0
  41. package/esm/node/relay-host.d.ts +35 -2
  42. package/esm/node/relay-host.js +150 -13
  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 +10 -0
  60. package/lib/common/index.js +10 -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-cipher.d.ts +15 -0
  66. package/lib/common/relay-cipher.js +63 -3
  67. package/lib/common/relay-content.d.ts +105 -0
  68. package/lib/common/relay-content.js +320 -0
  69. package/lib/common/relay-conversation.d.ts +60 -0
  70. package/lib/common/relay-conversation.js +12 -0
  71. package/lib/common/relay-files.d.ts +109 -0
  72. package/lib/common/relay-files.js +174 -0
  73. package/lib/common/relay-hub-util.d.ts +92 -0
  74. package/lib/common/relay-hub-util.js +167 -0
  75. package/lib/common/relay-hub.d.ts +126 -0
  76. package/lib/common/relay-hub.js +442 -0
  77. package/lib/common/relay-hubs.d.ts +272 -0
  78. package/lib/common/relay-hubs.js +848 -0
  79. package/lib/common/relay-identity.d.ts +47 -0
  80. package/lib/common/relay-identity.js +129 -0
  81. package/lib/common/relay-protocol.d.ts +217 -2
  82. package/lib/common/relay-protocol.js +54 -1
  83. package/lib/common/relay-room-chat.d.ts +81 -0
  84. package/lib/common/relay-room-chat.js +156 -0
  85. package/lib/common/relay-socket.d.ts +8 -0
  86. package/lib/common/relay-socket.js +32 -3
  87. package/lib/guest/guest-i18n.d.ts +48 -0
  88. package/lib/guest/guest-i18n.js +100 -0
  89. package/lib/guest/guest-style.d.ts +2 -0
  90. package/lib/guest/guest-style.js +81 -0
  91. package/lib/guest/guest.d.ts +2 -0
  92. package/lib/guest/guest.js +373 -0
  93. package/lib/node/index.d.ts +3 -0
  94. package/lib/node/index.js +3 -0
  95. package/lib/node/relay-files-host.d.ts +28 -0
  96. package/lib/node/relay-files-host.js +134 -0
  97. package/lib/node/relay-host.d.ts +35 -2
  98. package/lib/node/relay-host.js +149 -12
  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 +87 -0
@@ -0,0 +1,316 @@
1
+ import { RelayBytes } from './relay-bytes.js';
2
+ import { RelayIdentityUtil } from './relay-identity.js';
3
+ import { RELAY_BLOB_PATH, RELAY_CONTENT_MAX_BYTES, RELAY_CONTENT_PATH, RELAY_ID, RelayCloseCode } from './relay-protocol.js';
4
+ import { RelaySocket } from './relay-socket.js';
5
+ const encoder = new TextEncoder();
6
+ const decoder = new TextDecoder();
7
+ export class RelayContentError extends Error {
8
+ constructor(reason, message) {
9
+ super(message);
10
+ this.reason = reason;
11
+ this.name = 'RelayContentError';
12
+ }
13
+ }
14
+ const PBKDF2_ITERATIONS = 600000;
15
+ /** Kinds the links of before carry no `c` for. */
16
+ const PLAIN_KINDS = new Set(['ta-conversation', 'file']);
17
+ const KIND = /^[a-z0-9][a-z0-9-]{0,31}$/;
18
+ /**
19
+ * Content shared by a link (docs/design/ta-link.md): its link, its keys, and how it is fetched, from the
20
+ * computer that shared it through the relay, or from the copy the relay keeps sealed. Runs the same in a
21
+ * browser (the viewer of the relay), in ta serve and in a Worker: WebCrypto, fetch and WebSocket only.
22
+ */
23
+ export var RelayContentUtil;
24
+ (function (RelayContentUtil) {
25
+ /**
26
+ * `https://<relay>/s#v=1&h=<host>&s=<share>&k=<key>`, with `p=1` for a password, `m=self`, `o=1` for a copy on the relay,
27
+ * `c=<kind>` for what is no conversation or file.
28
+ */
29
+ function link(content) {
30
+ var _a;
31
+ const fragment = new URLSearchParams({ v: '1', h: content.host, s: content.share });
32
+ if (content.access === 'self') {
33
+ fragment.set('m', 'self');
34
+ }
35
+ else if (content.access === 'people') {
36
+ fragment.set('m', 'people');
37
+ fragment.set('o', (_a = content.owner) !== null && _a !== void 0 ? _a : '');
38
+ }
39
+ else if (content.key) {
40
+ fragment.set('k', content.key);
41
+ }
42
+ if (content.access === 'password') {
43
+ fragment.set('p', '1');
44
+ }
45
+ if (content.offline && content.access !== 'self' && content.access !== 'people') {
46
+ fragment.set('o', '1');
47
+ }
48
+ if (content.kind && !PLAIN_KINDS.has(content.kind) && KIND.test(content.kind)) {
49
+ fragment.set('c', content.kind);
50
+ }
51
+ return `${content.relay}${RELAY_CONTENT_PATH}#${fragment}`;
52
+ }
53
+ RelayContentUtil.link = link;
54
+ function is(text) {
55
+ try {
56
+ parse(text);
57
+ return true;
58
+ }
59
+ catch (_a) {
60
+ return false;
61
+ }
62
+ }
63
+ RelayContentUtil.is = is;
64
+ /** Throws on what is not a link of {@link link}. */
65
+ function parse(text) {
66
+ var _a, _b;
67
+ const url = new URL(text.trim());
68
+ const fragment = new URLSearchParams(url.hash.slice(1));
69
+ const [host, share, key] = ['h', 's', 'k'].map(name => { var _a; return (_a = fragment.get(name)) !== null && _a !== void 0 ? _a : ''; });
70
+ const self = fragment.get('m') === 'self';
71
+ const people = fragment.get('m') === 'people';
72
+ const owner = (_a = fragment.get('o')) !== null && _a !== void 0 ? _a : '';
73
+ if (!/^https?:$/.test(url.protocol) ||
74
+ url.pathname !== RELAY_CONTENT_PATH ||
75
+ fragment.get('v') !== '1' ||
76
+ !RELAY_ID.test(host) ||
77
+ !RELAY_ID.test(share) ||
78
+ (people ? !/^[A-Za-z0-9_-]{22}$/.test(owner) : !self && !/^[A-Za-z0-9_-]{43}$/.test(key))) {
79
+ throw new RelayContentError('invalid', 'Not a link of something shared from Ta.');
80
+ }
81
+ const kind = (_b = fragment.get('c')) !== null && _b !== void 0 ? _b : '';
82
+ if (people) {
83
+ return { relay: url.origin, host, share, access: 'people', owner, offline: false, ...(KIND.test(kind) ? { kind } : {}) };
84
+ }
85
+ return {
86
+ relay: url.origin,
87
+ host,
88
+ share,
89
+ key: self ? undefined : key,
90
+ access: self ? 'self' : fragment.get('p') === '1' ? 'password' : 'link',
91
+ offline: !self && fragment.get('o') === '1',
92
+ ...(KIND.test(kind) ? { kind } : {}),
93
+ };
94
+ }
95
+ RelayContentUtil.parse = parse;
96
+ /**
97
+ * The key the content is sealed with: the key of the link, or with a password, one derived from both
98
+ * (PBKDF2 of the password, then HKDF with the key of the link), so that neither alone opens it.
99
+ */
100
+ async function contentKey(linkKey, share, password) {
101
+ if (password === undefined) {
102
+ return linkKey;
103
+ }
104
+ const subtle = globalThis.crypto.subtle;
105
+ const secret = await subtle.importKey('raw', encoder.encode(password.normalize('NFC')), 'PBKDF2', false, ['deriveBits']);
106
+ const stretched = await subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt: encoder.encode(`ta-share:${share}`), iterations: PBKDF2_ITERATIONS }, secret, 256);
107
+ return hkdf(linkKey, new Uint8Array(stretched), 'ta-share/1 password');
108
+ }
109
+ RelayContentUtil.contentKey = contentKey;
110
+ /**
111
+ * The key of content shared with a Ta friend (`people`): only the two make it, each with its own private key and the
112
+ * other's public one, for this share alone.
113
+ */
114
+ function peopleKey(identity, otherBox, share) {
115
+ return RelayIdentityUtil.agree(identity, otherBox, share, 'ta-share/1 people');
116
+ }
117
+ RelayContentUtil.peopleKey = peopleKey;
118
+ /** What reads the copy on the relay, which keeps only its SHA-256 (`x-ta-auth`). */
119
+ async function authToken(key) {
120
+ return RelayBytes.toBase64(await hkdf(key, new Uint8Array(0), 'ta-share/1 auth'));
121
+ }
122
+ RelayContentUtil.authToken = authToken;
123
+ async function sha256(text) {
124
+ return RelayBytes.toBase64(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', encoder.encode(text))));
125
+ }
126
+ RelayContentUtil.sha256 = sha256;
127
+ /** The bytes of the copy on the relay: a random IV, then AES-256-GCM of {@link encode}. */
128
+ async function seal(key, item) {
129
+ const iv = RelayBytes.random(12);
130
+ const sealed = await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv }, await blobKey(key), encode(item));
131
+ return RelayBytes.concat(iv, new Uint8Array(sealed));
132
+ }
133
+ RelayContentUtil.seal = seal;
134
+ /** Throws when it was not sealed with this key. */
135
+ async function open(key, bytes) {
136
+ const opened = await globalThis.crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.subarray(0, 12) }, await blobKey(key), bytes.subarray(12));
137
+ return decode(new Uint8Array(opened));
138
+ }
139
+ RelayContentUtil.open = open;
140
+ /** The header as JSON behind its length (4 bytes), then the data. */
141
+ function encode(item) {
142
+ const { data, ...header } = item;
143
+ const head = encoder.encode(JSON.stringify(header));
144
+ const length = new Uint8Array(4);
145
+ new DataView(length.buffer).setUint32(0, head.length);
146
+ return RelayBytes.concat(length, head, data);
147
+ }
148
+ RelayContentUtil.encode = encode;
149
+ function decode(bytes) {
150
+ const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0);
151
+ const header = JSON.parse(decoder.decode(bytes.subarray(4, 4 + length)));
152
+ return {
153
+ kind: String(header.kind),
154
+ title: String(header.title),
155
+ createdAt: Number(header.createdAt),
156
+ type: header.type,
157
+ data: bytes.slice(4 + length),
158
+ };
159
+ }
160
+ RelayContentUtil.decode = decode;
161
+ /**
162
+ * What a link shares: from the copy on the relay when it has one, else from the computer that shared it,
163
+ * end to end through the relay. Rejects with a RelayContentError that says why it cannot.
164
+ */
165
+ async function fetch(text, options = {}) {
166
+ const link = typeof text === 'string' ? parse(text) : text;
167
+ if (link.access === 'people') {
168
+ if (!options.people) {
169
+ throw new RelayContentError('people', 'Only the Ta friends it was shared with open it, in their own Ta.');
170
+ }
171
+ return fromHost(link, await peopleKey(options.people.identity, options.people.ownerBox, link.share), options);
172
+ }
173
+ if (link.access === 'self' || !link.key) {
174
+ throw new RelayContentError('self', 'Only the one who shared it opens it, in their own Ta.');
175
+ }
176
+ if (link.access === 'password' && !options.password) {
177
+ throw new RelayContentError('password', 'It is shared with a password.');
178
+ }
179
+ const key = await contentKey(RelayBytes.fromBase64(link.key), link.share, link.access === 'password' ? options.password : undefined);
180
+ if (link.offline) {
181
+ const copy = await fromRelay(link, key);
182
+ if (copy) {
183
+ return copy;
184
+ }
185
+ }
186
+ return fromHost(link, key, options);
187
+ }
188
+ RelayContentUtil.fetch = fetch;
189
+ /** The copy on the relay; undefined when there is none (any more), to ask the computer instead. */
190
+ async function fromRelay(link, key) {
191
+ let response;
192
+ try {
193
+ response = await globalThis.fetch(`${link.relay}${RELAY_BLOB_PATH}${link.share}`, { headers: { 'x-ta-auth': await authToken(key) } });
194
+ }
195
+ catch (_a) {
196
+ return undefined;
197
+ }
198
+ if (response.status === 403) {
199
+ throw link.access === 'password'
200
+ ? new RelayContentError('wrong', 'The password is wrong.')
201
+ : new RelayContentError('gone', 'This link no longer works.');
202
+ }
203
+ if (response.status === 429) {
204
+ throw new RelayContentError('busy', 'Too many wrong passwords: try again in a few minutes.');
205
+ }
206
+ if (!response.ok) {
207
+ return undefined;
208
+ }
209
+ try {
210
+ return await open(key, new Uint8Array(await response.arrayBuffer()));
211
+ }
212
+ catch (_b) {
213
+ throw new RelayContentError('wrong', 'The password is wrong.');
214
+ }
215
+ }
216
+ function fromHost(link, key, options) {
217
+ var _a;
218
+ const max = (_a = options.maxBytes) !== null && _a !== void 0 ? _a : RELAY_CONTENT_MAX_BYTES;
219
+ const pairing = { relay: link.relay, host: link.host, device: link.share, key: RelayBytes.toBase64(key) };
220
+ return new Promise((resolve, reject) => {
221
+ var _a;
222
+ const socket = new RelaySocket(pairing, { proveFirst: true });
223
+ const chunks = [];
224
+ let received = 0;
225
+ let header;
226
+ let done = false;
227
+ const finish = (error, item) => {
228
+ if (done) {
229
+ return;
230
+ }
231
+ done = true;
232
+ clearTimeout(timer);
233
+ socket.onclose = null;
234
+ socket.close();
235
+ if (item) {
236
+ resolve(item);
237
+ }
238
+ else {
239
+ reject(error);
240
+ }
241
+ };
242
+ const timer = setTimeout(() => finish(new RelayContentError('timeout', 'The computer that shared it took too long to send it.')), (_a = options.timeoutMs) !== null && _a !== void 0 ? _a : 60000);
243
+ socket.onmessage = ({ data }) => {
244
+ let message;
245
+ try {
246
+ message = JSON.parse(data);
247
+ }
248
+ catch (_a) {
249
+ finish(new RelayContentError('invalid', 'The computer that shared it sent what is not content.'));
250
+ return;
251
+ }
252
+ if (message.t === 'error') {
253
+ finish(new RelayContentError('gone', message.message));
254
+ }
255
+ else if (message.t === 'content') {
256
+ if (!(message.size >= 0) || message.size > max) {
257
+ finish(new RelayContentError('large', `It is larger than ${Math.round(max / 1024 / 1024)} MB.`));
258
+ return;
259
+ }
260
+ header = {
261
+ kind: String(message.kind),
262
+ title: String(message.title),
263
+ createdAt: Number(message.createdAt),
264
+ type: message.type,
265
+ size: message.size,
266
+ };
267
+ }
268
+ else if (message.t === 'chunk' && header) {
269
+ const bytes = RelayBytes.fromBase64(message.d);
270
+ received += bytes.length;
271
+ if (received > header.size) {
272
+ finish(new RelayContentError('invalid', 'It is larger than it said.'));
273
+ return;
274
+ }
275
+ chunks.push(bytes);
276
+ }
277
+ else if (message.t === 'end' && header) {
278
+ if (received !== header.size) {
279
+ finish(new RelayContentError('invalid', 'It came short.'));
280
+ return;
281
+ }
282
+ const { size: _size, ...rest } = header;
283
+ finish(undefined, { ...rest, data: RelayBytes.concat(...chunks) });
284
+ }
285
+ };
286
+ socket.onclose = ({ code, reason }) => finish(closed(code, reason, link));
287
+ });
288
+ }
289
+ function closed(code, reason, link) {
290
+ if (code === RelaySocket.REFUSED) {
291
+ if (reason === 'key') {
292
+ return link.access === 'password'
293
+ ? new RelayContentError('wrong', 'The password is wrong.')
294
+ : new RelayContentError('gone', 'This link no longer works.');
295
+ }
296
+ if (reason === 'busy') {
297
+ return new RelayContentError('busy', 'Too many wrong passwords: try again in a few minutes.');
298
+ }
299
+ return new RelayContentError('gone', 'This link no longer works: the share was stopped or ran out.');
300
+ }
301
+ return code === RelayCloseCode.HOST_OFFLINE || code === RelayCloseCode.TIMEOUT
302
+ ? new RelayContentError('offline', 'The computer that shared it is not running Ta now. Try again later.')
303
+ : new RelayContentError('offline', 'The computer that shared it cannot be reached now. Try again later.');
304
+ }
305
+ async function blobKey(key) {
306
+ const bytes = await hkdf(key, new Uint8Array(0), 'ta-share/1 blob');
307
+ return globalThis.crypto.subtle.importKey('raw', bytes, 'AES-GCM', false, ['encrypt', 'decrypt']);
308
+ }
309
+ async function hkdf(key, salt, info) {
310
+ const subtle = globalThis.crypto.subtle;
311
+ const secret = await subtle.importKey('raw', key, 'HKDF', false, ['deriveBits']);
312
+ const bits = await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: salt, info: encoder.encode(info) }, secret, 256);
313
+ return new Uint8Array(bits);
314
+ }
315
+ })(RelayContentUtil || (RelayContentUtil = {}));
316
+ //# sourceMappingURL=relay-content.js.map
@@ -0,0 +1,59 @@
1
+ /**
2
+ * A conversation shared by a link (RelayContentHeader.kind `ta-conversation`): pi's messages of its branch, as
3
+ * the one who shared it chose to hand on (docs/design/ta-link.md 2.8). The viewer of the relay draws it; Ta
4
+ * draws it too, and imports it as a conversation of its own.
5
+ */
6
+ export declare const RELAY_CONVERSATION_KIND = "ta-conversation";
7
+ /** A file or a page: its bytes, with RelayContentHeader.type. */
8
+ export declare const RELAY_FILE_KIND = "file";
9
+ export type RelayConversationPart = {
10
+ type: 'text';
11
+ text: string;
12
+ } | {
13
+ type: 'thinking';
14
+ thinking: string;
15
+ } | {
16
+ type: 'image';
17
+ data?: string;
18
+ mimeType?: string;
19
+ } | {
20
+ type: 'toolCall';
21
+ id: string;
22
+ name: string;
23
+ arguments: Record<string, unknown>;
24
+ };
25
+ /** pi's AgentMessage, the parts a conversation shows; the rest of what pi keeps passes through untouched. */
26
+ export type RelayConversationMessage = {
27
+ role: 'user';
28
+ content: string | RelayConversationPart[];
29
+ timestamp?: number;
30
+ } | {
31
+ role: 'assistant';
32
+ content: RelayConversationPart[];
33
+ model?: string;
34
+ provider?: string;
35
+ stopReason?: string;
36
+ errorMessage?: string;
37
+ timestamp?: number;
38
+ } | {
39
+ role: 'toolResult';
40
+ toolCallId: string;
41
+ toolName: string;
42
+ content: RelayConversationPart[];
43
+ isError?: boolean;
44
+ timestamp?: number;
45
+ };
46
+ export interface RelayConversation {
47
+ v: 1;
48
+ title: string;
49
+ /** The name of its directory, for a line under the title. */
50
+ place?: string;
51
+ messages: RelayConversationMessage[];
52
+ /** What was left out when it was shared: the outputs of its tools, and how many images. */
53
+ omitted?: {
54
+ outputs?: boolean;
55
+ images?: number;
56
+ };
57
+ /** How many places looked like a secret, and were taken out. */
58
+ redacted?: number;
59
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A conversation shared by a link (RelayContentHeader.kind `ta-conversation`): pi's messages of its branch, as
3
+ * the one who shared it chose to hand on (docs/design/ta-link.md 2.8). The viewer of the relay draws it; Ta
4
+ * draws it too, and imports it as a conversation of its own.
5
+ */
6
+ export const RELAY_CONVERSATION_KIND = 'ta-conversation';
7
+ /** A file or a page: its bytes, with RelayContentHeader.type. */
8
+ export const RELAY_FILE_KIND = 'file';
9
+ //# sourceMappingURL=relay-conversation.js.map
@@ -0,0 +1,108 @@
1
+ import type { RelayPairing } from './relay-pairing.js';
2
+ import { RelaySocket } from './relay-socket.js';
3
+ /**
4
+ * The files of the workspace through the relay, for a page of a device that cannot load them by URL: behind
5
+ * a relay, and in the app on a phone, only the calls on the WebSocket reach ta serve, so `/api/files` is
6
+ * asked for here instead, on a channel of its own. The frames below are what that channel carries in place
7
+ * of the JSON-RPC of `/api/ws`; the relay forwards them sealed as it does the rest, and reads neither.
8
+ *
9
+ * The host answers only a path of {@link RELAY_FILES_PREFIX}, with GET, at the loopback address of its own
10
+ * ta serve: a device has the whole of ta serve already, and a relay that could be made to ask for anything
11
+ * else would be a way into the machine.
12
+ */
13
+ export type RelayFilesFrame =
14
+ /** The first frame of a device on a channel: this one asks for files, not for `/api/ws`. */
15
+ {
16
+ t: 'files';
17
+ v: 1;
18
+ }
19
+ /** A file to read; a URL of {@link RELAY_FILES_PREFIX}. */
20
+ | {
21
+ t: 'get';
22
+ id: number;
23
+ url: string;
24
+ }
25
+ /** What ta serve answers before the bytes. */
26
+ | {
27
+ t: 'head';
28
+ id: number;
29
+ status: number;
30
+ type?: string;
31
+ size?: number;
32
+ } | {
33
+ t: 'chunk';
34
+ id: number;
35
+ d: string;
36
+ } | {
37
+ t: 'end';
38
+ id: number;
39
+ } | {
40
+ t: 'error';
41
+ id: number;
42
+ message: string;
43
+ };
44
+ /** The only paths of ta serve a device may ask for: the ones answered without its token. */
45
+ export declare const RELAY_FILES_PREFIX = "/api/files/";
46
+ /** The bytes of a chunk, base64 in a sealed frame: well under the 1 MiB of a message of Cloudflare. */
47
+ export declare const RELAY_FILE_CHUNK_BYTES: number;
48
+ /** The largest file a device reads this way: a video of a workspace is previewed by its first bytes, not all of it. */
49
+ export declare const RELAY_FILE_MAX_BYTES: number;
50
+ /** Files read at once on one channel; a page that loads its pictures asks for several. */
51
+ export declare const RELAY_FILES_MAX_PARALLEL = 4;
52
+ /** For one file, all of it. */
53
+ export declare const RELAY_FILES_TIMEOUT_MS = 30000;
54
+ /** A file as the page gets it: its type as ta serve answers it, and the bytes. */
55
+ export interface RelayFileBytes {
56
+ type: string;
57
+ size: number;
58
+ data: Uint8Array;
59
+ }
60
+ export declare namespace RelayFilesUtil {
61
+ /** The frame that turns a channel into a channel of files. */
62
+ function hello(): RelayFilesFrame;
63
+ /** Whether a frame of a device asks for files, rather than for ta serve's socket (`{t:'files', v:1}`). */
64
+ function isHello(text: string): boolean;
65
+ }
66
+ /** One file asked for, and what came of it so far. */
67
+ interface Pending {
68
+ readonly chunks: Uint8Array[];
69
+ received: number;
70
+ head?: {
71
+ type: string;
72
+ size: number;
73
+ };
74
+ readonly resolve: (bytes: RelayFileBytes) => void;
75
+ readonly reject: (error: Error) => void;
76
+ readonly timer: ReturnType<typeof setTimeout>;
77
+ }
78
+ export interface RelayFilesOptions {
79
+ /** For one file. Default RELAY_FILES_TIMEOUT_MS. */
80
+ timeoutMs?: number;
81
+ }
82
+ /**
83
+ * The files of the ta serve of a pairing, through the relay: a channel of its own, kept open for the page,
84
+ * sealed end to end as the connection of a device is. It behaves for the page as loading the URL does.
85
+ */
86
+ export declare class RelayFiles {
87
+ protected readonly pairing: RelayPairing;
88
+ protected readonly options: RelayFilesOptions;
89
+ protected socket?: RelaySocket;
90
+ protected opening?: Promise<void>;
91
+ protected called: number;
92
+ protected readonly pending: Map<number, Pending>;
93
+ constructor(pairing: RelayPairing, options?: RelayFilesOptions);
94
+ /** The bytes of a URL of {@link RELAY_FILES_PREFIX}, as ta serve answers them. */
95
+ get(url: string): Promise<RelayFileBytes>;
96
+ /** Whether the channel is open: the page may keep one for as long as it shows files. */
97
+ get open(): boolean;
98
+ close(): void;
99
+ protected send(frame: RelayFilesFrame): void;
100
+ /** Opens the channel, once: the first file asked for opens it. */
101
+ protected connect(): Promise<void>;
102
+ protected receive(text: string): void;
103
+ protected settle(id: number, error: Error): void;
104
+ protected finish(id: number, bytes: RelayFileBytes): void;
105
+ /** The channel went: what was asked for is not coming. */
106
+ protected fail(error: Error): void;
107
+ }
108
+ export {};
@@ -0,0 +1,170 @@
1
+ import { RelayBytes } from './relay-bytes.js';
2
+ import { RelaySocket } from './relay-socket.js';
3
+ /** The only paths of ta serve a device may ask for: the ones answered without its token. */
4
+ export const RELAY_FILES_PREFIX = '/api/files/';
5
+ /** The bytes of a chunk, base64 in a sealed frame: well under the 1 MiB of a message of Cloudflare. */
6
+ export const RELAY_FILE_CHUNK_BYTES = 192 * 1024;
7
+ /** The largest file a device reads this way: a video of a workspace is previewed by its first bytes, not all of it. */
8
+ export const RELAY_FILE_MAX_BYTES = 128 * 1024 * 1024;
9
+ /** Files read at once on one channel; a page that loads its pictures asks for several. */
10
+ export const RELAY_FILES_MAX_PARALLEL = 4;
11
+ /** For one file, all of it. */
12
+ export const RELAY_FILES_TIMEOUT_MS = 30000;
13
+ export var RelayFilesUtil;
14
+ (function (RelayFilesUtil) {
15
+ /** The frame that turns a channel into a channel of files. */
16
+ function hello() {
17
+ return { t: 'files', v: 1 };
18
+ }
19
+ RelayFilesUtil.hello = hello;
20
+ /** Whether a frame of a device asks for files, rather than for ta serve's socket (`{t:'files', v:1}`). */
21
+ function isHello(text) {
22
+ try {
23
+ const frame = JSON.parse(text);
24
+ return frame.t === 'files' && frame.v === 1;
25
+ }
26
+ catch (_a) {
27
+ return false;
28
+ }
29
+ }
30
+ RelayFilesUtil.isHello = isHello;
31
+ })(RelayFilesUtil || (RelayFilesUtil = {}));
32
+ /**
33
+ * The files of the ta serve of a pairing, through the relay: a channel of its own, kept open for the page,
34
+ * sealed end to end as the connection of a device is. It behaves for the page as loading the URL does.
35
+ */
36
+ export class RelayFiles {
37
+ constructor(pairing, options = {}) {
38
+ this.pairing = pairing;
39
+ this.options = options;
40
+ this.called = 1;
41
+ this.pending = new Map();
42
+ }
43
+ /** The bytes of a URL of {@link RELAY_FILES_PREFIX}, as ta serve answers them. */
44
+ async get(url) {
45
+ if (!url.startsWith(RELAY_FILES_PREFIX)) {
46
+ throw new Error('Ta reads only the files it offers by URL.');
47
+ }
48
+ await this.connect();
49
+ const id = this.called++;
50
+ return new Promise((resolve, reject) => {
51
+ var _a;
52
+ const timeout = (_a = this.options.timeoutMs) !== null && _a !== void 0 ? _a : RELAY_FILES_TIMEOUT_MS;
53
+ const timer = setTimeout(() => this.settle(id, new Error('The file took too long to come.')), timeout);
54
+ this.pending.set(id, { chunks: [], received: 0, resolve, reject, timer });
55
+ this.send({ t: 'get', id, url });
56
+ });
57
+ }
58
+ /** Whether the channel is open: the page may keep one for as long as it shows files. */
59
+ get open() {
60
+ var _a;
61
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === RelaySocket.OPEN;
62
+ }
63
+ close() {
64
+ const socket = this.socket;
65
+ this.socket = undefined;
66
+ this.opening = undefined;
67
+ this.fail(new Error('The files are closed.'));
68
+ socket === null || socket === void 0 ? void 0 : socket.close();
69
+ }
70
+ send(frame) {
71
+ var _a;
72
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(frame));
73
+ }
74
+ /** Opens the channel, once: the first file asked for opens it. */
75
+ connect() {
76
+ var _a;
77
+ if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === RelaySocket.OPEN) {
78
+ return Promise.resolve();
79
+ }
80
+ if (!this.opening) {
81
+ const socket = new RelaySocket(this.pairing);
82
+ this.socket = socket;
83
+ this.opening = new Promise((resolve, reject) => {
84
+ socket.onmessage = ({ data }) => this.receive(data);
85
+ socket.onopen = () => {
86
+ this.send(RelayFilesUtil.hello());
87
+ resolve();
88
+ };
89
+ socket.onclose = ({ code }) => {
90
+ const error = new Error(code === RelaySocket.REFUSED
91
+ ? 'This device is no longer paired with the computer.'
92
+ : 'The computer is not running Ta, or cannot be reached.');
93
+ if (this.socket === socket) {
94
+ this.socket = undefined;
95
+ }
96
+ this.fail(error);
97
+ reject(error);
98
+ };
99
+ });
100
+ const clear = () => {
101
+ this.opening = undefined;
102
+ };
103
+ this.opening.then(clear, clear);
104
+ }
105
+ return this.opening;
106
+ }
107
+ receive(text) {
108
+ var _a, _b;
109
+ let frame;
110
+ try {
111
+ frame = JSON.parse(text);
112
+ }
113
+ catch (_c) {
114
+ this.close();
115
+ return;
116
+ }
117
+ if (!('id' in frame) || typeof frame.id !== 'number') {
118
+ return;
119
+ }
120
+ const pending = this.pending.get(frame.id);
121
+ if (!pending) {
122
+ return;
123
+ }
124
+ if (frame.t === 'head') {
125
+ pending.head = { type: (_a = frame.type) !== null && _a !== void 0 ? _a : 'application/octet-stream', size: (_b = frame.size) !== null && _b !== void 0 ? _b : 0 };
126
+ }
127
+ else if (frame.t === 'chunk') {
128
+ const bytes = RelayBytes.fromBase64(frame.d);
129
+ pending.received += bytes.length;
130
+ if (pending.received > RELAY_FILE_MAX_BYTES) {
131
+ this.settle(frame.id, new Error('The file is too large to show here.'));
132
+ return;
133
+ }
134
+ pending.chunks.push(bytes);
135
+ }
136
+ else if (frame.t === 'end') {
137
+ if (!pending.head) {
138
+ this.settle(frame.id, new Error('The file came without its head.'));
139
+ return;
140
+ }
141
+ this.finish(frame.id, { type: pending.head.type, size: pending.received, data: RelayBytes.concat(...pending.chunks) });
142
+ }
143
+ else if (frame.t === 'error') {
144
+ this.settle(frame.id, new Error(frame.message));
145
+ }
146
+ }
147
+ settle(id, error) {
148
+ const pending = this.pending.get(id);
149
+ if (pending) {
150
+ this.pending.delete(id);
151
+ clearTimeout(pending.timer);
152
+ pending.reject(error);
153
+ }
154
+ }
155
+ finish(id, bytes) {
156
+ const pending = this.pending.get(id);
157
+ if (pending) {
158
+ this.pending.delete(id);
159
+ clearTimeout(pending.timer);
160
+ pending.resolve(bytes);
161
+ }
162
+ }
163
+ /** The channel went: what was asked for is not coming. */
164
+ fail(error) {
165
+ for (const [id] of [...this.pending]) {
166
+ this.settle(id, error);
167
+ }
168
+ }
169
+ }
170
+ //# sourceMappingURL=relay-files.js.map