@celljs/ta-relay 4.9.1 → 4.10.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/README.en.md +16 -1
- package/README.md +16 -1
- package/esm/common/index.d.ts +1 -0
- package/esm/common/index.js +1 -0
- package/esm/common/relay-cipher.d.ts +15 -0
- package/esm/common/relay-cipher.js +62 -2
- package/esm/common/relay-files.d.ts +108 -0
- package/esm/common/relay-files.js +170 -0
- package/esm/common/relay-protocol.d.ts +7 -1
- package/esm/common/relay-socket.js +10 -2
- package/esm/node/index.d.ts +1 -0
- package/esm/node/index.js +1 -0
- package/esm/node/relay-files-host.d.ts +27 -0
- package/esm/node/relay-files-host.js +130 -0
- package/esm/node/relay-host.d.ts +12 -1
- package/esm/node/relay-host.js +37 -11
- package/lib/common/index.d.ts +1 -0
- package/lib/common/index.js +1 -0
- package/lib/common/relay-cipher.d.ts +15 -0
- package/lib/common/relay-cipher.js +63 -3
- package/lib/common/relay-files.d.ts +109 -0
- package/lib/common/relay-files.js +174 -0
- package/lib/common/relay-protocol.d.ts +7 -1
- package/lib/common/relay-socket.js +9 -1
- package/lib/node/index.d.ts +1 -0
- package/lib/node/index.js +1 -0
- package/lib/node/relay-files-host.d.ts +28 -0
- package/lib/node/relay-files-host.js +134 -0
- package/lib/node/relay-host.d.ts +12 -1
- package/lib/node/relay-host.js +36 -10
- package/package.json +2 -2
package/README.en.md
CHANGED
|
@@ -24,8 +24,23 @@ Pairing links look like `https://<relay>/pair#v=1&h=<host-id>&d=<device-id>&k=<k
|
|
|
24
24
|
- `/v1/connect/<host-id>`: devices connect here. Relay assigns each a channel and forwards it to the host (`{t:'open'|'data'|'close', ch, d}`).
|
|
25
25
|
- Handshake: the device sends first `{t:'hello', v:1, device, nonce}`; the host finds the device's key and replies `{t:'ready', nonce, proof}`. Both sides use HKDF-SHA-256 (device key, salt is both nonces) to derive one AES-256-GCM key for each direction, ensuring every connection has a different key. `proof` is the host's first encrypted message, proving it has this device's key. After that, every message is encrypted with the IV set to the message sequence number, so Relay's replay, drop, or reorder attempts all fail decryption.
|
|
26
26
|
- The host opens one connection per device to localhost's `/api/ws`, including the localhost token. Devices never receive or need the token.
|
|
27
|
+
- Files (see below) take a channel of the device's own: after the handshake, the device's first sealed message is `{t:'files', v:1}`, and the host opens no `/api/ws` for it but answers `{t:'get', id, url}` on that channel with `{t:'head', id, status, type, size}`, chunks `{t:'chunk', id, d}` of 192 KB, and `{t:'end', id}`, or `{t:'error', id, message}` — sealed all the same.
|
|
27
28
|
- Heartbeat: the host and devices send `ping` to Relay every 25 seconds (outside the channels), and Relay answers `pong` itself (without waking the Durable Object). A connection can be gone while it still looks open (common behind proxies, after a network change, or after the computer sleeps). So when `pong` stops coming, or the computer wakes, the host reconnects to Relay and a device drops its connection and reconnects (close code 4408). An older Relay that has never answered `pong` is left alone. Relay closes connections with no heartbeat for 80 seconds. When a host reconnects, Relay closes the devices on its old connection (4404) so that they connect again. A device with no handshake reply within 15 seconds also drops the connection and retries (4408).
|
|
28
29
|
|
|
30
|
+
## Previewing files
|
|
31
|
+
|
|
32
|
+
A page on a phone (the Ta app through Relay, or a browser through Relay) cannot load `/api/files` of `ta serve`: that address exists only where the server runs, and through Relay only the calls on the WebSocket get there. So a device opens a channel of its own and asks the host for the bytes of a file (`RelayFiles` on the device, `RelayFilesHost` on the host): pictures, videos, sounds and PDFs become `blob:` URLs the page shows, and an HTML report is shown from the text of the file in a sandboxed frame.
|
|
33
|
+
|
|
34
|
+
Only that one thing is allowed, for the sake of safety:
|
|
35
|
+
|
|
36
|
+
- Only paths under `/api/files/`, only GET, and the path is taken from the parsed URL, never from the text a device sent: a device cannot make the host reach another address (`RelayFilesHost.target`).
|
|
37
|
+
- Only `127.0.0.1:<the port of ta serve>`, with the `Host` written by the host itself: devices reach no other port, no other machine, and no other `/api/*` call.
|
|
38
|
+
- The requests carry no Cookie and no Authorization; a device already has the whole RPC of the machine, so this widens nothing — it hands it `/api/files` too.
|
|
39
|
+
- At most 4 files at once on a channel, 128 MB for one and 30 seconds.
|
|
40
|
+
- The bytes stay sealed end to end: the relay reads neither the request nor the file.
|
|
41
|
+
|
|
42
|
+
A web extension can tell and read it with `pi.files` (`read(url)` while `byUrl` is false); the previews of `@celljs/ta-workspace` do.
|
|
43
|
+
|
|
29
44
|
## Sharing extensions
|
|
30
45
|
|
|
31
46
|
A Ta service can also hand an extension of its computer to another through the relay (`RelayStore.shareRoot`, `RelayShareUtil`): a link `https://<relay>/share#v=1&h=<host id>&s=<share id>&k=<key>&n=<name>`, good for 7 days. The other side connects with the handshake of a device (the share id as its device id); instead of a connection to the local `/api/ws`, the host sends `{t:'package', name, size}`, chunks `{t:'chunk', d}` of 192 KB and `{t:'end'}`, then closes the channel, all sealed; the relay keeps nothing, and a package is at most 8 MB. With a share and no device, the host connects to the relay too.
|
|
@@ -37,5 +52,5 @@ A Ta service can also hand an extension of its computer to another through the r
|
|
|
37
52
|
|
|
38
53
|
## Known Limitations
|
|
39
54
|
|
|
40
|
-
- When going through Relay, only WebSocket calls work
|
|
55
|
+
- When going through Relay, only WebSocket calls work: local file preview goes through the channel of `RelayFiles` (above), while other uses of `/api/files` (an address put together for a phone) still do not.
|
|
41
56
|
- Device keys are long-term with no forward secrecy: if a key leaks, old traffic in recordings can be decrypted. Unpairing invalidates the key.
|
package/README.md
CHANGED
|
@@ -24,8 +24,23 @@ ta pair --remove <设备 id> # 取消配对,立即生效
|
|
|
24
24
|
- `/v1/connect/<主机 id>`:设备连这里,Relay 给它分一个通道,转给主机(`{t:'open'|'data'|'close', ch, d}`)。
|
|
25
25
|
- 握手:设备先发 `{t:'hello', v:1, device, nonce}`;主机找到设备的密钥后回 `{t:'ready', nonce, proof}`。两边用 HKDF-SHA-256(设备密钥,盐是两个 nonce)给每个方向各派生一个 AES-256-GCM 密钥,所以每次连接的密钥都不同。`proof` 是主机加密的第一条消息,证明对方有这台设备的密钥;之后每条消息都加密,IV 就是消息序号,Relay 重放、丢弃或调换顺序的消息都会解密失败。
|
|
26
26
|
- 主机给每台设备单独开一条到本机 `/api/ws` 的连接,带上本机 token。设备拿不到 token,也不需要。
|
|
27
|
+
- 文件(见下节)走设备自己的另一个通道:握手之后,设备的第一条加密消息是 `{t:'files', v:1}`,主机就不开 `/api/ws`,而在这个通道上收 `{t:'get', id, url}`、回 `{t:'head', id, status, type, size}`、若干 `{t:'chunk', id, d}`(每块 192 KB)和 `{t:'end', id}`,出错回 `{t:'error', id, message}`,同样全程加密。
|
|
27
28
|
- 心跳:主机和设备每 25 秒给 Relay 发一次 `ping`(不经过通道),Relay 自己回 `pong`(Durable Object 不会因此唤醒)。连接可能已经断了却仍显示为打开(经过代理、换了网络、电脑睡眠后常见),所以收不到 `pong` 或电脑睡醒时,主机会重新连 Relay,设备会断开重连(关闭码 4408)。从没回过 `pong` 的旧 Relay 不受影响。Relay 会关掉 80 秒没有心跳的连接。主机重新连上时,Relay 会关掉旧连接上的设备(4404),让它们重新连。设备 15 秒内没收到握手应答,也会断开重试(4408)。
|
|
28
29
|
|
|
30
|
+
## 预览文件
|
|
31
|
+
|
|
32
|
+
手机上(Ta 应用经 Relay,或浏览器经 Relay)的页面拿不到 `ta serve` 的 `/api/files`:那道地址只在服务本机存在,经 Relay 时只有 WebSocket 上的调用能到。所以设备另开一个通道,请主机把文件的字节读来(`RelayFiles` 在设备一侧、`RelayFilesHost` 在主机一侧):图片、视频、声音、PDF 由页面做成 `blob:` 直接显示,HTML 报告以文件的文本放进沙框的 iframe 里显示。
|
|
33
|
+
|
|
34
|
+
安全上只放行这一件事:
|
|
35
|
+
|
|
36
|
+
- 只认 `/api/files/` 开头的路径,只发 GET,并且把 URL 解析后再取路径,绝不按设备给的字符串去连别的地址(`RelayFilesHost.target`)。
|
|
37
|
+
- 只连 `127.0.0.1:<ta serve 的端口>`,并且由主机自己写 `Host`,设备碰不到别的端口、别的机器,也碰不到 `/api/*` 的其他接口。
|
|
38
|
+
- 主机发的请求不带 Cookie、不带 Authorization;设备本来就有整台机器的 RPC 权限,这里不扩大它的权力,只是把 `/api/files` 也给它。
|
|
39
|
+
- 一个通道最多同时读 4 个文件,单个文件 128 MB、30 秒为限。
|
|
40
|
+
- 字节仍然端到端加密:Relay 读不到请求,也读不到文件。
|
|
41
|
+
|
|
42
|
+
`web-src` 一侧的扩展用 `pi.files` 判断与读取(`byUrl` 为 false 时用 `pi.files.read(url)`),`@celljs/ta-workspace` 的预览就是这么做的。
|
|
43
|
+
|
|
29
44
|
## 分享扩展
|
|
30
45
|
|
|
31
46
|
Ta 服务也能经中继把本机的一个扩展交给另一台电脑(`RelayStore.shareRoot`、`RelayShareUtil`):链接形如 `https://<relay>/share#v=1&h=<主机 id>&s=<分享 id>&k=<密钥>&n=<名字>`,7 天有效。对方用和设备相同的握手连进来(分享 id 当设备 id),主机不接本机的 `/api/ws`,而是发 `{t:'package', name, size}`、若干 `{t:'chunk', d}`(每块 192 KB)和 `{t:'end'}` 后关闭通道,全程加密;中继不存储,包最大 8 MB。只有分享、没有设备时主机也会连中继。
|
|
@@ -37,5 +52,5 @@ Ta 服务也能经中继把本机的一个扩展交给另一台电脑(`RelaySt
|
|
|
37
52
|
|
|
38
53
|
## 已知限制
|
|
39
54
|
|
|
40
|
-
- 经 Relay
|
|
55
|
+
- 经 Relay 时只有 WebSocket 上的调用可用:本地文件的预览走 `RelayFiles` 的通道(见上),`/api/files` 的其他用法(比如自己拼一个地址给手机)仍然不行。
|
|
41
56
|
- 设备密钥是长期的,没有前向保密:密钥泄露后,录下的旧流量也能解开。取消配对即可让它失效。
|
package/esm/common/index.d.ts
CHANGED
package/esm/common/index.js
CHANGED
|
@@ -4,10 +4,16 @@ export type RelaySide = 'client' | 'host';
|
|
|
4
4
|
* each direction, derived (HKDF-SHA-256) from the device's key and a nonce of each side, so that every
|
|
5
5
|
* connection has keys of its own. The IV is the number of the message, which must arrive in order: a
|
|
6
6
|
* message replayed, dropped or reordered by the relay fails to open.
|
|
7
|
+
*
|
|
8
|
+
* Encrypted bytes do not compress, so a message is compressed before it is sealed, once both sides said
|
|
9
|
+
* they can (`RelayHello.z`, `RelayWelcome.z`, then `compress`): JSON shrinks to a third or less, which
|
|
10
|
+
* is what a phone on a slow network waits for.
|
|
7
11
|
*/
|
|
8
12
|
export declare class RelayCipher {
|
|
9
13
|
protected readonly sendKey: CryptoKey;
|
|
10
14
|
protected readonly receiveKey: CryptoKey;
|
|
15
|
+
/** Messages sealed from now are compressed when large, and those opened may be: both sides set it at the same message. */
|
|
16
|
+
compress: boolean;
|
|
11
17
|
protected sent: number;
|
|
12
18
|
protected received: number;
|
|
13
19
|
protected sealing: Promise<unknown>;
|
|
@@ -18,5 +24,14 @@ export declare class RelayCipher {
|
|
|
18
24
|
seal(text: string): Promise<string>;
|
|
19
25
|
/** Rejects what this side's peer did not seal, or not as the next message. */
|
|
20
26
|
open(frame: string): Promise<string>;
|
|
27
|
+
/** The bytes of a message to seal: as they are until compression is agreed, then behind the byte that says how. */
|
|
28
|
+
protected pack(text: string): Promise<Uint8Array>;
|
|
29
|
+
protected unpack(bytes: Uint8Array): Promise<string>;
|
|
21
30
|
protected static iv(counter: number): Uint8Array;
|
|
22
31
|
}
|
|
32
|
+
/** deflate-raw of the platform (CompressionStream), where it has it: browsers, Node.js 21.2 and later, Bun, Deno. */
|
|
33
|
+
export declare namespace RelayDeflate {
|
|
34
|
+
function supported(): boolean;
|
|
35
|
+
function compress(bytes: Uint8Array): Promise<Uint8Array>;
|
|
36
|
+
function decompress(bytes: Uint8Array): Promise<Uint8Array>;
|
|
37
|
+
}
|
|
@@ -2,16 +2,27 @@ import { RelayBytes } from './relay-bytes.js';
|
|
|
2
2
|
const encoder = new TextEncoder();
|
|
3
3
|
const decoder = new TextDecoder();
|
|
4
4
|
const IV_LENGTH = 12;
|
|
5
|
+
/** The first byte of a message once compression is agreed: what follows. */
|
|
6
|
+
const PLAIN = 0;
|
|
7
|
+
const DEFLATED = 1;
|
|
8
|
+
/** Smaller messages go as they are: they are about as small compressed. */
|
|
9
|
+
const DEFLATE_MIN_BYTES = 1024;
|
|
5
10
|
/**
|
|
6
11
|
* The encryption of one connection between a paired device and ta serve: AES-256-GCM with a key for
|
|
7
12
|
* each direction, derived (HKDF-SHA-256) from the device's key and a nonce of each side, so that every
|
|
8
13
|
* connection has keys of its own. The IV is the number of the message, which must arrive in order: a
|
|
9
14
|
* message replayed, dropped or reordered by the relay fails to open.
|
|
15
|
+
*
|
|
16
|
+
* Encrypted bytes do not compress, so a message is compressed before it is sealed, once both sides said
|
|
17
|
+
* they can (`RelayHello.z`, `RelayWelcome.z`, then `compress`): JSON shrinks to a third or less, which
|
|
18
|
+
* is what a phone on a slow network waits for.
|
|
10
19
|
*/
|
|
11
20
|
export class RelayCipher {
|
|
12
21
|
constructor(sendKey, receiveKey) {
|
|
13
22
|
this.sendKey = sendKey;
|
|
14
23
|
this.receiveKey = receiveKey;
|
|
24
|
+
/** Messages sealed from now are compressed when large, and those opened may be: both sides set it at the same message. */
|
|
25
|
+
this.compress = false;
|
|
15
26
|
this.sent = 0;
|
|
16
27
|
this.received = 0;
|
|
17
28
|
this.sealing = Promise.resolve();
|
|
@@ -29,7 +40,7 @@ export class RelayCipher {
|
|
|
29
40
|
seal(text) {
|
|
30
41
|
const iv = RelayCipher.iv(this.sent++);
|
|
31
42
|
const sealed = this.sealing.then(async () => {
|
|
32
|
-
const data = await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv }, this.sendKey,
|
|
43
|
+
const data = await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv }, this.sendKey, (await this.pack(text)));
|
|
33
44
|
return RelayBytes.toBase64(new Uint8Array(data));
|
|
34
45
|
});
|
|
35
46
|
this.sealing = sealed.catch(() => undefined);
|
|
@@ -40,11 +51,29 @@ export class RelayCipher {
|
|
|
40
51
|
const iv = RelayCipher.iv(this.received++);
|
|
41
52
|
const opened = this.opening.then(async () => {
|
|
42
53
|
const data = await globalThis.crypto.subtle.decrypt({ name: 'AES-GCM', iv: iv }, this.receiveKey, RelayBytes.fromBase64(frame));
|
|
43
|
-
return
|
|
54
|
+
return this.unpack(new Uint8Array(data));
|
|
44
55
|
});
|
|
45
56
|
this.opening = opened.catch(() => undefined);
|
|
46
57
|
return opened;
|
|
47
58
|
}
|
|
59
|
+
/** The bytes of a message to seal: as they are until compression is agreed, then behind the byte that says how. */
|
|
60
|
+
async pack(text) {
|
|
61
|
+
const bytes = encoder.encode(text);
|
|
62
|
+
if (!this.compress) {
|
|
63
|
+
return bytes;
|
|
64
|
+
}
|
|
65
|
+
const deflated = bytes.length >= DEFLATE_MIN_BYTES ? await RelayDeflate.compress(bytes) : undefined;
|
|
66
|
+
return deflated && deflated.length < bytes.length
|
|
67
|
+
? RelayBytes.concat(Uint8Array.of(DEFLATED), deflated)
|
|
68
|
+
: RelayBytes.concat(Uint8Array.of(PLAIN), bytes);
|
|
69
|
+
}
|
|
70
|
+
async unpack(bytes) {
|
|
71
|
+
if (!this.compress) {
|
|
72
|
+
return decoder.decode(bytes);
|
|
73
|
+
}
|
|
74
|
+
const body = bytes.subarray(1);
|
|
75
|
+
return decoder.decode(bytes[0] === DEFLATED ? await RelayDeflate.decompress(body) : body);
|
|
76
|
+
}
|
|
48
77
|
static iv(counter) {
|
|
49
78
|
const iv = new Uint8Array(IV_LENGTH);
|
|
50
79
|
new DataView(iv.buffer).setUint32(IV_LENGTH - 8, Math.floor(counter / 2 ** 32));
|
|
@@ -52,4 +81,35 @@ export class RelayCipher {
|
|
|
52
81
|
return iv;
|
|
53
82
|
}
|
|
54
83
|
}
|
|
84
|
+
/** deflate-raw of the platform (CompressionStream), where it has it: browsers, Node.js 21.2 and later, Bun, Deno. */
|
|
85
|
+
export var RelayDeflate;
|
|
86
|
+
(function (RelayDeflate) {
|
|
87
|
+
let support;
|
|
88
|
+
function supported() {
|
|
89
|
+
if (support === undefined) {
|
|
90
|
+
try {
|
|
91
|
+
new CompressionStream('deflate-raw');
|
|
92
|
+
new DecompressionStream('deflate-raw');
|
|
93
|
+
support = true;
|
|
94
|
+
}
|
|
95
|
+
catch (_a) {
|
|
96
|
+
support = false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return support;
|
|
100
|
+
}
|
|
101
|
+
RelayDeflate.supported = supported;
|
|
102
|
+
function compress(bytes) {
|
|
103
|
+
return through(bytes, new CompressionStream('deflate-raw'));
|
|
104
|
+
}
|
|
105
|
+
RelayDeflate.compress = compress;
|
|
106
|
+
function decompress(bytes) {
|
|
107
|
+
return through(bytes, new DecompressionStream('deflate-raw'));
|
|
108
|
+
}
|
|
109
|
+
RelayDeflate.decompress = decompress;
|
|
110
|
+
async function through(bytes, stream) {
|
|
111
|
+
const piped = new Blob([bytes]).stream().pipeThrough(stream);
|
|
112
|
+
return new Uint8Array(await new Response(piped).arrayBuffer());
|
|
113
|
+
}
|
|
114
|
+
})(RelayDeflate || (RelayDeflate = {}));
|
|
55
115
|
//# sourceMappingURL=relay-cipher.js.map
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { RelayPairing } from './relay-pairing.js';
|
|
2
|
+
import { RelaySocket } from './relay-socket.js';
|
|
3
|
+
/**
|
|
4
|
+
* The files of the workspace through the relay, for a page of a device that cannot load them by URL: behind
|
|
5
|
+
* a relay, and in the app on a phone, only the calls on the WebSocket reach ta serve, so `/api/files` is
|
|
6
|
+
* asked for here instead, on a channel of its own. The frames below are what that channel carries in place
|
|
7
|
+
* of the JSON-RPC of `/api/ws`; the relay forwards them sealed as it does the rest, and reads neither.
|
|
8
|
+
*
|
|
9
|
+
* The host answers only a path of {@link RELAY_FILES_PREFIX}, with GET, at the loopback address of its own
|
|
10
|
+
* ta serve: a device has the whole of ta serve already, and a relay that could be made to ask for anything
|
|
11
|
+
* else would be a way into the machine.
|
|
12
|
+
*/
|
|
13
|
+
export type RelayFilesFrame =
|
|
14
|
+
/** The first frame of a device on a channel: this one asks for files, not for `/api/ws`. */
|
|
15
|
+
{
|
|
16
|
+
t: 'files';
|
|
17
|
+
v: 1;
|
|
18
|
+
}
|
|
19
|
+
/** A file to read; a URL of {@link RELAY_FILES_PREFIX}. */
|
|
20
|
+
| {
|
|
21
|
+
t: 'get';
|
|
22
|
+
id: number;
|
|
23
|
+
url: string;
|
|
24
|
+
}
|
|
25
|
+
/** What ta serve answers before the bytes. */
|
|
26
|
+
| {
|
|
27
|
+
t: 'head';
|
|
28
|
+
id: number;
|
|
29
|
+
status: number;
|
|
30
|
+
type?: string;
|
|
31
|
+
size?: number;
|
|
32
|
+
} | {
|
|
33
|
+
t: 'chunk';
|
|
34
|
+
id: number;
|
|
35
|
+
d: string;
|
|
36
|
+
} | {
|
|
37
|
+
t: 'end';
|
|
38
|
+
id: number;
|
|
39
|
+
} | {
|
|
40
|
+
t: 'error';
|
|
41
|
+
id: number;
|
|
42
|
+
message: string;
|
|
43
|
+
};
|
|
44
|
+
/** The only paths of ta serve a device may ask for: the ones answered without its token. */
|
|
45
|
+
export declare const RELAY_FILES_PREFIX = "/api/files/";
|
|
46
|
+
/** The bytes of a chunk, base64 in a sealed frame: well under the 1 MiB of a message of Cloudflare. */
|
|
47
|
+
export declare const RELAY_FILE_CHUNK_BYTES: number;
|
|
48
|
+
/** The largest file a device reads this way: a video of a workspace is previewed by its first bytes, not all of it. */
|
|
49
|
+
export declare const RELAY_FILE_MAX_BYTES: number;
|
|
50
|
+
/** Files read at once on one channel; a page that loads its pictures asks for several. */
|
|
51
|
+
export declare const RELAY_FILES_MAX_PARALLEL = 4;
|
|
52
|
+
/** For one file, all of it. */
|
|
53
|
+
export declare const RELAY_FILES_TIMEOUT_MS = 30000;
|
|
54
|
+
/** A file as the page gets it: its type as ta serve answers it, and the bytes. */
|
|
55
|
+
export interface RelayFileBytes {
|
|
56
|
+
type: string;
|
|
57
|
+
size: number;
|
|
58
|
+
data: Uint8Array;
|
|
59
|
+
}
|
|
60
|
+
export declare namespace RelayFilesUtil {
|
|
61
|
+
/** The frame that turns a channel into a channel of files. */
|
|
62
|
+
function hello(): RelayFilesFrame;
|
|
63
|
+
/** Whether a frame of a device asks for files, rather than for ta serve's socket (`{t:'files', v:1}`). */
|
|
64
|
+
function isHello(text: string): boolean;
|
|
65
|
+
}
|
|
66
|
+
/** One file asked for, and what came of it so far. */
|
|
67
|
+
interface Pending {
|
|
68
|
+
readonly chunks: Uint8Array[];
|
|
69
|
+
received: number;
|
|
70
|
+
head?: {
|
|
71
|
+
type: string;
|
|
72
|
+
size: number;
|
|
73
|
+
};
|
|
74
|
+
readonly resolve: (bytes: RelayFileBytes) => void;
|
|
75
|
+
readonly reject: (error: Error) => void;
|
|
76
|
+
readonly timer: ReturnType<typeof setTimeout>;
|
|
77
|
+
}
|
|
78
|
+
export interface RelayFilesOptions {
|
|
79
|
+
/** For one file. Default RELAY_FILES_TIMEOUT_MS. */
|
|
80
|
+
timeoutMs?: number;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The files of the ta serve of a pairing, through the relay: a channel of its own, kept open for the page,
|
|
84
|
+
* sealed end to end as the connection of a device is. It behaves for the page as loading the URL does.
|
|
85
|
+
*/
|
|
86
|
+
export declare class RelayFiles {
|
|
87
|
+
protected readonly pairing: RelayPairing;
|
|
88
|
+
protected readonly options: RelayFilesOptions;
|
|
89
|
+
protected socket?: RelaySocket;
|
|
90
|
+
protected opening?: Promise<void>;
|
|
91
|
+
protected called: number;
|
|
92
|
+
protected readonly pending: Map<number, Pending>;
|
|
93
|
+
constructor(pairing: RelayPairing, options?: RelayFilesOptions);
|
|
94
|
+
/** The bytes of a URL of {@link RELAY_FILES_PREFIX}, as ta serve answers them. */
|
|
95
|
+
get(url: string): Promise<RelayFileBytes>;
|
|
96
|
+
/** Whether the channel is open: the page may keep one for as long as it shows files. */
|
|
97
|
+
get open(): boolean;
|
|
98
|
+
close(): void;
|
|
99
|
+
protected send(frame: RelayFilesFrame): void;
|
|
100
|
+
/** Opens the channel, once: the first file asked for opens it. */
|
|
101
|
+
protected connect(): Promise<void>;
|
|
102
|
+
protected receive(text: string): void;
|
|
103
|
+
protected settle(id: number, error: Error): void;
|
|
104
|
+
protected finish(id: number, bytes: RelayFileBytes): void;
|
|
105
|
+
/** The channel went: what was asked for is not coming. */
|
|
106
|
+
protected fail(error: Error): void;
|
|
107
|
+
}
|
|
108
|
+
export {};
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { RelayBytes } from './relay-bytes.js';
|
|
2
|
+
import { RelaySocket } from './relay-socket.js';
|
|
3
|
+
/** The only paths of ta serve a device may ask for: the ones answered without its token. */
|
|
4
|
+
export const RELAY_FILES_PREFIX = '/api/files/';
|
|
5
|
+
/** The bytes of a chunk, base64 in a sealed frame: well under the 1 MiB of a message of Cloudflare. */
|
|
6
|
+
export const RELAY_FILE_CHUNK_BYTES = 192 * 1024;
|
|
7
|
+
/** The largest file a device reads this way: a video of a workspace is previewed by its first bytes, not all of it. */
|
|
8
|
+
export const RELAY_FILE_MAX_BYTES = 128 * 1024 * 1024;
|
|
9
|
+
/** Files read at once on one channel; a page that loads its pictures asks for several. */
|
|
10
|
+
export const RELAY_FILES_MAX_PARALLEL = 4;
|
|
11
|
+
/** For one file, all of it. */
|
|
12
|
+
export const RELAY_FILES_TIMEOUT_MS = 30000;
|
|
13
|
+
export var RelayFilesUtil;
|
|
14
|
+
(function (RelayFilesUtil) {
|
|
15
|
+
/** The frame that turns a channel into a channel of files. */
|
|
16
|
+
function hello() {
|
|
17
|
+
return { t: 'files', v: 1 };
|
|
18
|
+
}
|
|
19
|
+
RelayFilesUtil.hello = hello;
|
|
20
|
+
/** Whether a frame of a device asks for files, rather than for ta serve's socket (`{t:'files', v:1}`). */
|
|
21
|
+
function isHello(text) {
|
|
22
|
+
try {
|
|
23
|
+
const frame = JSON.parse(text);
|
|
24
|
+
return frame.t === 'files' && frame.v === 1;
|
|
25
|
+
}
|
|
26
|
+
catch (_a) {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
RelayFilesUtil.isHello = isHello;
|
|
31
|
+
})(RelayFilesUtil || (RelayFilesUtil = {}));
|
|
32
|
+
/**
|
|
33
|
+
* The files of the ta serve of a pairing, through the relay: a channel of its own, kept open for the page,
|
|
34
|
+
* sealed end to end as the connection of a device is. It behaves for the page as loading the URL does.
|
|
35
|
+
*/
|
|
36
|
+
export class RelayFiles {
|
|
37
|
+
constructor(pairing, options = {}) {
|
|
38
|
+
this.pairing = pairing;
|
|
39
|
+
this.options = options;
|
|
40
|
+
this.called = 1;
|
|
41
|
+
this.pending = new Map();
|
|
42
|
+
}
|
|
43
|
+
/** The bytes of a URL of {@link RELAY_FILES_PREFIX}, as ta serve answers them. */
|
|
44
|
+
async get(url) {
|
|
45
|
+
if (!url.startsWith(RELAY_FILES_PREFIX)) {
|
|
46
|
+
throw new Error('Ta reads only the files it offers by URL.');
|
|
47
|
+
}
|
|
48
|
+
await this.connect();
|
|
49
|
+
const id = this.called++;
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
var _a;
|
|
52
|
+
const timeout = (_a = this.options.timeoutMs) !== null && _a !== void 0 ? _a : RELAY_FILES_TIMEOUT_MS;
|
|
53
|
+
const timer = setTimeout(() => this.settle(id, new Error('The file took too long to come.')), timeout);
|
|
54
|
+
this.pending.set(id, { chunks: [], received: 0, resolve, reject, timer });
|
|
55
|
+
this.send({ t: 'get', id, url });
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** Whether the channel is open: the page may keep one for as long as it shows files. */
|
|
59
|
+
get open() {
|
|
60
|
+
var _a;
|
|
61
|
+
return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === RelaySocket.OPEN;
|
|
62
|
+
}
|
|
63
|
+
close() {
|
|
64
|
+
const socket = this.socket;
|
|
65
|
+
this.socket = undefined;
|
|
66
|
+
this.opening = undefined;
|
|
67
|
+
this.fail(new Error('The files are closed.'));
|
|
68
|
+
socket === null || socket === void 0 ? void 0 : socket.close();
|
|
69
|
+
}
|
|
70
|
+
send(frame) {
|
|
71
|
+
var _a;
|
|
72
|
+
(_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(frame));
|
|
73
|
+
}
|
|
74
|
+
/** Opens the channel, once: the first file asked for opens it. */
|
|
75
|
+
connect() {
|
|
76
|
+
var _a;
|
|
77
|
+
if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === RelaySocket.OPEN) {
|
|
78
|
+
return Promise.resolve();
|
|
79
|
+
}
|
|
80
|
+
if (!this.opening) {
|
|
81
|
+
const socket = new RelaySocket(this.pairing);
|
|
82
|
+
this.socket = socket;
|
|
83
|
+
this.opening = new Promise((resolve, reject) => {
|
|
84
|
+
socket.onmessage = ({ data }) => this.receive(data);
|
|
85
|
+
socket.onopen = () => {
|
|
86
|
+
this.send(RelayFilesUtil.hello());
|
|
87
|
+
resolve();
|
|
88
|
+
};
|
|
89
|
+
socket.onclose = ({ code }) => {
|
|
90
|
+
const error = new Error(code === RelaySocket.REFUSED
|
|
91
|
+
? 'This device is no longer paired with the computer.'
|
|
92
|
+
: 'The computer is not running Ta, or cannot be reached.');
|
|
93
|
+
if (this.socket === socket) {
|
|
94
|
+
this.socket = undefined;
|
|
95
|
+
}
|
|
96
|
+
this.fail(error);
|
|
97
|
+
reject(error);
|
|
98
|
+
};
|
|
99
|
+
});
|
|
100
|
+
const clear = () => {
|
|
101
|
+
this.opening = undefined;
|
|
102
|
+
};
|
|
103
|
+
this.opening.then(clear, clear);
|
|
104
|
+
}
|
|
105
|
+
return this.opening;
|
|
106
|
+
}
|
|
107
|
+
receive(text) {
|
|
108
|
+
var _a, _b;
|
|
109
|
+
let frame;
|
|
110
|
+
try {
|
|
111
|
+
frame = JSON.parse(text);
|
|
112
|
+
}
|
|
113
|
+
catch (_c) {
|
|
114
|
+
this.close();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (!('id' in frame) || typeof frame.id !== 'number') {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const pending = this.pending.get(frame.id);
|
|
121
|
+
if (!pending) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (frame.t === 'head') {
|
|
125
|
+
pending.head = { type: (_a = frame.type) !== null && _a !== void 0 ? _a : 'application/octet-stream', size: (_b = frame.size) !== null && _b !== void 0 ? _b : 0 };
|
|
126
|
+
}
|
|
127
|
+
else if (frame.t === 'chunk') {
|
|
128
|
+
const bytes = RelayBytes.fromBase64(frame.d);
|
|
129
|
+
pending.received += bytes.length;
|
|
130
|
+
if (pending.received > RELAY_FILE_MAX_BYTES) {
|
|
131
|
+
this.settle(frame.id, new Error('The file is too large to show here.'));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
pending.chunks.push(bytes);
|
|
135
|
+
}
|
|
136
|
+
else if (frame.t === 'end') {
|
|
137
|
+
if (!pending.head) {
|
|
138
|
+
this.settle(frame.id, new Error('The file came without its head.'));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
this.finish(frame.id, { type: pending.head.type, size: pending.received, data: RelayBytes.concat(...pending.chunks) });
|
|
142
|
+
}
|
|
143
|
+
else if (frame.t === 'error') {
|
|
144
|
+
this.settle(frame.id, new Error(frame.message));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
settle(id, error) {
|
|
148
|
+
const pending = this.pending.get(id);
|
|
149
|
+
if (pending) {
|
|
150
|
+
this.pending.delete(id);
|
|
151
|
+
clearTimeout(pending.timer);
|
|
152
|
+
pending.reject(error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
finish(id, bytes) {
|
|
156
|
+
const pending = this.pending.get(id);
|
|
157
|
+
if (pending) {
|
|
158
|
+
this.pending.delete(id);
|
|
159
|
+
clearTimeout(pending.timer);
|
|
160
|
+
pending.resolve(bytes);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** The channel went: what was asked for is not coming. */
|
|
164
|
+
fail(error) {
|
|
165
|
+
for (const [id] of [...this.pending]) {
|
|
166
|
+
this.settle(id, error);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
//# sourceMappingURL=relay-files.js.map
|
|
@@ -84,12 +84,18 @@ export interface RelayHello {
|
|
|
84
84
|
v: 1;
|
|
85
85
|
device: string;
|
|
86
86
|
nonce: string;
|
|
87
|
+
/** 1: the device inflates deflate-raw (RelayCipher.compress). A device of before says nothing. */
|
|
88
|
+
z?: 1;
|
|
87
89
|
}
|
|
88
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* The host's answer: its nonce, and a first sealed message that shows it has the device's key; `z` when
|
|
92
|
+
* both compress what they seal after the proof (the device offered it, and the host can).
|
|
93
|
+
*/
|
|
89
94
|
export type RelayWelcome = {
|
|
90
95
|
t: 'ready';
|
|
91
96
|
nonce: string;
|
|
92
97
|
proof: string;
|
|
98
|
+
z?: 1;
|
|
93
99
|
} | {
|
|
94
100
|
t: 'refused';
|
|
95
101
|
reason: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RelayBytes } from './relay-bytes.js';
|
|
2
|
-
import { RelayCipher } from './relay-cipher.js';
|
|
2
|
+
import { RelayCipher, RelayDeflate } from './relay-cipher.js';
|
|
3
3
|
import { RelayPairingUtil } from './relay-pairing.js';
|
|
4
4
|
import { RELAY_CONNECT_PATH, RELAY_PING, RELAY_PING_MS, RELAY_PONG, RELAY_PROOF, RelayCloseCode } from './relay-protocol.js';
|
|
5
5
|
const CONNECTING = 0;
|
|
@@ -32,7 +32,13 @@ export class RelaySocket {
|
|
|
32
32
|
this.helloTimer = setTimeout(() => this.drop(RelayCloseCode.TIMEOUT, 'The host did not answer.'), (_a = options.helloMs) !== null && _a !== void 0 ? _a : HELLO_MS);
|
|
33
33
|
this.socket.onopen = () => {
|
|
34
34
|
var _a;
|
|
35
|
-
const hello = {
|
|
35
|
+
const hello = {
|
|
36
|
+
t: 'hello',
|
|
37
|
+
v: 1,
|
|
38
|
+
device: pairing.device,
|
|
39
|
+
nonce: RelayBytes.toBase64(this.nonce),
|
|
40
|
+
...(RelayDeflate.supported() ? { z: 1 } : {}),
|
|
41
|
+
};
|
|
36
42
|
this.socket.send(JSON.stringify(hello));
|
|
37
43
|
this.pingTimer = setInterval(() => this.ping(), (_a = options.pingMs) !== null && _a !== void 0 ? _a : RELAY_PING_MS);
|
|
38
44
|
};
|
|
@@ -89,6 +95,8 @@ export class RelaySocket {
|
|
|
89
95
|
if ((await cipher.open(welcome.proof)) !== RELAY_PROOF) {
|
|
90
96
|
throw new Error('The host did not show the key.');
|
|
91
97
|
}
|
|
98
|
+
// The messages after the proof, both ways.
|
|
99
|
+
cipher.compress = welcome.z === 1 && RelayDeflate.supported();
|
|
92
100
|
this.cipher = cipher;
|
|
93
101
|
clearTimeout(this.helloTimer);
|
|
94
102
|
this.state = OPEN;
|
package/esm/node/index.d.ts
CHANGED
package/esm/node/index.js
CHANGED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type RelayFilesFrame } from '../common/relay-files.js';
|
|
2
|
+
export interface RelayFilesHostOptions {
|
|
3
|
+
/** The address of ta serve, always at loopback: the one of its WebSocket (RelayHostOptions.localUrl). */
|
|
4
|
+
localUrl: string;
|
|
5
|
+
/** Sends a frame of the sealed channel of this device. */
|
|
6
|
+
send(frame: RelayFilesFrame): void;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The files of the workspace on a channel of a device (RelayFiles): asks them of the ta serve of this
|
|
10
|
+
* machine and sends them back sealed. It asks for nothing but a path of {@link RELAY_FILES_PREFIX}, with
|
|
11
|
+
* GET, at the loopback port of ta serve and never at another host: a device has the whole of ta serve
|
|
12
|
+
* already, and what a device cannot be trusted with is not this.
|
|
13
|
+
*/
|
|
14
|
+
export declare class RelayFilesHost {
|
|
15
|
+
protected readonly options: RelayFilesHostOptions;
|
|
16
|
+
protected readonly base: string;
|
|
17
|
+
protected reading: number;
|
|
18
|
+
protected readonly running: Set<AbortController>;
|
|
19
|
+
constructor(options: RelayFilesHostOptions);
|
|
20
|
+
/** A frame of the device: a file to read, or something of a version it does not know. */
|
|
21
|
+
receive(text: string): Promise<void>;
|
|
22
|
+
/** The device went: what it asked for is not read to the end. */
|
|
23
|
+
close(): void;
|
|
24
|
+
/** What to fetch for what a device asked, or undefined: a path of {@link RELAY_FILES_PREFIX} of this ta serve alone. */
|
|
25
|
+
static target(base: string, url: string): string | undefined;
|
|
26
|
+
protected read(id: number, url: string): Promise<void>;
|
|
27
|
+
}
|