@celljs/ta-relay 4.10.0 → 4.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +13 -1
- package/README.md +13 -1
- package/esm/common/index.d.ts +9 -0
- package/esm/common/index.js +9 -0
- package/esm/common/relay-blobs.d.ts +54 -0
- package/esm/common/relay-blobs.js +153 -0
- package/esm/common/relay-card.d.ts +23 -0
- package/esm/common/relay-card.js +30 -0
- package/esm/common/relay-content.d.ts +104 -0
- package/esm/common/relay-content.js +316 -0
- package/esm/common/relay-conversation.d.ts +59 -0
- package/esm/common/relay-conversation.js +9 -0
- package/esm/common/relay-hub-util.d.ts +91 -0
- package/esm/common/relay-hub-util.js +164 -0
- package/esm/common/relay-hub.d.ts +125 -0
- package/esm/common/relay-hub.js +438 -0
- package/esm/common/relay-hubs.d.ts +271 -0
- package/esm/common/relay-hubs.js +844 -0
- package/esm/common/relay-identity.d.ts +46 -0
- package/esm/common/relay-identity.js +126 -0
- package/esm/common/relay-protocol.d.ts +211 -2
- package/esm/common/relay-protocol.js +53 -0
- package/esm/common/relay-room-chat.d.ts +80 -0
- package/esm/common/relay-room-chat.js +152 -0
- package/esm/common/relay-socket.d.ts +8 -0
- package/esm/common/relay-socket.js +23 -2
- package/esm/guest/guest-i18n.d.ts +47 -0
- package/esm/guest/guest-i18n.js +97 -0
- package/esm/guest/guest-style.d.ts +1 -0
- package/esm/guest/guest-style.js +78 -0
- package/esm/guest/guest.d.ts +1 -0
- package/esm/guest/guest.js +371 -0
- package/esm/node/index.d.ts +2 -0
- package/esm/node/index.js +2 -0
- package/esm/node/relay-host.d.ts +25 -3
- package/esm/node/relay-host.js +115 -4
- package/esm/node/relay-hub-files.d.ts +12 -0
- package/esm/node/relay-hub-files.js +39 -0
- package/esm/node/relay-server.d.ts +46 -1
- package/esm/node/relay-server.js +227 -1
- package/esm/node/relay-store.d.ts +72 -0
- package/esm/node/relay-store.js +123 -2
- package/esm/node/relay-viewer.d.ts +7 -0
- package/esm/node/relay-viewer.js +33 -0
- package/esm/viewer/viewer-i18n.d.ts +56 -0
- package/esm/viewer/viewer-i18n.js +117 -0
- package/esm/viewer/viewer-markdown.d.ts +7 -0
- package/esm/viewer/viewer-markdown.js +198 -0
- package/esm/viewer/viewer-style.d.ts +1 -0
- package/esm/viewer/viewer-style.js +72 -0
- package/esm/viewer/viewer.d.ts +8 -0
- package/esm/viewer/viewer.js +378 -0
- package/lib/common/index.d.ts +9 -0
- package/lib/common/index.js +9 -0
- package/lib/common/relay-blobs.d.ts +55 -0
- package/lib/common/relay-blobs.js +157 -0
- package/lib/common/relay-card.d.ts +24 -0
- package/lib/common/relay-card.js +33 -0
- package/lib/common/relay-content.d.ts +105 -0
- package/lib/common/relay-content.js +320 -0
- package/lib/common/relay-conversation.d.ts +60 -0
- package/lib/common/relay-conversation.js +12 -0
- package/lib/common/relay-hub-util.d.ts +92 -0
- package/lib/common/relay-hub-util.js +167 -0
- package/lib/common/relay-hub.d.ts +126 -0
- package/lib/common/relay-hub.js +442 -0
- package/lib/common/relay-hubs.d.ts +272 -0
- package/lib/common/relay-hubs.js +848 -0
- package/lib/common/relay-identity.d.ts +47 -0
- package/lib/common/relay-identity.js +129 -0
- package/lib/common/relay-protocol.d.ts +211 -2
- package/lib/common/relay-protocol.js +54 -1
- package/lib/common/relay-room-chat.d.ts +81 -0
- package/lib/common/relay-room-chat.js +156 -0
- package/lib/common/relay-socket.d.ts +8 -0
- package/lib/common/relay-socket.js +23 -2
- package/lib/guest/guest-i18n.d.ts +48 -0
- package/lib/guest/guest-i18n.js +100 -0
- package/lib/guest/guest-style.d.ts +2 -0
- package/lib/guest/guest-style.js +81 -0
- package/lib/guest/guest.d.ts +2 -0
- package/lib/guest/guest.js +373 -0
- package/lib/node/index.d.ts +2 -0
- package/lib/node/index.js +2 -0
- package/lib/node/relay-host.d.ts +25 -3
- package/lib/node/relay-host.js +115 -4
- package/lib/node/relay-hub-files.d.ts +13 -0
- package/lib/node/relay-hub-files.js +43 -0
- package/lib/node/relay-server.d.ts +46 -1
- package/lib/node/relay-server.js +226 -0
- package/lib/node/relay-store.d.ts +72 -0
- package/lib/node/relay-store.js +121 -0
- package/lib/node/relay-viewer.d.ts +8 -0
- package/lib/node/relay-viewer.js +32 -0
- package/lib/viewer/viewer-i18n.d.ts +57 -0
- package/lib/viewer/viewer-i18n.js +120 -0
- package/lib/viewer/viewer-markdown.d.ts +8 -0
- package/lib/viewer/viewer-markdown.js +201 -0
- package/lib/viewer/viewer-style.d.ts +2 -0
- package/lib/viewer/viewer-style.js +75 -0
- package/lib/viewer/viewer.d.ts +9 -0
- package/lib/viewer/viewer.js +381 -0
- package/package.json +5 -4
- package/viewer/frame.html +1 -0
- package/viewer/page.html +80 -0
- package/viewer/room.html +87 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { userInfo } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
/** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
|
|
5
|
+
export class RelayHubFiles {
|
|
6
|
+
constructor(agentDir) {
|
|
7
|
+
this.agentDir = agentDir;
|
|
8
|
+
}
|
|
9
|
+
file(name) {
|
|
10
|
+
return join(this.agentDir, `${name}.json`);
|
|
11
|
+
}
|
|
12
|
+
read(name) {
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(readFileSync(this.file(name), 'utf8'));
|
|
15
|
+
}
|
|
16
|
+
catch (_a) {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Written whole, then renamed over the file, readable by the user alone: it holds keys. */
|
|
21
|
+
write(name, value) {
|
|
22
|
+
const file = this.file(name);
|
|
23
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
24
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
25
|
+
writeFileSync(temporary, `${JSON.stringify(value, undefined, 2)}\n`, { mode: 0o600 });
|
|
26
|
+
chmodSync(temporary, 0o600);
|
|
27
|
+
renameSync(temporary, file);
|
|
28
|
+
}
|
|
29
|
+
/** The name of a new identity: the user's on this system. */
|
|
30
|
+
static userName() {
|
|
31
|
+
try {
|
|
32
|
+
return userInfo().username || 'Ta';
|
|
33
|
+
}
|
|
34
|
+
catch (_a) {
|
|
35
|
+
return 'Ta';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=relay-hub-files.js.map
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { type IncomingMessage, type Server } from 'node:http';
|
|
1
|
+
import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
|
2
2
|
import type { Duplex } from 'node:stream';
|
|
3
3
|
import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
4
|
+
import { type RelayBlobStorage, RelayBlobs } from '../common/relay-blobs.js';
|
|
5
|
+
import { RelayHub, type RelayHubStorage, type RelayHubWho } from '../common/relay-hub.js';
|
|
4
6
|
import { RelayRoom } from '../common/relay-room.js';
|
|
5
7
|
export interface RelayServerOptions {
|
|
6
8
|
host?: string;
|
|
@@ -12,6 +14,37 @@ interface Room {
|
|
|
12
14
|
clients: Map<string, WebSocketConnection>;
|
|
13
15
|
relay: RelayRoom;
|
|
14
16
|
}
|
|
17
|
+
/** A copy of content in memory, deleted when it runs out. */
|
|
18
|
+
declare class MemoryBlobStorage implements RelayBlobStorage {
|
|
19
|
+
protected readonly values: Map<string, unknown>;
|
|
20
|
+
protected timer?: ReturnType<typeof setTimeout>;
|
|
21
|
+
get<T>(key: string): Promise<T | undefined>;
|
|
22
|
+
put(key: string, value: unknown): Promise<void>;
|
|
23
|
+
deleteAll(): Promise<void>;
|
|
24
|
+
/** No copy is kept: nothing of it need stay in the relay's memory. */
|
|
25
|
+
get empty(): boolean;
|
|
26
|
+
setAlarm(at: number): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/** A room in memory, as a Durable Object keeps it. */
|
|
29
|
+
declare class MemoryHubStorage implements RelayHubStorage {
|
|
30
|
+
protected readonly values: Map<string, unknown>;
|
|
31
|
+
get<T>(key: string): Promise<T | undefined>;
|
|
32
|
+
put(key: string, value: unknown): Promise<void>;
|
|
33
|
+
delete(key: string): Promise<boolean>;
|
|
34
|
+
list<T>(options: {
|
|
35
|
+
prefix: string;
|
|
36
|
+
}): Promise<Map<string, T>>;
|
|
37
|
+
deleteAll(): Promise<void>;
|
|
38
|
+
/** No room was made, or it was closed. */
|
|
39
|
+
get empty(): boolean;
|
|
40
|
+
}
|
|
41
|
+
interface Hub {
|
|
42
|
+
hub: RelayHub;
|
|
43
|
+
storage: MemoryHubStorage;
|
|
44
|
+
sockets: Map<WebSocketConnection, {
|
|
45
|
+
who?: RelayHubWho;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
15
48
|
/**
|
|
16
49
|
* `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
|
|
17
50
|
* and keeps the hash of each host's secret in memory, for as long as it runs.
|
|
@@ -19,14 +52,26 @@ interface Room {
|
|
|
19
52
|
export declare class RelayServer {
|
|
20
53
|
protected readonly options: RelayServerOptions;
|
|
21
54
|
protected readonly rooms: Map<string, Room>;
|
|
55
|
+
protected readonly blobs: Map<string, {
|
|
56
|
+
blobs: RelayBlobs;
|
|
57
|
+
storage: MemoryBlobStorage;
|
|
58
|
+
pending: number;
|
|
59
|
+
}>;
|
|
60
|
+
protected readonly hubs: Map<string, Hub>;
|
|
22
61
|
protected server?: Server;
|
|
23
62
|
constructor(options?: RelayServerOptions);
|
|
24
63
|
listen(): Promise<string>;
|
|
25
64
|
close(): Promise<void>;
|
|
65
|
+
/** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
|
|
66
|
+
protected blob(id: string, request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
67
|
+
/** The body of a request, or undefined past `max` bytes: the rest is read and dropped. */
|
|
68
|
+
protected static body(request: IncomingMessage, max: number): Promise<Buffer<ArrayBuffer> | undefined>;
|
|
26
69
|
protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void;
|
|
27
70
|
/** The first host to come with an id keeps it, for as long as the relay runs. */
|
|
28
71
|
protected openHost(id: string, secret: string, connection: WebSocketConnection): void;
|
|
29
72
|
protected openClient(id: string, connection: WebSocketConnection): void;
|
|
73
|
+
/** A connection to the hub of a room (RelayHub), kept in memory for as long as the relay runs. */
|
|
74
|
+
protected openHub(id: string, connection: WebSocketConnection): void;
|
|
30
75
|
protected createRoom(id: string, secretHash: string): Room;
|
|
31
76
|
protected static same(a: string, b: string): boolean;
|
|
32
77
|
}
|
package/esm/node/relay-server.js
CHANGED
|
@@ -1,9 +1,71 @@
|
|
|
1
1
|
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { createServer } from 'node:http';
|
|
3
3
|
import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
4
|
-
import {
|
|
4
|
+
import { RelayBlobs } from '../common/relay-blobs.js';
|
|
5
|
+
import { RelayHub } from '../common/relay-hub.js';
|
|
6
|
+
import { RELAY_BLOB_PATH, RELAY_CONNECT_PATH, RELAY_CONTENT_PATH, RELAY_FRAME_HEADER_CSP, RELAY_FRAME_PATH, RELAY_HOST_PATH, RELAY_HUB_PATH, RELAY_ID, RELAY_PAIR_PAGE, RELAY_PAIR_PATH, RELAY_ROOM_PATH, RELAY_SHARE_PAGE, RELAY_SHARE_PATH, RELAY_VIEWER_HEADERS, RelayCloseCode, } from '../common/relay-protocol.js';
|
|
5
7
|
import { RelayRoom } from '../common/relay-room.js';
|
|
8
|
+
import { RelayViewer } from './relay-viewer.js';
|
|
6
9
|
const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
|
|
10
|
+
/** A copy of content in memory, deleted when it runs out. */
|
|
11
|
+
class MemoryBlobStorage {
|
|
12
|
+
constructor() {
|
|
13
|
+
this.values = new Map();
|
|
14
|
+
}
|
|
15
|
+
async get(key) {
|
|
16
|
+
return this.values.get(key);
|
|
17
|
+
}
|
|
18
|
+
async put(key, value) {
|
|
19
|
+
this.values.set(key, value);
|
|
20
|
+
}
|
|
21
|
+
async deleteAll() {
|
|
22
|
+
this.values.clear();
|
|
23
|
+
clearTimeout(this.timer);
|
|
24
|
+
}
|
|
25
|
+
/** No copy is kept: nothing of it need stay in the relay's memory. */
|
|
26
|
+
get empty() {
|
|
27
|
+
return this.values.size === 0;
|
|
28
|
+
}
|
|
29
|
+
async setAlarm(at) {
|
|
30
|
+
var _a, _b;
|
|
31
|
+
clearTimeout(this.timer);
|
|
32
|
+
// Past the 24 days of a timer, it is found run out on the next read.
|
|
33
|
+
this.timer = setTimeout(() => this.values.clear(), Math.min(Math.max(at - Date.now(), 0), 2 ** 31 - 1));
|
|
34
|
+
(_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** A room in memory, as a Durable Object keeps it. */
|
|
38
|
+
class MemoryHubStorage {
|
|
39
|
+
constructor() {
|
|
40
|
+
this.values = new Map();
|
|
41
|
+
}
|
|
42
|
+
async get(key) {
|
|
43
|
+
const value = this.values.get(key);
|
|
44
|
+
return value === undefined ? undefined : structuredClone(value);
|
|
45
|
+
}
|
|
46
|
+
async put(key, value) {
|
|
47
|
+
this.values.set(key, structuredClone(value));
|
|
48
|
+
}
|
|
49
|
+
async delete(key) {
|
|
50
|
+
return this.values.delete(key);
|
|
51
|
+
}
|
|
52
|
+
async list(options) {
|
|
53
|
+
const found = new Map();
|
|
54
|
+
for (const [key, value] of [...this.values].sort(([a], [b]) => a.localeCompare(b))) {
|
|
55
|
+
if (key.startsWith(options.prefix)) {
|
|
56
|
+
found.set(key, structuredClone(value));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return found;
|
|
60
|
+
}
|
|
61
|
+
async deleteAll() {
|
|
62
|
+
this.values.clear();
|
|
63
|
+
}
|
|
64
|
+
/** No room was made, or it was closed. */
|
|
65
|
+
get empty() {
|
|
66
|
+
return this.values.size === 0;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
7
69
|
const peer = (connection) => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
|
|
8
70
|
/**
|
|
9
71
|
* `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
|
|
@@ -13,11 +75,37 @@ export class RelayServer {
|
|
|
13
75
|
constructor(options = {}) {
|
|
14
76
|
this.options = options;
|
|
15
77
|
this.rooms = new Map();
|
|
78
|
+
this.blobs = new Map();
|
|
79
|
+
this.hubs = new Map();
|
|
16
80
|
}
|
|
17
81
|
listen() {
|
|
18
82
|
const server = createServer((request, response) => {
|
|
19
83
|
var _a;
|
|
20
84
|
const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split(/[?#]/)[0];
|
|
85
|
+
if (path.startsWith(RELAY_BLOB_PATH)) {
|
|
86
|
+
this.blob(path.slice(RELAY_BLOB_PATH.length), request, response).catch(() => {
|
|
87
|
+
// A request aborted or that failed: an unhandled rejection would end the relay.
|
|
88
|
+
if (!response.headersSent) {
|
|
89
|
+
response.writeHead(400);
|
|
90
|
+
}
|
|
91
|
+
response.end();
|
|
92
|
+
});
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (path === RELAY_ROOM_PATH) {
|
|
96
|
+
response.writeHead(200, { ...RELAY_VIEWER_HEADERS, 'x-frame-options': 'DENY' });
|
|
97
|
+
response.end(RelayViewer.room());
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (path === RELAY_CONTENT_PATH || path === RELAY_FRAME_PATH) {
|
|
101
|
+
const frame = path === RELAY_FRAME_PATH;
|
|
102
|
+
response.writeHead(200, {
|
|
103
|
+
...RELAY_VIEWER_HEADERS,
|
|
104
|
+
...(frame ? { 'content-security-policy': RELAY_FRAME_HEADER_CSP } : { 'x-frame-options': 'DENY' }),
|
|
105
|
+
});
|
|
106
|
+
response.end(frame ? RelayViewer.frame() : RelayViewer.page());
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
21
109
|
const page = path === RELAY_PAIR_PATH ? RELAY_PAIR_PAGE : path === RELAY_SHARE_PATH ? RELAY_SHARE_PAGE : undefined;
|
|
22
110
|
response.writeHead(200, { 'content-type': page ? 'text/html; charset=utf-8' : 'text/plain' });
|
|
23
111
|
response.end(page !== null && page !== void 0 ? page : 'Ta relay\n');
|
|
@@ -35,6 +123,12 @@ export class RelayServer {
|
|
|
35
123
|
}
|
|
36
124
|
close() {
|
|
37
125
|
var _a;
|
|
126
|
+
for (const { sockets } of this.hubs.values()) {
|
|
127
|
+
for (const connection of sockets.keys()) {
|
|
128
|
+
connection.close(1001, 'The relay is stopping.');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
this.hubs.clear();
|
|
38
132
|
for (const room of this.rooms.values()) {
|
|
39
133
|
(_a = room.host) === null || _a === void 0 ? void 0 : _a.close(1001, 'The relay is stopping.');
|
|
40
134
|
for (const client of room.clients.values()) {
|
|
@@ -44,6 +138,70 @@ export class RelayServer {
|
|
|
44
138
|
this.rooms.clear();
|
|
45
139
|
return new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
|
|
46
140
|
}
|
|
141
|
+
/** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
|
|
142
|
+
async blob(id, request, response) {
|
|
143
|
+
var _a;
|
|
144
|
+
if (!RELAY_ID.test(id)) {
|
|
145
|
+
response.writeHead(404).end();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const read = await RelayServer.body(request, RelayBlobs.MAX_BYTES);
|
|
149
|
+
if (!read) {
|
|
150
|
+
// Refused before it is all in memory, whatever its content-length said.
|
|
151
|
+
response.writeHead(413, { connection: 'close' }).end('Too large.\n');
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
// Kept only while it holds a copy: requests for ids of no copy leave nothing behind.
|
|
155
|
+
let copy = this.blobs.get(id);
|
|
156
|
+
if (!copy) {
|
|
157
|
+
const storage = new MemoryBlobStorage();
|
|
158
|
+
copy = { blobs: new RelayBlobs(storage), storage, pending: 0 };
|
|
159
|
+
this.blobs.set(id, copy);
|
|
160
|
+
}
|
|
161
|
+
const headers = new Headers();
|
|
162
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
163
|
+
if (typeof value === 'string') {
|
|
164
|
+
headers.set(name, value);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const method = (_a = request.method) !== null && _a !== void 0 ? _a : 'GET';
|
|
168
|
+
const body = read.length && method !== 'GET' && method !== 'HEAD' ? read : undefined;
|
|
169
|
+
copy.pending++;
|
|
170
|
+
let answer;
|
|
171
|
+
try {
|
|
172
|
+
answer = await copy.blobs.handle(new Request(`http://relay${request.url}`, { method, headers, body }));
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
copy.pending--;
|
|
176
|
+
if (copy.pending === 0 && copy.storage.empty && this.blobs.get(id) === copy) {
|
|
177
|
+
this.blobs.delete(id);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
response.writeHead(answer.status, Object.fromEntries(answer.headers));
|
|
181
|
+
response.end(Buffer.from(await answer.arrayBuffer()));
|
|
182
|
+
}
|
|
183
|
+
/** The body of a request, or undefined past `max` bytes: the rest is read and dropped. */
|
|
184
|
+
static body(request, max) {
|
|
185
|
+
return new Promise((resolve, reject) => {
|
|
186
|
+
const chunks = [];
|
|
187
|
+
let size = 0;
|
|
188
|
+
request.on('data', (chunk) => {
|
|
189
|
+
if (size < 0) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
size += chunk.length;
|
|
193
|
+
if (size > max) {
|
|
194
|
+
size = -1;
|
|
195
|
+
chunks.length = 0;
|
|
196
|
+
resolve(undefined);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
chunks.push(chunk);
|
|
200
|
+
});
|
|
201
|
+
request.on('end', () => size >= 0 && resolve(Buffer.concat(chunks)));
|
|
202
|
+
request.on('error', reject);
|
|
203
|
+
});
|
|
204
|
+
}
|
|
47
205
|
upgrade(request, socket, head) {
|
|
48
206
|
var _a, _b;
|
|
49
207
|
const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://relay');
|
|
@@ -52,6 +210,15 @@ export class RelayServer {
|
|
|
52
210
|
WebSocketConnection.refuse(socket, checked.status, checked.message);
|
|
53
211
|
return;
|
|
54
212
|
}
|
|
213
|
+
if (url.pathname.startsWith(RELAY_HUB_PATH)) {
|
|
214
|
+
const id = url.pathname.slice(RELAY_HUB_PATH.length);
|
|
215
|
+
if (!RELAY_ID.test(id)) {
|
|
216
|
+
WebSocketConnection.refuse(socket, 404, 'Not found.');
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
this.openHub(id, WebSocketConnection.open(socket, checked.key, head, WEBSOCKET));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
55
222
|
const [path, id] = url.pathname.startsWith(RELAY_HOST_PATH)
|
|
56
223
|
? [RELAY_HOST_PATH, url.pathname.slice(RELAY_HOST_PATH.length)]
|
|
57
224
|
: [RELAY_CONNECT_PATH, url.pathname.slice(RELAY_CONNECT_PATH.length)];
|
|
@@ -107,6 +274,65 @@ export class RelayServer {
|
|
|
107
274
|
}
|
|
108
275
|
});
|
|
109
276
|
}
|
|
277
|
+
/** A connection to the hub of a room (RelayHub), kept in memory for as long as the relay runs. */
|
|
278
|
+
openHub(id, connection) {
|
|
279
|
+
let hub = this.hubs.get(id);
|
|
280
|
+
if (!hub) {
|
|
281
|
+
const sockets = new Map();
|
|
282
|
+
const socketOf = (other) => {
|
|
283
|
+
var _a;
|
|
284
|
+
const state = (_a = sockets.get(other)) !== null && _a !== void 0 ? _a : {};
|
|
285
|
+
return {
|
|
286
|
+
key: other,
|
|
287
|
+
get who() {
|
|
288
|
+
return state.who;
|
|
289
|
+
},
|
|
290
|
+
set who(who) {
|
|
291
|
+
state.who = who;
|
|
292
|
+
},
|
|
293
|
+
send: text => other.send(text),
|
|
294
|
+
close: (code, reason) => other.close(code, reason),
|
|
295
|
+
};
|
|
296
|
+
};
|
|
297
|
+
const storage = new MemoryHubStorage();
|
|
298
|
+
hub = { sockets, storage, hub: new RelayHub(storage, () => [...sockets.keys()].map(socketOf)) };
|
|
299
|
+
this.hubs.set(id, hub);
|
|
300
|
+
}
|
|
301
|
+
const current = hub;
|
|
302
|
+
const { sockets, hub: relay } = current;
|
|
303
|
+
sockets.set(connection, {});
|
|
304
|
+
let chain = Promise.resolve();
|
|
305
|
+
const socket = {
|
|
306
|
+
key: connection,
|
|
307
|
+
get who() {
|
|
308
|
+
var _a;
|
|
309
|
+
return (_a = sockets.get(connection)) === null || _a === void 0 ? void 0 : _a.who;
|
|
310
|
+
},
|
|
311
|
+
set who(who) {
|
|
312
|
+
const state = sockets.get(connection);
|
|
313
|
+
if (state) {
|
|
314
|
+
state.who = who;
|
|
315
|
+
}
|
|
316
|
+
},
|
|
317
|
+
send: text => connection.send(text),
|
|
318
|
+
close: (code, reason) => connection.close(code, reason),
|
|
319
|
+
};
|
|
320
|
+
connection.onMessage(text => {
|
|
321
|
+
chain = chain.then(() => relay.receive(socket, text)).catch(() => undefined);
|
|
322
|
+
});
|
|
323
|
+
connection.onClose(() => {
|
|
324
|
+
void chain.then(() => {
|
|
325
|
+
if (sockets.has(connection)) {
|
|
326
|
+
relay.closed(socket);
|
|
327
|
+
sockets.delete(connection);
|
|
328
|
+
}
|
|
329
|
+
// Connections to ids of no room (refused, or the room closed) leave nothing behind.
|
|
330
|
+
if (sockets.size === 0 && current.storage.empty && this.hubs.get(id) === current) {
|
|
331
|
+
this.hubs.delete(id);
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
}
|
|
110
336
|
createRoom(id, secretHash) {
|
|
111
337
|
const room = {
|
|
112
338
|
secretHash,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type RelayContentAccess, type RelayContentHeader, type RelayContentLink } from '../common/relay-content.js';
|
|
2
|
+
import { type RelayIdentity, type RelayPublicIdentity } from '../common/relay-identity.js';
|
|
1
3
|
import type { RelayPairing } from '../common/relay-pairing.js';
|
|
2
4
|
import type { RelayShareLink } from '../common/relay-share.js';
|
|
3
5
|
export interface RelayDevice {
|
|
@@ -18,6 +20,47 @@ export interface RelayShare {
|
|
|
18
20
|
createdAt: number;
|
|
19
21
|
expiresAt: number;
|
|
20
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* Content shared by a link (docs/design/ta-link.md): a conversation, a page, a file, as it was when shared. Its
|
|
25
|
+
* bytes are in `shares/<id>` of the agent directory; this ta serve hands them to whoever opens the link.
|
|
26
|
+
*/
|
|
27
|
+
export interface RelayContentShare extends RelayContentHeader {
|
|
28
|
+
id: string;
|
|
29
|
+
access: RelayContentAccess;
|
|
30
|
+
/** base64url, 32 bytes: what the content is sealed with (with a password, derived from it and the key of the link). */
|
|
31
|
+
key: string;
|
|
32
|
+
/** base64url, 32 bytes: the key of the link, for the link again; none for `self`. */
|
|
33
|
+
linkKey?: string;
|
|
34
|
+
size: number;
|
|
35
|
+
/** None: until stopped. */
|
|
36
|
+
expiresAt?: number;
|
|
37
|
+
/** A copy kept on the relay, sealed: the token that writes and deletes it there, and when it runs out. */
|
|
38
|
+
offline?: {
|
|
39
|
+
token: string;
|
|
40
|
+
expiresAt: number;
|
|
41
|
+
};
|
|
42
|
+
/** For `people`: the Ta friends it is shared with, each with the key made with it (RelayContentUtil.peopleKey). */
|
|
43
|
+
people?: {
|
|
44
|
+
id: string;
|
|
45
|
+
name: string;
|
|
46
|
+
key: string;
|
|
47
|
+
}[];
|
|
48
|
+
/** For `people`: this Ta's identity, which the link names. */
|
|
49
|
+
owner?: string;
|
|
50
|
+
}
|
|
51
|
+
/** What a share of content is made of (RelayStore.addContent). */
|
|
52
|
+
export interface RelayContentInput extends RelayContentHeader {
|
|
53
|
+
data: Uint8Array;
|
|
54
|
+
access: RelayContentAccess;
|
|
55
|
+
/** For `password`. */
|
|
56
|
+
password?: string;
|
|
57
|
+
/** None or 0: until stopped (not with `offline`, which is RELAY_BLOB_MAX_DAYS at most). */
|
|
58
|
+
days?: number;
|
|
59
|
+
offline?: boolean;
|
|
60
|
+
/** For `people`: the Ta friends it is shared with, and this Ta's identity. */
|
|
61
|
+
people?: RelayPublicIdentity[];
|
|
62
|
+
identity?: RelayIdentity;
|
|
63
|
+
}
|
|
21
64
|
/** relay.json in the agent directory. Without devices, ta serve does not connect to the relay. */
|
|
22
65
|
export interface RelayConfig {
|
|
23
66
|
/** The relay, without a trailing slash. */
|
|
@@ -30,6 +73,8 @@ export interface RelayConfig {
|
|
|
30
73
|
devices: RelayDevice[];
|
|
31
74
|
/** Packages handed on; those past their time are dropped when it is written. */
|
|
32
75
|
shares?: RelayShare[];
|
|
76
|
+
/** Content shared; those past their time are dropped, with their bytes, when it is written. */
|
|
77
|
+
contents?: RelayContentShare[];
|
|
33
78
|
}
|
|
34
79
|
/** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
|
|
35
80
|
export declare class RelayStore {
|
|
@@ -43,6 +88,33 @@ export declare class RelayStore {
|
|
|
43
88
|
share(shareId: string, now?: number): RelayShare | undefined;
|
|
44
89
|
/** The shares still on. */
|
|
45
90
|
shares(now?: number): RelayShare[];
|
|
91
|
+
/** Content shared, still on, by its id. */
|
|
92
|
+
content(contentId: string, now?: number): RelayContentShare | undefined;
|
|
93
|
+
/** Content shared, still on, the latest first. */
|
|
94
|
+
contents(now?: number): RelayContentShare[];
|
|
95
|
+
/** The bytes of content shared; undefined when they are gone. */
|
|
96
|
+
contentData(content: RelayContentShare): Uint8Array | undefined;
|
|
97
|
+
/**
|
|
98
|
+
* Shares content: its bytes kept here, a link for it on the relay of the devices (the default one when there is
|
|
99
|
+
* none), which this ta serve then connects to for any but `self`.
|
|
100
|
+
*/
|
|
101
|
+
addContent(input: RelayContentInput, now?: number): Promise<{
|
|
102
|
+
content: RelayContentShare;
|
|
103
|
+
link: RelayContentLink;
|
|
104
|
+
}>;
|
|
105
|
+
/** The link of content shared here. */
|
|
106
|
+
contentLink(content: RelayContentShare, config?: Pick<RelayConfig, 'url' | 'host'>): RelayContentLink;
|
|
107
|
+
/** Stops a share of content: its link no longer works, its bytes are deleted. The share, if there was one. */
|
|
108
|
+
removeContent(contentId: string): RelayContentShare | undefined;
|
|
109
|
+
/** The key of each Ta friend content is shared with, made with this Ta's identity for this share. */
|
|
110
|
+
protected static people(input: RelayContentInput, id: string): Promise<{
|
|
111
|
+
id: string;
|
|
112
|
+
name: string;
|
|
113
|
+
key: string;
|
|
114
|
+
}[]>;
|
|
115
|
+
protected contentFile(contentId: string): string;
|
|
116
|
+
protected static live(content: RelayContentShare, now: number): boolean;
|
|
117
|
+
protected static id(): string;
|
|
46
118
|
/**
|
|
47
119
|
* A link of the package in `root`: the one of before while it lasts, else a new one for RELAY_SHARE_DAYS,
|
|
48
120
|
* on the relay of the devices (the default one when there is none), which this ta serve then connects to.
|
package/esm/node/relay-store.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { hostname } from 'node:os';
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
|
-
import {
|
|
5
|
+
import { RelayBytes } from '../common/relay-bytes.js';
|
|
6
|
+
import { RelayContentUtil } from '../common/relay-content.js';
|
|
7
|
+
import { RelayIdentityUtil } from '../common/relay-identity.js';
|
|
8
|
+
import { RELAY_BLOB_MAX_DAYS, RELAY_DEFAULT_URL, RELAY_SHARE_DAYS } from '../common/relay-protocol.js';
|
|
6
9
|
const id = () => randomBytes(16).toString('base64url');
|
|
7
10
|
/** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
|
|
8
11
|
export class RelayStore {
|
|
@@ -20,6 +23,7 @@ export class RelayStore {
|
|
|
20
23
|
host: config.host,
|
|
21
24
|
devices: Array.isArray(config.devices) ? config.devices : [],
|
|
22
25
|
shares: Array.isArray(config.shares) ? config.shares : [],
|
|
26
|
+
contents: Array.isArray(config.contents) ? config.contents : [],
|
|
23
27
|
};
|
|
24
28
|
}
|
|
25
29
|
catch (_a) {
|
|
@@ -39,6 +43,114 @@ export class RelayStore {
|
|
|
39
43
|
var _a;
|
|
40
44
|
return ((_a = this.read().shares) !== null && _a !== void 0 ? _a : []).filter(share => share.expiresAt > now);
|
|
41
45
|
}
|
|
46
|
+
/** Content shared, still on, by its id. */
|
|
47
|
+
content(contentId, now = Date.now()) {
|
|
48
|
+
return this.contents(now).find(content => content.id === contentId);
|
|
49
|
+
}
|
|
50
|
+
/** Content shared, still on, the latest first. */
|
|
51
|
+
contents(now = Date.now()) {
|
|
52
|
+
var _a;
|
|
53
|
+
return ((_a = this.read().contents) !== null && _a !== void 0 ? _a : []).filter(content => RelayStore.live(content, now)).sort((a, b) => b.createdAt - a.createdAt);
|
|
54
|
+
}
|
|
55
|
+
/** The bytes of content shared; undefined when they are gone. */
|
|
56
|
+
contentData(content) {
|
|
57
|
+
try {
|
|
58
|
+
return new Uint8Array(readFileSync(this.contentFile(content.id)));
|
|
59
|
+
}
|
|
60
|
+
catch (_a) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Shares content: its bytes kept here, a link for it on the relay of the devices (the default one when there is
|
|
66
|
+
* none), which this ta serve then connects to for any but `self`.
|
|
67
|
+
*/
|
|
68
|
+
async addContent(input, now = Date.now()) {
|
|
69
|
+
var _a, _b, _c;
|
|
70
|
+
const linkKey = randomBytes(32);
|
|
71
|
+
const id = randomBytes(16).toString('base64url');
|
|
72
|
+
const password = input.access === 'password' ? input.password : undefined;
|
|
73
|
+
if (input.access === 'password' && !password) {
|
|
74
|
+
throw new Error('A share with a password needs the password.');
|
|
75
|
+
}
|
|
76
|
+
const people = input.access === 'people' ? await RelayStore.people(input, id) : undefined;
|
|
77
|
+
const key = await RelayContentUtil.contentKey(new Uint8Array(linkKey), id, password);
|
|
78
|
+
const days = input.offline ? Math.min(input.days || RELAY_BLOB_MAX_DAYS, RELAY_BLOB_MAX_DAYS) : input.days;
|
|
79
|
+
const expiresAt = days ? now + days * 24 * 60 * 60 * 1000 : undefined;
|
|
80
|
+
const offline = input.offline && input.access !== 'self' && input.access !== 'people';
|
|
81
|
+
const content = {
|
|
82
|
+
id,
|
|
83
|
+
kind: input.kind,
|
|
84
|
+
title: input.title,
|
|
85
|
+
createdAt: input.createdAt,
|
|
86
|
+
...(input.type ? { type: input.type } : {}),
|
|
87
|
+
access: input.access,
|
|
88
|
+
key: RelayBytes.toBase64(key),
|
|
89
|
+
...(input.access === 'self' || people ? {} : { linkKey: linkKey.toString('base64url') }),
|
|
90
|
+
...(people && input.identity ? { people, owner: input.identity.id } : {}),
|
|
91
|
+
size: input.data.length,
|
|
92
|
+
...(expiresAt ? { expiresAt } : {}),
|
|
93
|
+
...(offline && expiresAt ? { offline: { token: randomBytes(32).toString('base64url'), expiresAt } } : {}),
|
|
94
|
+
};
|
|
95
|
+
mkdirSync(dirname(this.contentFile(id)), { recursive: true, mode: 0o700 });
|
|
96
|
+
writeFileSync(this.contentFile(id), input.data, { mode: 0o600 });
|
|
97
|
+
const before = this.read();
|
|
98
|
+
const url = (_a = before.url) !== null && _a !== void 0 ? _a : RELAY_DEFAULT_URL;
|
|
99
|
+
const host = (_b = before.host) !== null && _b !== void 0 ? _b : { id: RelayStore.id(), secret: randomBytes(32).toString('base64url') };
|
|
100
|
+
this.write({ ...before, url, host, contents: [...((_c = before.contents) !== null && _c !== void 0 ? _c : []), content] });
|
|
101
|
+
return { content, link: this.contentLink(content, { url, host }) };
|
|
102
|
+
}
|
|
103
|
+
/** The link of content shared here. */
|
|
104
|
+
contentLink(content, config = this.read()) {
|
|
105
|
+
var _a;
|
|
106
|
+
var _b, _c;
|
|
107
|
+
return {
|
|
108
|
+
relay: (_b = config.url) !== null && _b !== void 0 ? _b : RELAY_DEFAULT_URL,
|
|
109
|
+
host: (_c = (_a = config.host) === null || _a === void 0 ? void 0 : _a.id) !== null && _c !== void 0 ? _c : '',
|
|
110
|
+
share: content.id,
|
|
111
|
+
key: content.linkKey,
|
|
112
|
+
access: content.access,
|
|
113
|
+
...(content.owner ? { owner: content.owner } : {}),
|
|
114
|
+
offline: !!content.offline,
|
|
115
|
+
kind: content.kind,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** Stops a share of content: its link no longer works, its bytes are deleted. The share, if there was one. */
|
|
119
|
+
removeContent(contentId) {
|
|
120
|
+
var _a, _b;
|
|
121
|
+
const config = this.read();
|
|
122
|
+
const content = (_a = config.contents) === null || _a === void 0 ? void 0 : _a.find(candidate => candidate.id === contentId);
|
|
123
|
+
if (!content) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
this.write({ ...config, contents: (_b = config.contents) === null || _b === void 0 ? void 0 : _b.filter(candidate => candidate.id !== contentId) });
|
|
127
|
+
rmSync(this.contentFile(contentId), { force: true });
|
|
128
|
+
return content;
|
|
129
|
+
}
|
|
130
|
+
/** The key of each Ta friend content is shared with, made with this Ta's identity for this share. */
|
|
131
|
+
static async people(input, id) {
|
|
132
|
+
var _a;
|
|
133
|
+
const { identity } = input;
|
|
134
|
+
const people = (_a = input.people) !== null && _a !== void 0 ? _a : [];
|
|
135
|
+
if (!identity || people.length === 0) {
|
|
136
|
+
throw new Error('A share with Ta friends needs them, and this Ta.');
|
|
137
|
+
}
|
|
138
|
+
return Promise.all(people.map(async (person) => {
|
|
139
|
+
if (!(await RelayIdentityUtil.check(person))) {
|
|
140
|
+
throw new Error(`${person.name} is not a Ta friend whose keys check.`);
|
|
141
|
+
}
|
|
142
|
+
return { id: person.id, name: person.name, key: RelayBytes.toBase64(await RelayContentUtil.peopleKey(identity, person.box, id)) };
|
|
143
|
+
}));
|
|
144
|
+
}
|
|
145
|
+
contentFile(contentId) {
|
|
146
|
+
return join(this.agentDir, 'shares', contentId);
|
|
147
|
+
}
|
|
148
|
+
static live(content, now) {
|
|
149
|
+
return content.expiresAt === undefined || content.expiresAt > now;
|
|
150
|
+
}
|
|
151
|
+
static id() {
|
|
152
|
+
return id();
|
|
153
|
+
}
|
|
42
154
|
/**
|
|
43
155
|
* A link of the package in `root`: the one of before while it lasts, else a new one for RELAY_SHARE_DAYS,
|
|
44
156
|
* on the relay of the devices (the default one when there is none), which this ta serve then connects to.
|
|
@@ -100,6 +212,15 @@ export class RelayStore {
|
|
|
100
212
|
return createHash('sha256').update(secret).digest('base64url');
|
|
101
213
|
}
|
|
102
214
|
write(config) {
|
|
215
|
+
var _a;
|
|
216
|
+
var _b;
|
|
217
|
+
const now = Date.now();
|
|
218
|
+
for (const content of (_b = config.contents) !== null && _b !== void 0 ? _b : []) {
|
|
219
|
+
if (!RelayStore.live(content, now)) {
|
|
220
|
+
rmSync(this.contentFile(content.id), { force: true });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
config = { ...config, contents: (_a = config.contents) === null || _a === void 0 ? void 0 : _a.filter(content => RelayStore.live(content, now)) };
|
|
103
224
|
mkdirSync(dirname(this.file), { recursive: true });
|
|
104
225
|
const temporary = `${this.file}.${process.pid}.tmp`;
|
|
105
226
|
writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** The viewer of the relay as `ta relay` serves it: the pages scripts/build-viewer.ts built, next to lib/. */
|
|
2
|
+
export declare namespace RelayViewer {
|
|
3
|
+
/** The page of guests of rooms: a link that invites, opened in a browser. */
|
|
4
|
+
function room(): string;
|
|
5
|
+
function page(): string;
|
|
6
|
+
function frame(): string;
|
|
7
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { fileURLToPath as __cellFileURLToPath } from "node:url";
|
|
2
|
+
import { dirname as __cellDirname } from "node:path";
|
|
3
|
+
const __filename = __cellFileURLToPath(import.meta.url);
|
|
4
|
+
const __dirname = __cellDirname(__filename);
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
/** The viewer of the relay as `ta relay` serves it: the pages scripts/build-viewer.ts built, next to lib/. */
|
|
8
|
+
export var RelayViewer;
|
|
9
|
+
(function (RelayViewer) {
|
|
10
|
+
let pages;
|
|
11
|
+
function read() {
|
|
12
|
+
if (!pages) {
|
|
13
|
+
const dir = join(__dirname, '../../viewer');
|
|
14
|
+
const file = (name) => readFileSync(join(dir, name), 'utf8');
|
|
15
|
+
pages = { page: file('page.html'), frame: file('frame.html'), room: file('room.html') };
|
|
16
|
+
}
|
|
17
|
+
return pages;
|
|
18
|
+
}
|
|
19
|
+
/** The page of guests of rooms: a link that invites, opened in a browser. */
|
|
20
|
+
function room() {
|
|
21
|
+
return read().room;
|
|
22
|
+
}
|
|
23
|
+
RelayViewer.room = room;
|
|
24
|
+
function page() {
|
|
25
|
+
return read().page;
|
|
26
|
+
}
|
|
27
|
+
RelayViewer.page = page;
|
|
28
|
+
function frame() {
|
|
29
|
+
return read().frame;
|
|
30
|
+
}
|
|
31
|
+
RelayViewer.frame = frame;
|
|
32
|
+
})(RelayViewer || (RelayViewer = {}));
|
|
33
|
+
//# sourceMappingURL=relay-viewer.js.map
|