@byoky/relay 0.4.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 byoky contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/server.js ADDED
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ import { WebSocketServer, WebSocket } from "ws";
3
+ import { timingSafeEqual } from "node:crypto";
4
+ const PORT = parseInt(process.env.PORT || "8787", 10);
5
+ const IDLE_TIMEOUT_MS = 5 * 60 * 1000;
6
+ const rooms = new Map();
7
+ const authAttempts = new Map();
8
+ const AUTH_RATE_LIMIT = 5;
9
+ const AUTH_RATE_WINDOW = 60_000;
10
+ function send(ws, data) {
11
+ if (ws.readyState === WebSocket.OPEN) {
12
+ ws.send(JSON.stringify(data));
13
+ }
14
+ }
15
+ function touchRoom(room) {
16
+ room.lastActivity = Date.now();
17
+ }
18
+ function cleanupIdleRooms() {
19
+ const now = Date.now();
20
+ for (const [roomId, room] of rooms) {
21
+ if (now - room.lastActivity > IDLE_TIMEOUT_MS) {
22
+ if (room.sender?.readyState === WebSocket.OPEN)
23
+ room.sender.close();
24
+ if (room.recipient?.readyState === WebSocket.OPEN)
25
+ room.recipient.close();
26
+ rooms.delete(roomId);
27
+ console.log(`[cleanup] removed idle room ${roomId.slice(0, 8)}...`);
28
+ }
29
+ }
30
+ }
31
+ const cleanupInterval = setInterval(cleanupIdleRooms, 60_000);
32
+ const wss = new WebSocketServer({ port: PORT, maxPayload: 1 * 1024 * 1024 }, () => {
33
+ console.log(`relay listening on port ${PORT}`);
34
+ });
35
+ wss.on("connection", (ws) => {
36
+ let authedRoomId = null;
37
+ let authedRole = null;
38
+ console.log("[connect] new connection");
39
+ ws.on("message", (raw) => {
40
+ let msg;
41
+ try {
42
+ msg = JSON.parse(String(raw));
43
+ }
44
+ catch {
45
+ return;
46
+ }
47
+ if (!authedRoomId) {
48
+ if (msg.type !== "relay:auth")
49
+ return;
50
+ const { roomId, authToken, role } = msg;
51
+ if (typeof roomId !== "string" ||
52
+ typeof authToken !== "string" ||
53
+ (role !== "sender" && role !== "recipient")) {
54
+ send(ws, { type: "relay:auth:result", success: false, error: "invalid auth payload" });
55
+ return;
56
+ }
57
+ // Rate limit auth attempts per room
58
+ const now = Date.now();
59
+ const attempts = (authAttempts.get(roomId) ?? []).filter((t) => now - t < AUTH_RATE_WINDOW);
60
+ if (attempts.length >= AUTH_RATE_LIMIT) {
61
+ send(ws, { type: "relay:auth:result", success: false, error: "too many auth attempts" });
62
+ return;
63
+ }
64
+ attempts.push(now);
65
+ authAttempts.set(roomId, attempts);
66
+ let room = rooms.get(roomId);
67
+ if (room) {
68
+ // Constant-time comparison — pad to equal length so the length
69
+ // check itself does not leak timing information.
70
+ const expected = Buffer.from(room.authToken);
71
+ const provided = Buffer.from(authToken);
72
+ const maxLen = Math.max(expected.length, provided.length);
73
+ const a = Buffer.alloc(maxLen);
74
+ const b = Buffer.alloc(maxLen);
75
+ expected.copy(a);
76
+ provided.copy(b);
77
+ if (!timingSafeEqual(a, b) || expected.length !== provided.length) {
78
+ send(ws, { type: "relay:auth:result", success: false, error: "auth token mismatch" });
79
+ return;
80
+ }
81
+ if (room[role] && room[role].readyState === WebSocket.OPEN) {
82
+ send(ws, { type: "relay:auth:result", success: false, error: `${role} already connected` });
83
+ return;
84
+ }
85
+ }
86
+ else {
87
+ room = { authToken, lastActivity: Date.now() };
88
+ rooms.set(roomId, room);
89
+ }
90
+ room[role] = ws;
91
+ touchRoom(room);
92
+ authedRoomId = roomId;
93
+ authedRole = role;
94
+ const peer = role === "sender" ? room.recipient : room.sender;
95
+ const peerOnline = !!peer && peer.readyState === WebSocket.OPEN;
96
+ send(ws, { type: "relay:auth:result", success: true, peerOnline });
97
+ console.log(`[auth] ${role} joined room ${roomId.slice(0, 8)}... (peer ${peerOnline ? "online" : "offline"})`);
98
+ if (peerOnline) {
99
+ send(peer, { type: "relay:peer:status", online: true });
100
+ }
101
+ return;
102
+ }
103
+ const room = rooms.get(authedRoomId);
104
+ if (!room)
105
+ return;
106
+ touchRoom(room);
107
+ if (authedRole === "recipient" && (msg.type === "relay:request" || msg.type === "relay:pair:ack")) {
108
+ if (room.sender && room.sender.readyState === WebSocket.OPEN) {
109
+ room.sender.send(String(raw));
110
+ }
111
+ return;
112
+ }
113
+ if (authedRole === "sender") {
114
+ if (msg.type === "relay:response:meta" ||
115
+ msg.type === "relay:response:chunk" ||
116
+ msg.type === "relay:response:done" ||
117
+ msg.type === "relay:response:error" ||
118
+ msg.type === "relay:usage" ||
119
+ msg.type === "relay:pair:hello") {
120
+ if (room.recipient && room.recipient.readyState === WebSocket.OPEN) {
121
+ room.recipient.send(String(raw));
122
+ }
123
+ return;
124
+ }
125
+ }
126
+ });
127
+ ws.on("close", () => {
128
+ if (!authedRoomId || !authedRole) {
129
+ console.log("[disconnect] unauthenticated connection closed");
130
+ return;
131
+ }
132
+ console.log(`[disconnect] ${authedRole} left room ${authedRoomId.slice(0, 8)}...`);
133
+ const room = rooms.get(authedRoomId);
134
+ if (!room)
135
+ return;
136
+ room[authedRole] = undefined;
137
+ const peer = authedRole === "sender" ? room.recipient : room.sender;
138
+ if (peer && peer.readyState === WebSocket.OPEN) {
139
+ send(peer, { type: "relay:peer:status", online: false });
140
+ }
141
+ if (!room.sender && !room.recipient) {
142
+ rooms.delete(authedRoomId);
143
+ console.log(`[cleanup] removed empty room ${authedRoomId.slice(0, 8)}...`);
144
+ }
145
+ });
146
+ ws.on("error", (err) => {
147
+ console.error("[error]", err.message);
148
+ });
149
+ });
150
+ process.on("SIGINT", () => {
151
+ console.log("shutting down...");
152
+ clearInterval(cleanupInterval);
153
+ wss.close();
154
+ process.exit(0);
155
+ });
156
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAS9C,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,MAAM,EAAE,EAAE,CAAC,CAAC;AACtD,MAAM,eAAe,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEtC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAgB,CAAC;AACtC,MAAM,YAAY,GAAG,IAAI,GAAG,EAAoB,CAAC;AACjD,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,SAAS,IAAI,CAAC,EAAa,EAAE,IAAa;IACxC,IAAI,EAAE,CAAC,UAAU,KAAK,SAAS,CAAC,IAAI,EAA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": "dist/server.js",
7
+ "bin": {
8
+ "byoky-relay": "dist/server.js"
9
+ },
10
+ "dependencies": {
11
+ "ws": "^8.16.0"
12
+ },
13
+ "devDependencies": {
14
+ "typescript": "^5.4.0",
15
+ "tsx": "^4.7.0",
16
+ "@types/ws": "^8.5.10"
17
+ },
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "start": "node dist/server.js",
21
+ "dev": "tsx src/server.ts"
22
+ }
23
+ }
package/src/server.ts ADDED
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { WebSocketServer, WebSocket } from "ws";
4
+ import { timingSafeEqual } from "node:crypto";
5
+
6
+ interface Room {
7
+ sender?: WebSocket;
8
+ recipient?: WebSocket;
9
+ authToken: string;
10
+ lastActivity: number;
11
+ }
12
+
13
+ const PORT = parseInt(process.env.PORT || "8787", 10);
14
+ const IDLE_TIMEOUT_MS = 5 * 60 * 1000;
15
+
16
+ const rooms = new Map<string, Room>();
17
+ const authAttempts = new Map<string, number[]>();
18
+ const AUTH_RATE_LIMIT = 5;
19
+ const AUTH_RATE_WINDOW = 60_000;
20
+
21
+ function send(ws: WebSocket, data: unknown): void {
22
+ if (ws.readyState === WebSocket.OPEN) {
23
+ ws.send(JSON.stringify(data));
24
+ }
25
+ }
26
+
27
+ function touchRoom(room: Room): void {
28
+ room.lastActivity = Date.now();
29
+ }
30
+
31
+ function cleanupIdleRooms(): void {
32
+ const now = Date.now();
33
+ for (const [roomId, room] of rooms) {
34
+ if (now - room.lastActivity > IDLE_TIMEOUT_MS) {
35
+ if (room.sender?.readyState === WebSocket.OPEN) room.sender.close();
36
+ if (room.recipient?.readyState === WebSocket.OPEN) room.recipient.close();
37
+ rooms.delete(roomId);
38
+ console.log(`[cleanup] removed idle room ${roomId.slice(0, 8)}...`);
39
+ }
40
+ }
41
+ }
42
+
43
+ const cleanupInterval = setInterval(cleanupIdleRooms, 60_000);
44
+
45
+ const wss = new WebSocketServer({ port: PORT, maxPayload: 1 * 1024 * 1024 }, () => {
46
+ console.log(`relay listening on port ${PORT}`);
47
+ });
48
+
49
+ wss.on("connection", (ws) => {
50
+ let authedRoomId: string | null = null;
51
+ let authedRole: "sender" | "recipient" | null = null;
52
+
53
+ console.log("[connect] new connection");
54
+
55
+ ws.on("message", (raw) => {
56
+ let msg: { type: string; roomId?: string; authToken?: string; role?: string; [k: string]: unknown };
57
+ try {
58
+ msg = JSON.parse(String(raw));
59
+ } catch {
60
+ return;
61
+ }
62
+
63
+ if (!authedRoomId) {
64
+ if (msg.type !== "relay:auth") return;
65
+
66
+ const { roomId, authToken, role } = msg;
67
+ if (
68
+ typeof roomId !== "string" ||
69
+ typeof authToken !== "string" ||
70
+ (role !== "sender" && role !== "recipient")
71
+ ) {
72
+ send(ws, { type: "relay:auth:result", success: false, error: "invalid auth payload" });
73
+ return;
74
+ }
75
+
76
+ // Rate limit auth attempts per room
77
+ const now = Date.now();
78
+ const attempts = (authAttempts.get(roomId) ?? []).filter((t) => now - t < AUTH_RATE_WINDOW);
79
+ if (attempts.length >= AUTH_RATE_LIMIT) {
80
+ send(ws, { type: "relay:auth:result", success: false, error: "too many auth attempts" });
81
+ return;
82
+ }
83
+ attempts.push(now);
84
+ authAttempts.set(roomId, attempts);
85
+
86
+ let room = rooms.get(roomId);
87
+
88
+ if (room) {
89
+ // Constant-time comparison — pad to equal length so the length
90
+ // check itself does not leak timing information.
91
+ const expected = Buffer.from(room.authToken);
92
+ const provided = Buffer.from(authToken);
93
+ const maxLen = Math.max(expected.length, provided.length);
94
+ const a = Buffer.alloc(maxLen);
95
+ const b = Buffer.alloc(maxLen);
96
+ expected.copy(a);
97
+ provided.copy(b);
98
+ if (!timingSafeEqual(a, b) || expected.length !== provided.length) {
99
+ send(ws, { type: "relay:auth:result", success: false, error: "auth token mismatch" });
100
+ return;
101
+ }
102
+ if (room[role] && room[role]!.readyState === WebSocket.OPEN) {
103
+ send(ws, { type: "relay:auth:result", success: false, error: `${role} already connected` });
104
+ return;
105
+ }
106
+ } else {
107
+ room = { authToken, lastActivity: Date.now() };
108
+ rooms.set(roomId, room);
109
+ }
110
+
111
+ room[role] = ws;
112
+ touchRoom(room);
113
+ authedRoomId = roomId;
114
+ authedRole = role;
115
+
116
+ const peer = role === "sender" ? room.recipient : room.sender;
117
+ const peerOnline = !!peer && peer.readyState === WebSocket.OPEN;
118
+
119
+ send(ws, { type: "relay:auth:result", success: true, peerOnline });
120
+ console.log(`[auth] ${role} joined room ${roomId.slice(0, 8)}... (peer ${peerOnline ? "online" : "offline"})`);
121
+
122
+ if (peerOnline) {
123
+ send(peer!, { type: "relay:peer:status", online: true });
124
+ }
125
+
126
+ return;
127
+ }
128
+
129
+ const room = rooms.get(authedRoomId);
130
+ if (!room) return;
131
+
132
+ touchRoom(room);
133
+
134
+ if (authedRole === "recipient" && (msg.type === "relay:request" || msg.type === "relay:pair:ack")) {
135
+ if (room.sender && room.sender.readyState === WebSocket.OPEN) {
136
+ room.sender.send(String(raw));
137
+ }
138
+ return;
139
+ }
140
+
141
+ if (authedRole === "sender") {
142
+ if (
143
+ msg.type === "relay:response:meta" ||
144
+ msg.type === "relay:response:chunk" ||
145
+ msg.type === "relay:response:done" ||
146
+ msg.type === "relay:response:error" ||
147
+ msg.type === "relay:usage" ||
148
+ msg.type === "relay:pair:hello"
149
+ ) {
150
+ if (room.recipient && room.recipient.readyState === WebSocket.OPEN) {
151
+ room.recipient.send(String(raw));
152
+ }
153
+ return;
154
+ }
155
+ }
156
+ });
157
+
158
+ ws.on("close", () => {
159
+ if (!authedRoomId || !authedRole) {
160
+ console.log("[disconnect] unauthenticated connection closed");
161
+ return;
162
+ }
163
+
164
+ console.log(`[disconnect] ${authedRole} left room ${authedRoomId.slice(0, 8)}...`);
165
+ const room = rooms.get(authedRoomId);
166
+ if (!room) return;
167
+
168
+ room[authedRole] = undefined;
169
+
170
+ const peer = authedRole === "sender" ? room.recipient : room.sender;
171
+ if (peer && peer.readyState === WebSocket.OPEN) {
172
+ send(peer, { type: "relay:peer:status", online: false });
173
+ }
174
+
175
+ if (!room.sender && !room.recipient) {
176
+ rooms.delete(authedRoomId);
177
+ console.log(`[cleanup] removed empty room ${authedRoomId.slice(0, 8)}...`);
178
+ }
179
+ });
180
+
181
+ ws.on("error", (err) => {
182
+ console.error("[error]", err.message);
183
+ });
184
+ });
185
+
186
+ process.on("SIGINT", () => {
187
+ console.log("shutting down...");
188
+ clearInterval(cleanupInterval);
189
+ wss.close();
190
+ process.exit(0);
191
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "Node16",
5
+ "moduleResolution": "node16",
6
+ "outDir": "dist",
7
+ "rootDir": "src",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "declaration": true,
11
+ "sourceMap": true,
12
+ "skipLibCheck": true
13
+ },
14
+ "include": ["src"]
15
+ }