@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
@@ -1,141 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const bun_test_1 = require("bun:test");
4
- const node_child_process_1 = require("node:child_process");
5
- const node_fs_1 = require("node:fs");
6
- const node_os_1 = require("node:os");
7
- const node_path_1 = require("node:path");
8
- const relay_pairing_1 = require("../common/relay-pairing");
9
- const relay_protocol_1 = require("../common/relay-protocol");
10
- const relay_socket_1 = require("../common/relay-socket");
11
- const relay_host_1 = require("./relay-host");
12
- const relay_store_1 = require("./relay-store");
13
- /** In Node.js: the HTTP server of Bun before 1.4 cannot answer WebSocket upgrades. Prints what reached the host side. */
14
- function startRelay(port = 0) {
15
- var _a;
16
- const script = `const { RelayServer } = require(${JSON.stringify((0, node_path_1.join)(__dirname, 'relay-server.js'))});
17
- const { RelayRoom } = require(${JSON.stringify((0, node_path_1.join)(__dirname, '../common/relay-room.js'))});
18
- const fromClient = RelayRoom.prototype.fromClient;
19
- RelayRoom.prototype.fromClient = function (channel, text) { console.error('SEEN ' + text); return fromClient.call(this, channel, text); };
20
- new RelayServer({ port: ${port} }).listen().then(url => console.log(url));`;
21
- const child = (0, node_child_process_1.spawn)('node', ['-e', script], { stdio: ['ignore', 'pipe', 'pipe'] });
22
- const seen = [];
23
- (_a = child.stderr) === null || _a === void 0 ? void 0 : _a.on('data', data => seen.push(String(data)));
24
- return new Promise(resolve => { var _a; return (_a = child.stdout) === null || _a === void 0 ? void 0 : _a.once('data', data => resolve({ child, url: String(data).trim(), seen })); });
25
- }
26
- /** Stands in for ta serve: answers every message with what it got, to connections with the token. */
27
- function startLocal() {
28
- return Bun.serve({
29
- port: 0,
30
- hostname: '127.0.0.1',
31
- fetch: (request, server) => new URL(request.url).searchParams.get('token') === 'local-token' && server.upgrade(request) ? undefined : new Response('no', { status: 401 }),
32
- websocket: {
33
- message: (socket, message) => {
34
- socket.send(`echo ${message}`);
35
- },
36
- },
37
- });
38
- }
39
- function open(socket) {
40
- return new Promise(resolve => {
41
- socket.onopen = () => resolve(undefined);
42
- socket.onclose = event => resolve({ code: event.code });
43
- });
44
- }
45
- function next(socket) {
46
- return new Promise(resolve => {
47
- socket.onmessage = message => resolve(message.data);
48
- });
49
- }
50
- (0, bun_test_1.describe)('the relay', () => {
51
- let relay;
52
- const local = startLocal();
53
- const store = new relay_store_1.RelayStore((0, node_fs_1.mkdtempSync)((0, node_path_1.join)((0, node_os_1.tmpdir)(), 'ta-relay-')));
54
- let host;
55
- (0, bun_test_1.beforeAll)(async () => {
56
- relay = await startRelay();
57
- host = new relay_host_1.RelayHost({ store, localUrl: `ws://127.0.0.1:${local.port}/?token=local-token`, reconnectDelayMs: 20 });
58
- });
59
- (0, bun_test_1.afterAll)(() => {
60
- host.stop();
61
- local.stop(true);
62
- relay.child.kill();
63
- });
64
- const online = async () => {
65
- host.refresh();
66
- while (!host.online) {
67
- await Bun.sleep(10);
68
- }
69
- };
70
- (0, bun_test_1.it)('does not connect ta serve before a device is paired', () => {
71
- host.start();
72
- (0, bun_test_1.expect)(host.online).toBe(false);
73
- });
74
- (0, bun_test_1.it)('takes a paired device to ta serve, and the relay sees only what is sealed', async () => {
75
- const pairing = store.pair(relay.url, 'phone');
76
- await online();
77
- const socket = new relay_socket_1.RelaySocket(relay_pairing_1.RelayPairingUtil.parse(relay_pairing_1.RelayPairingUtil.link(pairing)));
78
- (0, bun_test_1.expect)(await open(socket)).toBeUndefined();
79
- const answer = next(socket);
80
- socket.send('a secret question');
81
- (0, bun_test_1.expect)(await answer).toBe('echo a secret question');
82
- const seen = relay.seen.join('');
83
- (0, bun_test_1.expect)(seen).toContain('SEEN');
84
- (0, bun_test_1.expect)(seen).not.toContain('secret');
85
- socket.close();
86
- });
87
- (0, bun_test_1.it)('refuses a device that is not paired, or no longer', async () => {
88
- var _a, _b;
89
- const pairing = store.pair(relay.url, 'tablet');
90
- const stranger = new relay_socket_1.RelaySocket({ ...pairing, device: 'x'.repeat(22) });
91
- (0, bun_test_1.expect)((_a = (await open(stranger))) === null || _a === void 0 ? void 0 : _a.code).toBe(4403);
92
- store.remove(pairing.device);
93
- const removed = new relay_socket_1.RelaySocket(pairing);
94
- (0, bun_test_1.expect)((_b = (await open(removed))) === null || _b === void 0 ? void 0 : _b.code).toBe(4403);
95
- });
96
- (0, bun_test_1.it)('refuses a device whose key is wrong', async () => {
97
- var _a;
98
- const pairing = store.pair(relay.url, 'laptop');
99
- const forged = new relay_socket_1.RelaySocket({ ...pairing, key: store.pair(relay.url, 'other').key });
100
- (0, bun_test_1.expect)((_a = (await open(forged))) === null || _a === void 0 ? void 0 : _a.code).toBe(4403);
101
- });
102
- (0, bun_test_1.it)('tells a device when its host is offline', async () => {
103
- var _a;
104
- const pairing = store.pair(relay.url, 'watch');
105
- const socket = new relay_socket_1.RelaySocket({ ...pairing, host: 'n'.repeat(22) });
106
- (0, bun_test_1.expect)((_a = (await open(socket))) === null || _a === void 0 ? void 0 : _a.code).toBe(relay_protocol_1.RelayCloseCode.HOST_OFFLINE);
107
- });
108
- (0, bun_test_1.it)('does not let another host take the id', async () => {
109
- const { host: id } = store.read();
110
- const thief = new WebSocket(`${relay_pairing_1.RelayPairingUtil.websocketUrl(relay.url, '/v1/host/')}${id === null || id === void 0 ? void 0 : id.id}?secret=${'w'.repeat(43)}`);
111
- const code = await new Promise(resolve => {
112
- thief.onclose = event => resolve(event.code);
113
- });
114
- (0, bun_test_1.expect)(code).toBe(relay_protocol_1.RelayCloseCode.REFUSED);
115
- (0, bun_test_1.expect)(host.online).toBe(true);
116
- });
117
- (0, bun_test_1.it)('comes back when the relay does', async () => {
118
- const port = Number(new URL(relay.url).port);
119
- relay.child.kill();
120
- await new Promise(resolve => relay.child.once('exit', resolve));
121
- while (host.online) {
122
- await Bun.sleep(10);
123
- }
124
- relay = await startRelay(port);
125
- while (!host.online) {
126
- await Bun.sleep(10);
127
- }
128
- const pairing = store.pair(relay.url, 'again');
129
- const socket = new relay_socket_1.RelaySocket(pairing);
130
- (0, bun_test_1.expect)(await open(socket)).toBeUndefined();
131
- socket.close();
132
- });
133
- (0, bun_test_1.it)('leaves the relay when the last device is removed', async () => {
134
- for (const device of store.read().devices) {
135
- store.remove(device.id);
136
- }
137
- host.refresh();
138
- (0, bun_test_1.expect)(host.online).toBe(false);
139
- });
140
- });
141
- //# sourceMappingURL=relay.spec.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"relay.spec.js","sourceRoot":"","sources":["../../src/node/relay.spec.ts"],"names":[],"mappings":";;AAAA,uCAAqE;AACrE,2DAA8D;AAC9D,qCAAsC;AACtC,qCAAiC;AACjC,yCAAiC;AACjC,2DAA2D;AAC3D,6DAA0D;AAC1D,yDAAqD;AACrD,6CAAyC;AACzC,+CAA2C;AAE3C,yHAAyH;AACzH,SAAS,UAAU,CAAC,IAAI,GAAG,CAAC;;IACxB,MAAM,MAAM,GAAG,mCAAmC,IAAI,CAAC,SAAS,CAAC,IAAA,gBAAI,EAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;gCACxE,IAAI,CAAC,SAAS,CAAC,IAAA,gBAAI,EAAC,SAAS,EAAE,yBAAyB,CAAC,CAAC;;;0BAGhE,IAAI,6CAA6C,CAAC;IACxE,MAAM,KAAK,GAAG,IAAA,0BAAK,EAAC,MAAM,EA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- export * from './relay-bytes';
2
- export * from './relay-cipher';
3
- export * from './relay-pairing';
4
- export * from './relay-protocol';
5
- export * from './relay-room';
6
- export * from './relay-socket';
@@ -1,37 +0,0 @@
1
- /** Bytes as text and back, in base64url, with what every platform has (no Buffer in a browser). */
2
- export namespace RelayBytes {
3
- export function random(length: number): Uint8Array {
4
- return globalThis.crypto.getRandomValues(new Uint8Array(length));
5
- }
6
-
7
- export function toBase64(bytes: Uint8Array): string {
8
- let binary = '';
9
- for (const byte of bytes) {
10
- binary += String.fromCharCode(byte);
11
- }
12
- return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
13
- }
14
-
15
- /** Throws on what is not base64url. */
16
- export function fromBase64(text: string): Uint8Array {
17
- if (!/^[A-Za-z0-9_-]*$/.test(text)) {
18
- throw new Error('Not base64url.');
19
- }
20
- const binary = atob(text.replace(/-/g, '+').replace(/_/g, '/'));
21
- const bytes = new Uint8Array(binary.length);
22
- for (let i = 0; i < binary.length; i++) {
23
- bytes[i] = binary.charCodeAt(i);
24
- }
25
- return bytes;
26
- }
27
-
28
- export function concat(...parts: Uint8Array[]): Uint8Array {
29
- const bytes = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
30
- let offset = 0;
31
- for (const part of parts) {
32
- bytes.set(part, offset);
33
- offset += part.length;
34
- }
35
- return bytes;
36
- }
37
- }
@@ -1,45 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { RelayBytes } from './relay-bytes';
3
- import { RelayCipher } from './relay-cipher';
4
-
5
- async function pair(key = RelayBytes.random(32)) {
6
- const [client, host] = [RelayBytes.random(16), RelayBytes.random(16)];
7
- return { client: await RelayCipher.derive(key, client, host, 'client'), host: await RelayCipher.derive(key, client, host, 'host') };
8
- }
9
-
10
- describe('RelayCipher', () => {
11
- it('opens on one side what the other sealed, both ways, in order', async () => {
12
- const { client, host } = await pair();
13
- const frames = await Promise.all(['a', 'b', 'c'].map(text => client.seal(text)));
14
- expect(await Promise.all(frames.map(frame => host.open(frame)))).toEqual(['a', 'b', 'c']);
15
- expect(await client.open(await host.seal('back'))).toBe('back');
16
- });
17
-
18
- it('does not open a message replayed, skipped or changed', async () => {
19
- const { client, host } = await pair();
20
- const first = await client.seal('first');
21
- const second = await client.seal('second');
22
- expect(await host.open(first)).toBe('first');
23
- await expect(host.open(first)).rejects.toThrow();
24
- const other = await pair();
25
- await other.client.seal('skipped');
26
- await expect(other.host.open(await other.client.seal('second'))).rejects.toThrow();
27
- const bytes = RelayBytes.fromBase64(second);
28
- bytes[0] ^= 1;
29
- await expect(host.open(RelayBytes.toBase64(bytes))).rejects.toThrow();
30
- });
31
-
32
- it('does not open what a side sealed for the other direction, or with another key', async () => {
33
- const { client } = await pair();
34
- const frame = await client.seal('x');
35
- await expect(client.open(frame)).rejects.toThrow();
36
- const other = await pair();
37
- await expect(other.host.open(frame)).rejects.toThrow();
38
- });
39
-
40
- it('keeps base64url as it was', () => {
41
- const bytes = RelayBytes.random(33);
42
- expect(RelayBytes.fromBase64(RelayBytes.toBase64(bytes))).toEqual(bytes);
43
- expect(() => RelayBytes.fromBase64('a+b')).toThrow();
44
- });
45
- });
@@ -1,74 +0,0 @@
1
- import { RelayBytes } from './relay-bytes';
2
-
3
- const encoder = new TextEncoder();
4
- const decoder = new TextDecoder();
5
- const IV_LENGTH = 12;
6
-
7
- export type RelaySide = 'client' | 'host';
8
-
9
- /**
10
- * The encryption of one connection between a paired device and ta serve: AES-256-GCM with a key for
11
- * each direction, derived (HKDF-SHA-256) from the device's key and a nonce of each side, so that every
12
- * connection has keys of its own. The IV is the number of the message, which must arrive in order: a
13
- * message replayed, dropped or reordered by the relay fails to open.
14
- */
15
- export class RelayCipher {
16
- protected sent = 0;
17
- protected received = 0;
18
- protected sealing: Promise<unknown> = Promise.resolve();
19
- protected opening: Promise<unknown> = Promise.resolve();
20
-
21
- protected constructor(
22
- protected readonly sendKey: CryptoKey,
23
- protected readonly receiveKey: CryptoKey,
24
- ) {}
25
-
26
- static async derive(deviceKey: Uint8Array, clientNonce: Uint8Array, hostNonce: Uint8Array, side: RelaySide): Promise<RelayCipher> {
27
- const subtle = globalThis.crypto.subtle;
28
- const secret = await subtle.importKey('raw', deviceKey as BufferSource, 'HKDF', false, ['deriveKey']);
29
- const salt = RelayBytes.concat(clientNonce, hostNonce);
30
- const key = (direction: string) =>
31
- subtle.deriveKey(
32
- { name: 'HKDF', hash: 'SHA-256', salt: salt as BufferSource, info: encoder.encode(`ta-relay/1 ${direction}`) },
33
- secret,
34
- { name: 'AES-GCM', length: 256 },
35
- false,
36
- ['encrypt', 'decrypt'],
37
- );
38
- const [toHost, toClient] = await Promise.all([key('client-to-host'), key('host-to-client')]);
39
- return side === 'client' ? new RelayCipher(toHost, toClient) : new RelayCipher(toClient, toHost);
40
- }
41
-
42
- /** Resolves in the order of the calls, so that sending in `then` sends in order. */
43
- seal(text: string): Promise<string> {
44
- const iv = RelayCipher.iv(this.sent++);
45
- const sealed = this.sealing.then(async () => {
46
- const data = await globalThis.crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv as BufferSource }, this.sendKey, encoder.encode(text));
47
- return RelayBytes.toBase64(new Uint8Array(data));
48
- });
49
- this.sealing = sealed.catch(() => undefined);
50
- return sealed;
51
- }
52
-
53
- /** Rejects what this side's peer did not seal, or not as the next message. */
54
- open(frame: string): Promise<string> {
55
- const iv = RelayCipher.iv(this.received++);
56
- const opened = this.opening.then(async () => {
57
- const data = await globalThis.crypto.subtle.decrypt(
58
- { name: 'AES-GCM', iv: iv as BufferSource },
59
- this.receiveKey,
60
- RelayBytes.fromBase64(frame) as BufferSource,
61
- );
62
- return decoder.decode(data);
63
- });
64
- this.opening = opened.catch(() => undefined);
65
- return opened;
66
- }
67
-
68
- protected static iv(counter: number): Uint8Array {
69
- const iv = new Uint8Array(IV_LENGTH);
70
- new DataView(iv.buffer).setUint32(IV_LENGTH - 8, Math.floor(counter / 2 ** 32));
71
- new DataView(iv.buffer).setUint32(IV_LENGTH - 4, counter >>> 0);
72
- return iv;
73
- }
74
- }
@@ -1,26 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { RelayBytes } from './relay-bytes';
3
- import { RelayPairingUtil } from './relay-pairing';
4
-
5
- const pairing = { relay: 'https://relay.example', host: 'h'.repeat(22), device: 'd'.repeat(22), key: RelayBytes.toBase64(RelayBytes.random(32)), name: 'Mac' };
6
-
7
- describe('RelayPairingUtil', () => {
8
- it('keeps everything but the relay in the fragment, and reads it back', () => {
9
- const link = RelayPairingUtil.link(pairing);
10
- const url = new URL(link);
11
- expect(url.origin + url.pathname + url.search).toBe('https://relay.example/pair');
12
- expect(url.hash).toContain(pairing.key);
13
- expect(RelayPairingUtil.parse(link)).toEqual(pairing);
14
- });
15
-
16
- it('refuses what is not a pairing link', () => {
17
- expect(() => RelayPairingUtil.parse('https://relay.example/pair#v=1')).toThrow();
18
- expect(() => RelayPairingUtil.parse(RelayPairingUtil.link({ ...pairing, key: 'short' }))).toThrow();
19
- expect(() => RelayPairingUtil.parse(RelayPairingUtil.link(pairing).replace('https:', 'javascript:'))).toThrow();
20
- });
21
-
22
- it('turns the relay into its WebSocket address', () => {
23
- expect(RelayPairingUtil.websocketUrl('https://r.example', '/v1/connect/x')).toBe('wss://r.example/v1/connect/x');
24
- expect(RelayPairingUtil.websocketUrl('http://127.0.0.1:9', '/x')).toBe('ws://127.0.0.1:9/x');
25
- });
26
- });
@@ -1,46 +0,0 @@
1
- import { RELAY_ID, RELAY_PAIR_PATH } from './relay-protocol';
2
-
3
- /** What a device needs to reach a ta serve through a relay. The key never goes to the relay. */
4
- export interface RelayPairing {
5
- /** The relay, https or http, without a trailing slash. */
6
- relay: string;
7
- host: string;
8
- device: string;
9
- /** base64url, 32 bytes. */
10
- key: string;
11
- /** What the host is called, for the device to show. */
12
- name?: string;
13
- }
14
-
15
- export namespace RelayPairingUtil {
16
- /** A link to open on the device: all but the relay's address is in the fragment, which is not sent to it. */
17
- export function link(pairing: RelayPairing): string {
18
- const fragment = new URLSearchParams({ v: '1', h: pairing.host, d: pairing.device, k: pairing.key });
19
- if (pairing.name) {
20
- fragment.set('n', pairing.name);
21
- }
22
- return `${pairing.relay}${RELAY_PAIR_PATH}#${fragment}`;
23
- }
24
-
25
- /** Throws on a link that is not one of {@link link}. */
26
- export function parse(link: string): RelayPairing {
27
- const url = new URL(link.trim());
28
- const fragment = new URLSearchParams(url.hash.slice(1));
29
- const [host, device, key] = ['h', 'd', 'k'].map(name => fragment.get(name) ?? '');
30
- if (
31
- !/^https?:$/.test(url.protocol) ||
32
- url.pathname !== RELAY_PAIR_PATH ||
33
- fragment.get('v') !== '1' ||
34
- !RELAY_ID.test(host) ||
35
- !RELAY_ID.test(device) ||
36
- !/^[A-Za-z0-9_-]{43}$/.test(key)
37
- ) {
38
- throw new Error('Not a pairing link of Ta.');
39
- }
40
- return { relay: url.origin, host, device, key, name: fragment.get('n') ?? undefined };
41
- }
42
-
43
- export function websocketUrl(relay: string, path: string): string {
44
- return relay.replace(/^http/, 'ws') + path;
45
- }
46
- }
@@ -1,50 +0,0 @@
1
- /** The relay of Ta, on Cloudflare Workers (apps/ta-relay), when the user names none. */
2
- export const RELAY_DEFAULT_URL = 'https://relay.cellbang.com';
3
-
4
- /** What the relay serves: hosts connect to the first, devices to the second. */
5
- export const RELAY_HOST_PATH = '/v1/host/';
6
- export const RELAY_CONNECT_PATH = '/v1/connect/';
7
- export const RELAY_PAIR_PATH = '/pair';
8
-
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. */
10
- export const RELAY_PAIR_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
11
- <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
12
- <h1>Ta</h1><p>Open this link in the Ta app, or paste it there, to reach your Ta from this device.</p>
13
- <p>打开 Ta 应用,粘贴这个链接,就能从这台设备连到你的 Ta。</p></body>`;
14
-
15
- /** Hosts and devices: what the relay knows of them, and nothing it could read from. */
16
- export const RELAY_ID = /^[A-Za-z0-9_-]{16,64}$/;
17
-
18
- /** Close codes of the relay. */
19
- export enum RelayCloseCode {
20
- /** The host is not connected. */
21
- HOST_OFFLINE = 4404,
22
- /** Another host holds this id, or the secret is wrong. */
23
- REFUSED = 4401,
24
- /** The same host connected again; the older connection goes. */
25
- REPLACED = 4409,
26
- /** The host closed this channel, or refused the device. */
27
- CLOSED_BY_HOST = 4410,
28
- /** Too many devices are connected to this host. */
29
- FULL = 4429,
30
- }
31
-
32
- /**
33
- * Between the relay and a host, which takes the connections of many devices over one WebSocket: each
34
- * device connection is a channel. What a device sends goes to the host as `data`, and back; the relay
35
- * cannot read it (RelayCipher).
36
- */
37
- export type RelayHostMessage = { t: 'open'; ch: string } | { t: 'data'; ch: string; d: string } | { t: 'close'; ch: string };
38
-
39
- /** The first message of a device on a channel, in the clear; after it every message is sealed. */
40
- export interface RelayHello {
41
- t: 'hello';
42
- v: 1;
43
- device: string;
44
- nonce: string;
45
- }
46
-
47
- /** The host's answer: its nonce, and a first sealed message that shows it has the device's key. */
48
- export type RelayWelcome = { t: 'ready'; nonce: string; proof: string } | { t: 'refused'; reason: string };
49
-
50
- export const RELAY_PROOF = 'ta-relay ready';
@@ -1,79 +0,0 @@
1
- import { RelayCloseCode, type RelayHostMessage } from './relay-protocol';
2
-
3
- /** One end of a WebSocket at the relay. */
4
- export interface RelayPeer {
5
- send(text: string): void;
6
- close(code: number, reason: string): void;
7
- }
8
-
9
- /** Where the room finds its connections: kept in memory, or in a Durable Object that sleeps between messages. */
10
- export interface RelayPeers {
11
- host(): RelayPeer | undefined;
12
- client(channel: string): RelayPeer | undefined;
13
- clients(): RelayPeer[];
14
- }
15
-
16
- /** Devices at once on one host. */
17
- export const RELAY_MAX_CLIENTS = 16;
18
-
19
- /**
20
- * The relay's whole job for one host: pass what a device sends to the host on the device's channel, and
21
- * what the host sends on a channel to that device. It holds no state of its own, so that it runs the same
22
- * in `ta relay` and in a Durable Object.
23
- */
24
- export class RelayRoom {
25
- constructor(protected readonly peers: RelayPeers) {}
26
-
27
- /** False when the device cannot stay: the host is away or has too many devices; close it with the code. */
28
- clientOpened(channel: string): RelayCloseCode | undefined {
29
- const host = this.peers.host();
30
- if (!host) {
31
- return RelayCloseCode.HOST_OFFLINE;
32
- }
33
- if (this.peers.clients().length > RELAY_MAX_CLIENTS) {
34
- return RelayCloseCode.FULL;
35
- }
36
- this.toHost(host, { t: 'open', ch: channel });
37
- return undefined;
38
- }
39
-
40
- fromClient(channel: string, text: string): void {
41
- const host = this.peers.host();
42
- if (host) {
43
- this.toHost(host, { t: 'data', ch: channel, d: text });
44
- }
45
- }
46
-
47
- clientClosed(channel: string): void {
48
- const host = this.peers.host();
49
- if (host) {
50
- this.toHost(host, { t: 'close', ch: channel });
51
- }
52
- }
53
-
54
- /** What the host sends that is not a message of the protocol is dropped. */
55
- fromHost(text: string): void {
56
- let message: RelayHostMessage;
57
- try {
58
- message = JSON.parse(text);
59
- } catch {
60
- return;
61
- }
62
- const client = typeof message.ch === 'string' ? this.peers.client(message.ch) : undefined;
63
- if (message.t === 'data' && typeof message.d === 'string') {
64
- client?.send(message.d);
65
- } else if (message.t === 'close') {
66
- client?.close(RelayCloseCode.CLOSED_BY_HOST, 'Closed by the host.');
67
- }
68
- }
69
-
70
- hostClosed(): void {
71
- for (const client of this.peers.clients()) {
72
- client.close(RelayCloseCode.HOST_OFFLINE, 'The host went offline.');
73
- }
74
- }
75
-
76
- protected toHost(host: RelayPeer, message: RelayHostMessage): void {
77
- host.send(JSON.stringify(message));
78
- }
79
- }
@@ -1,106 +0,0 @@
1
- import { RelayBytes } from './relay-bytes';
2
- import { RelayCipher } from './relay-cipher';
3
- import { type RelayPairing, RelayPairingUtil } from './relay-pairing';
4
- import { RELAY_CONNECT_PATH, RELAY_PROOF, type RelayHello, type RelayWelcome } from './relay-protocol';
5
-
6
- const CONNECTING = 0;
7
- const OPEN = 1;
8
- const CLOSING = 2;
9
- const CLOSED = 3;
10
-
11
- /**
12
- * A WebSocket to ta serve through a relay, for a paired device: it says hello, checks that the host has
13
- * the device's key, and then seals and opens every message. It behaves as much like a WebSocket as
14
- * TaConnection needs: `readyState`, `send`, `close` and the four handlers.
15
- */
16
- export class RelaySocket {
17
- static readonly CONNECTING = CONNECTING;
18
- static readonly OPEN = OPEN;
19
- static readonly CLOSING = CLOSING;
20
- static readonly CLOSED = CLOSED;
21
- /** The close code when the host does not know the device, or does not show its key. */
22
- static readonly REFUSED = 4403;
23
-
24
- onopen: (() => void) | null = null;
25
- onmessage: ((message: { data: string }) => void) | null = null;
26
- onclose: ((event: { code: number; reason: string }) => void) | null = null;
27
- onerror: ((event: unknown) => void) | null = null;
28
-
29
- protected state = CONNECTING;
30
- protected code?: number;
31
- protected cipher?: RelayCipher;
32
- protected readonly socket: WebSocket;
33
- protected readonly nonce = RelayBytes.random(16);
34
-
35
- constructor(protected readonly pairing: RelayPairing) {
36
- this.socket = new WebSocket(RelayPairingUtil.websocketUrl(pairing.relay, RELAY_CONNECT_PATH + pairing.host));
37
- this.socket.onopen = () => {
38
- const hello: RelayHello = { t: 'hello', v: 1, device: pairing.device, nonce: RelayBytes.toBase64(this.nonce) };
39
- this.socket.send(JSON.stringify(hello));
40
- };
41
- this.socket.onmessage = message => void this.receive(String(message.data));
42
- this.socket.onerror = event => this.onerror?.(event);
43
- this.socket.onclose = event => this.finish(event.code, event.reason);
44
- }
45
-
46
- get readyState(): number {
47
- return this.state;
48
- }
49
-
50
- /** Why it closed, once it has. */
51
- get closeCode(): number | undefined {
52
- return this.code;
53
- }
54
-
55
- send(text: string): void {
56
- if (this.state !== OPEN || !this.cipher) {
57
- throw new Error('The connection is not open.');
58
- }
59
- this.cipher.seal(text).then(frame => this.socket.readyState === OPEN && this.socket.send(frame));
60
- }
61
-
62
- close(code = 1000, reason = ''): void {
63
- if (this.state === CLOSED) {
64
- return;
65
- }
66
- this.state = CLOSING;
67
- this.socket.close(code, reason);
68
- }
69
-
70
- protected async receive(text: string): Promise<void> {
71
- if (this.cipher) {
72
- try {
73
- const data = await this.cipher.open(text);
74
- this.onmessage?.({ data });
75
- } catch {
76
- this.close(4400, 'A message did not open.');
77
- }
78
- return;
79
- }
80
- try {
81
- const welcome = JSON.parse(text) as RelayWelcome;
82
- if (welcome.t !== 'ready') {
83
- throw new Error(welcome.reason);
84
- }
85
- const cipher = await RelayCipher.derive(RelayBytes.fromBase64(this.pairing.key), this.nonce, RelayBytes.fromBase64(welcome.nonce), 'client');
86
- if ((await cipher.open(welcome.proof)) !== RELAY_PROOF) {
87
- throw new Error('The host did not show the key.');
88
- }
89
- this.cipher = cipher;
90
- this.state = OPEN;
91
- this.onopen?.();
92
- } catch {
93
- // A host without the key is not this device's host, whoever answered.
94
- this.close(RelaySocket.REFUSED, 'The host refused this device.');
95
- }
96
- }
97
-
98
- protected finish(code: number, reason: string): void {
99
- if (this.state === CLOSED) {
100
- return;
101
- }
102
- this.state = CLOSED;
103
- this.code = code;
104
- this.onclose?.({ code, reason });
105
- }
106
- }
package/src/node/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from '../common';
2
- export * from './relay-host';
3
- export * from './relay-server';
4
- export * from './relay-store';