-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathborgHUIchatSoc.js
More file actions
481 lines (411 loc) · 12.5 KB
/
Copy pathborgHUIchatSoc.js
File metadata and controls
481 lines (411 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Client-side secure WebSocket connection
class SecureBORGWebSocket {
constructor(options) {
this.ws = null;
this.token = options.token;
this.userId = options.userId;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 10;
this.reconnectDelay = 1000;
this.messageQueue = [];
this.connected = false;
this.heartbeatInterval = null;
this.connect();
}
connect() {
try {
// Use wss:// for secure connection
const wsUrl = `wss://${this.getEndpoint()}?token=${this.token}&userId=${this.userId}`;
// Create WebSocket with SSL
this.ws = new WebSocket(wsUrl, {
// Security options
rejectUnauthorized: true, // Verify SSL certificate
perMessageDeflate: true,
// Optional: Add custom headers
headers: {
'X-BORG-Version': '1.0',
'User-Agent': 'BORG-Client/1.0'
}
});
this.ws.onopen = () => {
console.log('✅ Secure WebSocket connected');
this.connected = true;
this.reconnectAttempts = 0;
this.flushQueue();
this.startHeartbeat();
};
this.ws.onmessage = (event) => {
this.handleMessage(event.data);
};
this.ws.onclose = (event) => {
console.log(`🔒 WebSocket closed: ${event.code} - ${event.reason}`);
this.connected = false;
this.stopHeartbeat();
this.handleDisconnect();
};
this.ws.onerror = (error) => {
console.error('❌ WebSocket error:', error);
};
} catch (error) {
console.error('❌ Failed to connect:', error);
this.handleDisconnect();
}
}
startHeartbeat() {
// Send periodic ping to keep connection alive
this.heartbeatInterval = setInterval(() => {
if (this.connected && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({
type: 'ping',
timestamp: Date.now()
}));
}
}, 30000); // Every 30 seconds
}
stopHeartbeat() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
}
sendSecure(data) {
// Encrypt sensitive data before sending
const encrypted = this.encryptData(data);
this.ws.send(JSON.stringify({
type: 'secure',
data: encrypted,
timestamp: Date.now(),
signature: this.signData(data)
}));
}
encryptData(data) {
// Use client-side encryption
const key = this.deriveKey();
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const encrypted = Buffer.concat([
cipher.update(JSON.stringify(data), 'utf8'),
cipher.final()
]);
const tag = cipher.getAuthTag();
return {
iv: iv.toString('hex'),
tag: tag.toString('hex'),
data: encrypted.toString('hex')
};
}
deriveKey() {
// Derive key from user's private key
return crypto.createHash('sha256')
.update(this.privateKey)
.digest();
}
signData(data) {
// Sign data with private key
const signature = crypto.createSign('sha256');
signature.update(JSON.stringify(data));
return signature.sign(this.privateKey, 'hex');
}
}
// Borg Chat Client with Dynamic Endpoint Selection + Failover
class BorgChatClient {
constructor(options = {}) {
this.userId = options.userId;
this.token = options.token;
this.portal = new ServiceDiscovery();
this.currentEndpoint = null;
this.ws = null;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = options.maxReconnectAttempts || 10;
this.reconnectDelay = options.reconnectDelay || 1000;
this.messageQueue = [];
this.connected = false;
this.rooms = ['general'];
this.listeners = [];
}
async connect() {
try {
// 1. Discover endpoints
const endpoints = await this.getEndpoints();
// 2. Try each endpoint until one works
for (const endpoint of endpoints) {
try {
const connected = await this.tryConnect(endpoint);
if (connected) {
this.currentEndpoint = endpoint;
console.log(`✅ Connected to ${endpoint.url}`);
return true;
}
} catch (err) {
console.log(`❌ Failed to connect to ${endpoint.url}:`, err.message);
// Mark endpoint as failed
this.markEndpointFailed(endpoint);
continue;
}
}
// 3. All endpoints failed
console.error('❌ All endpoints failed');
return false;
} catch (err) {
console.error('Connection error:', err);
return false;
}
}
async getEndpoints() {
// Get endpoints from portal
const endpoints = await this.portal.getWebSocketEndpoints();
// Filter out recently failed endpoints
const healthy = endpoints.filter(e => !this.isFailed(e));
// Sort by lastSeen (newer first) and load (lighter first)
healthy.sort((a, b) => {
if (a.load !== b.load) return a.load - b.load;
return new Date(b.lastSeen) - new Date(a.lastSeen);
});
// Randomize first 3 for load balancing
const top = healthy.slice(0, 3);
const rest = healthy.slice(3);
// Shuffle top 3
for (let i = top.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[top[i], top[j]] = [top[j], top[i]];
}
return [...top, ...rest];
}
tryConnect(endpoint) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(endpoint.url);
const timeout = setTimeout(() => {
ws.close();
reject(new Error('Connection timeout'));
}, 10000);
ws.onopen = () => {
clearTimeout(timeout);
this.ws = ws;
this.connected = true;
this.reconnectAttempts = 0;
this.setupHandlers();
resolve(true);
};
ws.onerror = (err) => {
clearTimeout(timeout);
reject(err);
};
ws.onclose = () => {
clearTimeout(timeout);
// Don't reject if close is intentional
if (!this.connected) {
reject(new Error('Connection closed'));
}
};
});
}
setupHandlers() {
this.ws.onmessage = (event) => {
const message = JSON.parse(event.data);
this.handleMessage(message);
};
this.ws.onclose = () => {
this.connected = false;
this.handleDisconnect();
};
this.ws.onerror = (err) => {
console.error('WebSocket error:', err);
};
}
handleDisconnect() {
// Attempt to reconnect
this.reconnectAttempts++;
if (this.reconnectAttempts > this.maxReconnectAttempts) {
console.error('❌ Max reconnect attempts reached');
this.emit('disconnected', 'Max reconnect attempts');
return;
}
const delay = this.reconnectDelay * Math.min(this.reconnectAttempts, 5);
console.log(`🔄 Reconnecting in ${delay}ms... (attempt ${this.reconnectAttempts})`);
setTimeout(async () => {
const connected = await this.connect();
if (connected) {
// Resubscribe to rooms
for (const room of this.rooms) {
this.joinRoom(room);
}
// Resend queued messages
this.flushQueue();
}
}, delay);
}
async failover() {
console.log('🔄 Initiating failover...');
// Close current connection
if (this.ws) {
this.ws.close();
}
// Mark current endpoint as failed
if (this.currentEndpoint) {
this.markEndpointFailed(this.currentEndpoint);
}
// Try to connect to new endpoint
const connected = await this.connect();
if (connected) {
// Resubscribe to rooms
for (const room of this.rooms) {
this.joinRoom(room);
}
// Resend queued messages
this.flushQueue();
this.emit('failover', this.currentEndpoint);
console.log(`✅ Failover complete, new endpoint: ${this.currentEndpoint.url}`);
} else {
console.error('❌ Failover failed');
this.emit('failover_failed');
}
}
sendMessage(text) {
if (this.connected && this.ws && this.ws.readyState === WebSocket.OPEN) {
const message = {
type: 'message',
room: this.currentRoom || 'general',
text: text,
userId: this.userId,
timestamp: Date.now()
};
this.ws.send(JSON.stringify(message));
this.emit('message_sent', message);
} else {
// Queue message for later
this.messageQueue.push({ text, room: this.currentRoom });
console.log('📦 Message queued (offline)');
}
}
flushQueue() {
while (this.messageQueue.length > 0) {
const msg = this.messageQueue.shift();
this.sendMessage(msg.text);
}
}
joinRoom(room) {
if (!this.rooms.includes(room)) {
this.rooms.push(room);
}
if (this.connected) {
this.ws.send(JSON.stringify({
type: 'join',
room: room
}));
}
this.currentRoom = room;
}
markEndpointFailed(endpoint) {
// Store in local storage
const failures = JSON.parse(localStorage.getItem('failedEndpoints') || '{}');
failures[endpoint.url] = {
failedAt: Date.now(),
cooldown: 60000 // 1 minute cooldown
};
localStorage.setItem('failedEndpoints', JSON.stringify(failures));
}
isFailed(endpoint) {
const failures = JSON.parse(localStorage.getItem('failedEndpoints') || '{}');
const failure = failures[endpoint.url];
if (!failure) return false;
// Check if cooldown expired
if (Date.now() - failure.failedAt > failure.cooldown) {
delete failures[endpoint.url];
localStorage.setItem('failedEndpoints', JSON.stringify(failures));
return false;
}
return true;
}
}
// Periodic health checks for endpoints
class EndpointHealthMonitor {
constructor(client) {
this.client = client;
this.healthCheckInterval = 30000; // 30 seconds
this.startMonitoring();
}
startMonitoring() {
setInterval(async () => {
await this.checkCurrentEndpoint();
}, this.healthCheckInterval);
}
async checkCurrentEndpoint() {
if (!this.client.currentEndpoint) return;
try {
// Send ping
const response = await fetch(
`https://${this.client.currentEndpoint.ip}:${this.client.currentEndpoint.port}/health`
);
const health = await response.json();
if (health.status !== 'healthy') {
console.warn('⚠️ Endpoint unhealthy, initiating failover');
await this.client.failover();
}
if (health.load > 0.8) {
console.warn('⚠️ Endpoint overloaded, considering failover');
// Maybe failover if load is too high
}
} catch (err) {
console.warn('⚠️ Health check failed:', err.message);
await this.client.failover();
}
}
}
// Portal file includes WebSocket endpoints
const portalRegistry = {
netName: 'borgChatCell',
recpPort: 1396, // HTTP API port
wsPort: 1397, // WebSocket port
activeNodes: [
{
ip: '192.168.1.100',
wsPort: 1397,
lastSeen: '2024-01-15T12:00:00Z',
load: 0.3,
status: 'healthy'
},
{
ip: '192.168.1.101',
wsPort: 1397,
lastSeen: '2024-01-15T12:00:00Z',
load: 0.2,
status: 'healthy'
},
{
ip: '192.168.1.102',
wsPort: 1397,
lastSeen: '2024-01-15T11:58:00Z',
load: 0.1,
status: 'healthy'
}
]
};
// Client asks for WebSocket endpoints
class WebSocketDiscovery {
async getWebSocketEndpoints() {
// 1. Load portal file
const portals = this.loadPortals();
const chatService = portals.find(p => p.netName === 'borgChatCell');
// 2. Get all active nodes
const nodes = chatService.activeNodes
.filter(n => n.status === 'healthy')
.map(n => ({
url: `wss://${n.ip}:${n.wsPort || chatService.wsPort}/chat`,
ip: n.ip,
port: n.wsPort || chatService.wsPort,
load: n.load || 0,
lastSeen: n.lastSeen
}));
// 3. Sort by load (lightest first)
nodes.sort((a, b) => a.load - b.load);
return nodes;
}
async getRandomEndpoint() {
const endpoints = await this.getWebSocketEndpoints();
// If only one, return it
if (endpoints.length === 1) return endpoints[0];
// Random selection (load balancing)
const index = Math.floor(Math.random() * endpoints.length);
return endpoints[index];
}
}