peerpigeon 0.0.4 → 0.0.6

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.
@@ -0,0 +1,612 @@
1
+ import { EventEmitter } from './EventEmitter.js';
2
+
3
+ // Dynamic import for unsea to handle both Node.js and browser environments
4
+ let unsea = null;
5
+
6
+ async function initializeUnsea() {
7
+ if (unsea) return unsea;
8
+
9
+ try {
10
+ // Detect environment - prioritize Node.js detection for tests
11
+ const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
12
+ const isBrowser = !isNode && typeof window !== 'undefined' && typeof document !== 'undefined';
13
+
14
+ if (isNode) {
15
+ // For Node.js environments (including tests), use npm package
16
+ unsea = await import('unsea');
17
+ console.log('✅ Loaded unsea from npm package (Node.js)');
18
+ } else if (isBrowser) {
19
+ // For browser environments, try CDN sources
20
+ try {
21
+ unsea = await import('https://cdn.jsdelivr.net/npm/unsea@latest/+esm');
22
+ console.log('✅ Loaded unsea from jsDelivr CDN');
23
+ } catch (jsDelivrError) {
24
+ console.warn('Failed to load from jsDelivr, trying unpkg:', jsDelivrError);
25
+ try {
26
+ unsea = await import('https://unpkg.com/unsea@latest/dist/unsea.esm.js');
27
+ console.log('✅ Loaded unsea from unpkg CDN');
28
+ } catch (unpkgError) {
29
+ console.warn('Failed to load from unpkg, trying Skypack:', unpkgError);
30
+ unsea = await import('https://cdn.skypack.dev/unsea');
31
+ console.log('✅ Loaded unsea from Skypack CDN');
32
+ }
33
+ }
34
+ } else {
35
+ throw new Error('Unknown environment - cannot load unsea');
36
+ }
37
+
38
+ if (!unsea) {
39
+ throw new Error('Unsea not found after loading');
40
+ }
41
+
42
+ return unsea;
43
+ } catch (error) {
44
+ console.error('Failed to load unsea:', error);
45
+ throw error;
46
+ }
47
+ }
48
+
49
+ export class CryptoManager extends EventEmitter {
50
+ constructor() {
51
+ super();
52
+ this.unsea = null;
53
+ this.keypair = null;
54
+ this.peerKeys = new Map(); // Store peer public keys
55
+ this.encryptionEnabled = false;
56
+ this.initialized = false;
57
+ this.groupKeys = new Map(); // Store group encryption keys
58
+ this.messageNonces = new Set(); // Prevent replay attacks
59
+ this.maxNonceAge = 300000; // 5 minutes
60
+
61
+ // Performance metrics
62
+ this.stats = {
63
+ messagesEncrypted: 0,
64
+ messagesDecrypted: 0,
65
+ encryptionTime: 0,
66
+ decryptionTime: 0,
67
+ keyExchanges: 0
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Initialize the crypto manager
73
+ * @param {Object} options - Configuration options
74
+ * @param {string} options.alias - Optional user alias for persistent identity
75
+ * @param {string} options.password - Optional password for user account
76
+ * @param {boolean} options.generateKeypair - Whether to generate a new keypair if no credentials
77
+ * @returns {Promise<Object>} The generated or loaded keypair
78
+ */
79
+ async init(options = {}) {
80
+ try {
81
+ this.unsea = await initializeUnsea();
82
+
83
+ if (options.alias && options.password) {
84
+ // Try to create or authenticate with persistent identity
85
+ await this.createOrAuthenticateUser(options.alias, options.password);
86
+ } else if (options.generateKeypair !== false) {
87
+ // Generate ephemeral keypair
88
+ this.keypair = await this.unsea.generateRandomPair();
89
+ }
90
+
91
+ if (this.keypair) {
92
+ this.encryptionEnabled = true;
93
+ this.initialized = true;
94
+ this.emit('cryptoReady', { publicKey: this.getPublicKey() });
95
+
96
+ // Start nonce cleanup
97
+ this.startNonceCleanup();
98
+ }
99
+
100
+ return this.keypair;
101
+ } catch (error) {
102
+ console.error('CryptoManager initialization failed:', error);
103
+ this.emit('cryptoError', { error: error.message });
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Create or authenticate a persistent user account
110
+ */
111
+ async createOrAuthenticateUser(alias, password) {
112
+ try {
113
+ // For unsea, we'll generate a deterministic keypair from credentials
114
+ // Note: unsea doesn't have built-in user accounts like GUN
115
+ // We can simulate this by generating deterministic keys from password+alias
116
+
117
+ // Use unsea's key persistence if available (browser only)
118
+ if (typeof window !== 'undefined') {
119
+ try {
120
+ // Try to load existing keys
121
+ const existingKeys = await this.unsea.loadKeys(alias, password);
122
+ if (existingKeys) {
123
+ this.keypair = existingKeys;
124
+ } else {
125
+ // Generate new keys and save them
126
+ this.keypair = await this.unsea.generateRandomPair();
127
+ await this.unsea.saveKeys(alias, this.keypair, password);
128
+ }
129
+ } catch (error) {
130
+ // Fallback to generating ephemeral keys
131
+ console.warn('Failed to use persistent storage, generating ephemeral keys:', error);
132
+ this.keypair = await this.unsea.generateRandomPair();
133
+ }
134
+ } else {
135
+ // For Node.js, just generate ephemeral keys
136
+ this.keypair = await this.unsea.generateRandomPair();
137
+ }
138
+
139
+ this.emit('userAuthenticated', { alias, publicKey: this.getPublicKey() });
140
+ } catch (error) {
141
+ console.error('User authentication failed:', error);
142
+ throw error;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Get the public key for sharing
148
+ * @returns {string} The public key
149
+ */
150
+ getPublicKey() {
151
+ // In unsea, the public key is likely in the 'pub' property
152
+ return this.keypair?.pub || this.keypair?.publicKey;
153
+ }
154
+
155
+ /**
156
+ * Get crypto status information
157
+ * @returns {Object} Status information
158
+ */
159
+ getStatus() {
160
+ // Convert group keys Map to object for UI consumption
161
+ const groups = {};
162
+ this.groupKeys.forEach((groupKey, groupId) => {
163
+ groups[groupId] = {
164
+ publicKey: groupKey.pub,
165
+ created: groupKey.created || Date.now() // Use stored creation time or fallback to current time
166
+ };
167
+ });
168
+
169
+ return {
170
+ initialized: this.initialized,
171
+ enabled: this.encryptionEnabled,
172
+ hasKeypair: !!this.keypair,
173
+ publicKey: this.getPublicKey(),
174
+ peerCount: this.peerKeys.size,
175
+ groupCount: this.groupKeys.size,
176
+ groups,
177
+ stats: { ...this.stats }
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Store a peer's public keys (both pub and epub)
183
+ * @param {string} peerId - The peer ID
184
+ * @param {string|Object} publicKey - The peer's public key(s) - can be string (pub) or object with {pub, epub}
185
+ */
186
+ addPeerKey(peerId, publicKey) {
187
+ if (!publicKey) return false;
188
+
189
+ // Handle both string (just pub) and object (pub + epub) formats
190
+ let keyData;
191
+ if (typeof publicKey === 'string') {
192
+ keyData = { pub: publicKey, epub: null };
193
+ } else if (typeof publicKey === 'object' && (publicKey.pub || publicKey.epub)) {
194
+ keyData = publicKey;
195
+ } else {
196
+ return false;
197
+ }
198
+
199
+ this.peerKeys.set(peerId, keyData);
200
+ this.stats.keyExchanges++;
201
+ this.emit('peerKeyAdded', { peerId, publicKey: keyData });
202
+ return true;
203
+ }
204
+
205
+ /**
206
+ * Remove a peer's public key
207
+ * @param {string} peerId - The peer ID
208
+ */
209
+ removePeerKey(peerId) {
210
+ const removed = this.peerKeys.delete(peerId);
211
+ if (removed) {
212
+ this.emit('peerKeyRemoved', { peerId });
213
+ }
214
+ return removed;
215
+ }
216
+
217
+ /**
218
+ * Encrypt a message for a specific peer
219
+ * @param {any} message - The message to encrypt
220
+ * @param {string} peerId - The target peer ID
221
+ * @returns {Promise<Object>} Encrypted message object
222
+ */
223
+ async encryptForPeer(message, peerId) {
224
+ if (!this.encryptionEnabled) {
225
+ return { encrypted: false, data: message };
226
+ }
227
+
228
+ const peerKeyData = this.peerKeys.get(peerId);
229
+ if (!peerKeyData) {
230
+ throw new Error(`No public key found for peer ${peerId}`);
231
+ }
232
+
233
+ // Check if we have the encryption public key (epub)
234
+ if (!peerKeyData.epub) {
235
+ throw new Error(`No encryption public key (epub) found for peer ${peerId}. Only regular public key (pub) available.`);
236
+ }
237
+
238
+ const startTime = Date.now();
239
+ try {
240
+ const nonce = await this.generateNonce();
241
+ const serialized = JSON.stringify(message);
242
+
243
+ // Create a keypair object for unsea with both pub and epub
244
+ const peerKeypair = {
245
+ pub: peerKeyData.pub,
246
+ epub: peerKeyData.epub
247
+ };
248
+ const encrypted = await this.unsea.encryptMessageWithMeta(serialized, peerKeypair);
249
+
250
+ const result = {
251
+ encrypted: true,
252
+ data: encrypted,
253
+ from: this.getPublicKey(),
254
+ nonce,
255
+ timestamp: Date.now()
256
+ };
257
+
258
+ this.stats.messagesEncrypted++;
259
+ this.stats.encryptionTime += Date.now() - startTime;
260
+
261
+ return result;
262
+ } catch (error) {
263
+ console.error('Peer encryption failed:', error);
264
+ throw error;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Decrypt a message from a peer
270
+ * @param {Object} encryptedData - The encrypted message object
271
+ * @returns {Promise<any>} The decrypted message
272
+ */
273
+ async decryptFromPeer(encryptedData) {
274
+ if (!this.encryptionEnabled || !encryptedData.encrypted) {
275
+ return encryptedData.data || encryptedData;
276
+ }
277
+
278
+ // Check for replay attacks
279
+ if (encryptedData.nonce && this.messageNonces.has(encryptedData.nonce)) {
280
+ throw new Error('Replay attack detected: duplicate nonce');
281
+ }
282
+
283
+ const startTime = Date.now();
284
+ try {
285
+ // Use unsea's decryptMessageWithMeta - pass our ephemeral private key (epriv)
286
+ const decrypted = await this.unsea.decryptMessageWithMeta(encryptedData.data, this.keypair.epriv);
287
+ const parsed = JSON.parse(decrypted);
288
+
289
+ // Store nonce to prevent replay
290
+ if (encryptedData.nonce) {
291
+ this.messageNonces.add(encryptedData.nonce);
292
+ }
293
+
294
+ this.stats.messagesDecrypted++;
295
+ this.stats.decryptionTime += Date.now() - startTime;
296
+
297
+ return parsed;
298
+ } catch (error) {
299
+ console.error('Peer decryption failed:', error);
300
+ throw error;
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Sign data with our private key
306
+ * @param {any} data - The data to sign
307
+ * @returns {Promise<string>} The signature
308
+ */
309
+ async sign(data) {
310
+ if (!this.encryptionEnabled) return null;
311
+
312
+ try {
313
+ const serialized = typeof data === 'string' ? data : JSON.stringify(data);
314
+ return await this.unsea.signMessage(serialized, this.keypair.priv);
315
+ } catch (error) {
316
+ console.error('Signing failed:', error);
317
+ throw error;
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Verify a signature
323
+ * @param {string} signature - The signature to verify
324
+ * @param {any} data - The original data
325
+ * @param {string} publicKey - The signer's public key
326
+ * @returns {Promise<boolean>} Whether the signature is valid
327
+ */
328
+ async verify(signature, data, publicKey) {
329
+ if (!this.encryptionEnabled) return true;
330
+
331
+ try {
332
+ const serialized = typeof data === 'string' ? data : JSON.stringify(data);
333
+ return await this.unsea.verifyMessage(serialized, signature, publicKey);
334
+ } catch (error) {
335
+ console.error('Signature verification failed:', error);
336
+ return false;
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Generate a shared group key
342
+ * @param {string} groupId - The group identifier
343
+ * @returns {Promise<Object>} The group key pair
344
+ */
345
+ async generateGroupKey(groupId) {
346
+ try {
347
+ const groupKey = await this.unsea.generateRandomPair();
348
+ // Add metadata to the group key
349
+ const groupKeyWithMeta = {
350
+ ...groupKey,
351
+ created: Date.now(),
352
+ groupId
353
+ };
354
+ this.groupKeys.set(groupId, groupKeyWithMeta);
355
+ this.emit('groupKeyGenerated', { groupId, publicKey: groupKey.pub });
356
+ return groupKeyWithMeta;
357
+ } catch (error) {
358
+ console.error('Group key generation failed:', error);
359
+ throw error;
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Add an existing group key
365
+ * @param {string} groupId - The group identifier
366
+ * @param {Object} groupKey - The group key pair
367
+ */
368
+ addGroupKey(groupId, groupKey) {
369
+ this.groupKeys.set(groupId, groupKey);
370
+ this.emit('groupKeyAdded', { groupId, publicKey: groupKey.pub });
371
+ }
372
+
373
+ /**
374
+ * Encrypt a message for a group
375
+ * @param {any} message - The message to encrypt
376
+ * @param {string} groupId - The group identifier
377
+ * @returns {Promise<Object>} Encrypted message object
378
+ */
379
+ async encryptForGroup(message, groupId) {
380
+ if (!this.encryptionEnabled) {
381
+ return { encrypted: false, data: message };
382
+ }
383
+
384
+ const groupKey = this.groupKeys.get(groupId);
385
+ if (!groupKey) {
386
+ throw new Error(`No group key found for group ${groupId}`);
387
+ }
388
+
389
+ const startTime = Date.now();
390
+ try {
391
+ const nonce = await this.generateNonce();
392
+ const serialized = JSON.stringify(message);
393
+ const encrypted = await this.unsea.encryptMessageWithMeta(serialized, groupKey);
394
+
395
+ const result = {
396
+ encrypted: true,
397
+ group: true,
398
+ groupId,
399
+ data: encrypted,
400
+ from: this.getPublicKey(),
401
+ nonce,
402
+ timestamp: Date.now()
403
+ };
404
+
405
+ this.stats.messagesEncrypted++;
406
+ this.stats.encryptionTime += Date.now() - startTime;
407
+
408
+ return result;
409
+ } catch (error) {
410
+ console.error('Group encryption failed:', error);
411
+ throw error;
412
+ }
413
+ }
414
+
415
+ /**
416
+ * Decrypt a group message
417
+ * @param {Object} encryptedData - The encrypted message object
418
+ * @returns {Promise<any>} The decrypted message
419
+ */
420
+ async decryptFromGroup(encryptedData) {
421
+ if (!this.encryptionEnabled || !encryptedData.encrypted || !encryptedData.group) {
422
+ return encryptedData.data || encryptedData;
423
+ }
424
+
425
+ const groupKey = this.groupKeys.get(encryptedData.groupId);
426
+ if (!groupKey) {
427
+ throw new Error(`No group key found for group ${encryptedData.groupId}`);
428
+ }
429
+
430
+ // Check for replay attacks
431
+ if (encryptedData.nonce && this.messageNonces.has(encryptedData.nonce)) {
432
+ throw new Error('Replay attack detected: duplicate nonce');
433
+ }
434
+
435
+ const startTime = Date.now();
436
+ try {
437
+ const decrypted = await this.unsea.decryptMessageWithMeta(encryptedData.data, groupKey.epriv);
438
+ const parsed = JSON.parse(decrypted);
439
+
440
+ // Store nonce to prevent replay
441
+ if (encryptedData.nonce) {
442
+ this.messageNonces.add(encryptedData.nonce);
443
+ }
444
+
445
+ this.stats.messagesDecrypted++;
446
+ this.stats.decryptionTime += Date.now() - startTime;
447
+
448
+ return parsed;
449
+ } catch (error) {
450
+ console.error('Group decryption failed:', error);
451
+ throw error;
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Generate a cryptographically secure nonce
457
+ * @returns {Promise<string>} A unique nonce
458
+ */
459
+ async generateNonce() {
460
+ // Generate a simple nonce using timestamp and random
461
+ const timestamp = Date.now().toString();
462
+ const random = Math.random().toString(36).substring(2);
463
+ const combined = `${timestamp}-${random}-${Math.floor(Math.random() * 1000000)}`;
464
+
465
+ // Use crypto.subtle to hash the combined string if available
466
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
467
+ try {
468
+ const encoder = new TextEncoder();
469
+ const data = encoder.encode(combined);
470
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
471
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
472
+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('').substring(0, 16);
473
+ } catch (error) {
474
+ console.warn('Could not use crypto.subtle for nonce generation:', error);
475
+ }
476
+ }
477
+
478
+ // Fallback to simple combined string
479
+ return combined;
480
+ }
481
+
482
+ /**
483
+ * Start periodic cleanup of old nonces
484
+ */
485
+ startNonceCleanup() {
486
+ setInterval(() => {
487
+ // Remove old nonces (this is a simplified approach)
488
+ // In a real implementation, you'd store nonces with timestamps
489
+ if (this.messageNonces.size > 1000) {
490
+ this.messageNonces.clear();
491
+ }
492
+ }, 60000); // Clean up every minute
493
+ }
494
+
495
+ /**
496
+ * Export public key for sharing
497
+ * @returns {Object} Export data
498
+ */
499
+ exportPublicKey() {
500
+ if (!this.keypair) return null;
501
+
502
+ return {
503
+ pub: this.keypair.pub,
504
+ epub: this.keypair.epub,
505
+ algorithm: 'ECDSA',
506
+ created: Date.now()
507
+ };
508
+ }
509
+
510
+ /**
511
+ * Clear all stored keys and reset state
512
+ */
513
+ reset() {
514
+ this.keypair = null;
515
+ this.peerKeys.clear();
516
+ this.groupKeys.clear();
517
+ this.messageNonces.clear();
518
+ this.encryptionEnabled = false;
519
+ this.initialized = false;
520
+
521
+ // Reset stats
522
+ this.stats = {
523
+ messagesEncrypted: 0,
524
+ messagesDecrypted: 0,
525
+ encryptionTime: 0,
526
+ decryptionTime: 0,
527
+ keyExchanges: 0
528
+ };
529
+
530
+ this.emit('cryptoReset');
531
+ }
532
+
533
+ /**
534
+ * Test crypto functionality
535
+ * @returns {Promise<Object>} Test results
536
+ */
537
+ async runSelfTest() {
538
+ const results = {
539
+ keypairGeneration: false,
540
+ encryption: false,
541
+ decryption: false,
542
+ signing: false,
543
+ verification: false,
544
+ groupEncryption: false,
545
+ errors: []
546
+ };
547
+
548
+ // Check if crypto is properly initialized
549
+ if (!this.unsea) {
550
+ results.errors.push('Unsea library not loaded');
551
+ return results;
552
+ }
553
+
554
+ if (!this.initialized) {
555
+ results.errors.push('CryptoManager not initialized');
556
+ return results;
557
+ }
558
+
559
+ console.log('🔍 Debug: unsea object:', this.unsea);
560
+ console.log('🔍 Debug: available methods:', Object.keys(this.unsea));
561
+
562
+ try {
563
+ // Test keypair generation
564
+ console.log('🧪 Testing keypair generation...');
565
+ const testKeypair = await this.unsea.generateRandomPair();
566
+ console.log('🔍 Generated keypair:', testKeypair);
567
+ results.keypairGeneration = !!(testKeypair && (testKeypair.pub || testKeypair.publicKey));
568
+
569
+ // Test encryption/decryption - create two keypairs to simulate peer-to-peer encryption
570
+ console.log('🧪 Testing encryption...');
571
+ const testMessage = 'Hello, crypto world!';
572
+
573
+ // Create a second keypair to simulate a peer
574
+ const peerKeypair = await this.unsea.generateRandomPair();
575
+
576
+ // Encrypt from our keypair TO the peer keypair
577
+ const encrypted = await this.unsea.encryptMessageWithMeta(testMessage, peerKeypair);
578
+ console.log('🔍 Encrypted result:', encrypted);
579
+ results.encryption = !!encrypted;
580
+
581
+ console.log('🧪 Testing decryption...');
582
+ // Use the ephemeral private key (epriv) for decryption as shown in the example
583
+ const decrypted = await this.unsea.decryptMessageWithMeta(encrypted, peerKeypair.epriv);
584
+ console.log('🔍 Decrypted result:', decrypted);
585
+ results.decryption = decrypted === testMessage;
586
+
587
+ // Test signing/verification
588
+ console.log('🧪 Testing signing...');
589
+ const signature = await this.unsea.signMessage(testMessage, this.keypair.priv);
590
+ console.log('🔍 Signature:', signature);
591
+ results.signing = !!signature;
592
+
593
+ console.log('🧪 Testing verification...');
594
+ const verified = await this.unsea.verifyMessage(testMessage, signature, this.keypair.pub);
595
+ console.log('🔍 Verification result:', verified);
596
+ results.verification = verified === true;
597
+
598
+ // Test group encryption (same as regular encryption with different key)
599
+ console.log('🧪 Testing group encryption...');
600
+ const groupKey = await this.unsea.generateRandomPair();
601
+ const groupEncrypted = await this.unsea.encryptMessageWithMeta(testMessage, groupKey);
602
+ const groupDecrypted = await this.unsea.decryptMessageWithMeta(groupEncrypted, groupKey.epriv);
603
+ results.groupEncryption = groupDecrypted === testMessage;
604
+ } catch (error) {
605
+ console.error('🔍 Self-test error:', error);
606
+ results.errors.push(error.message);
607
+ }
608
+
609
+ console.log('🔍 Final test results:', results);
610
+ return results;
611
+ }
612
+ }