@celljs/ta-share 4.24.0 → 4.25.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.
package/host/index.mjs CHANGED
@@ -2,9 +2,1113 @@
2
2
  import { readFile, stat } from "node:fs/promises";
3
3
  import { extname, isAbsolute, resolve } from "node:path";
4
4
 
5
+ // ../ta-relay/esm/common/relay-bytes.js
6
+ var RelayBytes;
7
+ (function(RelayBytes2) {
8
+ function random(length) {
9
+ return globalThis.crypto.getRandomValues(new Uint8Array(length));
10
+ }
11
+ RelayBytes2.random = random;
12
+ function toBase64(bytes) {
13
+ let binary = "";
14
+ for (const byte of bytes) {
15
+ binary += String.fromCharCode(byte);
16
+ }
17
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
18
+ }
19
+ RelayBytes2.toBase64 = toBase64;
20
+ function fromBase64(text) {
21
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) {
22
+ throw new Error("Not base64url.");
23
+ }
24
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
25
+ const bytes = new Uint8Array(binary.length);
26
+ for (let i = 0;i < binary.length; i++) {
27
+ bytes[i] = binary.charCodeAt(i);
28
+ }
29
+ return bytes;
30
+ }
31
+ RelayBytes2.fromBase64 = fromBase64;
32
+ function concat(...parts) {
33
+ const bytes = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
34
+ let offset = 0;
35
+ for (const part of parts) {
36
+ bytes.set(part, offset);
37
+ offset += part.length;
38
+ }
39
+ return bytes;
40
+ }
41
+ RelayBytes2.concat = concat;
42
+ })(RelayBytes || (RelayBytes = {}));
43
+
44
+ // ../ta-relay/esm/common/relay-protocol.js
45
+ var RELAY_CONNECT_PATH = "/v1/connect/";
46
+ var RELAY_PAIR_PATH = "/pair";
47
+ var RELAY_CONTENT_PATH = "/s";
48
+ var RELAY_FRAME_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' https: data: blob:; style-src 'unsafe-inline' https: data:; img-src https: data: blob:; font-src https: data:; media-src https: data: blob:; connect-src 'none'; form-action 'none'";
49
+ var RELAY_FRAME_HEADER_CSP = `${RELAY_FRAME_CSP}; frame-ancestors 'self'; sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox`;
50
+ var RELAY_BLOB_PATH = "/v1/blob/";
51
+ var OPEN_IN_TA = `<p><a id="open" style="display:inline-block;padding:10px 18px;border-radius:20px;background:#111;color:#fff;text-decoration:none;font-weight:600">Open in Ta · 在 Ta 中打开</a></p>
52
+ <script>document.getElementById('open').href='ta://open?link='+encodeURIComponent(location.href)</script>`;
53
+ var RELAY_PAIR_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
54
+ <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
55
+ <h1>Ta</h1><p>Open this link in the Ta app, or paste it there, to reach your Ta from this device.</p>
56
+ <p>打开 Ta 应用,粘贴这个链接,就能从这台设备连到你的 Ta。</p>${OPEN_IN_TA}</body>`;
57
+ var RELAY_SHARE_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
58
+ <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
59
+ <h1>Ta</h1><p>Someone shared an extension of Ta. Scan the code in the Ta app, or paste this link in its Quick open, to open it.</p>
60
+ <p>有人分享了一个 Ta 扩展。在 Ta 应用里扫码,或把这个链接粘贴到“快捷打开”,就能打开它。</p>${OPEN_IN_TA}</body>`;
61
+ var RELAY_SHARE_MAX_BYTES = 8 * 1024 * 1024;
62
+ var RELAY_SHARE_CHUNK_BYTES = 192 * 1024;
63
+ var RELAY_CONTENT_MAX_BYTES = 8 * 1024 * 1024;
64
+ var RELAY_ID = /^[A-Za-z0-9_-]{16,64}$/;
65
+ var RelayCloseCode;
66
+ (function(RelayCloseCode2) {
67
+ RelayCloseCode2[RelayCloseCode2["HOST_OFFLINE"] = 4404] = "HOST_OFFLINE";
68
+ RelayCloseCode2[RelayCloseCode2["REFUSED"] = 4401] = "REFUSED";
69
+ RelayCloseCode2[RelayCloseCode2["REPLACED"] = 4409] = "REPLACED";
70
+ RelayCloseCode2[RelayCloseCode2["CLOSED_BY_HOST"] = 4410] = "CLOSED_BY_HOST";
71
+ RelayCloseCode2[RelayCloseCode2["FULL"] = 4429] = "FULL";
72
+ RelayCloseCode2[RelayCloseCode2["TIMEOUT"] = 4408] = "TIMEOUT";
73
+ RelayCloseCode2[RelayCloseCode2["BLOCKED"] = 4451] = "BLOCKED";
74
+ RelayCloseCode2[RelayCloseCode2["SIGN_IN"] = 4452] = "SIGN_IN";
75
+ })(RelayCloseCode || (RelayCloseCode = {}));
76
+ var RELAY_PING = "ping";
77
+ var RELAY_PONG = "pong";
78
+ var RELAY_PING_MS = 25000;
79
+ var RELAY_PROOF = "ta-relay ready";
80
+ var RELAY_HUB_MAX_VALUE = 96 * 1024;
81
+ var RELAY_HUB_MAX_STATE = 3 * 1024 * 1024;
82
+ var RELAY_PICTURE_MAX_CHARS = 16 * 1024;
83
+ var RELAY_HUB_LOG_CHARS = 4 * 1024 * 1024;
84
+
85
+ // ../ta-relay/esm/common/relay-identity.js
86
+ var encoder = new TextEncoder;
87
+ var decoder = new TextDecoder;
88
+ var subtle = () => globalThis.crypto.subtle;
89
+ var SIGN = { name: "ECDSA", namedCurve: "P-256" };
90
+ var BOX = { name: "ECDH", namedCurve: "P-256" };
91
+ var SIGNATURE = { name: "ECDSA", hash: "SHA-256" };
92
+ var RelayKeys;
93
+ (function(RelayKeys2) {
94
+ async function hkdf(key, salt, info) {
95
+ const secret = await subtle().importKey("raw", key, "HKDF", false, ["deriveBits"]);
96
+ const bits = await subtle().deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: encoder.encode(info) }, secret, 256);
97
+ return new Uint8Array(bits);
98
+ }
99
+ RelayKeys2.hkdf = hkdf;
100
+ async function sha256(bytes) {
101
+ const data = typeof bytes === "string" ? encoder.encode(bytes) : bytes;
102
+ return new Uint8Array(await subtle().digest("SHA-256", data));
103
+ }
104
+ RelayKeys2.sha256 = sha256;
105
+ async function hash(text) {
106
+ return RelayBytes.toBase64(await sha256(text));
107
+ }
108
+ RelayKeys2.hash = hash;
109
+ async function hmac(key, text) {
110
+ const imported = await subtle().importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
111
+ return RelayBytes.toBase64(new Uint8Array(await subtle().sign("HMAC", imported, encoder.encode(text))));
112
+ }
113
+ RelayKeys2.hmac = hmac;
114
+ function aesKey(key) {
115
+ return subtle().importKey("raw", key, "AES-GCM", false, ["encrypt", "decrypt"]);
116
+ }
117
+ RelayKeys2.aesKey = aesKey;
118
+ async function seal(key, text) {
119
+ const iv = RelayBytes.random(12);
120
+ const sealed = await subtle().encrypt({ name: "AES-GCM", iv }, key, encoder.encode(text));
121
+ return RelayBytes.toBase64(RelayBytes.concat(iv, new Uint8Array(sealed)));
122
+ }
123
+ RelayKeys2.seal = seal;
124
+ async function open(key, sealed) {
125
+ const bytes = RelayBytes.fromBase64(sealed);
126
+ const opened = await subtle().decrypt({ name: "AES-GCM", iv: bytes.subarray(0, 12) }, key, bytes.subarray(12));
127
+ return decoder.decode(opened);
128
+ }
129
+ RelayKeys2.open = open;
130
+ })(RelayKeys || (RelayKeys = {}));
131
+ var RelayIdentityUtil;
132
+ (function(RelayIdentityUtil2) {
133
+ async function create(name, now = Date.now()) {
134
+ const sign2 = await subtle().generateKey(SIGN, true, ["sign", "verify"]);
135
+ const box = await subtle().generateKey(BOX, true, ["deriveBits"]);
136
+ const raw = async (key) => RelayBytes.toBase64(new Uint8Array(await subtle().exportKey("raw", key)));
137
+ const [signPublic, boxPublic] = await Promise.all([raw(sign2.publicKey), raw(box.publicKey)]);
138
+ return {
139
+ id: await id(signPublic, boxPublic),
140
+ name,
141
+ sign: signPublic,
142
+ box: boxPublic,
143
+ signKey: await subtle().exportKey("jwk", sign2.privateKey),
144
+ boxKey: await subtle().exportKey("jwk", box.privateKey),
145
+ createdAt: now
146
+ };
147
+ }
148
+ RelayIdentityUtil2.create = create;
149
+ async function id(sign2, box) {
150
+ const digest = await RelayKeys.sha256(RelayBytes.concat(RelayBytes.fromBase64(sign2), RelayBytes.fromBase64(box)));
151
+ return RelayBytes.toBase64(digest.subarray(0, 16));
152
+ }
153
+ RelayIdentityUtil2.id = id;
154
+ async function check(identity) {
155
+ try {
156
+ if (identity.id !== await id(identity.sign, identity.box)) {
157
+ return false;
158
+ }
159
+ await Promise.all([importSign(identity.sign), importBox(identity.box)]);
160
+ return true;
161
+ } catch (_a) {
162
+ return false;
163
+ }
164
+ }
165
+ RelayIdentityUtil2.check = check;
166
+ function publicOf(identity) {
167
+ return withLook({ id: identity.id, name: identity.name, sign: identity.sign, box: identity.box }, identity.look);
168
+ }
169
+ RelayIdentityUtil2.publicOf = publicOf;
170
+ function isLook(look) {
171
+ return typeof look === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(look);
172
+ }
173
+ RelayIdentityUtil2.isLook = isLook;
174
+ function isPicture(picture) {
175
+ return typeof picture === "string" && picture.length <= RELAY_PICTURE_MAX_CHARS && /^data:image\/(png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/.test(picture);
176
+ }
177
+ RelayIdentityUtil2.isPicture = isPicture;
178
+ function withLook(value, look) {
179
+ const { look: _, ...rest } = value;
180
+ return isLook(look) ? { ...rest, look } : rest;
181
+ }
182
+ RelayIdentityUtil2.withLook = withLook;
183
+ async function sign(identity, text) {
184
+ const key = await subtle().importKey("jwk", identity.signKey, SIGN, false, ["sign"]);
185
+ return RelayBytes.toBase64(new Uint8Array(await subtle().sign(SIGNATURE, key, encoder.encode(text))));
186
+ }
187
+ RelayIdentityUtil2.sign = sign;
188
+ async function verify(signPublic, text, signature) {
189
+ try {
190
+ return await subtle().verify(SIGNATURE, await importSign(signPublic), RelayBytes.fromBase64(signature), encoder.encode(text));
191
+ } catch (_a) {
192
+ return false;
193
+ }
194
+ }
195
+ RelayIdentityUtil2.verify = verify;
196
+ async function agree(identity, otherBox, salt, info) {
197
+ const own = await subtle().importKey("jwk", identity.boxKey, BOX, false, ["deriveBits"]);
198
+ const shared = await subtle().deriveBits({ name: "ECDH", public: await importBox(otherBox) }, own, 256);
199
+ return RelayKeys.hkdf(new Uint8Array(shared), encoder.encode(salt), info);
200
+ }
201
+ RelayIdentityUtil2.agree = agree;
202
+ function importSign(raw) {
203
+ return subtle().importKey("raw", RelayBytes.fromBase64(raw), SIGN, false, ["verify"]);
204
+ }
205
+ function importBox(raw) {
206
+ return subtle().importKey("raw", RelayBytes.fromBase64(raw), BOX, false, []);
207
+ }
208
+ })(RelayIdentityUtil || (RelayIdentityUtil = {}));
209
+
210
+ // ../ta-relay/esm/common/relay-cipher.js
211
+ var encoder2 = new TextEncoder;
212
+ var decoder2 = new TextDecoder;
213
+ var IV_LENGTH = 12;
214
+ var PLAIN = 0;
215
+ var DEFLATED = 1;
216
+ var DEFLATE_MIN_BYTES = 1024;
217
+
218
+ class RelayCipher {
219
+ constructor(sendKey, receiveKey) {
220
+ this.sendKey = sendKey;
221
+ this.receiveKey = receiveKey;
222
+ this.compress = false;
223
+ this.sent = 0;
224
+ this.received = 0;
225
+ this.sealing = Promise.resolve();
226
+ this.opening = Promise.resolve();
227
+ }
228
+ static async derive(deviceKey, clientNonce, hostNonce, side) {
229
+ const subtle2 = globalThis.crypto.subtle;
230
+ const secret = await subtle2.importKey("raw", deviceKey, "HKDF", false, ["deriveKey"]);
231
+ const salt = RelayBytes.concat(clientNonce, hostNonce);
232
+ const key = (direction) => subtle2.deriveKey({ name: "HKDF", hash: "SHA-256", salt, info: encoder2.encode(`ta-relay/1 ${direction}`) }, secret, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
233
+ const [toHost, toClient] = await Promise.all([key("client-to-host"), key("host-to-client")]);
234
+ return side === "client" ? new RelayCipher(toHost, toClient) : new RelayCipher(toClient, toHost);
235
+ }
236
+ seal(text) {
237
+ const iv = RelayCipher.iv(this.sent++);
238
+ const sealed = this.sealing.then(async () => {
239
+ const data = await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv }, this.sendKey, await this.pack(text));
240
+ return RelayBytes.toBase64(new Uint8Array(data));
241
+ });
242
+ this.sealing = sealed.catch(() => {
243
+ return;
244
+ });
245
+ return sealed;
246
+ }
247
+ open(frame) {
248
+ const iv = RelayCipher.iv(this.received++);
249
+ const opened = this.opening.then(async () => {
250
+ const data = await globalThis.crypto.subtle.decrypt({ name: "AES-GCM", iv }, this.receiveKey, RelayBytes.fromBase64(frame));
251
+ return this.unpack(new Uint8Array(data));
252
+ });
253
+ this.opening = opened.catch(() => {
254
+ return;
255
+ });
256
+ return opened;
257
+ }
258
+ async pack(text) {
259
+ const bytes = encoder2.encode(text);
260
+ if (!this.compress) {
261
+ return bytes;
262
+ }
263
+ const deflated = bytes.length >= DEFLATE_MIN_BYTES ? await RelayDeflate.compress(bytes) : undefined;
264
+ return deflated && deflated.length < bytes.length ? RelayBytes.concat(Uint8Array.of(DEFLATED), deflated) : RelayBytes.concat(Uint8Array.of(PLAIN), bytes);
265
+ }
266
+ async unpack(bytes) {
267
+ if (!this.compress) {
268
+ return decoder2.decode(bytes);
269
+ }
270
+ const body = bytes.subarray(1);
271
+ return decoder2.decode(bytes[0] === DEFLATED ? await RelayDeflate.decompress(body) : body);
272
+ }
273
+ static iv(counter) {
274
+ const iv = new Uint8Array(IV_LENGTH);
275
+ new DataView(iv.buffer).setUint32(IV_LENGTH - 8, Math.floor(counter / 2 ** 32));
276
+ new DataView(iv.buffer).setUint32(IV_LENGTH - 4, counter >>> 0);
277
+ return iv;
278
+ }
279
+ }
280
+ var RelayDeflate;
281
+ (function(RelayDeflate2) {
282
+ let support;
283
+ function supported() {
284
+ if (support === undefined) {
285
+ try {
286
+ new CompressionStream("deflate-raw");
287
+ new DecompressionStream("deflate-raw");
288
+ support = true;
289
+ } catch (_a) {
290
+ support = false;
291
+ }
292
+ }
293
+ return support;
294
+ }
295
+ RelayDeflate2.supported = supported;
296
+ function compress(bytes) {
297
+ return through(bytes, new CompressionStream("deflate-raw"));
298
+ }
299
+ RelayDeflate2.compress = compress;
300
+ function decompress(bytes) {
301
+ return through(bytes, new DecompressionStream("deflate-raw"));
302
+ }
303
+ RelayDeflate2.decompress = decompress;
304
+ async function through(bytes, stream) {
305
+ const piped = new Blob([bytes]).stream().pipeThrough(stream);
306
+ return new Uint8Array(await new Response(piped).arrayBuffer());
307
+ }
308
+ })(RelayDeflate || (RelayDeflate = {}));
309
+
310
+ // ../ta-relay/esm/common/relay-pairing.js
311
+ var RelayPairingUtil;
312
+ (function(RelayPairingUtil2) {
313
+ function link(pairing) {
314
+ const fragment = new URLSearchParams({ v: "1", h: pairing.host, d: pairing.device, k: pairing.key });
315
+ if (pairing.name) {
316
+ fragment.set("n", pairing.name);
317
+ }
318
+ return `${pairing.relay}${RELAY_PAIR_PATH}#${fragment}`;
319
+ }
320
+ RelayPairingUtil2.link = link;
321
+ function parse(link2) {
322
+ var _a;
323
+ const url = new URL(link2.trim());
324
+ const fragment = new URLSearchParams(url.hash.slice(1));
325
+ const [host, device, key] = ["h", "d", "k"].map((name) => {
326
+ var _a2;
327
+ return (_a2 = fragment.get(name)) !== null && _a2 !== undefined ? _a2 : "";
328
+ });
329
+ if (!/^https?:$/.test(url.protocol) || url.pathname !== RELAY_PAIR_PATH || fragment.get("v") !== "1" || !RELAY_ID.test(host) || !RELAY_ID.test(device) || !/^[A-Za-z0-9_-]{43}$/.test(key)) {
330
+ throw new Error("Not a pairing link of Ta.");
331
+ }
332
+ return { relay: url.origin, host, device, key, name: (_a = fragment.get("n")) !== null && _a !== undefined ? _a : undefined };
333
+ }
334
+ RelayPairingUtil2.parse = parse;
335
+ function websocketUrl(relay, path) {
336
+ return relay.replace(/^http/, "ws") + path;
337
+ }
338
+ RelayPairingUtil2.websocketUrl = websocketUrl;
339
+ })(RelayPairingUtil || (RelayPairingUtil = {}));
340
+
341
+ // ../ta-relay/esm/common/relay-socket.js
342
+ var CONNECTING = 0;
343
+ var OPEN = 1;
344
+ var CLOSING = 2;
345
+ var CLOSED = 3;
346
+ var HELLO_MS = 15000;
347
+
348
+ class RelaySocket {
349
+ constructor(pairing, options = {}) {
350
+ var _a;
351
+ this.pairing = pairing;
352
+ this.options = options;
353
+ this.onopen = null;
354
+ this.onmessage = null;
355
+ this.onclose = null;
356
+ this.onerror = null;
357
+ this.state = CONNECTING;
358
+ this.nonce = RelayBytes.random(16);
359
+ this.ponged = false;
360
+ this.awaitingPong = false;
361
+ this.receiving = Promise.resolve();
362
+ this.socket = new WebSocket(RelayPairingUtil.websocketUrl(pairing.relay, RELAY_CONNECT_PATH + pairing.host));
363
+ this.helloTimer = setTimeout(() => this.drop(RelayCloseCode.TIMEOUT, "The host did not answer."), (_a = options.helloMs) !== null && _a !== undefined ? _a : HELLO_MS);
364
+ this.socket.onopen = () => {
365
+ var _a2;
366
+ const hello = {
367
+ t: "hello",
368
+ v: 1,
369
+ device: pairing.device,
370
+ nonce: RelayBytes.toBase64(this.nonce),
371
+ ...RelayDeflate.supported() ? { z: 1 } : {}
372
+ };
373
+ this.socket.send(JSON.stringify(hello));
374
+ this.pingTimer = setInterval(() => this.ping(), (_a2 = options.pingMs) !== null && _a2 !== undefined ? _a2 : RELAY_PING_MS);
375
+ };
376
+ this.socket.onmessage = (message) => {
377
+ const text = String(message.data);
378
+ if (text === RELAY_PONG) {
379
+ this.ponged = true;
380
+ this.awaitingPong = false;
381
+ return;
382
+ }
383
+ this.receiving = this.receiving.then(() => this.receive(text));
384
+ };
385
+ this.socket.onerror = (event) => {
386
+ var _a2;
387
+ return (_a2 = this.onerror) === null || _a2 === undefined ? undefined : _a2.call(this, event);
388
+ };
389
+ this.socket.onclose = (event) => void this.receiving.then(() => this.finish(event.code, event.reason));
390
+ }
391
+ get readyState() {
392
+ return this.state;
393
+ }
394
+ get closeCode() {
395
+ return this.code;
396
+ }
397
+ send(text) {
398
+ if (this.state !== OPEN || !this.cipher) {
399
+ throw new Error("The connection is not open.");
400
+ }
401
+ this.cipher.seal(text).then((frame) => this.socket.readyState === OPEN && this.socket.send(frame));
402
+ }
403
+ close(code = 1000, reason = "") {
404
+ if (this.state === CLOSED) {
405
+ return;
406
+ }
407
+ this.state = CLOSING;
408
+ this.socket.close(code, reason);
409
+ }
410
+ async receive(text) {
411
+ var _a, _b;
412
+ if (this.cipher) {
413
+ if (this.options.proveFirst && text.startsWith("{")) {
414
+ this.drop(RelaySocket.REFUSED, RelaySocket.refusal(text));
415
+ return;
416
+ }
417
+ try {
418
+ const data = await this.cipher.open(text);
419
+ (_a = this.onmessage) === null || _a === undefined || _a.call(this, { data });
420
+ } catch (_c) {
421
+ this.close(4400, "A message did not open.");
422
+ }
423
+ return;
424
+ }
425
+ try {
426
+ const welcome = JSON.parse(text);
427
+ if (welcome.t !== "ready") {
428
+ this.drop(RelaySocket.REFUSED, this.options.proveFirst ? RelaySocket.refusal(text) : "The host refused this device.");
429
+ return;
430
+ }
431
+ const cipher = await RelayCipher.derive(RelayBytes.fromBase64(this.pairing.key), this.nonce, RelayBytes.fromBase64(welcome.nonce), "client");
432
+ if (welcome.proof === undefined && this.options.proveFirst) {
433
+ this.socket.send(await cipher.seal(RELAY_PROOF));
434
+ } else if (welcome.proof === undefined || await cipher.open(welcome.proof) !== RELAY_PROOF) {
435
+ throw new Error("The host did not show the key.");
436
+ }
437
+ cipher.compress = welcome.z === 1 && RelayDeflate.supported();
438
+ this.cipher = cipher;
439
+ clearTimeout(this.helloTimer);
440
+ this.state = OPEN;
441
+ (_b = this.onopen) === null || _b === undefined || _b.call(this);
442
+ } catch (_d) {
443
+ this.drop(RelaySocket.REFUSED, "The host refused this device.");
444
+ }
445
+ }
446
+ static refusal(text) {
447
+ try {
448
+ const reason = JSON.parse(text).reason;
449
+ return reason === "key" || reason === "busy" ? reason : "gone";
450
+ } catch (_a) {
451
+ return "gone";
452
+ }
453
+ }
454
+ ping() {
455
+ if (this.awaitingPong && this.ponged) {
456
+ this.drop(RelayCloseCode.TIMEOUT, "The relay did not answer.");
457
+ return;
458
+ }
459
+ this.awaitingPong = true;
460
+ if (this.socket.readyState === OPEN) {
461
+ this.socket.send(RELAY_PING);
462
+ }
463
+ }
464
+ drop(code, reason) {
465
+ this.close(code, reason);
466
+ this.finish(code, reason);
467
+ }
468
+ finish(code, reason) {
469
+ var _a;
470
+ if (this.state === CLOSED) {
471
+ return;
472
+ }
473
+ clearTimeout(this.helloTimer);
474
+ clearInterval(this.pingTimer);
475
+ this.state = CLOSED;
476
+ this.code = code;
477
+ (_a = this.onclose) === null || _a === undefined || _a.call(this, { code, reason });
478
+ }
479
+ }
480
+ RelaySocket.CONNECTING = CONNECTING;
481
+ RelaySocket.OPEN = OPEN;
482
+ RelaySocket.CLOSING = CLOSING;
483
+ RelaySocket.CLOSED = CLOSED;
484
+ RelaySocket.REFUSED = 4403;
485
+
486
+ // ../ta-relay/esm/common/relay-content.js
487
+ var encoder3 = new TextEncoder;
488
+ var decoder3 = new TextDecoder;
489
+
490
+ class RelayContentError extends Error {
491
+ constructor(reason, message) {
492
+ super(message);
493
+ this.reason = reason;
494
+ this.name = "RelayContentError";
495
+ }
496
+ }
497
+ var PBKDF2_ITERATIONS = 600000;
498
+ var BLOCKED_MESSAGE = "The operator of the relay blocked this link after a report.";
499
+ var PLAIN_KINDS = new Set(["ta-conversation", "file"]);
500
+ var KIND = /^[a-z0-9][a-z0-9-]{0,31}$/;
501
+ var RelayContentUtil;
502
+ (function(RelayContentUtil2) {
503
+ function link(content) {
504
+ var _a, _b;
505
+ const fragment = new URLSearchParams({ v: "1", h: content.host, s: content.share });
506
+ if (content.access === "self") {
507
+ fragment.set("m", "self");
508
+ } else if (content.access === "people") {
509
+ fragment.set("m", "people");
510
+ fragment.set("o", (_a = content.owner) !== null && _a !== undefined ? _a : "");
511
+ } else if (content.key) {
512
+ fragment.set("k", content.key);
513
+ }
514
+ if (content.access === "password") {
515
+ fragment.set("p", "1");
516
+ }
517
+ if (content.offline && content.access !== "self" && content.access !== "people") {
518
+ fragment.set("o", "1");
519
+ }
520
+ if (content.kind && !PLAIN_KINDS.has(content.kind) && KIND.test(content.kind)) {
521
+ fragment.set("c", content.kind);
522
+ }
523
+ return `${(_b = content.page) !== null && _b !== undefined ? _b : content.relay}${RELAY_CONTENT_PATH}#${fragment}`;
524
+ }
525
+ RelayContentUtil2.link = link;
526
+ function is(text) {
527
+ try {
528
+ parse(text);
529
+ return true;
530
+ } catch (_a) {
531
+ return false;
532
+ }
533
+ }
534
+ RelayContentUtil2.is = is;
535
+ function parse(text) {
536
+ var _a, _b;
537
+ const url = new URL(text.trim());
538
+ const fragment = new URLSearchParams(url.hash.slice(1));
539
+ const [host, share, key] = ["h", "s", "k"].map((name) => {
540
+ var _a2;
541
+ return (_a2 = fragment.get(name)) !== null && _a2 !== undefined ? _a2 : "";
542
+ });
543
+ const self = fragment.get("m") === "self";
544
+ const people = fragment.get("m") === "people";
545
+ const owner = (_a = fragment.get("o")) !== null && _a !== undefined ? _a : "";
546
+ if (!/^https?:$/.test(url.protocol) || url.pathname !== RELAY_CONTENT_PATH || fragment.get("v") !== "1" || !RELAY_ID.test(host) || !RELAY_ID.test(share) || (people ? !/^[A-Za-z0-9_-]{22}$/.test(owner) : !self && !/^[A-Za-z0-9_-]{43}$/.test(key))) {
547
+ throw new RelayContentError("invalid", "Not a link of something shared from Ta.");
548
+ }
549
+ const kind = (_b = fragment.get("c")) !== null && _b !== undefined ? _b : "";
550
+ if (people) {
551
+ return { relay: url.origin, host, share, access: "people", owner, offline: false, ...KIND.test(kind) ? { kind } : {} };
552
+ }
553
+ return {
554
+ relay: url.origin,
555
+ host,
556
+ share,
557
+ key: self ? undefined : key,
558
+ access: self ? "self" : fragment.get("p") === "1" ? "password" : "link",
559
+ offline: !self && fragment.get("o") === "1",
560
+ ...KIND.test(kind) ? { kind } : {}
561
+ };
562
+ }
563
+ RelayContentUtil2.parse = parse;
564
+ async function contentKey(linkKey, share, password) {
565
+ if (password === undefined) {
566
+ return linkKey;
567
+ }
568
+ const subtle2 = globalThis.crypto.subtle;
569
+ const secret = await subtle2.importKey("raw", encoder3.encode(password.normalize("NFC")), "PBKDF2", false, ["deriveBits"]);
570
+ const stretched = await subtle2.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: encoder3.encode(`ta-share:${share}`), iterations: PBKDF2_ITERATIONS }, secret, 256);
571
+ return hkdf(linkKey, new Uint8Array(stretched), "ta-share/1 password");
572
+ }
573
+ RelayContentUtil2.contentKey = contentKey;
574
+ function peopleKey(identity, otherBox, share) {
575
+ return RelayIdentityUtil.agree(identity, otherBox, share, "ta-share/1 people");
576
+ }
577
+ RelayContentUtil2.peopleKey = peopleKey;
578
+ async function authToken(key) {
579
+ return RelayBytes.toBase64(await hkdf(key, new Uint8Array(0), "ta-share/1 auth"));
580
+ }
581
+ RelayContentUtil2.authToken = authToken;
582
+ async function sha256(text) {
583
+ return RelayBytes.toBase64(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", encoder3.encode(text))));
584
+ }
585
+ RelayContentUtil2.sha256 = sha256;
586
+ async function seal(key, item) {
587
+ const iv = RelayBytes.random(12);
588
+ const sealed = await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv }, await blobKey(key), encode(item));
589
+ return RelayBytes.concat(iv, new Uint8Array(sealed));
590
+ }
591
+ RelayContentUtil2.seal = seal;
592
+ async function open(key, bytes) {
593
+ const opened = await globalThis.crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.subarray(0, 12) }, await blobKey(key), bytes.subarray(12));
594
+ return decode(new Uint8Array(opened));
595
+ }
596
+ RelayContentUtil2.open = open;
597
+ function encode(item) {
598
+ const { data, ...header } = item;
599
+ const head = encoder3.encode(JSON.stringify(header));
600
+ const length = new Uint8Array(4);
601
+ new DataView(length.buffer).setUint32(0, head.length);
602
+ return RelayBytes.concat(length, head, data);
603
+ }
604
+ RelayContentUtil2.encode = encode;
605
+ function decode(bytes) {
606
+ const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0);
607
+ const header = JSON.parse(decoder3.decode(bytes.subarray(4, 4 + length)));
608
+ return {
609
+ kind: String(header.kind),
610
+ title: String(header.title),
611
+ createdAt: Number(header.createdAt),
612
+ type: header.type,
613
+ data: bytes.slice(4 + length)
614
+ };
615
+ }
616
+ RelayContentUtil2.decode = decode;
617
+ async function fetch2(text, options = {}) {
618
+ const link2 = typeof text === "string" ? parse(text) : text;
619
+ if (link2.access === "people") {
620
+ if (!options.people) {
621
+ throw new RelayContentError("people", "Only the Ta friends it was shared with open it, in their own Ta.");
622
+ }
623
+ return fromHost(link2, await peopleKey(options.people.identity, options.people.ownerBox, link2.share), options);
624
+ }
625
+ if (link2.access === "self" || !link2.key) {
626
+ throw new RelayContentError("self", "Only the one who shared it opens it, in their own Ta.");
627
+ }
628
+ if (link2.access === "password" && !options.password) {
629
+ throw new RelayContentError("password", "It is shared with a password.");
630
+ }
631
+ const key = await contentKey(RelayBytes.fromBase64(link2.key), link2.share, link2.access === "password" ? options.password : undefined);
632
+ if (link2.offline) {
633
+ const copy = await fromRelay(link2, key);
634
+ if (copy) {
635
+ return copy;
636
+ }
637
+ }
638
+ return fromHost(link2, key, options);
639
+ }
640
+ RelayContentUtil2.fetch = fetch2;
641
+ async function fromRelay(link2, key) {
642
+ let response;
643
+ try {
644
+ response = await globalThis.fetch(`${link2.relay}${RELAY_BLOB_PATH}${link2.share}`, { headers: { "x-ta-auth": await authToken(key) } });
645
+ } catch (_a) {
646
+ return;
647
+ }
648
+ if (response.status === 403) {
649
+ throw link2.access === "password" ? new RelayContentError("wrong", "The password is wrong.") : new RelayContentError("gone", "This link no longer works.");
650
+ }
651
+ if (response.status === 410 || response.status === 451) {
652
+ throw new RelayContentError("gone", BLOCKED_MESSAGE);
653
+ }
654
+ if (response.status === 429) {
655
+ throw new RelayContentError("busy", "Too many wrong passwords: try again in a few minutes.");
656
+ }
657
+ if (!response.ok) {
658
+ return;
659
+ }
660
+ try {
661
+ return await open(key, new Uint8Array(await response.arrayBuffer()));
662
+ } catch (_b) {
663
+ throw new RelayContentError("wrong", "The password is wrong.");
664
+ }
665
+ }
666
+ function fromHost(link2, key, options) {
667
+ var _a;
668
+ const max = (_a = options.maxBytes) !== null && _a !== undefined ? _a : RELAY_CONTENT_MAX_BYTES;
669
+ const pairing = { relay: link2.relay, host: link2.host, device: link2.share, key: RelayBytes.toBase64(key) };
670
+ return new Promise((resolve, reject) => {
671
+ var _a2;
672
+ const socket = new RelaySocket(pairing, { proveFirst: true });
673
+ const chunks = [];
674
+ let received = 0;
675
+ let header;
676
+ let done = false;
677
+ const finish = (error, item) => {
678
+ if (done) {
679
+ return;
680
+ }
681
+ done = true;
682
+ clearTimeout(timer);
683
+ socket.onclose = null;
684
+ socket.close();
685
+ if (item) {
686
+ resolve(item);
687
+ } else {
688
+ reject(error);
689
+ }
690
+ };
691
+ const timer = setTimeout(() => finish(new RelayContentError("timeout", "The computer that shared it took too long to send it.")), (_a2 = options.timeoutMs) !== null && _a2 !== undefined ? _a2 : 60000);
692
+ socket.onmessage = ({ data }) => {
693
+ let message;
694
+ try {
695
+ message = JSON.parse(data);
696
+ } catch (_a3) {
697
+ finish(new RelayContentError("invalid", "The computer that shared it sent what is not content."));
698
+ return;
699
+ }
700
+ if (message.t === "error") {
701
+ finish(new RelayContentError("gone", message.message));
702
+ } else if (message.t === "content") {
703
+ if (!(message.size >= 0) || message.size > max) {
704
+ finish(new RelayContentError("large", `It is larger than ${Math.round(max / 1024 / 1024)} MB.`));
705
+ return;
706
+ }
707
+ header = {
708
+ kind: String(message.kind),
709
+ title: String(message.title),
710
+ createdAt: Number(message.createdAt),
711
+ type: message.type,
712
+ size: message.size
713
+ };
714
+ } else if (message.t === "chunk" && header) {
715
+ const bytes = RelayBytes.fromBase64(message.d);
716
+ received += bytes.length;
717
+ if (received > header.size) {
718
+ finish(new RelayContentError("invalid", "It is larger than it said."));
719
+ return;
720
+ }
721
+ chunks.push(bytes);
722
+ } else if (message.t === "end" && header) {
723
+ if (received !== header.size) {
724
+ finish(new RelayContentError("invalid", "It came short."));
725
+ return;
726
+ }
727
+ const { size: _size, ...rest } = header;
728
+ finish(undefined, { ...rest, data: RelayBytes.concat(...chunks) });
729
+ }
730
+ };
731
+ socket.onclose = ({ code, reason }) => finish(closed(code, reason, link2));
732
+ });
733
+ }
734
+ function closed(code, reason, link2) {
735
+ if (code === RelaySocket.REFUSED) {
736
+ if (reason === "key") {
737
+ return link2.access === "password" ? new RelayContentError("wrong", "The password is wrong.") : new RelayContentError("gone", "This link no longer works.");
738
+ }
739
+ if (reason === "busy") {
740
+ return new RelayContentError("busy", "Too many wrong passwords: try again in a few minutes.");
741
+ }
742
+ return new RelayContentError("gone", "This link no longer works: the share was stopped or ran out.");
743
+ }
744
+ if (code === RelayCloseCode.BLOCKED) {
745
+ return new RelayContentError("gone", BLOCKED_MESSAGE);
746
+ }
747
+ if (code === RelayCloseCode.SIGN_IN) {
748
+ return new RelayContentError("gone", "The one who shared it has not signed in to an account, which this relay needs of public links.");
749
+ }
750
+ return code === RelayCloseCode.HOST_OFFLINE || code === RelayCloseCode.TIMEOUT ? new RelayContentError("offline", "The computer that shared it is not running Ta now. Try again later.") : new RelayContentError("offline", "The computer that shared it cannot be reached now. Try again later.");
751
+ }
752
+ async function blobKey(key) {
753
+ const bytes = await hkdf(key, new Uint8Array(0), "ta-share/1 blob");
754
+ return globalThis.crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]);
755
+ }
756
+ async function hkdf(key, salt, info) {
757
+ const subtle2 = globalThis.crypto.subtle;
758
+ const secret = await subtle2.importKey("raw", key, "HKDF", false, ["deriveBits"]);
759
+ const bits = await subtle2.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: encoder3.encode(info) }, secret, 256);
760
+ return new Uint8Array(bits);
761
+ }
762
+ })(RelayContentUtil || (RelayContentUtil = {}));
763
+ var RelayContentHandoff;
764
+ (function(RelayContentHandoff2) {
765
+ const KEY = "ta.shared";
766
+ function keep(share, item, password) {
767
+ const { data, ...header } = item;
768
+ const store = (kept) => {
769
+ var _a;
770
+ return (_a = globalThis.sessionStorage) === null || _a === undefined ? undefined : _a.setItem(KEY, JSON.stringify(kept));
771
+ };
772
+ try {
773
+ store({ share, ...password === undefined ? {} : { password }, item: { ...header, data: RelayBytes.toBase64(data) } });
774
+ } catch (_a) {
775
+ try {
776
+ store({ share, ...password === undefined ? {} : { password } });
777
+ } catch (_b) {}
778
+ }
779
+ }
780
+ RelayContentHandoff2.keep = keep;
781
+ function take(share) {
782
+ var _a;
783
+ var _b;
784
+ try {
785
+ const kept = JSON.parse((_b = (_a = globalThis.sessionStorage) === null || _a === undefined ? undefined : _a.getItem(KEY)) !== null && _b !== undefined ? _b : "null");
786
+ if ((kept === null || kept === undefined ? undefined : kept.share) !== share) {
787
+ return {};
788
+ }
789
+ const item = kept.item && { ...kept.item, data: RelayBytes.fromBase64(kept.item.data) };
790
+ return { ...item ? { item } : {}, ...kept.password === undefined ? {} : { password: kept.password } };
791
+ } catch (_c) {
792
+ return {};
793
+ }
794
+ }
795
+ RelayContentHandoff2.take = take;
796
+ })(RelayContentHandoff || (RelayContentHandoff = {}));
797
+
798
+ // ../ta-relay/esm/common/relay-moderation-policy.js
799
+ var RELAY_OUTWARD_FEATURES = ["share", "rooms", "moments", "nearby"];
800
+ var RELAY_MODERATION_POLICY = {
801
+ auto: false,
802
+ people: 3,
803
+ severe: 2,
804
+ hostAfter: 3,
805
+ limitDays: 7,
806
+ needsAccount: [],
807
+ banCovers: ["share", "rooms", "moments", "nearby"]
808
+ };
809
+ var RELAY_BIND_PATH = "/v1/bind";
810
+ var RELAY_STANDING_PATH = "/v1/standing";
811
+ var RELAY_APPEAL_PATH = "/v1/appeal";
812
+ var RelayModerationPolicyUtil;
813
+ (function(RelayModerationPolicyUtil2) {
814
+ function count(value, fallback, min, max = 100) {
815
+ const n = Math.round(Number(value));
816
+ return Number.isFinite(n) && n >= min ? Math.min(n, max) : fallback;
817
+ }
818
+ function features(value, fallback) {
819
+ return Array.isArray(value) ? RELAY_OUTWARD_FEATURES.filter((feature) => value.includes(feature)) : fallback;
820
+ }
821
+ function of(given) {
822
+ const base = RELAY_MODERATION_POLICY;
823
+ return {
824
+ auto: (given === null || given === undefined ? undefined : given.auto) === true,
825
+ people: count(given === null || given === undefined ? undefined : given.people, base.people, 1),
826
+ severe: count(given === null || given === undefined ? undefined : given.severe, base.severe, 1),
827
+ hostAfter: count(given === null || given === undefined ? undefined : given.hostAfter, base.hostAfter, 0),
828
+ limitDays: count(given === null || given === undefined ? undefined : given.limitDays, base.limitDays, 1, 30),
829
+ needsAccount: features(given === null || given === undefined ? undefined : given.needsAccount, base.needsAccount),
830
+ banCovers: features(given === null || given === undefined ? undefined : given.banCovers, base.banCovers)
831
+ };
832
+ }
833
+ RelayModerationPolicyUtil2.of = of;
834
+ function active(sanction, now) {
835
+ return !!sanction && (sanction.until === undefined || sanction.until > now);
836
+ }
837
+ RelayModerationPolicyUtil2.active = active;
838
+ function takes(sanction, feature, policy, now) {
839
+ if (!active(sanction, now)) {
840
+ return false;
841
+ }
842
+ return sanction.level === "limit" ? feature === "share" : policy.banCovers.includes(feature);
843
+ }
844
+ RelayModerationPolicyUtil2.takes = takes;
845
+ })(RelayModerationPolicyUtil || (RelayModerationPolicyUtil = {}));
846
+
847
+ // ../ta-relay/esm/common/relay-moderation.js
848
+ var RELAY_MODERATION_PATH = "/v1/moderation";
849
+ var RELAY_REPORT_REASONS = ["phishing", "malware", "sexual", "illegal", "harassment", "other"];
850
+ var HOUR_MS = 60 * 60 * 1000;
851
+ var DAY_MS = 24 * HOUR_MS;
852
+
853
+ // ../ta-relay/esm/common/relay-moderation-client.js
854
+ async function call(url, token, init) {
855
+ var _a, _b;
856
+ const response = await fetch(url, {
857
+ ...init,
858
+ headers: { authorization: `Bearer ${token}`, ...(init === null || init === undefined ? undefined : init.body) ? { "content-type": "application/json" } : {} }
859
+ });
860
+ const body = await response.json().catch(() => {
861
+ return;
862
+ });
863
+ if (response.status === 401) {
864
+ throw new Error((_a = body === null || body === undefined ? undefined : body.error) !== null && _a !== undefined ? _a : "The token is wrong.");
865
+ }
866
+ if (response.status === 404) {
867
+ throw new Error("This relay does not answer it.");
868
+ }
869
+ if (!response.ok || !body) {
870
+ throw new Error((_b = body === null || body === undefined ? undefined : body.error) !== null && _b !== undefined ? _b : `The relay answered ${response.status}.`);
871
+ }
872
+ return body;
873
+ }
874
+ var base = (relay) => relay.replace(/\/+$/, "");
875
+ var RelayModerationClient;
876
+ (function(RelayModerationClient2) {
877
+ function read(relay, token) {
878
+ return call(`${base(relay)}${RELAY_MODERATION_PATH}`, token);
879
+ }
880
+ RelayModerationClient2.read = read;
881
+ function apply(relay, token, action) {
882
+ return call(`${base(relay)}${RELAY_MODERATION_PATH}`, token, { method: "POST", body: JSON.stringify(action) });
883
+ }
884
+ RelayModerationClient2.apply = apply;
885
+ })(RelayModerationClient || (RelayModerationClient = {}));
886
+ var RelayStandingClient;
887
+ (function(RelayStandingClient2) {
888
+ function bind(relay, token, host) {
889
+ return call(`${base(relay)}${RELAY_BIND_PATH}`, token, { method: "POST", body: JSON.stringify({ host: host.id, secret: host.secret }) });
890
+ }
891
+ RelayStandingClient2.bind = bind;
892
+ function standing(relay, token) {
893
+ return call(`${base(relay)}${RELAY_STANDING_PATH}`, token);
894
+ }
895
+ RelayStandingClient2.standing = standing;
896
+ function appeal(relay, token, text) {
897
+ return call(`${base(relay)}${RELAY_APPEAL_PATH}`, token, { method: "POST", body: JSON.stringify({ text }) });
898
+ }
899
+ RelayStandingClient2.appeal = appeal;
900
+ })(RelayStandingClient || (RelayStandingClient = {}));
901
+
902
+ // ../ta-protocol/esm/common/language.js
903
+ var TaLanguageUtil;
904
+ (function(TaLanguageUtil2) {
905
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
906
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
907
+ function of(tag) {
908
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
909
+ if (/^zh(\b|-)/.test(said)) {
910
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
911
+ }
912
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
913
+ }
914
+ TaLanguageUtil2.of = of;
915
+ function server(env = typeof process === "undefined" ? {} : process.env) {
916
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
917
+ }
918
+ TaLanguageUtil2.server = server;
919
+ function pick(language, words) {
920
+ return words[of(language)];
921
+ }
922
+ TaLanguageUtil2.pick = pick;
923
+ function say(words) {
924
+ return words[server()];
925
+ }
926
+ TaLanguageUtil2.say = say;
927
+ function chinese(language) {
928
+ return of(language).startsWith("zh");
929
+ }
930
+ TaLanguageUtil2.chinese = chinese;
931
+ function cjk(language) {
932
+ return of(language) !== "en-US";
933
+ }
934
+ TaLanguageUtil2.cjk = cjk;
935
+ function list(language, items) {
936
+ return items.join(cjk(language) ? "、" : ", ");
937
+ }
938
+ TaLanguageUtil2.list = list;
939
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
940
+
941
+ // web-src/server-texts.ts
942
+ var REASONS = {
943
+ "zh-CN": { phishing: "钓鱼或诈骗", malware: "病毒或恶意软件", sexual: "色情内容", illegal: "违法内容", harassment: "骚扰或侵权", other: "其他" },
944
+ "zh-TW": { phishing: "釣魚或詐騙", malware: "病毒或惡意軟體", sexual: "色情內容", illegal: "違法內容", harassment: "騷擾或侵權", other: "其他" },
945
+ "en-US": {
946
+ phishing: "Phishing or scam",
947
+ malware: "Virus or malware",
948
+ sexual: "Sexual content",
949
+ illegal: "Illegal content",
950
+ harassment: "Harassment or infringement",
951
+ other: "Other"
952
+ },
953
+ "ja-JP": {
954
+ phishing: "フィッシング・詐欺",
955
+ malware: "ウイルス・マルウェア",
956
+ sexual: "性的なコンテンツ",
957
+ illegal: "違法なコンテンツ",
958
+ harassment: "嫌がらせ・権利侵害",
959
+ other: "その他"
960
+ }
961
+ };
962
+ var ShareServerTexts;
963
+ ((ShareServerTexts) => {
964
+ function language(env = process.env) {
965
+ return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
966
+ }
967
+ ShareServerTexts.language = language;
968
+ function access(access2, lang) {
969
+ return TaLanguageUtil.pick(lang, {
970
+ "zh-CN": access2 === "password" ? "知道口令的人" : access2 === "self" ? "只有你自己" : "拿到链接的任何人",
971
+ "zh-TW": access2 === "password" ? "知道密碼的人" : access2 === "self" ? "只有你自己" : "拿到連結的任何人",
972
+ "en-US": access2 === "password" ? "whoever has the password" : access2 === "self" ? "only you" : "anyone with the link",
973
+ "ja-JP": access2 === "password" ? "パスワードを持っている人" : access2 === "self" ? "あなただけ" : "リンクを持つ誰でも"
974
+ });
975
+ }
976
+ function days(days2, lang) {
977
+ return TaLanguageUtil.pick(lang, {
978
+ "zh-CN": days2 > 0 ? `${days2} 天内有效` : "停止分享前一直有效",
979
+ "zh-TW": days2 > 0 ? `${days2} 天內有效` : "停止分享前一直有效",
980
+ "en-US": days2 > 0 ? `for ${days2} day${days2 === 1 ? "" : "s"}` : "until you stop it",
981
+ "ja-JP": days2 > 0 ? `${days2}日間有効` : "停止するまで有効"
982
+ });
983
+ }
984
+ function confirm(what, options) {
985
+ const lang = language();
986
+ const offlineText = options.offline ? TaLanguageUtil.pick(lang, {
987
+ "zh-CN": "另在中继上存一份加密副本,电脑关机也能看。",
988
+ "zh-TW": "另在中繼上存一份加密副本,電腦關機也能看。",
989
+ "en-US": "A sealed copy is kept on the relay, to open while this computer is off.",
990
+ "ja-JP": "リレーに暗号化されたコピーを保存し、コンピュータがオフでも開くことができます。"
991
+ }) : TaLanguageUtil.pick(lang, {
992
+ "zh-CN": "只在这台电脑运行 Ta 时能打开。",
993
+ "zh-TW": "只在這台電腦執行 Ta 時能開啟。",
994
+ "en-US": "It opens while this computer runs Ta.",
995
+ "ja-JP": "このコンピュータで Ta を実行している間に開きます。"
996
+ });
997
+ return TaLanguageUtil.pick(lang, {
998
+ "zh-CN": [
999
+ `分享“${what}”?`,
1000
+ `${access(options.access, lang)}可以查看,${days(options.days, lang)}。${offlineText}看起来像密钥的内容会被隐去。可以在“发现 → 我的分享”里随时停止。`
1001
+ ],
1002
+ "zh-TW": [
1003
+ `分享「${what}」?`,
1004
+ `${access(options.access, lang)}可以檢視,${days(options.days, lang)}。${offlineText}看起來像金鑰的內容會被隱去。可以在「發現 → 我的分享」裡隨時停止。`
1005
+ ],
1006
+ "en-US": [
1007
+ `Share ${what}?`,
1008
+ `${access(options.access, lang)} can see it, ${days(options.days, lang)}. ${offlineText} What looks like a secret is hidden. Stop it any time in Discover → My shares.`
1009
+ ],
1010
+ "ja-JP": [
1011
+ `${what}を共有しますか?`,
1012
+ `${access(options.access, lang)}はこれを見ることができます。${days(options.days, lang)}。${offlineText}秘密に見える内容は隠されます。見つける → 私の共有でいつでも停止できます。`
1013
+ ]
1014
+ });
1015
+ }
1016
+ ShareServerTexts.confirm = confirm;
1017
+ function publicConfirm(port, minutes) {
1018
+ const hours = minutes % 60 === 0 ? minutes / 60 : undefined;
1019
+ return TaLanguageUtil.say({
1020
+ "zh-CN": [
1021
+ `公开本机服务 localhost:${port}?`,
1022
+ `拿到链接的任何人都能访问这个服务,${hours ? `${hours} 小时` : `${minutes} 分钟`}后自动停止,关掉 Ta 也会停止。链接经 Cloudflare 转发,域名是随机的 trycloudflare.com。只公开你愿意给别人看的服务;公司网络通常禁止这样做。`
1023
+ ],
1024
+ "zh-TW": [
1025
+ `公開本機服務 localhost:${port}?`,
1026
+ `拿到連結的任何人都能存取這個服務,${hours ? `${hours} 小時` : `${minutes} 分鐘`}後自動停止,關掉 Ta 也會停止。連結經 Cloudflare 轉發,網域是隨機的 trycloudflare.com。只公開你願意給別人看的服務;公司網路通常禁止這樣做。`
1027
+ ],
1028
+ "en-US": [
1029
+ `Make localhost:${port} public?`,
1030
+ `Anyone with the link can reach this service, for ${hours ? `${hours} hour${hours === 1 ? "" : "s"}` : `${minutes} minutes`} or until Ta stops. It goes through Cloudflare, on a random domain of trycloudflare.com. Make public only what you would show anyone; company networks usually forbid it.`
1031
+ ],
1032
+ "ja-JP": [
1033
+ `localhost:${port} を公開しますか?`,
1034
+ `リンクを持つ誰でもこのサービスにアクセスできます。${hours ? `${hours} 時間` : `${minutes} 分`}後、または Ta を閉じると停止します。Cloudflare 経由で、ランダムな trycloudflare.com のドメインになります。誰に見られてもよいものだけを公開してください。会社のネットワークでは通常禁止されています。`
1035
+ ]
1036
+ });
1037
+ }
1038
+ ShareServerTexts.publicConfirm = publicConfirm;
1039
+ function reportsTitle() {
1040
+ return TaLanguageUtil.say({ "zh-CN": "分享被举报", "zh-TW": "分享被檢舉", "en-US": "A share was reported", "ja-JP": "共有が報告されました" });
1041
+ }
1042
+ ShareServerTexts.reportsTitle = reportsTitle;
1043
+ function reported(reason, count, note) {
1044
+ const lang = language();
1045
+ const why = TaLanguageUtil.pick(lang, REASONS)[reason] ?? reason;
1046
+ const times = TaLanguageUtil.pick(lang, {
1047
+ "zh-CN": count > 1 ? `(${count} 次)` : "",
1048
+ "zh-TW": count > 1 ? `(${count} 次)` : "",
1049
+ "en-US": count > 1 ? ` (${count} times)` : "",
1050
+ "ja-JP": count > 1 ? `(${count} 回)` : ""
1051
+ });
1052
+ return `${why}${times}${note ? `:${note.slice(0, 120)}` : ""}`;
1053
+ }
1054
+ ShareServerTexts.reported = reported;
1055
+ function logged(entry) {
1056
+ const [kind] = entry.target.split(":");
1057
+ const what = TaLanguageUtil.say({
1058
+ "zh-CN": kind === "account" ? "一个账号" : kind === "host" ? "一台电脑" : "一条链接",
1059
+ "zh-TW": kind === "account" ? "一個帳號" : kind === "host" ? "一台電腦" : "一條連結",
1060
+ "en-US": kind === "account" ? "an account" : kind === "host" ? "a computer" : "a link",
1061
+ "ja-JP": kind === "account" ? "アカウント" : kind === "host" ? "コンピュータ" : "リンク"
1062
+ });
1063
+ if (entry.action === "appeal") {
1064
+ return TaLanguageUtil.say({
1065
+ "zh-CN": `收到申诉:${entry.reason ?? ""}`,
1066
+ "zh-TW": `收到申訴:${entry.reason ?? ""}`,
1067
+ "en-US": `An appeal: ${entry.reason ?? ""}`,
1068
+ "ja-JP": `異議申し立て:${entry.reason ?? ""}`
1069
+ });
1070
+ }
1071
+ const done = TaLanguageUtil.say({
1072
+ "zh-CN": entry.action === "limit" ? "限制了公开分享:" : "封禁了",
1073
+ "zh-TW": entry.action === "limit" ? "限制了公開分享:" : "封鎖了",
1074
+ "en-US": entry.action === "limit" ? "limited the public links of" : "blocked",
1075
+ "ja-JP": entry.action === "limit" ? "公開共有を制限しました:" : "ブロックしました:"
1076
+ });
1077
+ return TaLanguageUtil.say({
1078
+ "zh-CN": `自动规则${done}${what},误判可在举报处理里撤销。`,
1079
+ "zh-TW": `自動規則${done}${what},誤判可在檢舉處理裡撤銷。`,
1080
+ "en-US": `The rules ${done} ${what}; undo it in Reports if it was wrong.`,
1081
+ "ja-JP": `自動ルールが${what}を${done}誤りなら「報告の対応」で取り消せます。`
1082
+ });
1083
+ }
1084
+ ShareServerTexts.logged = logged;
1085
+ function password() {
1086
+ return TaLanguageUtil.say({
1087
+ "zh-CN": "设置查看口令",
1088
+ "zh-TW": "設定檢視密碼",
1089
+ "en-US": "A password to open it",
1090
+ "ja-JP": "パスワード"
1091
+ });
1092
+ }
1093
+ ShareServerTexts.password = password;
1094
+ function conversation() {
1095
+ return TaLanguageUtil.say({
1096
+ "zh-CN": "这段对话",
1097
+ "zh-TW": "這段對話",
1098
+ "en-US": "this conversation",
1099
+ "ja-JP": "この会話"
1100
+ });
1101
+ }
1102
+ ShareServerTexts.conversation = conversation;
1103
+ })(ShareServerTexts ||= {});
1104
+
5
1105
  // web-src/share-protocol.ts
1106
+ var NAME = "@celljs/ta-share";
1107
+ var REPORTS_VIEW = "@celljs/ta-share/reports";
1108
+ var TUNNELS_KEY = "tunnels.enabled";
6
1109
  var CONVERSATION_KIND = "ta-conversation";
7
1110
  var FILE_KIND = "file";
1111
+ var MAX_FILE_BYTES = 8 * 1024 * 1024;
8
1112
  var ShareLink;
9
1113
  ((ShareLink) => {
10
1114
  const LINK = /^https?:\/\/[^/\s#?]+\/s#v=1&\S+$/i;
@@ -22,6 +1126,352 @@ var ShareLink;
22
1126
  ShareLink.needsPassword = needsPassword;
23
1127
  })(ShareLink ||= {});
24
1128
 
1129
+ // web-src/share-moderation.ts
1130
+ var OPERATOR_LOOK_MS = 15 * 60 * 1000;
1131
+ var TOLD_KEY = "operator.told";
1132
+ var TOLD_LOG_KEY = "operator.toldLog";
1133
+
1134
+ class ShareModeration {
1135
+ host;
1136
+ timer;
1137
+ constructor(host) {
1138
+ this.host = host;
1139
+ }
1140
+ start() {
1141
+ this.timer = setInterval(() => void this.look().catch(() => {
1142
+ return;
1143
+ }), OPERATOR_LOOK_MS);
1144
+ this.timer.unref?.();
1145
+ setTimeout(() => void this.look().catch(() => {
1146
+ return;
1147
+ }), 30000).unref?.();
1148
+ }
1149
+ dispose() {
1150
+ clearInterval(this.timer);
1151
+ }
1152
+ async relay() {
1153
+ const service = await this.host.relays.serviceFor("share");
1154
+ if (!service.url) {
1155
+ throw new Error("Links of content go through no relay of Ta here.");
1156
+ }
1157
+ return service.url.replace(/\/+$/, "");
1158
+ }
1159
+ static id(relay) {
1160
+ return `relay-operator:${relay}`;
1161
+ }
1162
+ async token(relay) {
1163
+ if (!this.host.credentials.available()) {
1164
+ return;
1165
+ }
1166
+ return (await this.host.credentials.get(ShareModeration.id(relay)))?.password;
1167
+ }
1168
+ async state() {
1169
+ const relay = await this.relay();
1170
+ const token = await this.token(relay);
1171
+ if (!token) {
1172
+ return { relay, operator: false };
1173
+ }
1174
+ try {
1175
+ return { relay, operator: true, ...await RelayModerationClient.read(relay, token) };
1176
+ } catch (error) {
1177
+ return { relay, operator: true, error: error.message };
1178
+ }
1179
+ }
1180
+ async setToken(token) {
1181
+ const relay = await this.relay();
1182
+ if (token === null) {
1183
+ await this.host.credentials.remove(ShareModeration.id(relay));
1184
+ return this.state();
1185
+ }
1186
+ const given = String(token ?? "").trim();
1187
+ if (!given) {
1188
+ throw new Error("Give the token of the operator of the relay.");
1189
+ }
1190
+ if (!this.host.credentials.available()) {
1191
+ throw new Error("The vault of Ta is off: turn on Secrets to keep the token.");
1192
+ }
1193
+ await RelayModerationClient.read(relay, given);
1194
+ await this.host.credentials.set(ShareModeration.id(relay), { password: given }, { feature: "relay", name: new URL(relay).host });
1195
+ const state = await this.state();
1196
+ await this.host.setExtensionData(NAME, TOLD_KEY, ShareModeration.toldOf(state.reports ?? []));
1197
+ await this.host.setExtensionData(NAME, TOLD_LOG_KEY, state.log?.[0]?.at ?? 0);
1198
+ return state;
1199
+ }
1200
+ async act(action) {
1201
+ const relay = await this.relay();
1202
+ const token = await this.token(relay);
1203
+ if (!token) {
1204
+ throw new Error("This Ta keeps no token of the operator of the relay.");
1205
+ }
1206
+ return { relay, operator: true, ...await RelayModerationClient.apply(relay, token, action) };
1207
+ }
1208
+ async look() {
1209
+ const relay = await this.relay();
1210
+ const token = await this.token(relay);
1211
+ if (!token) {
1212
+ return [];
1213
+ }
1214
+ const state = await RelayModerationClient.read(relay, token);
1215
+ const told = await this.host.getExtensionData(NAME, TOLD_KEY) ?? {};
1216
+ const fresh = ShareModeration.fresh(state.reports, told, state.blocks.shares, state.blocks.hosts);
1217
+ for (const report of fresh) {
1218
+ await this.host.callPackageHost("@celljs/ta-notify", "notify", [
1219
+ {
1220
+ from: NAME,
1221
+ id: `report:${report.share}:${report.last}`,
1222
+ level: "ask",
1223
+ title: ShareServerTexts.reportsTitle(),
1224
+ text: ShareServerTexts.reported(report.reason, report.count, report.note),
1225
+ view: REPORTS_VIEW
1226
+ }
1227
+ ]).catch(() => {
1228
+ return;
1229
+ });
1230
+ }
1231
+ if (fresh.length) {
1232
+ await this.host.setExtensionData(NAME, TOLD_KEY, ShareModeration.toldOf(state.reports));
1233
+ }
1234
+ const toldLog = Number(await this.host.getExtensionData(NAME, TOLD_LOG_KEY)) || 0;
1235
+ for (const entry of ShareModeration.news(state.log, toldLog)) {
1236
+ await this.host.callPackageHost("@celljs/ta-notify", "notify", [
1237
+ {
1238
+ from: NAME,
1239
+ id: `log:${entry.at}:${entry.target}`,
1240
+ level: "ask",
1241
+ title: ShareServerTexts.reportsTitle(),
1242
+ text: ShareServerTexts.logged(entry),
1243
+ view: REPORTS_VIEW
1244
+ }
1245
+ ]).catch(() => {
1246
+ return;
1247
+ });
1248
+ }
1249
+ if ((state.log[0]?.at ?? 0) > toldLog) {
1250
+ await this.host.setExtensionData(NAME, TOLD_LOG_KEY, state.log[0].at);
1251
+ }
1252
+ return fresh;
1253
+ }
1254
+ static fresh(reports, told, shares, hosts) {
1255
+ return reports.filter((report) => RELAY_REPORT_REASONS.includes(report.reason) && report.last > (told[report.share] ?? 0) && !shares.includes(report.share) && !hosts.includes(report.host));
1256
+ }
1257
+ static news(log, since) {
1258
+ return log.filter((entry) => entry.at > since && (entry.by === "rule" || entry.action === "appeal")).slice(0, 10);
1259
+ }
1260
+ static toldOf(reports) {
1261
+ return Object.fromEntries(reports.map((report) => [report.share, report.last]));
1262
+ }
1263
+ }
1264
+
1265
+ // web-src/share-tunnels.ts
1266
+ import { spawn } from "node:child_process";
1267
+ import { createHash, randomBytes } from "node:crypto";
1268
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
1269
+ import { delimiter, join } from "node:path";
1270
+ var CLOUDFLARED_VERSION = "2026.11.1";
1271
+ var CLOUDFLARED_FILES = {
1272
+ "darwin-arm64": { file: "cloudflared-darwin-arm64.tgz", sha256: "1cd7041838e5b0943378763ca86ddc0af896d1727875f36b29f5cc35eb2c4df7", tgz: true },
1273
+ "darwin-x64": { file: "cloudflared-darwin-amd64.tgz", sha256: "52686df40889be19803c368470bd46d5228737462f10a40380bedb6af8ed49a2", tgz: true },
1274
+ "linux-x64": { file: "cloudflared-linux-amd64", sha256: "97bb3b02d23a5980fc9c15a1a270e692da1923f103f920d5b16d4931d5ab55e7" },
1275
+ "linux-arm64": { file: "cloudflared-linux-arm64", sha256: "b155cec3e48e489cfb8e5c602769fb8c771083018d8881d68b4d18a791567c5a" },
1276
+ "win32-x64": { file: "cloudflared-windows-amd64.exe", sha256: "341deda3db5ec498a0482254d6c38c0b7cf01a30c37bb5dd95d2216d08955e35" }
1277
+ };
1278
+ var TUNNEL_MINUTES = 60;
1279
+ var TUNNEL_MAX_MINUTES = 8 * 60;
1280
+ var TUNNEL_MAX = 3;
1281
+ var URL_PATTERN = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/;
1282
+ var START_MS = 45000;
1283
+
1284
+ class ShareTunnels {
1285
+ options;
1286
+ tunnels = new Map;
1287
+ fetching;
1288
+ constructor(options) {
1289
+ this.options = options;
1290
+ }
1291
+ get env() {
1292
+ return this.options.env ?? process.env;
1293
+ }
1294
+ now() {
1295
+ return (this.options.now ?? Date.now)();
1296
+ }
1297
+ get allowed() {
1298
+ return !/^(off|0|false|no)$/i.test(String(this.env.TA_PUBLIC_TUNNELS ?? "").trim());
1299
+ }
1300
+ async state() {
1301
+ return { allowed: this.allowed, enabled: this.allowed && await this.options.enabled(), tunnels: this.list() };
1302
+ }
1303
+ async setEnabled(enabled) {
1304
+ if (enabled && !this.allowed) {
1305
+ throw new Error(ShareTunnels.FORBIDDEN);
1306
+ }
1307
+ await this.options.setEnabled(!!enabled);
1308
+ if (!enabled) {
1309
+ this.stopAll();
1310
+ }
1311
+ return this.state();
1312
+ }
1313
+ list() {
1314
+ return [...this.tunnels.values()].map(({ child: _child, timer: _timer, ...info }) => info);
1315
+ }
1316
+ async open(port, minutes = TUNNEL_MINUTES, title) {
1317
+ if (!this.allowed) {
1318
+ throw new Error(ShareTunnels.FORBIDDEN);
1319
+ }
1320
+ if (!await this.options.enabled()) {
1321
+ throw new Error("Public links of services of this computer are off: the user turns them on in Discover → My shares.");
1322
+ }
1323
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1324
+ throw new Error("Give the port of a service of this computer, 1 to 65535.");
1325
+ }
1326
+ if (port === this.servePort()) {
1327
+ throw new Error("That is the port of Ta itself, which is never made public: reach it from a phone through Ta instead.");
1328
+ }
1329
+ const same = [...this.tunnels.values()].find((tunnel2) => tunnel2.port === port);
1330
+ if (same) {
1331
+ return this.list().find((tunnel2) => tunnel2.id === same.id);
1332
+ }
1333
+ if (this.tunnels.size >= TUNNEL_MAX) {
1334
+ throw new Error(`At most ${TUNNEL_MAX} public links are open at once: stop one in Discover → My shares.`);
1335
+ }
1336
+ const kept = Math.min(Math.max(Math.round(Number(minutes) || TUNNEL_MINUTES), 1), TUNNEL_MAX_MINUTES);
1337
+ const { command, args } = this.options.command ? await this.options.command(port) : { command: await this.cloudflared(), args: ShareTunnels.args(port) };
1338
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...this.env, TUNNEL_METRICS: "" }, windowsHide: true });
1339
+ const url = await new Promise((resolve, reject) => {
1340
+ let seen = "";
1341
+ const timer2 = setTimeout(() => done(new Error("Cloudflare gave no link in time: the network may not reach it.")), START_MS);
1342
+ const done = (error, found) => {
1343
+ clearTimeout(timer2);
1344
+ child.stdout?.off("data", read);
1345
+ child.stderr?.off("data", read);
1346
+ child.off("exit", exited);
1347
+ child.off("error", failed);
1348
+ if (found) {
1349
+ resolve(found);
1350
+ } else {
1351
+ child.kill();
1352
+ reject(error);
1353
+ }
1354
+ };
1355
+ const read = (data) => {
1356
+ seen = (seen + String(data)).slice(-8000);
1357
+ const found = URL_PATTERN.exec(seen)?.[0];
1358
+ if (found) {
1359
+ done(undefined, found);
1360
+ }
1361
+ };
1362
+ const exited = (code) => done(new Error(`cloudflared stopped (${code ?? "killed"}): ${seen.trim().split(`
1363
+ `).slice(-3).join(" ")}`));
1364
+ const failed = (error) => done(error);
1365
+ child.stdout?.on("data", read);
1366
+ child.stderr?.on("data", read);
1367
+ child.once("exit", exited);
1368
+ child.once("error", failed);
1369
+ });
1370
+ const now = this.now();
1371
+ const id = randomBytes(9).toString("base64url");
1372
+ const timer = setTimeout(() => this.stop(id), kept * 60000);
1373
+ timer.unref?.();
1374
+ const tunnel = {
1375
+ id,
1376
+ port,
1377
+ url,
1378
+ title: String(title ?? "").trim().slice(0, 80) || `localhost:${port}`,
1379
+ createdAt: now,
1380
+ expiresAt: now + kept * 60000,
1381
+ child,
1382
+ timer
1383
+ };
1384
+ child.stdout?.resume();
1385
+ child.stderr?.resume();
1386
+ child.once("exit", () => this.forget(id));
1387
+ this.tunnels.set(id, tunnel);
1388
+ return this.list().find((each) => each.id === id);
1389
+ }
1390
+ stop(id) {
1391
+ const tunnel = this.tunnels.get(String(id));
1392
+ if (!tunnel) {
1393
+ return false;
1394
+ }
1395
+ this.forget(tunnel.id);
1396
+ tunnel.child.kill();
1397
+ return true;
1398
+ }
1399
+ stopAll() {
1400
+ for (const id of [...this.tunnels.keys()]) {
1401
+ this.stop(id);
1402
+ }
1403
+ }
1404
+ forget(id) {
1405
+ const tunnel = this.tunnels.get(id);
1406
+ if (tunnel) {
1407
+ clearTimeout(tunnel.timer);
1408
+ this.tunnels.delete(id);
1409
+ }
1410
+ }
1411
+ servePort() {
1412
+ try {
1413
+ const port = JSON.parse(readFileSync(join(this.options.agentDir, "serve-state.json"), "utf8")).port;
1414
+ return typeof port === "number" ? port : undefined;
1415
+ } catch {
1416
+ return;
1417
+ }
1418
+ }
1419
+ static args(port) {
1420
+ return ["tunnel", "--no-autoupdate", "--url", `http://localhost:${port}`];
1421
+ }
1422
+ static FORBIDDEN = "Public links of services of this computer are turned off for this computer (TA_PUBLIC_TUNNELS=off).";
1423
+ cloudflared() {
1424
+ const name = process.platform === "win32" ? "cloudflared.exe" : "cloudflared";
1425
+ for (const dir of String(this.env.PATH ?? "").split(delimiter)) {
1426
+ if (dir && existsSync(join(dir, name))) {
1427
+ return Promise.resolve(join(dir, name));
1428
+ }
1429
+ }
1430
+ const kept = join(this.options.agentDir, "bin", `${name.replace(/\.exe$/, "")}-${CLOUDFLARED_VERSION}${name.endsWith(".exe") ? ".exe" : ""}`);
1431
+ if (existsSync(kept)) {
1432
+ return Promise.resolve(kept);
1433
+ }
1434
+ this.fetching ??= ShareTunnels.download(kept).finally(() => {
1435
+ this.fetching = undefined;
1436
+ });
1437
+ return this.fetching;
1438
+ }
1439
+ static async download(to, platform = `${process.platform}-${process.arch}`) {
1440
+ const release = CLOUDFLARED_FILES[platform];
1441
+ if (!release) {
1442
+ throw new Error(`There is no cloudflared for ${platform}: install it and put it on the PATH.`);
1443
+ }
1444
+ const response = await fetch(`https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/${release.file}`);
1445
+ if (!response.ok) {
1446
+ throw new Error(`cloudflared could not be fetched (${response.status}).`);
1447
+ }
1448
+ const bytes = Buffer.from(await response.arrayBuffer());
1449
+ if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) {
1450
+ throw new Error("cloudflared fetched is not the release Ta knows (its SHA-256 differs): nothing was kept.");
1451
+ }
1452
+ const dir = join(to, "..");
1453
+ mkdirSync(dir, { recursive: true, mode: 448 });
1454
+ const temp = `${to}.${randomBytes(4).toString("hex")}`;
1455
+ if (release.tgz) {
1456
+ const work = `${temp}.d`;
1457
+ mkdirSync(work, { recursive: true });
1458
+ writeFileSync(join(work, "release.tgz"), bytes);
1459
+ await new Promise((resolve, reject) => {
1460
+ const tar = spawn("tar", ["-xzf", "release.tgz", "cloudflared"], { cwd: work, stdio: "ignore" });
1461
+ tar.once("error", reject);
1462
+ tar.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`tar could not unpack cloudflared (${code}).`)));
1463
+ });
1464
+ renameSync(join(work, "cloudflared"), temp);
1465
+ rmSync(work, { recursive: true, force: true });
1466
+ } else {
1467
+ writeFileSync(temp, bytes);
1468
+ }
1469
+ chmodSync(temp, 493);
1470
+ renameSync(temp, to);
1471
+ return to;
1472
+ }
1473
+ }
1474
+
25
1475
  // ../ta-protocol/esm/common/redactor.js
26
1476
  var REDACTED = "[redacted]";
27
1477
  var WHOLE = [
@@ -847,8 +2297,8 @@ var ConversationImport;
847
2297
  })(ConversationImport ||= {});
848
2298
 
849
2299
  // web-src/share-service.ts
850
- var encoder = new TextEncoder;
851
- var decoder = new TextDecoder;
2300
+ var encoder4 = new TextEncoder;
2301
+ var decoder4 = new TextDecoder;
852
2302
  var PICTURE_TYPES = {
853
2303
  png: "image/png",
854
2304
  jpg: "image/jpeg",
@@ -862,10 +2312,51 @@ var FAILURES = new Set(["password", "wrong", "busy", "gone", "offline", "self",
862
2312
 
863
2313
  class ShareService {
864
2314
  host;
865
- constructor(host) {
2315
+ tunnels;
2316
+ moderation;
2317
+ constructor(host, tunnels) {
866
2318
  this.host = host;
2319
+ this.tunnels = tunnels ?? new ShareTunnels({
2320
+ agentDir: host.agentDir,
2321
+ enabled: async () => await host.getExtensionData(NAME, TUNNELS_KEY) === true,
2322
+ setEnabled: (enabled) => host.setExtensionData(NAME, TUNNELS_KEY, enabled)
2323
+ });
2324
+ this.moderation = new ShareModeration(host);
2325
+ this.moderation.start();
2326
+ }
2327
+ dispose() {
2328
+ this.tunnels.stopAll();
2329
+ this.moderation.dispose();
2330
+ }
2331
+ operatorState() {
2332
+ return this.moderation.state();
2333
+ }
2334
+ setOperatorToken(token) {
2335
+ return this.moderation.setToken(token === null ? null : String(token));
2336
+ }
2337
+ moderate(action) {
2338
+ return this.moderation.act(action);
2339
+ }
2340
+ async standing() {
2341
+ return await this.host.shares.standing?.().catch(() => {
2342
+ return;
2343
+ }) ?? null;
2344
+ }
2345
+ async appeal(text) {
2346
+ if (!this.host.shares.appeal) {
2347
+ throw new Error("This Ta cannot appeal yet: update it.");
2348
+ }
2349
+ return await this.host.shares.appeal(String(text ?? "").trim()) ?? null;
2350
+ }
2351
+ tunnelState() {
2352
+ return this.tunnels.state();
2353
+ }
2354
+ setTunnelsEnabled(enabled) {
2355
+ return this.tunnels.setEnabled(enabled === true);
2356
+ }
2357
+ async stopTunnel(id) {
2358
+ return this.tunnels.stop(String(id));
867
2359
  }
868
- dispose() {}
869
2360
  async preview(sessionFile, options = {}) {
870
2361
  const { conversation, stats } = await this.snapshot(sessionFile, options, false);
871
2362
  const calls = conversation.messages.flatMap((message) => message.role === "assistant" ? message.content.filter((part) => part.type === "toolCall") : []);
@@ -889,13 +2380,17 @@ class ShareService {
889
2380
  kind: CONVERSATION_KIND,
890
2381
  title: conversation.title,
891
2382
  type: "application/json",
892
- data: encoder.encode(JSON.stringify(conversation)),
2383
+ data: encoder4.encode(JSON.stringify(conversation)),
893
2384
  ...ShareService.input(options)
894
2385
  });
895
2386
  return { share, stats };
896
2387
  }
897
2388
  async shareFile(title, type, data, options) {
898
- return { share: await this.shareBytes(title, type, ShareService.fromBase64(data), options) };
2389
+ const bytes = ShareService.fromBase64(data);
2390
+ if (bytes.length > MAX_FILE_BYTES) {
2391
+ throw new Error(`The file is larger than ${MAX_FILE_BYTES / 1024 / 1024} MB, too large to share by a link.`);
2392
+ }
2393
+ return { share: await this.shareBytes(title, type, bytes, options) };
899
2394
  }
900
2395
  shareBytes(title, type, data, options) {
901
2396
  return this.host.shares.create({
@@ -931,7 +2426,7 @@ class ShareService {
931
2426
  if (opened.content.kind !== CONVERSATION_KIND) {
932
2427
  throw new Error("This link shares a file, not a conversation.");
933
2428
  }
934
- const conversation = JSON.parse(decoder.decode(opened.content.data));
2429
+ const conversation = JSON.parse(decoder4.decode(opened.content.data));
935
2430
  if (conversation?.v !== 1 || !Array.isArray(conversation.messages)) {
936
2431
  throw new Error("Not a conversation shared from Ta.");
937
2432
  }