@celljs/ta-relay 4.8.0 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.en.md +8 -3
  2. package/README.md +8 -3
  3. package/esm/common/index.d.ts +2 -0
  4. package/esm/common/index.js +2 -0
  5. package/esm/common/qr-code.d.ts +42 -0
  6. package/esm/common/qr-code.js +366 -0
  7. package/esm/common/relay-protocol.d.ts +42 -1
  8. package/esm/common/relay-protocol.js +26 -0
  9. package/esm/common/relay-room.d.ts +1 -0
  10. package/esm/common/relay-room.js +13 -2
  11. package/esm/common/relay-share.d.ts +31 -0
  12. package/esm/common/relay-share.js +117 -0
  13. package/esm/common/relay-socket.d.ts +18 -1
  14. package/esm/common/relay-socket.js +43 -5
  15. package/esm/node/relay-host.d.ts +18 -3
  16. package/esm/node/relay-host.js +82 -8
  17. package/esm/node/relay-server.js +10 -6
  18. package/esm/node/relay-store.d.ts +29 -1
  19. package/esm/node/relay-store.js +54 -2
  20. package/lib/common/index.d.ts +2 -0
  21. package/lib/common/index.js +2 -0
  22. package/lib/common/qr-code.d.ts +43 -0
  23. package/lib/common/qr-code.js +370 -0
  24. package/lib/common/relay-protocol.d.ts +42 -1
  25. package/lib/common/relay-protocol.js +27 -1
  26. package/lib/common/relay-room.d.ts +1 -0
  27. package/lib/common/relay-room.js +12 -1
  28. package/lib/common/relay-share.d.ts +32 -0
  29. package/lib/common/relay-share.js +120 -0
  30. package/lib/common/relay-socket.d.ts +18 -1
  31. package/lib/common/relay-socket.js +42 -4
  32. package/lib/node/relay-host.d.ts +18 -3
  33. package/lib/node/relay-host.js +81 -7
  34. package/lib/node/relay-server.js +9 -5
  35. package/lib/node/relay-store.d.ts +29 -1
  36. package/lib/node/relay-store.js +54 -2
  37. package/package.json +4 -3
  38. package/esm/common/index.js.map +0 -1
  39. package/esm/common/relay-bytes.js.map +0 -1
  40. package/esm/common/relay-cipher.js.map +0 -1
  41. package/esm/common/relay-pairing.js.map +0 -1
  42. package/esm/common/relay-protocol.js.map +0 -1
  43. package/esm/common/relay-room.js.map +0 -1
  44. package/esm/common/relay-socket.js.map +0 -1
  45. package/esm/node/index.js.map +0 -1
  46. package/esm/node/relay-host.js.map +0 -1
  47. package/esm/node/relay-server.js.map +0 -1
  48. package/esm/node/relay-store.js.map +0 -1
  49. package/lib/common/index.d.ts.map +0 -1
  50. package/lib/common/index.js.map +0 -1
  51. package/lib/common/relay-bytes.d.ts.map +0 -1
  52. package/lib/common/relay-bytes.js.map +0 -1
  53. package/lib/common/relay-cipher.d.ts.map +0 -1
  54. package/lib/common/relay-cipher.js.map +0 -1
  55. package/lib/common/relay-cipher.spec.d.ts +0 -2
  56. package/lib/common/relay-cipher.spec.d.ts.map +0 -1
  57. package/lib/common/relay-cipher.spec.js +0 -43
  58. package/lib/common/relay-cipher.spec.js.map +0 -1
  59. package/lib/common/relay-pairing.d.ts.map +0 -1
  60. package/lib/common/relay-pairing.js.map +0 -1
  61. package/lib/common/relay-pairing.spec.d.ts +0 -2
  62. package/lib/common/relay-pairing.spec.d.ts.map +0 -1
  63. package/lib/common/relay-pairing.spec.js +0 -25
  64. package/lib/common/relay-pairing.spec.js.map +0 -1
  65. package/lib/common/relay-protocol.d.ts.map +0 -1
  66. package/lib/common/relay-protocol.js.map +0 -1
  67. package/lib/common/relay-room.d.ts.map +0 -1
  68. package/lib/common/relay-room.js.map +0 -1
  69. package/lib/common/relay-socket.d.ts.map +0 -1
  70. package/lib/common/relay-socket.js.map +0 -1
  71. package/lib/node/index.d.ts.map +0 -1
  72. package/lib/node/index.js.map +0 -1
  73. package/lib/node/relay-host.d.ts.map +0 -1
  74. package/lib/node/relay-host.js.map +0 -1
  75. package/lib/node/relay-server.d.ts.map +0 -1
  76. package/lib/node/relay-server.js.map +0 -1
  77. package/lib/node/relay-store.d.ts.map +0 -1
  78. package/lib/node/relay-store.js.map +0 -1
  79. package/lib/node/relay.spec.d.ts +0 -2
  80. package/lib/node/relay.spec.d.ts.map +0 -1
  81. package/lib/node/relay.spec.js +0 -141
  82. package/lib/node/relay.spec.js.map +0 -1
  83. package/src/common/index.ts +0 -6
  84. package/src/common/relay-bytes.ts +0 -37
  85. package/src/common/relay-cipher.spec.ts +0 -45
  86. package/src/common/relay-cipher.ts +0 -74
  87. package/src/common/relay-pairing.spec.ts +0 -26
  88. package/src/common/relay-pairing.ts +0 -46
  89. package/src/common/relay-protocol.ts +0 -50
  90. package/src/common/relay-room.ts +0 -79
  91. package/src/common/relay-socket.ts +0 -106
  92. package/src/node/index.ts +0 -4
  93. package/src/node/relay-host.ts +0 -230
  94. package/src/node/relay-server.ts +0 -143
  95. package/src/node/relay-store.ts +0 -84
  96. package/src/node/relay.spec.ts +0 -151
package/README.en.md CHANGED
@@ -10,13 +10,13 @@ Mobile (RelaySocket) ──wss──▶ Relay ◀──wss── ta serve (Relay
10
10
  ## Pairing
11
11
 
12
12
  ```bash
13
- ta pair # add a device, print pairing link; default Relay is https://relay.cellbang.com
13
+ ta pair # add a device, print pairing link (with its QR code in a terminal); default Relay is https://relay.cellbang.com
14
14
  ta pair https://<relay> --name phone # use your own Relay, name the device
15
15
  ta pair --list # list paired devices
16
16
  ta pair --remove <device-id> # unpair, takes effect immediately
17
17
  ```
18
18
 
19
- Pairing links look like `https://<relay>/pair#v=1&h=<host-id>&d=<device-id>&k=<key>`. The key is after the `#`, so the browser won't send it to Relay. Paste the link in the Ta app to connect. You can also pair from the Web client or desktop app: click the gear menu's "Use on your phone…" to show the link as a QR code (shown once only) and list paired devices, whether ta serve is connected to Relay, and allow you to unpair (`ta serve`'s `TaRelayServer`). Devices are saved in `relay.json` in the agent directory (file mode 0600); `ta serve` automatically reads changes as they happen, no restart needed.
19
+ Pairing links look like `https://<relay>/pair#v=1&h=<host-id>&d=<device-id>&k=<key>`. The key is after the `#`, so the browser won't send it to Relay. Scan the QR code or paste the link in the Ta app to connect; the code is drawn by `QrCode` (of this package, `lines()` in half blocks for a terminal), so `docker exec -it <container> ta pair` can be scanned too. You can also pair from the Web client or desktop app: click the gear menu's "Use on your phone…" to show the link as a QR code (shown once only) and list paired devices, whether ta serve is connected to Relay, and allow you to unpair (`ta serve`'s `TaRelayServer`). Devices are saved in `relay.json` in the agent directory (file mode 0600); `ta serve` automatically reads changes as they happen, no restart needed.
20
20
 
21
21
  ## Protocol
22
22
 
@@ -24,6 +24,11 @@ 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
+ - 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
+ ## Sharing extensions
30
+
31
+ 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.
27
32
 
28
33
  ## Deploying Relay
29
34
 
@@ -33,4 +38,4 @@ Pairing links look like `https://<relay>/pair#v=1&h=<host-id>&d=<device-id>&k=<k
33
38
  ## Known Limitations
34
39
 
35
40
  - When going through Relay, only WebSocket calls work. Local file preview in the Web client (`/api/files`) is not available.
36
- - Device keys are long-term with no forward secrecy: if a key leaks, old traffic in recordings can be decrypted. Unpairing invalidates the key.
41
+ - 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
@@ -10,13 +10,13 @@
10
10
  ## 配对
11
11
 
12
12
  ```bash
13
- ta pair # 新增一台设备,打印配对链接;默认 Relay 是 https://relay.cellbang.com
13
+ ta pair # 新增一台设备,打印配对链接(在终端里还有它的二维码);默认 Relay 是 https://relay.cellbang.com
14
14
  ta pair https://<relay> --name 手机 # 用自己的 Relay,给设备起名
15
15
  ta pair --list # 已配对的设备
16
16
  ta pair --remove <设备 id> # 取消配对,立即生效
17
17
  ```
18
18
 
19
- 配对链接形如 `https://<relay>/pair#v=1&h=<主机 id>&d=<设备 id>&k=<密钥>`。密钥在 `#` 之后,浏览器不会把它发给 Relay。在 Ta 应用里粘贴这个链接即可连接。Web 客户端和桌面应用里也能配对:齿轮菜单的"在手机上使用…"把链接显示成二维码(只显示一次),并列出已配对的设备、ta serve 是否连着 Relay,可以取消配对(ta serve 的 `TaRelayServer`)。设备记在 agent 目录的 `relay.json`(权限 0600),`ta serve` 运行时会自己读到改动,不用重启。
19
+ 配对链接形如 `https://<relay>/pair#v=1&h=<主机 id>&d=<设备 id>&k=<密钥>`。密钥在 `#` 之后,浏览器不会把它发给 Relay。在 Ta 应用里扫二维码或粘贴这个链接即可连接;二维码用 `QrCode`(本包自带,`lines()` 画成终端的半格字符),在容器里用 `docker exec -it <容器> ta pair` 也能扫。Web 客户端和桌面应用里也能配对:齿轮菜单的"在手机上使用…"把链接显示成二维码(只显示一次),并列出已配对的设备、ta serve 是否连着 Relay,可以取消配对(ta serve 的 `TaRelayServer`)。设备记在 agent 目录的 `relay.json`(权限 0600),`ta serve` 运行时会自己读到改动,不用重启。
20
20
 
21
21
  ## 协议
22
22
 
@@ -24,6 +24,11 @@ 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
+ - 心跳:主机和设备每 25 秒给 Relay 发一次 `ping`(不经过通道),Relay 自己回 `pong`(Durable Object 不会因此唤醒)。连接可能已经断了却仍显示为打开(经过代理、换了网络、电脑睡眠后常见),所以收不到 `pong` 或电脑睡醒时,主机会重新连 Relay,设备会断开重连(关闭码 4408)。从没回过 `pong` 的旧 Relay 不受影响。Relay 会关掉 80 秒没有心跳的连接。主机重新连上时,Relay 会关掉旧连接上的设备(4404),让它们重新连。设备 15 秒内没收到握手应答,也会断开重试(4408)。
28
+
29
+ ## 分享扩展
30
+
31
+ 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。只有分享、没有设备时主机也会连中继。
27
32
 
28
33
  ## 部署 Relay
29
34
 
@@ -33,4 +38,4 @@ ta pair --remove <设备 id> # 取消配对,立即生效
33
38
  ## 已知限制
34
39
 
35
40
  - 经 Relay 时,只有 WebSocket 上的调用可用;Web 客户端里本地文件的预览(`/api/files`)用不了。
36
- - 设备密钥是长期的,没有前向保密:密钥泄露后,录下的旧流量也能解开。取消配对即可让它失效。
41
+ - 设备密钥是长期的,没有前向保密:密钥泄露后,录下的旧流量也能解开。取消配对即可让它失效。
@@ -1,6 +1,8 @@
1
+ export * from './qr-code.js';
1
2
  export * from './relay-bytes.js';
2
3
  export * from './relay-cipher.js';
3
4
  export * from './relay-pairing.js';
4
5
  export * from './relay-protocol.js';
5
6
  export * from './relay-room.js';
7
+ export * from './relay-share.js';
6
8
  export * from './relay-socket.js';
@@ -1,7 +1,9 @@
1
+ export * from './qr-code.js';
1
2
  export * from './relay-bytes.js';
2
3
  export * from './relay-cipher.js';
3
4
  export * from './relay-pairing.js';
4
5
  export * from './relay-protocol.js';
5
6
  export * from './relay-room.js';
7
+ export * from './relay-share.js';
6
8
  export * from './relay-socket.js';
7
9
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A QR code (ISO/IEC 18004) of a text, in byte mode with the error correction level M, in the smallest
3
+ * version that holds it. Enough for a link a phone scans; written here rather than taken from a package.
4
+ * The steps and tables follow the standard, as does the well-known reference implementation by Nayuki.
5
+ */
6
+ export declare class QrCode {
7
+ readonly version: number;
8
+ /** Codewords for error correction per block, and blocks, at level M, by version (index 0 unused). */
9
+ protected static readonly ECC_PER_BLOCK: number[];
10
+ protected static readonly BLOCKS: number[];
11
+ /** Level M in the format bits. */
12
+ protected static readonly ECC_FORMAT = 0;
13
+ readonly size: number;
14
+ protected readonly modules: boolean[][];
15
+ protected readonly reserved: boolean[][];
16
+ protected constructor(version: number, data: number[]);
17
+ /** Throws when the text is too long for any version. */
18
+ static encode(text: string): QrCode;
19
+ isDark(x: number, y: number): boolean;
20
+ /** The code as an SVG path of its dark modules, one unit each, without the quiet zone. */
21
+ /**
22
+ * The code as lines of text for a terminal, two rows of modules a line in half blocks (▀ ▄ █), with
23
+ * `quiet` light modules around: print them dark on light.
24
+ */
25
+ lines(quiet?: number): string[];
26
+ path(): string;
27
+ protected static rawModules(version: number): number;
28
+ protected static dataCodewords(version: number): number;
29
+ protected alignmentPositions(): number[];
30
+ protected set(x: number, y: number, dark: boolean): void;
31
+ protected drawPatterns(): void;
32
+ protected drawFormat(mask: number): void;
33
+ /** The data split into blocks, each with its Reed-Solomon codewords, interleaved. */
34
+ protected withEcc(data: number[]): number[];
35
+ protected drawCodewords(codewords: number[]): void;
36
+ protected applyMask(mask: number): void;
37
+ /** How hard the code is to read with a mask: long runs, blocks, finder-like patterns, imbalance. */
38
+ protected penalty(): number;
39
+ protected static multiply(x: number, y: number): number;
40
+ protected static reedSolomonDivisor(degree: number): number[];
41
+ protected static reedSolomonRemainder(data: number[], divisor: number[]): number[];
42
+ }
@@ -0,0 +1,366 @@
1
+ /**
2
+ * A QR code (ISO/IEC 18004) of a text, in byte mode with the error correction level M, in the smallest
3
+ * version that holds it. Enough for a link a phone scans; written here rather than taken from a package.
4
+ * The steps and tables follow the standard, as does the well-known reference implementation by Nayuki.
5
+ */
6
+ export class QrCode {
7
+ constructor(version, data) {
8
+ this.version = version;
9
+ this.size = version * 4 + 17;
10
+ this.modules = Array.from({ length: this.size }, () => new Array(this.size).fill(false));
11
+ this.reserved = Array.from({ length: this.size }, () => new Array(this.size).fill(false));
12
+ this.drawPatterns();
13
+ this.drawCodewords(this.withEcc(data));
14
+ let best = 0;
15
+ let lowest = Number.POSITIVE_INFINITY;
16
+ for (let mask = 0; mask < 8; mask++) {
17
+ this.applyMask(mask);
18
+ this.drawFormat(mask);
19
+ const penalty = this.penalty();
20
+ if (penalty < lowest) {
21
+ best = mask;
22
+ lowest = penalty;
23
+ }
24
+ this.applyMask(mask);
25
+ }
26
+ this.applyMask(best);
27
+ this.drawFormat(best);
28
+ }
29
+ /** Throws when the text is too long for any version. */
30
+ static encode(text) {
31
+ const bytes = [...new TextEncoder().encode(text)];
32
+ for (let version = 1; version <= 40; version++) {
33
+ const capacity = QrCode.dataCodewords(version) * 8;
34
+ const countBits = version <= 9 ? 8 : 16;
35
+ const used = 4 + countBits + bytes.length * 8;
36
+ if (used <= capacity) {
37
+ const bits = [];
38
+ const push = (value, length) => {
39
+ for (let i = length - 1; i >= 0; i--) {
40
+ bits.push((value >>> i) & 1);
41
+ }
42
+ };
43
+ push(0b0100, 4);
44
+ push(bytes.length, countBits);
45
+ for (const byte of bytes) {
46
+ push(byte, 8);
47
+ }
48
+ push(0, Math.min(4, capacity - bits.length));
49
+ push(0, (8 - (bits.length % 8)) % 8);
50
+ for (let pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11) {
51
+ push(pad, 8);
52
+ }
53
+ const data = [];
54
+ for (let i = 0; i < bits.length; i += 8) {
55
+ data.push(bits.slice(i, i + 8).reduce((byte, bit) => (byte << 1) | bit, 0));
56
+ }
57
+ return new QrCode(version, data);
58
+ }
59
+ }
60
+ throw new Error('The text is too long for a QR code.');
61
+ }
62
+ isDark(x, y) {
63
+ return this.modules[y][x];
64
+ }
65
+ /** The code as an SVG path of its dark modules, one unit each, without the quiet zone. */
66
+ /**
67
+ * The code as lines of text for a terminal, two rows of modules a line in half blocks (▀ ▄ █), with
68
+ * `quiet` light modules around: print them dark on light.
69
+ */
70
+ lines(quiet = 2) {
71
+ const dark = (x, y) => x >= 0 && y >= 0 && x < this.size && y < this.size && this.isDark(x, y);
72
+ const lines = [];
73
+ for (let y = -quiet; y < this.size + quiet; y += 2) {
74
+ let line = '';
75
+ for (let x = -quiet; x < this.size + quiet; x++) {
76
+ const [top, bottom] = [dark(x, y), dark(x, y + 1)];
77
+ line += top && bottom ? '█' : top ? '▀' : bottom ? '▄' : ' ';
78
+ }
79
+ lines.push(line);
80
+ }
81
+ return lines;
82
+ }
83
+ path() {
84
+ let d = '';
85
+ for (let y = 0; y < this.size; y++) {
86
+ for (let x = 0; x < this.size; x++) {
87
+ if (this.modules[y][x]) {
88
+ d += `M${x} ${y}h1v1h-1z`;
89
+ }
90
+ }
91
+ }
92
+ return d;
93
+ }
94
+ static rawModules(version) {
95
+ let result = (16 * version + 128) * version + 64;
96
+ if (version >= 2) {
97
+ const align = Math.floor(version / 7) + 2;
98
+ result -= (25 * align - 10) * align - 55;
99
+ if (version >= 7) {
100
+ result -= 36;
101
+ }
102
+ }
103
+ return result;
104
+ }
105
+ static dataCodewords(version) {
106
+ return Math.floor(QrCode.rawModules(version) / 8) - QrCode.ECC_PER_BLOCK[version] * QrCode.BLOCKS[version];
107
+ }
108
+ alignmentPositions() {
109
+ if (this.version === 1) {
110
+ return [];
111
+ }
112
+ const count = Math.floor(this.version / 7) + 2;
113
+ const step = this.version === 32 ? 26 : Math.ceil((this.version * 4 + 4) / (count * 2 - 2)) * 2;
114
+ const result = [6];
115
+ for (let position = this.size - 7; result.length < count; position -= step) {
116
+ result.splice(1, 0, position);
117
+ }
118
+ return result;
119
+ }
120
+ set(x, y, dark) {
121
+ this.modules[y][x] = dark;
122
+ this.reserved[y][x] = true;
123
+ }
124
+ drawPatterns() {
125
+ for (let i = 0; i < this.size; i++) {
126
+ this.set(6, i, i % 2 === 0);
127
+ this.set(i, 6, i % 2 === 0);
128
+ }
129
+ const finder = (cx, cy) => {
130
+ for (let dy = -4; dy <= 4; dy++) {
131
+ for (let dx = -4; dx <= 4; dx++) {
132
+ const x = cx + dx;
133
+ const y = cy + dy;
134
+ if (x >= 0 && x < this.size && y >= 0 && y < this.size) {
135
+ const distance = Math.max(Math.abs(dx), Math.abs(dy));
136
+ this.set(x, y, distance !== 2 && distance !== 4);
137
+ }
138
+ }
139
+ }
140
+ };
141
+ finder(3, 3);
142
+ finder(this.size - 4, 3);
143
+ finder(3, this.size - 4);
144
+ const positions = this.alignmentPositions();
145
+ for (let i = 0; i < positions.length; i++) {
146
+ for (let j = 0; j < positions.length; j++) {
147
+ const corner = (i === 0 && j === 0) || (i === 0 && j === positions.length - 1) || (i === positions.length - 1 && j === 0);
148
+ if (!corner) {
149
+ for (let dy = -2; dy <= 2; dy++) {
150
+ for (let dx = -2; dx <= 2; dx++) {
151
+ this.set(positions[i] + dx, positions[j] + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ // Reserved now, drawn with each mask.
158
+ this.drawFormat(0);
159
+ if (this.version >= 7) {
160
+ let rem = this.version;
161
+ for (let i = 0; i < 12; i++) {
162
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
163
+ }
164
+ const bits = (this.version << 12) | rem;
165
+ for (let i = 0; i < 18; i++) {
166
+ const dark = ((bits >>> i) & 1) !== 0;
167
+ const a = this.size - 11 + (i % 3);
168
+ const b = Math.floor(i / 3);
169
+ this.set(a, b, dark);
170
+ this.set(b, a, dark);
171
+ }
172
+ }
173
+ }
174
+ drawFormat(mask) {
175
+ const data = (QrCode.ECC_FORMAT << 3) | mask;
176
+ let rem = data;
177
+ for (let i = 0; i < 10; i++) {
178
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
179
+ }
180
+ const bits = ((data << 10) | rem) ^ 0x5412;
181
+ const bit = (i) => ((bits >>> i) & 1) !== 0;
182
+ for (let i = 0; i <= 5; i++) {
183
+ this.set(8, i, bit(i));
184
+ }
185
+ this.set(8, 7, bit(6));
186
+ this.set(8, 8, bit(7));
187
+ this.set(7, 8, bit(8));
188
+ for (let i = 9; i < 15; i++) {
189
+ this.set(14 - i, 8, bit(i));
190
+ }
191
+ for (let i = 0; i < 8; i++) {
192
+ this.set(this.size - 1 - i, 8, bit(i));
193
+ }
194
+ for (let i = 8; i < 15; i++) {
195
+ this.set(8, this.size - 15 + i, bit(i));
196
+ }
197
+ this.set(8, this.size - 8, true);
198
+ }
199
+ /** The data split into blocks, each with its Reed-Solomon codewords, interleaved. */
200
+ withEcc(data) {
201
+ const blocks = QrCode.BLOCKS[this.version];
202
+ const eccLength = QrCode.ECC_PER_BLOCK[this.version];
203
+ const raw = Math.floor(QrCode.rawModules(this.version) / 8);
204
+ const shortBlocks = blocks - (raw % blocks);
205
+ const shortLength = Math.floor(raw / blocks);
206
+ const divisor = QrCode.reedSolomonDivisor(eccLength);
207
+ const all = [];
208
+ for (let i = 0, k = 0; i < blocks; i++) {
209
+ const dataLength = shortLength - eccLength + (i < shortBlocks ? 0 : 1);
210
+ const block = data.slice(k, k + dataLength);
211
+ k += dataLength;
212
+ const ecc = QrCode.reedSolomonRemainder(block, divisor);
213
+ if (i < shortBlocks) {
214
+ block.push(0);
215
+ }
216
+ all.push([...block, ...ecc]);
217
+ }
218
+ const result = [];
219
+ for (let i = 0; i < all[0].length; i++) {
220
+ for (let j = 0; j < all.length; j++) {
221
+ // The padding byte of a short block is not sent.
222
+ if (i !== shortLength - eccLength || j >= shortBlocks) {
223
+ result.push(all[j][i]);
224
+ }
225
+ }
226
+ }
227
+ return result;
228
+ }
229
+ drawCodewords(codewords) {
230
+ let i = 0;
231
+ for (let right = this.size - 1; right >= 1; right -= 2) {
232
+ if (right === 6) {
233
+ right = 5;
234
+ }
235
+ for (let vertical = 0; vertical < this.size; vertical++) {
236
+ for (let j = 0; j < 2; j++) {
237
+ const x = right - j;
238
+ const upward = ((right + 1) & 2) === 0;
239
+ const y = upward ? this.size - 1 - vertical : vertical;
240
+ if (!this.reserved[y][x] && i < codewords.length * 8) {
241
+ this.modules[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) !== 0;
242
+ i++;
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+ applyMask(mask) {
249
+ for (let y = 0; y < this.size; y++) {
250
+ for (let x = 0; x < this.size; x++) {
251
+ if (this.reserved[y][x]) {
252
+ continue;
253
+ }
254
+ const flip = [
255
+ (x + y) % 2,
256
+ y % 2,
257
+ x % 3,
258
+ (x + y) % 3,
259
+ (Math.floor(x / 3) + Math.floor(y / 2)) % 2,
260
+ ((x * y) % 2) + ((x * y) % 3),
261
+ (((x * y) % 2) + ((x * y) % 3)) % 2,
262
+ (((x + y) % 2) + ((x * y) % 3)) % 2,
263
+ ][mask];
264
+ if (flip === 0) {
265
+ this.modules[y][x] = !this.modules[y][x];
266
+ }
267
+ }
268
+ }
269
+ }
270
+ /** How hard the code is to read with a mask: long runs, blocks, finder-like patterns, imbalance. */
271
+ penalty() {
272
+ let result = 0;
273
+ const line = (get) => {
274
+ for (let i = 0; i < this.size; i++) {
275
+ let run = 1;
276
+ const seen = [];
277
+ for (let j = 0; j < this.size; j++) {
278
+ const dark = get(i, j);
279
+ if (j > 0 && dark === get(i, j - 1)) {
280
+ run++;
281
+ if (run === 5) {
282
+ result += 3;
283
+ }
284
+ else if (run > 5) {
285
+ result++;
286
+ }
287
+ }
288
+ else {
289
+ run = 1;
290
+ }
291
+ seen.push(dark);
292
+ }
293
+ const text = seen.map(dark => (dark ? '1' : '0')).join('');
294
+ for (const pattern of ['10111010000', '00001011101']) {
295
+ for (let at = text.indexOf(pattern); at >= 0; at = text.indexOf(pattern, at + 1)) {
296
+ result += 40;
297
+ }
298
+ }
299
+ }
300
+ };
301
+ line((i, j) => this.modules[i][j]);
302
+ line((i, j) => this.modules[j][i]);
303
+ let dark = 0;
304
+ for (let y = 0; y < this.size; y++) {
305
+ for (let x = 0; x < this.size; x++) {
306
+ const value = this.modules[y][x];
307
+ dark += value ? 1 : 0;
308
+ if (x < this.size - 1 &&
309
+ y < this.size - 1 &&
310
+ value === this.modules[y][x + 1] &&
311
+ value === this.modules[y + 1][x] &&
312
+ value === this.modules[y + 1][x + 1]) {
313
+ result += 3;
314
+ }
315
+ }
316
+ }
317
+ const total = this.size * this.size;
318
+ result += Math.floor(Math.abs(dark * 20 - total * 10) / total) * 10;
319
+ return result;
320
+ }
321
+ static multiply(x, y) {
322
+ let z = 0;
323
+ for (let i = 7; i >= 0; i--) {
324
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
325
+ z ^= ((y >>> i) & 1) * x;
326
+ }
327
+ return z & 0xff;
328
+ }
329
+ static reedSolomonDivisor(degree) {
330
+ const result = new Array(degree).fill(0);
331
+ result[degree - 1] = 1;
332
+ let root = 1;
333
+ for (let i = 0; i < degree; i++) {
334
+ for (let j = 0; j < result.length; j++) {
335
+ result[j] = QrCode.multiply(result[j], root);
336
+ if (j + 1 < result.length) {
337
+ result[j] ^= result[j + 1];
338
+ }
339
+ }
340
+ root = QrCode.multiply(root, 0x02);
341
+ }
342
+ return result;
343
+ }
344
+ static reedSolomonRemainder(data, divisor) {
345
+ const result = new Array(divisor.length).fill(0);
346
+ for (const byte of data) {
347
+ const factor = byte ^ result.shift();
348
+ result.push(0);
349
+ divisor.forEach((coefficient, i) => {
350
+ result[i] ^= QrCode.multiply(coefficient, factor);
351
+ });
352
+ }
353
+ return result;
354
+ }
355
+ }
356
+ /** Codewords for error correction per block, and blocks, at level M, by version (index 0 unused). */
357
+ QrCode.ECC_PER_BLOCK = [
358
+ -1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
359
+ 28, 28, 28,
360
+ ];
361
+ QrCode.BLOCKS = [
362
+ -1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,
363
+ ];
364
+ /** Level M in the format bits. */
365
+ QrCode.ECC_FORMAT = 0;
366
+ //# sourceMappingURL=qr-code.js.map
@@ -4,8 +4,36 @@ export declare const RELAY_DEFAULT_URL = "https://relay.cellbang.com";
4
4
  export declare const RELAY_HOST_PATH = "/v1/host/";
5
5
  export declare const RELAY_CONNECT_PATH = "/v1/connect/";
6
6
  export declare const RELAY_PAIR_PATH = "/pair";
7
+ /** A link of an extension handed on: its package comes from the computer of the one who shared it, through the relay. */
8
+ export declare const RELAY_SHARE_PATH = "/share";
7
9
  /** The page a pairing link opens in a browser: the link is for the app, and the key in it stays in the fragment. */
8
10
  export declare const RELAY_PAIR_PAGE = "<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>Ta</title>\n<body style=\"font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em\">\n<h1>Ta</h1><p>Open this link in the Ta app, or paste it there, to reach your Ta from this device.</p>\n<p>\u6253\u5F00 Ta \u5E94\u7528\uFF0C\u7C98\u8D34\u8FD9\u4E2A\u94FE\u63A5\uFF0C\u5C31\u80FD\u4ECE\u8FD9\u53F0\u8BBE\u5907\u8FDE\u5230\u4F60\u7684 Ta\u3002</p></body>";
11
+ /** The page a link of an extension opens in a browser. */
12
+ export declare const RELAY_SHARE_PAGE = "<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>Ta</title>\n<body style=\"font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em\">\n<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>\n<p>\u6709\u4EBA\u5206\u4EAB\u4E86\u4E00\u4E2A Ta \u6269\u5C55\u3002\u5728 Ta \u5E94\u7528\u91CC\u626B\u7801\uFF0C\u6216\u628A\u8FD9\u4E2A\u94FE\u63A5\u7C98\u8D34\u5230\u201C\u5FEB\u6377\u6253\u5F00\u201D\uFF0C\u5C31\u80FD\u6253\u5F00\u5B83\u3002</p></body>";
13
+ /**
14
+ * A package handed on through the relay (RelayShare): the host, asked on a channel by the key of the share,
15
+ * sends what the package is, then its bytes in chunks small enough for any relay, then the end; sealed as the
16
+ * rest. Never stored on the relay.
17
+ */
18
+ export type RelayShareMessage = {
19
+ t: 'package';
20
+ name: string;
21
+ size: number;
22
+ } | {
23
+ t: 'chunk';
24
+ d: string;
25
+ } | {
26
+ t: 'end';
27
+ } | {
28
+ t: 'error';
29
+ message: string;
30
+ };
31
+ /** The largest package that is handed on: a gzipped tar of a package of the user, its code and a few assets. */
32
+ export declare const RELAY_SHARE_MAX_BYTES: number;
33
+ /** The bytes of a chunk, base64 in a sealed message: well under the 1 MiB of a message of Cloudflare. */
34
+ export declare const RELAY_SHARE_CHUNK_BYTES: number;
35
+ /** How long a link of a package works. */
36
+ export declare const RELAY_SHARE_DAYS = 7;
9
37
  /** Hosts and devices: what the relay knows of them, and nothing it could read from. */
10
38
  export declare const RELAY_ID: RegExp;
11
39
  /** Close codes of the relay. */
@@ -19,8 +47,21 @@ export declare enum RelayCloseCode {
19
47
  /** The host closed this channel, or refused the device. */
20
48
  CLOSED_BY_HOST = 4410,
21
49
  /** Too many devices are connected to this host. */
22
- FULL = 4429
50
+ FULL = 4429,
51
+ /** No answer in time: to the hello, or to the pings of the heartbeat; the connection is gone without a word. */
52
+ TIMEOUT = 4408
23
53
  }
54
+ /**
55
+ * The heartbeat: hosts and devices send `ping` to the relay every so often, outside the channels, and it
56
+ * answers `pong` itself (a Durable Object without waking). A connection that stops being answered is gone
57
+ * without a word, as one through a proxy or a network that changed often is, and is made again; the relay
58
+ * finds such connections by the pings that stopped.
59
+ */
60
+ export declare const RELAY_PING = "ping";
61
+ export declare const RELAY_PONG = "pong";
62
+ /** Between pings. A peer is stale once it missed about three of them (RELAY_STALE_MS). */
63
+ export declare const RELAY_PING_MS = 25000;
64
+ export declare const RELAY_STALE_MS = 80000;
24
65
  /**
25
66
  * Between the relay and a host, which takes the connections of many devices over one WebSocket: each
26
67
  * device connection is a channel. What a device sends goes to the host as `data`, and back; the relay
@@ -4,11 +4,24 @@ export const RELAY_DEFAULT_URL = 'https://relay.cellbang.com';
4
4
  export const RELAY_HOST_PATH = '/v1/host/';
5
5
  export const RELAY_CONNECT_PATH = '/v1/connect/';
6
6
  export const RELAY_PAIR_PATH = '/pair';
7
+ /** A link of an extension handed on: its package comes from the computer of the one who shared it, through the relay. */
8
+ export const RELAY_SHARE_PATH = '/share';
7
9
  /** The page a pairing link opens in a browser: the link is for the app, and the key in it stays in the fragment. */
8
10
  export const RELAY_PAIR_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
9
11
  <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
10
12
  <h1>Ta</h1><p>Open this link in the Ta app, or paste it there, to reach your Ta from this device.</p>
11
13
  <p>打开 Ta 应用,粘贴这个链接,就能从这台设备连到你的 Ta。</p></body>`;
14
+ /** The page a link of an extension opens in a browser. */
15
+ export const RELAY_SHARE_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
16
+ <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
17
+ <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>
18
+ <p>有人分享了一个 Ta 扩展。在 Ta 应用里扫码,或把这个链接粘贴到“快捷打开”,就能打开它。</p></body>`;
19
+ /** The largest package that is handed on: a gzipped tar of a package of the user, its code and a few assets. */
20
+ export const RELAY_SHARE_MAX_BYTES = 8 * 1024 * 1024;
21
+ /** The bytes of a chunk, base64 in a sealed message: well under the 1 MiB of a message of Cloudflare. */
22
+ export const RELAY_SHARE_CHUNK_BYTES = 192 * 1024;
23
+ /** How long a link of a package works. */
24
+ export const RELAY_SHARE_DAYS = 7;
12
25
  /** Hosts and devices: what the relay knows of them, and nothing it could read from. */
13
26
  export const RELAY_ID = /^[A-Za-z0-9_-]{16,64}$/;
14
27
  /** Close codes of the relay. */
@@ -24,6 +37,19 @@ export var RelayCloseCode;
24
37
  RelayCloseCode[RelayCloseCode["CLOSED_BY_HOST"] = 4410] = "CLOSED_BY_HOST";
25
38
  /** Too many devices are connected to this host. */
26
39
  RelayCloseCode[RelayCloseCode["FULL"] = 4429] = "FULL";
40
+ /** No answer in time: to the hello, or to the pings of the heartbeat; the connection is gone without a word. */
41
+ RelayCloseCode[RelayCloseCode["TIMEOUT"] = 4408] = "TIMEOUT";
27
42
  })(RelayCloseCode || (RelayCloseCode = {}));
43
+ /**
44
+ * The heartbeat: hosts and devices send `ping` to the relay every so often, outside the channels, and it
45
+ * answers `pong` itself (a Durable Object without waking). A connection that stops being answered is gone
46
+ * without a word, as one through a proxy or a network that changed often is, and is made again; the relay
47
+ * finds such connections by the pings that stopped.
48
+ */
49
+ export const RELAY_PING = 'ping';
50
+ export const RELAY_PONG = 'pong';
51
+ /** Between pings. A peer is stale once it missed about three of them (RELAY_STALE_MS). */
52
+ export const RELAY_PING_MS = 25000;
53
+ export const RELAY_STALE_MS = 80000;
28
54
  export const RELAY_PROOF = 'ta-relay ready';
29
55
  //# sourceMappingURL=relay-protocol.js.map
@@ -26,6 +26,7 @@ export declare class RelayRoom {
26
26
  clientClosed(channel: string): void;
27
27
  /** What the host sends that is not a message of the protocol is dropped. */
28
28
  fromHost(text: string): void;
29
+ /** The host went, or connected again (its channels went with the connection before): its devices are told to come again. */
29
30
  hostClosed(): void;
30
31
  protected toHost(host: RelayPeer, message: RelayHostMessage): void;
31
32
  }
@@ -1,4 +1,4 @@
1
- import { RelayCloseCode } from './relay-protocol.js';
1
+ import { RELAY_PING, RELAY_PONG, RelayCloseCode } from './relay-protocol.js';
2
2
  /** Devices at once on one host. */
3
3
  export const RELAY_MAX_CLIENTS = 16;
4
4
  /**
@@ -23,6 +23,11 @@ export class RelayRoom {
23
23
  return undefined;
24
24
  }
25
25
  fromClient(channel, text) {
26
+ var _a;
27
+ if (text === RELAY_PING) {
28
+ (_a = this.peers.client(channel)) === null || _a === void 0 ? void 0 : _a.send(RELAY_PONG);
29
+ return;
30
+ }
26
31
  const host = this.peers.host();
27
32
  if (host) {
28
33
  this.toHost(host, { t: 'data', ch: channel, d: text });
@@ -36,11 +41,16 @@ export class RelayRoom {
36
41
  }
37
42
  /** What the host sends that is not a message of the protocol is dropped. */
38
43
  fromHost(text) {
44
+ var _a;
45
+ if (text === RELAY_PING) {
46
+ (_a = this.peers.host()) === null || _a === void 0 ? void 0 : _a.send(RELAY_PONG);
47
+ return;
48
+ }
39
49
  let message;
40
50
  try {
41
51
  message = JSON.parse(text);
42
52
  }
43
- catch (_a) {
53
+ catch (_b) {
44
54
  return;
45
55
  }
46
56
  const client = typeof message.ch === 'string' ? this.peers.client(message.ch) : undefined;
@@ -51,6 +61,7 @@ export class RelayRoom {
51
61
  client === null || client === void 0 ? void 0 : client.close(RelayCloseCode.CLOSED_BY_HOST, 'Closed by the host.');
52
62
  }
53
63
  }
64
+ /** The host went, or connected again (its channels went with the connection before): its devices are told to come again. */
54
65
  hostClosed() {
55
66
  for (const client of this.peers.clients()) {
56
67
  client.close(RelayCloseCode.HOST_OFFLINE, 'The host went offline.');