-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjamkernelp2p.js
More file actions
2896 lines (2682 loc) · 113 KB
/
Copy pathjamkernelp2p.js
File metadata and controls
2896 lines (2682 loc) · 113 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// jamkernelp2p v1.2.0
// ============================================================================
//
// PROYECTO OFICIAL: https://github.com/jamkernel/jamkernelp2p
// SITIO WEB: https://jamkernelp2p.github.io
// CONTACTO: jamkernelp2p@gmail.com
//
// AUTOR: Félix Martínez
// DEDICADO A: Jose Alejandro Martínez — motor e inspiración
// LICENCIA: GNU GPL v3
//
// CARACTERÍSTICAS:
// - Un solo archivo (~3500 líneas)
// - Cero dependencias externas
// - Multi-plataforma: Navegadores, Node.js, Deno, Bun
// - Cifrado AES-256-GCM + PBKDF2 (600,000 iteraciones)
// - Identidad ECDSA P-256 con firma y verificación
// - Purga forense de claves en RAM
// - Servidor de señalización WebSocket embebido (RFC 6455)
// - Mesh P2P con WebRTC (browser) y WebSocket relay (Node.js)
// - Rate limiting anti-DoS (60 msg/s)
// - Lista negra automática
// - ACKs de entrega con reintentos
// - Almacenamiento con mutex y backoff exponencial
// - EventBus con contexto blindado
// - Logger estructurado con rotación
// - Cluster mode multi-worker
// - Sistema de plugins
// ============================================================================
const JAM_ENCODER = new TextEncoder();
const JAM_DECODER = new TextDecoder();
// ===========================================================
// 1. CONTRATO UNIVERSAL DE PLATAFORMA (IPLATFORM)
// ===========================================================
class IPlatform {
async generateRandomBytes(size) { throw new Error('No implementado'); }
async getCryptoSubtle() { throw new Error('No implementado'); }
getWebSocketClass() { throw new Error('No implementado'); }
getFs() { return null; }
getPath() { return null; }
getOs() { return null; }
isBrowser() { return false; }
isNode() { return false; }
isDeno() { return false; }
isBun() { return false; }
hasWebRTC() { return false; }
onExit(fn) {}
}
// ===========================================================
// 2. ADAPTADORES DE ENTORNO NATIVOS
// ===========================================================
class BrowserAdapter extends IPlatform {
async generateRandomBytes(size) {
const bytes = new Uint8Array(size);
window.crypto.getRandomValues(bytes);
return bytes;
}
async getCryptoSubtle() {
if (!window.crypto || !window.crypto.subtle)
throw new Error("🔒 jamkernelp2p Crypto requiere HTTPS o localhost");
return window.crypto.subtle;
}
getWebSocketClass() { return WebSocket; }
isBrowser() { return true; }
hasWebRTC() { return typeof RTCPeerConnection !== 'undefined'; }
}
class NodeAdapter extends IPlatform {
constructor() {
super();
this._crypto = require('crypto');
this._fs = require('fs');
this._path = require('path');
this._os = require('os');
this._http = require('http');
this._https = require('https');
this._net = require('net');
}
get http() { return this._http; }
get https() { return this._https; }
get net() { return this._net; }
async generateRandomBytes(size) {
return new Uint8Array(this._crypto.randomBytes(size));
}
async getCryptoSubtle() {
return this._crypto.webcrypto.subtle;
}
getWebSocketClass() {
if (typeof globalThis.WebSocket !== 'undefined') return globalThis.WebSocket;
return null;
}
getFs() { return this._fs; }
getPath() { return this._path; }
getOs() { return this._os; }
isNode() { return true; }
// No WebRTC nativo en Node.js sin wrtc
hasWebRTC() { return false; }
onExit(fn) {
process.on('exit', fn);
process.on('SIGINT', () => { fn(); process.exit(0); });
process.on('SIGTERM', fn);
}
}
class DenoAdapter extends IPlatform {
async generateRandomBytes(size) {
const buf = new Uint8Array(size);
crypto.getRandomValues(buf);
return buf;
}
async getCryptoSubtle() {
return crypto.subtle;
}
getWebSocketClass() { return WebSocket; }
isDeno() { return true; }
hasWebRTC() { return false; }
}
class BunAdapter extends IPlatform {
async generateRandomBytes(size) {
const buf = new Uint8Array(size);
crypto.getRandomValues(buf);
return buf;
}
async getCryptoSubtle() {
return crypto.subtle;
}
getWebSocketClass() { return WebSocket; }
isBun() { return true; }
hasWebRTC() { return false; }
}
function detectPlatform() {
if (typeof window !== 'undefined' && typeof window.crypto !== 'undefined')
return new BrowserAdapter();
if (typeof process !== 'undefined' && process.versions && process.versions.node)
return new NodeAdapter();
if (typeof Deno !== 'undefined')
return new DenoAdapter();
if (typeof Bun !== 'undefined')
return new BunAdapter();
throw new Error('❌ Entorno no soportado por jamkernelp2p');
}
// ===========================================================
// 3. EVENT BUS (INMUNE A CONDICIONES DE CARRERA)
// ===========================================================
class EventBus {
constructor() {
this.listeners = new Map();
this._pluginListeners = new Map();
}
on(event, callback, pluginName = null) {
if (typeof event !== 'string') return;
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event).push(callback);
if (typeof pluginName === 'string') {
if (!this._pluginListeners.has(pluginName)) this._pluginListeners.set(pluginName, []);
this._pluginListeners.get(pluginName).push({ event, callback });
}
}
off(event, callback) {
if (!this.listeners.has(event)) return;
const idx = this.listeners.get(event).indexOf(callback);
if (idx !== -1) this.listeners.get(event).splice(idx, 1);
}
offByPlugin(pluginName) {
if (!this._pluginListeners.has(pluginName)) return;
for (const { event, callback } of this._pluginListeners.get(pluginName)) {
this.off(event, callback);
}
this._pluginListeners.delete(pluginName);
}
emit(event, data) {
if (!this.listeners.has(event)) return;
const callbacks = this.listeners.get(event).slice();
const schedule = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout;
for (const cb of callbacks) {
schedule(() => {
try { cb(data); } catch (e) { console.error('Error en callback de', event, e.message); }
}, 0);
}
}
}
// ===========================================================
// 4. MUTEX
// ===========================================================
class Mutex {
constructor() {
this._locked = false;
this._queue = [];
}
acquire() {
return new Promise(resolve => {
if (!this._locked) {
this._locked = true;
resolve();
} else {
this._queue.push(resolve);
}
});
}
release() {
if (this._queue.length > 0) {
const next = this._queue.shift();
next();
} else {
this._locked = false;
}
}
}
// ===========================================================
// 5. CACHE LRU
// ===========================================================
class Cache {
constructor(maxSize = 100) {
this._map = new Map();
this._maxSize = maxSize;
}
get(key) {
if (!this._map.has(key)) return null;
const val = this._map.get(key);
this._map.delete(key);
this._map.set(key, val);
return val;
}
set(key, value) {
if (this._map.has(key)) this._map.delete(key);
this._map.set(key, value);
if (this._map.size > this._maxSize) {
const oldest = this._map.keys().next().value;
this._map.delete(oldest);
}
}
delete(key) { this._map.delete(key); }
clear() { this._map.clear(); }
get size() { return this._map.size; }
}
// ===========================================================
// 6. STRUCTURED LOGGER
// ===========================================================
class StructuredLogger {
constructor(config = {}) {
this._level = config.logLevel || 'warn';
this._logFile = config.logFile || null;
this._levels = { error: 0, warn: 1, info: 2, debug: 3 };
this._fs = config.fs || null;
this._path = config.path || null;
this._logStream = null;
this._bytesWritten = 0;
this._maxSize = 10 * 1024 * 1024; // 10 MB
if (this._logFile && this._fs) this._openStream();
}
_openStream() {
try {
// append mode
const fd = this._fs.openSync(this._logFile, 'a');
this._logStream = this._fs.createWriteStream(this._logFile, { flags: 'a', fd });
this._bytesWritten = 0;
try { this._bytesWritten = this._fs.statSync(this._logFile).size; } catch (e) {}
} catch (e) {
console.error('❌ No se pudo abrir archivo de log:', e.message);
this._logFile = null;
}
}
_rotate() {
if (!this._logStream || !this._fs) return;
this._logStream.end();
const rotated = this._logFile + '.1.log';
try {
if (this._fs.existsSync(rotated)) this._fs.unlinkSync(rotated);
this._fs.renameSync(this._logFile, rotated);
} catch (e) {}
this._openStream();
}
_write(level, module, message, meta) {
if (this._levels[level] === undefined) return;
if (this._levels[level] > this._levels[this._level]) return;
const ts = new Date().toISOString();
const line = `[${ts}] [${level.toUpperCase()}] [${module}] ${message}`;
console.log(line);
if (meta && Object.keys(meta).length) console.log(' └─', JSON.stringify(meta));
if (this._logStream) {
const entry = JSON.stringify({ ts, level, module, msg: message, meta }) + '\n';
this._logStream.write(entry);
this._bytesWritten += Buffer.byteLength(entry);
if (this._bytesWritten >= this._maxSize) this._rotate();
}
}
error(module, message, meta) { this._write('error', module, message, meta); }
warn(module, message, meta) { this._write('warn', module, message, meta); }
info(module, message, meta) { this._write('info', module, message, meta); }
debug(module, message, meta) { this._write('debug', module, message, meta); }
close() {
if (this._logStream) this._logStream.end();
}
}
// ===========================================================
// 7. JAM CRYPTO (AES-256-GCM + PBKDF2 + ECDSA P-256)
// ===========================================================
class JamCrypto {
constructor(platform) {
this.platform = platform;
this.iterations = 600000;
}
async _deriveSalt(roomId) {
const cleanRoomId = roomId.replace(/[^a-zA-Z0-9_-]/g, '');
const msg = 'jamkernelp2p_Mesh_Salt_Default_' + cleanRoomId;
const subtle = await this.platform.getCryptoSubtle();
const hash = await subtle.digest('SHA-256', JAM_ENCODER.encode(msg));
return new Uint8Array(hash);
}
async deriveKey(password, roomId) {
if (typeof password !== 'string' || password.length < 8)
throw new Error('La contraseña debe tener al menos 8 caracteres');
if (typeof roomId !== 'string' || roomId.length < 3)
throw new Error('ID de sala inválido o demasiado corto');
const subtle = await this.platform.getCryptoSubtle();
const passwordBytes = JAM_ENCODER.encode(password);
const salt = await this._deriveSalt(roomId);
const baseKey = await subtle.importKey('raw', passwordBytes, { name: 'PBKDF2' }, false, ['deriveKey']);
return await subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: this.iterations, hash: 'SHA-256' },
baseKey,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
arrayBufferToBase64URL(buffer) {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
base64URLToArrayBuffer(base64) {
let b64 = base64.replace(/-/g, '+').replace(/_/g, '/');
while (b64.length % 4) b64 += '=';
const binaryString = atob(b64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
return bytes.buffer;
}
async _ensureCryptoKey(key) {
if (key && typeof key === 'object' && key.algorithm && key.algorithm.name === 'AES-GCM') return key;
if (typeof key === 'string') {
const subtle = await this.platform.getCryptoSubtle();
const raw = JAM_ENCODER.encode(key);
return await subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
}
throw new Error('Invalid crypto key');
}
async encrypt(text, cryptoKey) {
const subtle = await this.platform.getCryptoSubtle();
const key = await this._ensureCryptoKey(cryptoKey);
const dataBytes = JAM_ENCODER.encode(text);
const iv = await this.platform.generateRandomBytes(12);
const encryptedBuffer = await subtle.encrypt({ name: 'AES-GCM', iv }, key, dataBytes);
const combined = new Uint8Array(iv.length + encryptedBuffer.byteLength);
combined.set(iv);
combined.set(new Uint8Array(encryptedBuffer), iv.length);
return this.arrayBufferToBase64URL(combined.buffer);
}
async decrypt(base64Data, cryptoKey) {
const subtle = await this.platform.getCryptoSubtle();
const key = await this._ensureCryptoKey(cryptoKey);
const combined = new Uint8Array(this.base64URLToArrayBuffer(base64Data));
const iv = combined.slice(0, 12);
const dataBytes = combined.slice(12);
const decryptedBuffer = await subtle.decrypt({ name: 'AES-GCM', iv }, key, dataBytes);
return JAM_DECODER.decode(decryptedBuffer);
}
async purgeKeyFromMemory(container, keyProperty) {
try {
const subtle = await this.platform.getCryptoSubtle();
await subtle.importKey('raw', new Uint8Array(32), { name: 'AES-GCM' }, false, ['encrypt']);
container[keyProperty] = null;
if (typeof global !== 'undefined' && global.gc) global.gc();
if (typeof window !== 'undefined' && window.gc) window.gc();
} catch (e) {
console.warn('⚠️ Fallo en purga de memoria:', e.message);
}
}
// ── Encriptación para datos en reposo (identidad) ──
async _deriveStorageKey(passphrase) {
const subtle = await this.platform.getCryptoSubtle();
const material = await subtle.importKey('raw', JAM_ENCODER.encode('jamkernelp2p_identity_' + passphrase),
{ name: 'PBKDF2' }, false, ['deriveKey']);
return await subtle.deriveKey(
{ name: 'PBKDF2', salt: JAM_ENCODER.encode('jamkernelp2p_storage_salt'), iterations: 100000, hash: 'SHA-256' },
material,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
async encryptStorage(data, passphrase) {
const key = await this._deriveStorageKey(passphrase);
const subtle = await this.platform.getCryptoSubtle();
const iv = await this.platform.generateRandomBytes(12);
const encoded = JAM_ENCODER.encode(typeof data === 'string' ? data : JSON.stringify(data));
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, key, encoded);
const combined = new Uint8Array(iv.length + encrypted.byteLength);
combined.set(iv);
combined.set(new Uint8Array(encrypted), iv.length);
return this.arrayBufferToBase64URL(combined.buffer);
}
async decryptStorage(base64Data, passphrase) {
const key = await this._deriveStorageKey(passphrase);
const subtle = await this.platform.getCryptoSubtle();
const combined = new Uint8Array(this.base64URLToArrayBuffer(base64Data));
const iv = combined.slice(0, 12);
const dataBytes = combined.slice(12);
const decrypted = await subtle.decrypt({ name: 'AES-GCM', iv }, key, dataBytes);
return JAM_DECODER.decode(decrypted);
}
// ── ECDSA P-256 ──
async generateECDSAKeyPair() {
const subtle = await this.platform.getCryptoSubtle();
return await subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-256' },
true,
['sign', 'verify']
);
}
async exportPublicKey(publicKey) {
const subtle = await this.platform.getCryptoSubtle();
const raw = await subtle.exportKey('raw', publicKey);
return new Uint8Array(raw);
}
async exportPrivateKey(privateKey) {
const subtle = await this.platform.getCryptoSubtle();
const pkcs8 = await subtle.exportKey('pkcs8', privateKey);
return new Uint8Array(pkcs8);
}
async importPublicKey(rawBytes) {
const subtle = await this.platform.getCryptoSubtle();
return await subtle.importKey('raw', rawBytes, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify']);
}
async importPrivateKey(pkcs8Bytes) {
const subtle = await this.platform.getCryptoSubtle();
return await subtle.importKey('pkcs8', pkcs8Bytes, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign']);
}
async ecdsaSign(privateKey, data) {
const subtle = await this.platform.getCryptoSubtle();
const dataBytes = JAM_ENCODER.encode(data);
const signature = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, dataBytes);
return this.arrayBufferToBase64URL(signature);
}
async ecdsaVerify(publicKey, data, signatureBase64) {
const subtle = await this.platform.getCryptoSubtle();
const dataBytes = JAM_ENCODER.encode(data);
const sigBytes = new Uint8Array(this.base64URLToArrayBuffer(signatureBase64));
return await subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, publicKey, sigBytes, dataBytes);
}
async sha256(data) {
const subtle = await this.platform.getCryptoSubtle();
const hash = await subtle.digest('SHA-256', JAM_ENCODER.encode(data));
return this.arrayBufferToBase64URL(hash);
}
async sha256Raw(buffer) {
const subtle = await this.platform.getCryptoSubtle();
return new Uint8Array(await subtle.digest('SHA-256', buffer));
}
async generateUUID() {
const bytes = await this.platform.generateRandomBytes(16);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
return hex.slice(0,8)+'-'+hex.slice(8,12)+'-'+hex.slice(12,16)+'-'+hex.slice(16,20)+'-'+hex.slice(20);
}
}
// ===========================================================
// 8. IDENTITY MANAGER (ECDSA P-256)
// ===========================================================
class IdentityManager {
constructor(crypto) {
this._crypto = crypto;
this._publicKey = null;
this._privateKey = null;
this._peerId = null;
this._ready = false;
}
get peerId() { return this._peerId; }
get isReady() { return this._ready; }
async createIdentity() {
const keyPair = await this._crypto.generateECDSAKeyPair();
this._publicKey = keyPair.publicKey;
this._privateKey = keyPair.privateKey;
const rawPub = await this._crypto.exportPublicKey(this._publicKey);
const hash = await this._crypto.sha256Raw(rawPub.buffer);
this._peerId = this._crypto.arrayBufferToBase64URL(hash.buffer);
this._ready = true;
return { peerId: this._peerId };
}
async sign(data) {
if (!this._privateKey) throw new Error('Identity no inicializada');
return await this._crypto.ecdsaSign(this._privateKey, data);
}
async verify(peerId, data, signatureBase64, publicKeyRaw) {
try {
const pubKey = await this._crypto.importPublicKey(publicKeyRaw);
return await this._crypto.ecdsaVerify(pubKey, data, signatureBase64);
} catch (e) {
return false;
}
}
async derivePeerIdFromPublicKey(publicKeyRaw) {
const hash = await this._crypto.sha256Raw(publicKeyRaw.buffer);
return this._crypto.arrayBufferToBase64URL(hash.buffer);
}
async toJSON() {
if (!this._ready) return null;
const pubRaw = await this._crypto.exportPublicKey(this._publicKey);
const privRaw = await this._crypto.exportPrivateKey(this._privateKey);
return {
peerId: this._peerId,
publicKey: this._crypto.arrayBufferToBase64URL(pubRaw.buffer),
privateKey: this._crypto.arrayBufferToBase64URL(privRaw.buffer)
};
}
async fromJSON(json) {
const pubRaw = new Uint8Array(this._crypto.base64URLToArrayBuffer(json.publicKey));
const privRaw = new Uint8Array(this._crypto.base64URLToArrayBuffer(json.privateKey));
this._publicKey = await this._crypto.importPublicKey(pubRaw);
this._privateKey = await this._crypto.importPrivateKey(privRaw);
this._peerId = json.peerId;
this._ready = true;
}
}
// ===========================================================
// 9. WEBSOCKET (RFC 6455) — IMPLEMENTACIÓN CERO DEPENDENCIAS
// ===========================================================
const WS_GUID = '258EAFA5-E914-47DA-95CA-5AB5F9F13AB5';
class _WebSocketFrame {
static encode(opcode, payload, mask) {
const isBinary = typeof payload === 'object' && (payload instanceof Uint8Array || payload instanceof Buffer);
const data = isBinary ? new Uint8Array(payload) : JAM_ENCODER.encode(payload);
const fin = 0x80;
const b0 = fin | (opcode & 0x0f);
const len = data.length;
const maskBit = mask ? 0x80 : 0;
let frame;
let offset;
if (len < 126) {
frame = new Uint8Array(2 + (mask ? 4 : 0) + len);
frame[0] = b0;
frame[1] = len | maskBit;
offset = 2;
} else if (len < 65536) {
frame = new Uint8Array(4 + (mask ? 4 : 0) + len);
frame[0] = b0;
frame[1] = 126 | maskBit;
frame[2] = (len >> 8) & 0xff;
frame[3] = len & 0xff;
offset = 4;
} else {
frame = new Uint8Array(10 + (mask ? 4 : 0) + len);
frame[0] = b0;
frame[1] = 127 | maskBit;
for (let i = 7; i >= 0; i--) frame[9 - i] = (len >> (i * 8)) & 0xff;
offset = 10;
}
if (mask) {
const maskKey = new Uint8Array(4);
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
crypto.getRandomValues(maskKey);
} else if (typeof require !== 'undefined') {
try { maskKey.set(require('crypto').randomBytes(4)); } catch (e) {
for (let i = 0; i < 4; i++) maskKey[i] = (Math.random() * 256) | 0;
}
} else {
for (let i = 0; i < 4; i++) maskKey[i] = (Math.random() * 256) | 0;
}
frame.set(maskKey, offset);
offset += 4;
for (let i = 0; i < data.length; i++) frame[offset + i] = data[i] ^ maskKey[i % 4];
} else {
frame.set(data, offset);
}
return frame;
}
static decode(buffer) {
const buf = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
const first = view.getUint8(0);
const fin = (first & 0x80) !== 0;
const opcode = first & 0x0f;
if (buf.length < 2) return null;
const second = view.getUint8(1);
const masked = (second & 0x80) !== 0;
let len = second & 0x7f;
let offset = 2;
if (len === 126) {
if (buf.length < 4) return null;
len = view.getUint16(2);
offset = 4;
} else if (len === 127) {
if (buf.length < 10) return null;
let high = 0, low = 0;
for (let i = 0; i < 4; i++) high = (high << 8) | view.getUint8(2 + i);
for (let i = 0; i < 4; i++) low = (low << 8) | view.getUint8(6 + i);
len = high * 4294967296 + low;
offset = 10;
}
let maskKey = null;
if (masked) {
if (buf.length < offset + 4) return null;
maskKey = buf.slice(offset, offset + 4);
offset += 4;
}
if (buf.length < offset + len) return null;
let payload = buf.slice(offset, offset + len);
if (masked && maskKey) {
const unmasked = new Uint8Array(payload.length);
for (let i = 0; i < payload.length; i++) unmasked[i] = payload[i] ^ maskKey[i % 4];
payload = unmasked;
}
return { fin, opcode, payload, maskKey };
}
}
class _WebSocketServer {
constructor(httpServer) {
this.httpServer = httpServer;
this.clients = new Set();
this._onConnection = null;
this._onError = null;
httpServer.on('upgrade', (req, socket, head) => {
this._handleUpgrade(req, socket, head);
});
}
onConnection(cb) { this._onConnection = cb; }
onError(cb) { this._onError = cb; }
_handleUpgrade(req, socket, head) {
const key = req.headers['sec-websocket-key'];
if (!key) { socket.destroy(); return; }
const accept = require('crypto')
.createHash('sha1')
.update(key + WS_GUID)
.digest('base64');
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
'Sec-WebSocket-Accept: ' + accept + '\r\n' +
'\r\n'
);
const ws = new _WebSocketPeer(socket);
// Process any head data that was already buffered
if (head && head.length > 0) {
ws._buffer = Buffer.concat([ws._buffer, head]);
ws._processBuffer();
}
this.clients.add(ws);
ws._onClose = () => { this.clients.delete(ws); };
if (this._onConnection) this._onConnection(ws);
}
close() {
for (const client of this.clients) client.close();
this.httpServer.removeAllListeners('upgrade');
}
}
class _WebSocketPeer {
constructor(socket) {
this.socket = socket;
this._onMessage = null;
this._onClose = null;
this._onError = null;
this._buffer = Buffer.alloc(0);
this._closed = false;
socket.on('data', (data) => {
this._buffer = Buffer.concat([this._buffer, data]);
this._processBuffer();
});
socket.on('close', () => {
this._closed = true;
if (this._onClose) this._onClose();
});
socket.on('error', (err) => {
if (this._onError) this._onError(err);
});
}
_processBuffer() {
while (this._buffer.length >= 2) {
const bufArr = new Uint8Array(this._buffer);
const view = new DataView(bufArr.buffer, bufArr.byteOffset, bufArr.byteLength);
const second = view.getUint8(1);
let len = second & 0x7f;
let headerLen = 2;
if (len === 126) {
if (this._buffer.length < 4) return;
headerLen = 4;
len = view.getUint16(2);
} else if (len === 127) {
if (this._buffer.length < 10) return;
headerLen = 10;
let high = 0, low = 0;
for (let i = 0; i < 4; i++) high = (high << 8) | view.getUint8(2 + i);
for (let i = 0; i < 4; i++) low = (low << 8) | view.getUint8(6 + i);
len = high * 4294967296 + low;
}
const masked = (second & 0x80) !== 0;
const maskLen = masked ? 4 : 0;
const totalLen = headerLen + maskLen + len;
if (this._buffer.length < totalLen) return;
const frameData = this._buffer.slice(0, totalLen);
this._buffer = this._buffer.slice(totalLen);
const frame = _WebSocketFrame.decode(frameData);
if (!frame) continue;
const opcode = frame.opcode;
if (opcode === 0x8) {
this._closed = true;
try { this.socket.write(Buffer.from(_WebSocketFrame.encode(0x8, '', false))); } catch (e) {}
try { this.socket.end(); } catch (e) {}
if (this._onClose) this._onClose();
return;
} else if (opcode === 0x9) {
try { this.socket.write(Buffer.from(_WebSocketFrame.encode(0xA, frame.payload, false))); } catch (e) {}
} else if (opcode === 0xA) {
} else if (opcode === 0x1 || opcode === 0x2) {
let message;
if (opcode === 0x1) {
message = JAM_DECODER.decode(frame.payload);
} else message = frame.payload;
if (this._onMessage) this._onMessage(message, opcode === 0x2);
}
}
}
send(data) {
if (this._closed) return;
try {
const isBinary = typeof data !== 'string';
const frame = _WebSocketFrame.encode(isBinary ? 0x2 : 0x1, data, false);
this.socket.write(Buffer.from(frame));
} catch (e) {
if (this._onError) this._onError(e);
}
}
sendBinary(data) {
if (this._closed) return;
try {
const frame = _WebSocketFrame.encode(0x2, data, false);
this.socket.write(Buffer.from(frame));
} catch (e) {
if (this._onError) this._onError(e);
}
}
close(code, reason) {
if (this._closed) return;
let payload = '';
if (typeof code === 'number') {
const buf = Buffer.alloc(2);
buf.writeUInt16BE(code, 0);
payload = Buffer.concat([buf, Buffer.from(reason || '', 'utf-8')]);
}
try {
this.socket.write(Buffer.from(_WebSocketFrame.encode(0x8, payload, false)));
} catch (e) {}
try { this.socket.end(); } catch (e) {}
this._closed = true;
}
}
class _WebSocketClientNode {
constructor(url) {
this.url = url;
this._onOpen = null;
this._onMessage = null;
this._onClose = null;
this._onError = null;
this._socket = null;
this._buffer = Buffer.alloc(0);
this._closed = false;
this.readyState = 0; // CONNECTING
}
connect() {
const parsed = new URL(this.url);
const isTLS = parsed.protocol === 'wss:';
const port = parsed.port || (isTLS ? 443 : 80);
const key = require('crypto').randomBytes(16).toString('base64');
const acceptExpected = require('crypto')
.createHash('sha1')
.update(key + WS_GUID)
.digest('base64');
const netMod = isTLS ? require('tls') : require('net');
const socket = netMod.connect(port, parsed.hostname, () => {
const path = (parsed.pathname + parsed.search) || '/';
socket.write(
'GET ' + path + ' HTTP/1.1\r\n' +
'Host: ' + parsed.host + '\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
'Sec-WebSocket-Key: ' + key + '\r\n' +
'Sec-WebSocket-Version: 13\r\n' +
'\r\n'
);
});
let responseData = Buffer.alloc(0);
socket.on('data', (chunk) => {
responseData = Buffer.concat([responseData, chunk]);
const headerEnd = responseData.indexOf('\r\n\r\n');
if (headerEnd !== -1) {
const headerStr = responseData.slice(0, headerEnd).toString('latin1');
const statusLine = headerStr.split('\r\n')[0];
if (!statusLine.includes('101')) {
if (this._onError) this._onError(new Error('WebSocket handshake failed: ' + statusLine));
socket.destroy();
return;
}
// Validate Sec-WebSocket-Accept
let acceptHeader = null;
for (const line of headerStr.split('\r\n').slice(1)) {
const lower = line.toLowerCase();
if (lower.startsWith('sec-websocket-accept:')) {
acceptHeader = line.split(':')[1].trim();
break;
}
}
if (!acceptHeader || acceptHeader !== acceptExpected) {
if (this._onError) this._onError(new Error('WebSocket handshake: Sec-WebSocket-Accept inválido'));
socket.destroy();
return;
}
this.readyState = 1; // OPEN
this._socket = socket;
// Remove HTTP response handler, attach WS frame handler first
socket.removeAllListeners('data');
socket.on('data', (d) => {
this._buffer = Buffer.concat([this._buffer, d]);
this._processBuffer();
});
// Then process any data already buffered after HTTP headers
const leftover = responseData.slice(headerEnd + 4);
this._buffer = leftover;
if (this._onOpen) this._onOpen();
if (leftover.length > 0) this._processBuffer();
}
});
socket.on('error', (err) => { if (this._onError) this._onError(err); });
socket.on('close', () => {
this._closed = true;
this.readyState = 3; // CLOSED
if (this._onClose) this._onClose();
});
}
_processBuffer() {
while (this._buffer.length >= 2) {
const bufArr = new Uint8Array(this._buffer);
const view = new DataView(bufArr.buffer, bufArr.byteOffset, bufArr.byteLength);
const second = view.getUint8(1);
const opcode = view.getUint8(0) & 0x0f;
let len = second & 0x7f;
let headerLen = 2;
if (len === 126) {
if (this._buffer.length < 4) return;
headerLen = 4;
len = view.getUint16(2);
} else if (len === 127) {
if (this._buffer.length < 10) return;
headerLen = 10;
let high = 0, low = 0;
for (let i = 0; i < 4; i++) high = (high << 8) | view.getUint8(2 + i);
for (let i = 0; i < 4; i++) low = (low << 8) | view.getUint8(6 + i);
len = high * 4294967296 + low;
}
const masked = (second & 0x80) !== 0;
const maskLen = masked ? 4 : 0;
const totalLen = headerLen + maskLen + len;
if (this._buffer.length < totalLen) return;
const frameData = this._buffer.slice(0, totalLen);
this._buffer = this._buffer.slice(totalLen);
const frame = _WebSocketFrame.decode(frameData);
if (!frame) continue;
if (opcode === 0x8) {
this._closed = true;
this.readyState = 3;
try { this._socket.end(); } catch(e) {}
if (this._onClose) this._onClose();
return;
} else if (opcode === 0x9) {
try { this._socket.write(Buffer.from(_WebSocketFrame.encode(0xA, frame.payload, true))); } catch(e) {}
} else if (opcode === 0x1 || opcode === 0x2) {
let message;
if (opcode === 0x1) message = JAM_DECODER.decode(frame.payload);
else message = frame.payload;
if (this._onMessage) this._onMessage(message, opcode === 0x2);
}
}
}
send(data) {
if (this._closed || this.readyState !== 1) return;
try {
const isBinary = typeof data !== 'string';
const frame = _WebSocketFrame.encode(isBinary ? 0x2 : 0x1, data, true);
this._socket.write(Buffer.from(frame));
} catch (e) {
if (this._onError) this._onError(e);
}
}
close(code, reason) {
if (this._closed) return;
let payload = '';
if (typeof code === 'number') {
const buf = Buffer.alloc(2);
buf.writeUInt16BE(code, 0);
payload = Buffer.concat([buf, Buffer.from(reason || '', 'utf-8')]);
}
try { this._socket.write(Buffer.from(_WebSocketFrame.encode(0x8, payload, true))); } catch(e) {}
try { this._socket.end(); } catch(e) {}
this._closed = true;
this.readyState = 3;
}
}
// ===========================================================
// 10. MINI SIGNAL SERVER
// ===========================================================
class MiniSignalServer {
constructor(config = {}) {
this._port = config.port || 0;
this._host = config.host || '0.0.0.0';
this._platform = config.platform || null;
this._identityManager = config.identityManager || null;
this._events = config.events || null;
this._log = config.log || null;
this._httpServer = null;
this._wsServer = null;