@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,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,91 @@
1
+ import { type RelayIdentity, type RelayPublicIdentity } from './relay-identity.js';
2
+ /** What a link inviting into a room names (docs/design/ta-link.md 3.3); all of it in the fragment, which a browser does not send. */
3
+ export interface RelayHubLink {
4
+ relay: string;
5
+ room: string;
6
+ /** base64url, 32 bytes: what an ask proves and is sealed with. */
7
+ invite: string;
8
+ /** The identity id of the owner: the answer must be signed by it. */
9
+ owner: string;
10
+ title: string;
11
+ /** The owner's name, as they gave it. */
12
+ by: string;
13
+ }
14
+ /** One of a room, as its owner lists them in the roster. */
15
+ export interface RelayHubMember extends RelayPublicIdentity {
16
+ /** The id of the member in this room alone (not its identity). */
17
+ member: string;
18
+ owner?: boolean;
19
+ /** A guest in a browser (docs/design/ta-link.md 3.8): the others hear only what it says. */
20
+ guest?: boolean;
21
+ at: number;
22
+ }
23
+ export interface RelayHubRosterBody {
24
+ v: number;
25
+ members: RelayHubMember[];
26
+ }
27
+ /** What one asking to join says of itself, sealed with the key of the invitation and signed. */
28
+ export interface RelayHubAskBody extends RelayPublicIdentity {
29
+ member: string;
30
+ at: number;
31
+ /** Asks from a browser, without Ta: for the owner to know, and to admit as a guest. */
32
+ guest?: boolean;
33
+ }
34
+ /** What the owner gives one it admits, sealed for it alone: the key of the room, and what the room is. */
35
+ export interface RelayHubAnswerBody {
36
+ key: string;
37
+ kind: string;
38
+ title: string;
39
+ view?: string;
40
+ }
41
+ export interface RelayHubSigned<T> {
42
+ /** The member who signed it. */
43
+ m: string;
44
+ at: number;
45
+ b: T;
46
+ }
47
+ /** The keys of a room, made from its key `R` once. */
48
+ export interface RelayHubKeys {
49
+ seal: CryptoKey;
50
+ names: Uint8Array;
51
+ }
52
+ /** Links, keys, sealing and signatures of rooms (docs/design/ta-link.md 3.2, 3.3). */
53
+ export declare namespace RelayHubUtil {
54
+ /** `https://<relay>/r#v=1&r=<room>&i=<invite>&o=<owner>&n=<title>&by=<name>`. */
55
+ function link(link: RelayHubLink): string;
56
+ function is(text: string): boolean;
57
+ /** Throws on what is not a link of {@link link}. */
58
+ function parse(text: string): RelayHubLink;
59
+ function randomId(): string;
60
+ function randomKey(): string;
61
+ function keys(roomKey: string): Promise<RelayHubKeys>;
62
+ /** What the relay knows a key of the state by: HMAC of its name, 22 characters. */
63
+ function keyId(keys: RelayHubKeys, name: string): Promise<string>;
64
+ /** What proves an ask comes from one with the invitation; the relay keeps its {@link RelayKeys.hash}. */
65
+ function inviteProof(invite: string): Promise<string>;
66
+ function inviteKey(invite: string): Promise<CryptoKey>;
67
+ /** Signed by `identity` as `member`, then sealed with `key`. */
68
+ function seal<T>(key: CryptoKey, identity: RelayIdentity, member: string, body: T, at?: number): Promise<string>;
69
+ /**
70
+ * What {@link seal} sealed, once its signature checks with the signing key `signOf` gives for its member;
71
+ * undefined when it does not open, is not signed by that member, or is of another time than `now` (with `skewMs`).
72
+ */
73
+ function open<T>(key: CryptoKey, sealed: string, signOf: (member: string) => string | undefined, options?: {
74
+ now?: number;
75
+ skewMs?: number;
76
+ }): Promise<RelayHubSigned<T> | undefined>;
77
+ /** An ask: sealed with the key of the invitation, signed by the one who asks (its keys inside), whom the owner checks. */
78
+ function sealAsk(invite: string, identity: RelayIdentity, member: string, at?: number, guest?: boolean): Promise<string>;
79
+ /** Undefined for an ask that does not open with this invitation, or is not signed by the keys it gives. */
80
+ function openAsk(invite: string, sealed: string): Promise<RelayHubAskBody | undefined>;
81
+ /**
82
+ * The owner's answer to an ask: what the room is and its key, for the one who asked alone (ECDH of the two), signed by
83
+ * the owner; all of it sealed with the invitation the ask came with, so that the relay does not see who the owner is.
84
+ */
85
+ function sealAnswer(owner: RelayIdentity, room: string, ask: RelayHubAskBody, body: RelayHubAnswerBody, invite: string): Promise<string>;
86
+ /** Undefined unless it is signed by the owner the link names, and opens for this identity. */
87
+ function openAnswer(identity: RelayIdentity, room: string, member: string, ownerId: string, answer: string, invite: string): Promise<{
88
+ owner: RelayPublicIdentity;
89
+ body: RelayHubAnswerBody;
90
+ } | undefined>;
91
+ }
@@ -0,0 +1,164 @@
1
+ import { RelayBytes } from './relay-bytes.js';
2
+ import { RelayIdentityUtil, RelayKeys } from './relay-identity.js';
3
+ import { RELAY_ID, RELAY_ROOM_PATH } from './relay-protocol.js';
4
+ /** Links, keys, sealing and signatures of rooms (docs/design/ta-link.md 3.2, 3.3). */
5
+ export var RelayHubUtil;
6
+ (function (RelayHubUtil) {
7
+ /** `https://<relay>/r#v=1&r=<room>&i=<invite>&o=<owner>&n=<title>&by=<name>`. */
8
+ function link(link) {
9
+ const fragment = new URLSearchParams({ v: '1', r: link.room, i: link.invite, o: link.owner, n: link.title, by: link.by });
10
+ return `${link.relay}${RELAY_ROOM_PATH}#${fragment}`;
11
+ }
12
+ RelayHubUtil.link = link;
13
+ function is(text) {
14
+ try {
15
+ parse(text);
16
+ return true;
17
+ }
18
+ catch (_a) {
19
+ return false;
20
+ }
21
+ }
22
+ RelayHubUtil.is = is;
23
+ /** Throws on what is not a link of {@link link}. */
24
+ function parse(text) {
25
+ var _a, _b;
26
+ const url = new URL(text.trim());
27
+ const fragment = new URLSearchParams(url.hash.slice(1));
28
+ const [room, invite, owner] = ['r', 'i', 'o'].map(name => { var _a; return (_a = fragment.get(name)) !== null && _a !== void 0 ? _a : ''; });
29
+ if (!/^https?:$/.test(url.protocol) ||
30
+ url.pathname !== RELAY_ROOM_PATH ||
31
+ fragment.get('v') !== '1' ||
32
+ !RELAY_ID.test(room) ||
33
+ !/^[A-Za-z0-9_-]{43}$/.test(invite) ||
34
+ !/^[A-Za-z0-9_-]{22}$/.test(owner)) {
35
+ throw new Error('Not a link inviting into a room of Ta.');
36
+ }
37
+ return { relay: url.origin, room, invite, owner, title: ((_a = fragment.get('n')) !== null && _a !== void 0 ? _a : '').slice(0, 200), by: ((_b = fragment.get('by')) !== null && _b !== void 0 ? _b : '').slice(0, 100) };
38
+ }
39
+ RelayHubUtil.parse = parse;
40
+ function randomId() {
41
+ return RelayBytes.toBase64(RelayBytes.random(16));
42
+ }
43
+ RelayHubUtil.randomId = randomId;
44
+ function randomKey() {
45
+ return RelayBytes.toBase64(RelayBytes.random(32));
46
+ }
47
+ RelayHubUtil.randomKey = randomKey;
48
+ async function keys(roomKey) {
49
+ const key = RelayBytes.fromBase64(roomKey);
50
+ const none = new Uint8Array(0);
51
+ return {
52
+ seal: await RelayKeys.aesKey(await RelayKeys.hkdf(key, none, 'ta-room/1 seal')),
53
+ names: await RelayKeys.hkdf(key, none, 'ta-room/1 key'),
54
+ };
55
+ }
56
+ RelayHubUtil.keys = keys;
57
+ /** What the relay knows a key of the state by: HMAC of its name, 22 characters. */
58
+ async function keyId(keys, name) {
59
+ return (await RelayKeys.hmac(keys.names, name)).slice(0, 22);
60
+ }
61
+ RelayHubUtil.keyId = keyId;
62
+ /** What proves an ask comes from one with the invitation; the relay keeps its {@link RelayKeys.hash}. */
63
+ async function inviteProof(invite) {
64
+ return RelayBytes.toBase64(await RelayKeys.hkdf(RelayBytes.fromBase64(invite), new Uint8Array(0), 'ta-room/1 ask auth'));
65
+ }
66
+ RelayHubUtil.inviteProof = inviteProof;
67
+ async function inviteKey(invite) {
68
+ return RelayKeys.aesKey(await RelayKeys.hkdf(RelayBytes.fromBase64(invite), new Uint8Array(0), 'ta-room/1 ask seal'));
69
+ }
70
+ RelayHubUtil.inviteKey = inviteKey;
71
+ /** Signed by `identity` as `member`, then sealed with `key`. */
72
+ async function seal(key, identity, member, body, at = Date.now()) {
73
+ const p = JSON.stringify({ m: member, at, b: body });
74
+ return RelayKeys.seal(key, JSON.stringify({ p, s: await RelayIdentityUtil.sign(identity, p) }));
75
+ }
76
+ RelayHubUtil.seal = seal;
77
+ /**
78
+ * What {@link seal} sealed, once its signature checks with the signing key `signOf` gives for its member;
79
+ * undefined when it does not open, is not signed by that member, or is of another time than `now` (with `skewMs`).
80
+ */
81
+ async function open(key, sealed, signOf, options = {}) {
82
+ var _a;
83
+ try {
84
+ const envelope = JSON.parse(await RelayKeys.open(key, sealed));
85
+ const signed = JSON.parse(envelope.p);
86
+ const sign = typeof signed.m === 'string' ? signOf(signed.m) : undefined;
87
+ if (!sign || !(await RelayIdentityUtil.verify(sign, envelope.p, envelope.s))) {
88
+ return undefined;
89
+ }
90
+ if (options.skewMs !== undefined && Math.abs(((_a = options.now) !== null && _a !== void 0 ? _a : Date.now()) - Number(signed.at)) > options.skewMs) {
91
+ return undefined;
92
+ }
93
+ return signed;
94
+ }
95
+ catch (_b) {
96
+ return undefined;
97
+ }
98
+ }
99
+ RelayHubUtil.open = open;
100
+ /** An ask: sealed with the key of the invitation, signed by the one who asks (its keys inside), whom the owner checks. */
101
+ async function sealAsk(invite, identity, member, at = Date.now(), guest = false) {
102
+ const body = { ...RelayIdentityUtil.publicOf(identity), member, at, ...(guest ? { guest: true } : {}) };
103
+ return seal(await inviteKey(invite), identity, member, body, at);
104
+ }
105
+ RelayHubUtil.sealAsk = sealAsk;
106
+ /** Undefined for an ask that does not open with this invitation, or is not signed by the keys it gives. */
107
+ async function openAsk(invite, sealed) {
108
+ try {
109
+ const envelope = JSON.parse(await RelayKeys.open(await inviteKey(invite), sealed));
110
+ const signed = JSON.parse(envelope.p);
111
+ const body = signed.b;
112
+ if (!body ||
113
+ signed.m !== body.member ||
114
+ !RELAY_ID.test(String(body.member)) ||
115
+ !(await RelayIdentityUtil.check(body)) ||
116
+ !(await RelayIdentityUtil.verify(body.sign, envelope.p, envelope.s))) {
117
+ return undefined;
118
+ }
119
+ return {
120
+ ...RelayIdentityUtil.publicOf(body),
121
+ name: String(body.name).slice(0, 100),
122
+ member: body.member,
123
+ at: Number(body.at),
124
+ ...(body.guest === true ? { guest: true } : {}),
125
+ };
126
+ }
127
+ catch (_a) {
128
+ return undefined;
129
+ }
130
+ }
131
+ RelayHubUtil.openAsk = openAsk;
132
+ /**
133
+ * The owner's answer to an ask: what the room is and its key, for the one who asked alone (ECDH of the two), signed by
134
+ * the owner; all of it sealed with the invitation the ask came with, so that the relay does not see who the owner is.
135
+ */
136
+ async function sealAnswer(owner, room, ask, body, invite) {
137
+ const key = await RelayKeys.aesKey(await RelayIdentityUtil.agree(owner, ask.box, room, 'ta-room/1 answer'));
138
+ const d = await RelayKeys.seal(key, JSON.stringify(body));
139
+ const signed = `${room}\n${ask.member}\n${d}`;
140
+ const answer = JSON.stringify({ owner: RelayIdentityUtil.publicOf(owner), d, s: await RelayIdentityUtil.sign(owner, signed) });
141
+ return RelayKeys.seal(await inviteKey(invite), answer);
142
+ }
143
+ RelayHubUtil.sealAnswer = sealAnswer;
144
+ /** Undefined unless it is signed by the owner the link names, and opens for this identity. */
145
+ async function openAnswer(identity, room, member, ownerId, answer, invite) {
146
+ try {
147
+ const { owner, d, s } = JSON.parse(await RelayKeys.open(await inviteKey(invite), answer));
148
+ if (owner.id !== ownerId ||
149
+ !(await RelayIdentityUtil.check(owner)) ||
150
+ !(await RelayIdentityUtil.verify(owner.sign, `${room}\n${member}\n${d}`, s))) {
151
+ return undefined;
152
+ }
153
+ const key = await RelayKeys.aesKey(await RelayIdentityUtil.agree(identity, owner.box, room, 'ta-room/1 answer'));
154
+ const body = JSON.parse(await RelayKeys.open(key, d));
155
+ RelayBytes.fromBase64(body.key);
156
+ return { owner: { ...RelayIdentityUtil.publicOf(owner), name: String(owner.name).slice(0, 100) }, body };
157
+ }
158
+ catch (_a) {
159
+ return undefined;
160
+ }
161
+ }
162
+ RelayHubUtil.openAnswer = openAnswer;
163
+ })(RelayHubUtil || (RelayHubUtil = {}));
164
+ //# sourceMappingURL=relay-hub-util.js.map