-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser-example.html
More file actions
980 lines (830 loc) · 33.2 KB
/
browser-example.html
File metadata and controls
980 lines (830 loc) · 33.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PigeonIdP Browser Example</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h1 {
color: #333;
border-bottom: 2px solid #4CAF50;
padding-bottom: 10px;
}
.section {
margin: 20px 0;
padding: 15px;
background: #f9f9f9;
border-left: 4px solid #4CAF50;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px;
font-size: 14px;
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.log {
background: #1e1e1e;
color: #00ff00;
padding: 15px;
border-radius: 4px;
font-family: monospace;
font-size: 12px;
max-height: 400px;
overflow-y: auto;
margin-top: 20px;
}
.log-entry {
margin: 5px 0;
padding: 3px 0;
}
.log-entry.success { color: #00ff00; }
.log-entry.error { color: #ff4444; }
.log-entry.info { color: #4da6ff; }
input {
padding: 8px;
margin: 5px;
border: 1px solid #ddd;
border-radius: 4px;
width: 200px;
}
.status {
padding: 10px;
margin: 10px 0;
border-radius: 4px;
font-weight: bold;
}
.status.connected {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.status.disconnected {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
</style>
</head>
<body>
<div class="container">
<h1>🕊️ PigeonIdP Browser Demo</h1>
<div class="status disconnected" id="status">
Status: Not Connected
</div>
<div class="status disconnected" id="peerStatus">
Connected Peers: 0
</div>
<div class="section">
<h2>Configuration</h2>
<label>
Namespace:
<input type="text" id="namespace" value="demo-namespace" />
</label>
<label>
Alias:
<input type="text" id="alias" value="demo-user" />
</label>
<label>
Password:
<input type="password" id="password" value="demo-password-123" />
</label>
</div>
<div class="section">
<h2>Identity Management</h2>
<button onclick="initializeIdP()">Initialize IdP</button>
<button onclick="refreshPeers()" id="refreshBtn" disabled>Refresh Peers</button>
<button onclick="createIdentity()" id="createBtn" disabled>Create Identity</button>
<button onclick="loadIdentity()" id="loadBtn" disabled>Load Identity</button>
<button onclick="clearStoredKeys()" id="clearBtn" disabled style="background-color: #e74c3c;">Clear Stored Keys</button>
<button onclick="retrieveFromDHT()" id="retrieveBtn" disabled>Retrieve from DHT</button>
<button onclick="registerIdentity()" id="registerBtn" disabled>Register in DHT</button>
</div>
<div class="section">
<h2>Authentication</h2>
<button onclick="generateToken()" id="tokenBtn" disabled>Generate Auth Token</button>
<button onclick="verifyToken()" id="verifyBtn" disabled>Verify Token</button>
</div>
<div class="section">
<h2>Messaging</h2>
<label>
Message:
<input type="text" id="message" value="Hello from browser!" />
</label>
<button onclick="signMessage()" id="signBtn" disabled>Sign Message</button>
<button onclick="verifySignature()" id="verifySignBtn" disabled>Verify Signature</button>
<button onclick="encryptMessage()" id="encryptBtn" disabled>Encrypt Message</button>
<button onclick="decryptMessage()" id="decryptBtn" disabled>Decrypt Message</button>
</div>
<div class="section">
<h2>Cross-Browser Verification</h2>
<label>
Signature to verify:
<input type="text" id="signatureInput" placeholder="Paste signature here" style="width: 300px;" />
</label>
<label>
Public Key:
<input type="text" id="publicKeyInput" placeholder="Paste public key here" style="width: 300px;" />
</label>
</div>
<div class="section">
<h2>Export/Import</h2>
<button onclick="exportKeys()" id="exportBtn" disabled>Export Keys</button>
<button onclick="importKeys()" id="importBtn" disabled>Import Keys</button>
<button onclick="disconnect()" id="disconnectBtn" disabled>Disconnect</button>
</div>
<h2>Console Log</h2>
<div class="log" id="log"></div>
</div>
<!-- Load PeerPigeon browser bundle (includes UnSEA) -->
<script src="../node_modules/peerpigeon/dist/peerpigeon-browser.js"></script>
<script type="module">
// Get PeerPigeon components and UnSEA from the browser bundle
const { PeerPigeonMesh, WebDHT } = window.PeerPigeon || PeerPigeon;
const UnSEA = window.__PEERPIGEON_UNSEA__;
// Helper function to derive deterministic keys from password
async function deriveKeysFromPassword(seed) {
// Generate deterministic keys by deriving private keys from password
// then using UnSEA's internal p256 curve to compute public keys
console.log('🔑 Deriving deterministic keys from password');
const encoder = new TextEncoder();
// Use PBKDF2 to derive deterministic private keys
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(seed),
{ name: 'PBKDF2' },
false,
['deriveBits']
);
const salt = encoder.encode('PigeonIdP-v1');
// Derive 64 bytes: 32 for signing key, 32 for encryption key
const derivedBits = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256'
},
keyMaterial,
512 // 64 bytes
);
const derivedArray = new Uint8Array(derivedBits);
const signingPriv = derivedArray.slice(0, 32);
const encryptionPriv = derivedArray.slice(32, 64);
// Helper functions (copied from UnSEA internals)
const bufToB64Url = (buf) => {
const bin = String.fromCharCode(...new Uint8Array(buf));
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};
const keyToJWK = (pubBuf) => {
if (pubBuf[0] !== 4) throw new Error('Expected uncompressed key');
const x = pubBuf.slice(1, 33);
const y = pubBuf.slice(33, 65);
return `${bufToB64Url(x)}.${bufToB64Url(y)}`;
};
// OK so Web Crypto API won't compute x,y from d automatically
// We need to use noble-curves which is already in UnSEA
// Let's access it via a clever trick: monkey-patch generateRandomPair temporarily
// HACK: Inject our deterministic private keys by overriding crypto.getRandomValues
const originalGetRandomValues = crypto.getRandomValues.bind(crypto);
let callCount = 0;
console.log('🔧 Monkey-patching crypto.getRandomValues for deterministic key generation');
console.log('Derived signing key (first 16 bytes):', Array.from(signingPriv.slice(0, 16)).map(b => b.toString(16).padStart(2, '0')).join(''));
console.log('Derived encryption key (first 16 bytes):', Array.from(encryptionPriv.slice(0, 16)).map(b => b.toString(16).padStart(2, '0')).join(''));
crypto.getRandomValues = function(array) {
console.log(`crypto.getRandomValues called with array length: ${array.length}, callCount: ${callCount}`);
// UnSEA might request 32 bytes (just the key) or 48 bytes (key + extra data)
// We need to inject our deterministic bytes for the first two calls regardless of size
if (callCount === 0 && array.length >= 32) {
// First call: signing private key
array.set(signingPriv, 0);
console.log(`✅ Injected deterministic SIGNING key (first 32 bytes of ${array.length}-byte array)`);
callCount++;
return array;
} else if (callCount === 1 && array.length >= 32) {
// Second call: encryption private key
array.set(encryptionPriv, 0);
console.log(`✅ Injected deterministic ENCRYPTION key (first 32 bytes of ${array.length}-byte array)`);
callCount++;
return array;
}
console.log(`⚠️ Using original random values (length=${array.length}, callCount=${callCount})`);
return originalGetRandomValues(array);
};
try {
// Now generate keys - they'll use our deterministic values
console.log('Calling UnSEA.generateRandomPair()...');
const keys = await UnSEA.generateRandomPair();
console.log('✅ Deterministic keys generated successfully!');
console.log('📍 Public key fingerprint:', keys.pub.substring(0, 20) + '...');
console.log('📍 Full public key:', keys.pub);
console.log(`Total crypto.getRandomValues calls intercepted: ${callCount}`);
return keys;
} finally {
// Restore original function
crypto.getRandomValues = originalGetRandomValues;
console.log('🔧 Restored original crypto.getRandomValues');
}
}
// Inline PigeonIdP class for browser compatibility
class PigeonIdP {
constructor(options = {}) {
this.namespace = options.namespace || 'default';
this.signalingServers = options.signalingServers || ['ws://localhost:3000'];
this.meshOptions = options.meshOptions || {};
this.mesh = null;
this.webDHT = null;
this.keys = null;
this.initialized = false;
}
async init() {
if (this.initialized) {
return;
}
this.mesh = new PeerPigeonMesh({
networkName: this.namespace,
enableWebDHT: true, // Ensure WebDHT is enabled
autoConnect: true,
autoDiscovery: true,
maxPeers: 10,
minPeers: 1,
...this.meshOptions
});
await this.mesh.init();
// Connect to signaling server
const signalingServer = this.signalingServers[0];
await this.mesh.connect(signalingServer);
// Use the mesh's built-in WebDHT instead of creating a new one
this.webDHT = this.mesh.webDHT;
if (!this.webDHT) {
throw new Error('WebDHT not initialized on mesh');
}
this.initialized = true;
}
async createIdentity(alias, password) {
if (!this.initialized) {
throw new Error('IdP not initialized. Call init() first.');
}
// Use password-based key derivation if password is provided
if (password && password.length > 0) {
const seed = alias + ':' + password;
this.keys = await deriveKeysFromPassword(seed);
} else {
// Generate random keys
this.keys = await UnSEA.generateRandomPair();
}
await UnSEA.saveKeys(alias, this.keys, password);
return this.keys;
}
async loadIdentity(alias, password) {
if (!this.initialized) {
throw new Error('IdP not initialized. Call init() first.');
}
// Try loading from IndexedDB first
console.log('🔍 Attempting to load keys from storage for:', alias);
try {
this.keys = await UnSEA.loadKeys(alias, password);
console.log('📦 Keys loaded from storage:', this.keys ? 'SUCCESS' : 'NOT FOUND');
} catch (error) {
console.log('❌ Error loading from storage:', error.message);
this.keys = null;
}
if (!this.keys && password && password.length > 0) {
// Not found in storage, derive from password instead
console.log('🔑 Keys not found in storage, deriving from password...');
const seed = alias + ':' + password;
this.keys = await deriveKeysFromPassword(seed);
// Save for future use
await UnSEA.saveKeys(alias, this.keys, password);
console.log('💾 Derived keys saved to storage');
}
if (!this.keys) {
throw new Error('Identity not found or incorrect password');
}
return this.keys;
}
async retrieveIdentityFromDHT(username) {
if (!this.initialized) {
throw new Error('IdP not initialized. Call init() first.');
}
const key = `identity:${username}`;
console.log('Retrieving from DHT with key:', key);
console.log('Connected peers:', this.mesh.getConnectedPeerCount());
// Retrieve public identity data from DHT
const identityData = await this.webDHT.get(key);
console.log('Retrieved data:', identityData);
if (!identityData) {
throw new Error('Identity not found in DHT. Make sure the identity was registered and peers are connected.');
}
// Verify the signature
const dataToVerify = JSON.stringify({
username: identityData.username,
displayName: identityData.displayName,
timestamp: identityData.timestamp,
publicKey: identityData.publicKey,
createdAt: identityData.createdAt
});
const valid = await UnSEA.verifyMessage(dataToVerify, identityData.signature, identityData.publicKey);
if (!valid) {
throw new Error('Identity signature verification failed');
}
return identityData;
}
async registerIdentity(profile) {
if (!this.initialized) {
throw new Error('IdP not initialized. Call init() first.');
}
if (!this.keys) {
throw new Error('No identity loaded. Create or load an identity first.');
}
const identityData = {
...profile,
publicKey: this.keys.pub,
createdAt: Date.now()
};
const signature = await UnSEA.signMessage(JSON.stringify(identityData), this.keys.priv);
identityData.signature = signature;
const key = `identity:${profile.username}`;
console.log('Registering to DHT with key:', key);
console.log('Identity data:', identityData);
await this.webDHT.put(key, identityData);
return identityData;
}
async generateAuthToken(claims, expiresIn = 3600) {
if (!this.keys) {
throw new Error('No identity loaded. Create or load an identity first.');
}
const token = {
claims: {
...claims,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + expiresIn
},
publicKey: this.keys.pub
};
const signature = await UnSEA.signMessage(JSON.stringify(token.claims), this.keys.priv);
token.signature = signature;
return token;
}
async verifyAuthToken(token) {
try {
const valid = await UnSEA.verifyMessage(JSON.stringify(token.claims), token.signature, token.publicKey);
if (!valid) {
return { valid: false, error: 'Invalid signature' };
}
const now = Math.floor(Date.now() / 1000);
if (token.claims.exp && token.claims.exp < now) {
return { valid: false, error: 'Token expired' };
}
return { valid: true, claims: token.claims };
} catch (error) {
return { valid: false, error: error.message };
}
}
async sign(message) {
if (!this.keys) {
throw new Error('No identity loaded. Create or load an identity first.');
}
return await UnSEA.signMessage(message, this.keys.priv);
}
async verify(message, signature, publicKey) {
return await UnSEA.verifyMessage(message, signature, publicKey);
}
async encrypt(message) {
if (!this.keys) {
throw new Error('No identity loaded. Create or load an identity first.');
}
// Encrypt to ourselves (use our own keys as recipient)
return await UnSEA.encryptMessageWithMeta(message, this.keys);
}
async decrypt(encrypted) {
if (!this.keys) {
throw new Error('No identity loaded. Create or load an identity first.');
}
return await UnSEA.decryptMessageWithMeta(encrypted, this.keys.epriv);
}
getPublicKeys() {
if (!this.keys) {
throw new Error('No identity loaded. Create or load an identity first.');
}
return {
pub: this.keys.pub,
epub: this.keys.epub
};
}
async exportKeys() {
if (!this.keys) {
throw new Error('No identity loaded. Create or load an identity first.');
}
// Return the keys object directly (already in the correct format)
return this.keys;
}
async disconnect() {
if (this.mesh) {
await this.mesh.disconnect();
}
this.initialized = false;
}
}
// Global state
let idp = null;
let currentToken = null;
// Logging
function log(message, type = 'info') {
const logDiv = document.getElementById('log');
const entry = document.createElement('div');
entry.className = `log-entry ${type}`;
entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
logDiv.appendChild(entry);
logDiv.scrollTop = logDiv.scrollHeight;
}
function updateStatus(connected) {
const status = document.getElementById('status');
if (connected) {
status.textContent = 'Status: Connected';
status.className = 'status connected';
} else {
status.textContent = 'Status: Not Connected';
status.className = 'status disconnected';
}
}
function updatePeerStatus(count) {
const peerStatus = document.getElementById('peerStatus');
peerStatus.textContent = `Connected Peers: ${count}`;
if (count > 0) {
peerStatus.className = 'status connected';
} else {
peerStatus.className = 'status disconnected';
}
}
function enableButtons(enabled) {
document.getElementById('refreshBtn').disabled = !enabled;
document.getElementById('createBtn').disabled = !enabled;
document.getElementById('loadBtn').disabled = !enabled;
document.getElementById('clearBtn').disabled = !enabled;
document.getElementById('retrieveBtn').disabled = !enabled;
document.getElementById('registerBtn').disabled = !enabled;
document.getElementById('tokenBtn').disabled = !enabled;
document.getElementById('verifyBtn').disabled = !enabled;
document.getElementById('signBtn').disabled = !enabled;
document.getElementById('verifySignBtn').disabled = !enabled;
document.getElementById('encryptBtn').disabled = !enabled;
document.getElementById('decryptBtn').disabled = !enabled;
document.getElementById('exportBtn').disabled = !enabled;
document.getElementById('importBtn').disabled = !enabled;
document.getElementById('disconnectBtn').disabled = !enabled;
}
// Initialize IdP
window.initializeIdP = async function() {
try {
log('Initializing PigeonIdP...', 'info');
const namespace = document.getElementById('namespace').value;
const config = {
namespace: namespace,
signalingServers: ['ws://localhost:3000']
};
log(`Config: ${JSON.stringify(config)}`, 'info');
idp = new PigeonIdP(config);
await idp.init();
log(`Mesh options: ${JSON.stringify({
networkName: idp.mesh.networkName,
autoConnect: idp.mesh.connectionManager?.autoConnect,
autoDiscovery: idp.mesh.peerDiscovery?.autoDiscovery,
signalingServers: idp.mesh.signalingServers
})}`, 'info');
// Update initial peer count
const initialPeerCount = idp.mesh.getConnectedPeerCount();
updatePeerStatus(initialPeerCount);
// Listen for signaling events
idp.mesh.on('signalingConnected', () => {
log('✓ Connected to signaling server', 'success');
});
idp.mesh.on('signalingDisconnected', () => {
log('⚠️ Disconnected from signaling server', 'error');
});
idp.mesh.on('peerDiscovered', (data) => {
const peerId = data.peerId || data;
log(`🔍 Peer discovered: ${String(peerId).substring(0, 8)}...`, 'info');
});
// Listen for peer connections
idp.mesh.on('peerConnected', (data) => {
const peerId = data.peerId || data;
const peerCount = idp.mesh.getConnectedPeerCount();
log(`🔗 Peer connected: ${String(peerId).substring(0, 8)}...`, 'success');
log(`Total connected peers: ${peerCount}`, 'info');
updatePeerStatus(peerCount);
});
idp.mesh.on('peerDisconnected', (data) => {
const peerId = data.peerId || data;
const peerCount = idp.mesh.getConnectedPeerCount();
log(`🔌 Peer disconnected: ${String(peerId).substring(0, 8)}...`, 'info');
log(`Total connected peers: ${peerCount}`, 'info');
updatePeerStatus(peerCount);
});
log('✓ IdP initialized successfully', 'success');
log(`Peer ID: ${idp.mesh.peerId.substring(0, 16)}...`, 'info');
log(`Namespace: ${namespace}`, 'info');
log('Waiting for peer connections...', 'info');
// Check signaling connection status
if (idp.mesh.signalingClient && idp.mesh.signalingClient.isConnected) {
log('✓ Signaling server connected', 'success');
} else {
log('⚠️ Signaling server not connected', 'error');
}
log('🔍 Auto-discovery is enabled, waiting for peers...', 'info');
updateStatus(true);
enableButtons(true);
} catch (error) {
log(`✗ Error initializing: ${error.message}`, 'error');
console.error(error);
}
};
// Refresh peers
window.refreshPeers = async function() {
try {
log('🔄 Checking peer status...', 'info');
const peerCount = idp.mesh.getConnectedPeerCount();
log(`Current connected peers: ${peerCount}`, 'info');
// Log all discovered peers
if (idp.mesh.peerDiscovery && idp.mesh.peerDiscovery.discoveredPeers) {
log(`Discovered peers in registry: ${idp.mesh.peerDiscovery.discoveredPeers.size}`, 'info');
}
updatePeerStatus(peerCount);
} catch (error) {
log(`✗ Error refreshing peers: ${error.message}`, 'error');
console.error(error);
}
};
// Create identity
window.createIdentity = async function() {
try {
const alias = document.getElementById('alias').value;
const password = document.getElementById('password').value;
log(`Creating identity with alias: ${alias}...`, 'info');
const keys = await idp.createIdentity(alias, password);
log('✓ Identity created successfully', 'success');
log(`Public Key: ${keys.pub.substring(0, 50)}...`, 'info');
log('💡 To use this identity in another browser, click "Export Keys"', 'info');
} catch (error) {
log(`✗ Error creating identity: ${error.message}`, 'error');
console.error(error);
}
};
// Load identity
window.loadIdentity = async function() {
try {
const alias = document.getElementById('alias').value;
const password = document.getElementById('password').value;
log(`Loading identity: ${alias}...`, 'info');
const keys = await idp.loadIdentity(alias, password);
log('✓ Identity loaded successfully', 'success');
log(`Public Key: ${keys.pub.substring(0, 50)}...`, 'info');
} catch (error) {
log(`✗ Error loading identity: ${error.message}`, 'error');
console.error(error);
}
};
// Retrieve identity from DHT
window.retrieveFromDHT = async function() {
try {
const alias = document.getElementById('alias').value;
log(`Retrieving identity from DHT: ${alias}...`, 'info');
const identityData = await idp.retrieveIdentityFromDHT(alias);
log('✓ Identity retrieved from DHT', 'success');
log(`Username: ${identityData.username}`, 'info');
log(`Display Name: ${identityData.displayName}`, 'info');
log(`Public Key: ${identityData.publicKey.substring(0, 50)}...`, 'info');
log(`Created: ${new Date(identityData.createdAt).toLocaleString()}`, 'info');
log('Note: This is public info only. Use "Load Identity" with password to access private keys.', 'info');
} catch (error) {
log(`✗ Error retrieving from DHT: ${error.message}`, 'error');
console.error(error);
}
};
// Clear stored keys
window.clearStoredKeys = async function() {
try {
const alias = document.getElementById('alias').value;
if (!confirm(`Are you sure you want to delete stored keys for "${alias}"? This cannot be undone!`)) {
return;
}
log('Clearing stored keys...', 'info');
await UnSEA.clearKeys(alias);
log('✓ Stored keys cleared successfully', 'success');
log('💡 Use "Load Identity" with password to derive keys deterministically', 'info');
} catch (error) {
log(`✗ Error clearing keys: ${error.message}`, 'error');
console.error(error);
}
};
// Register identity
window.registerIdentity = async function() {
try {
const alias = document.getElementById('alias').value;
log('Registering identity in DHT...', 'info');
const result = await idp.registerIdentity({
username: alias,
displayName: alias.toUpperCase(),
timestamp: Date.now()
});
log('✓ Identity registered in DHT', 'success');
log(`Key: identity:${alias}`, 'info');
log('Wait 2-3 seconds for DHT to propagate before retrieving', 'info');
} catch (error) {
log(`✗ Error registering identity: ${error.message}`, 'error');
console.error(error);
}
};
// Generate token
window.generateToken = async function() {
try {
log('Generating authentication token...', 'info');
currentToken = await idp.generateAuthToken({
username: document.getElementById('alias').value,
role: 'user'
}, 3600);
log('✓ Token generated successfully', 'success');
log(`Claims: ${JSON.stringify(currentToken.claims)}`, 'info');
} catch (error) {
log(`✗ Error generating token: ${error.message}`, 'error');
console.error(error);
}
};
// Verify token
window.verifyToken = async function() {
try {
if (!currentToken) {
log('✗ No token to verify. Generate one first.', 'error');
return;
}
log('Verifying token...', 'info');
const result = await idp.verifyAuthToken(currentToken);
if (result.valid) {
log('✓ Token is valid', 'success');
log(`Username: ${result.claims.username}`, 'info');
} else {
log(`✗ Token is invalid: ${result.error}`, 'error');
}
} catch (error) {
log(`✗ Error verifying token: ${error.message}`, 'error');
console.error(error);
}
};
// Sign message
window.signMessage = async function() {
try {
const message = document.getElementById('message').value;
log(`Signing message: "${message}"...`, 'info');
const signature = await idp.sign(message);
log('✓ Message signed successfully', 'success');
log(`Signature: ${signature}`, 'info');
log('💡 Copy this signature to verify in another browser', 'info');
// Auto-populate signature input for easy testing
document.getElementById('signatureInput').value = signature;
// Verify it locally
const keys = idp.getPublicKeys();
const valid = await idp.verify(message, signature, keys.pub);
log(`✓ Local signature verification: ${valid}`, 'success');
} catch (error) {
log(`✗ Error signing message: ${error.message}`, 'error');
console.error(error);
}
};
// Verify signature from another user
window.verifySignature = async function() {
try {
const message = document.getElementById('message').value;
const signature = document.getElementById('signatureInput').value;
const publicKey = document.getElementById('publicKeyInput').value;
if (!signature || !publicKey) {
log('⚠️ Please enter both signature and public key', 'error');
return;
}
log(`Verifying signature...`, 'info');
log(`Message: "${message}"`, 'info');
log(`Public Key: ${publicKey.substring(0, 30)}...`, 'info');
const valid = await idp.verify(message, signature, publicKey);
if (valid) {
log('✅ Signature is VALID! Message was signed by this public key.', 'success');
} else {
log('❌ Signature is INVALID! Message was NOT signed by this public key.', 'error');
}
} catch (error) {
log(`✗ Error verifying signature: ${error.message}`, 'error');
console.error(error);
}
};
// Encrypt message
let lastEncryptedMessage = null;
window.encryptMessage = async function() {
try {
const message = document.getElementById('message').value;
log(`Encrypting message: "${message}"...`, 'info');
const encrypted = await idp.encrypt(message);
lastEncryptedMessage = encrypted;
log('✓ Message encrypted successfully', 'success');
log(`Encrypted ciphertext: ${encrypted.ciphertext.substring(0, 50)}...`, 'info');
} catch (error) {
log(`✗ Error encrypting message: ${error.message}`, 'error');
console.error(error);
}
};
// Decrypt message
window.decryptMessage = async function() {
try {
if (!lastEncryptedMessage) {
log('✗ No encrypted message to decrypt. Encrypt a message first.', 'error');
return;
}
log('Decrypting message...', 'info');
const decrypted = await idp.decrypt(lastEncryptedMessage);
log(`✓ Decrypted message: "${decrypted}"`, 'success');
} catch (error) {
log(`✗ Error decrypting message: ${error.message}`, 'error');
console.error(error);
}
};
// Export keys
window.exportKeys = async function() {
try {
log('Exporting keys to JWK format...', 'info');
const keys = await idp.exportKeys();
const keysJson = JSON.stringify(keys, null, 2);
// Copy to clipboard
await navigator.clipboard.writeText(keysJson);
log('✓ Keys exported successfully', 'success');
log('✓ Keys copied to clipboard!', 'success');
log('Paste these keys in another browser to import the same identity', 'info');
console.log('Exported keys:', keys);
} catch (error) {
log(`✗ Error exporting keys: ${error.message}`, 'error');
console.error(error);
}
};
// Import keys
window.importKeys = async function() {
try {
const keysJson = prompt('Paste the exported keys JSON:');
if (!keysJson) {
log('✗ Import cancelled', 'error');
return;
}
const keys = JSON.parse(keysJson);
const alias = document.getElementById('alias').value;
const password = document.getElementById('password').value;
log(`Importing keys for ${alias}...`, 'info');
// Save the imported keys
await UnSEA.saveKeys(alias, keys, password);
// Load them into the current session
idp.keys = keys;
log('✓ Keys imported successfully', 'success');
log(`Public Key: ${keys.pub.substring(0, 50)}...`, 'info');
log('You can now use this identity!', 'success');
} catch (error) {
log(`✗ Error importing keys: ${error.message}`, 'error');
console.error(error);
}
};
// Disconnect
window.disconnect = async function() {
try {
log('Disconnecting from mesh...', 'info');
await idp.disconnect();
log('✓ Disconnected successfully', 'success');
updateStatus(false);
enableButtons(false);
idp = null;
} catch (error) {
log(`✗ Error disconnecting: ${error.message}`, 'error');
console.error(error);
}
};
// Initial log message
log('PigeonIdP Browser Demo loaded', 'success');
log('Click "Initialize IdP" to begin', 'info');
</script>
</body>
</html>