-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.html
1034 lines (926 loc) · 34.7 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no" />
<title>Pulsar</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Chakra+Petch&family=Source+Code+Pro&family=UnifrakturCook:wght@700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="index.css?v=12" />
<script src="https://bitcoincore.tech/apps/bitcoinjs-ui/lib/bitcoinjs-lib.js"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script>
var $ = document.querySelector.bind(document);
var $$ = document.querySelectorAll.bind(document);
var url_params = new URLSearchParams(window.location.search);
var url_keys = url_params.keys();
var $_GET = {};
for (var key of url_keys) $_GET[key] = url_params.get(key);
</script>
<script>
var { getSharedSecret, schnorr, utils } = nobleSecp256k1;
var crypto = window.crypto;
var getRand = (size) => crypto.getRandomValues(new Uint8Array(size));
var sha256 = bitcoinjs.crypto.sha256;
var num_of_messages = 0;
var timestamp_of_oldest_message = null;
var message_queue = [];
var real_messages = [];
var displayed_msgs = [];
function bytesToHex(bytes) {
return bytes.reduce(
(str, byte) => str + byte.toString(16).padStart(2, "0"),
""
);
}
function hexToBytes(hex) {
return Uint8Array.from(
hex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))
);
}
function pubkeyToNpub(hex) {
return bech32.bech32.encode(
"npub",
bech32.bech32.toWords(hexToBytes(hex, "hex"))
);
}
function pubkeyFromNpub(npub) {
return bytesToHex(
bech32.bech32.fromWords(bech32.bech32.decode(npub).words)
);
}
function privkeyToNsec(hex) {
return bech32.bech32.encode(
"nsec",
bech32.bech32.toWords(hexToBytes(hex, "hex"))
);
}
function privkeyFromNsec(nsec) {
return bytesToHex(
bech32.bech32.fromWords(bech32.bech32.decode(nsec).words)
);
}
if (!$_GET["relays"]) {
if (window.location.href.endsWith("index.html")) {
var url =
window.location.protocol +
"//" +
window.location.hostname +
window.location.pathname.substring(
0,
window.location.pathname.length - 10
) +
"onboard.html";
} else {
var url =
window.location.protocol +
"//" +
window.location.hostname +
window.location.pathname +
"onboard.html";
}
window.location.href = url;
}
var shared_secret = null;
var shared_pub = null;
var real_privKey = null;
var real_pubKey = null;
var keypair = null;
var privKey = null;
var pubKey = null;
relays = JSON.parse(localStorage.getItem("relays"));
var sockets = [];
relays.forEach((relay) => {
const socket = new WebSocket(relay);
setupSocket(socket, relay);
sockets.push(socket);
});
function reconnectSocket(socket, relay) {
console.log(`Reconnecting to ${relay}...`);
const newSocket = new WebSocket(relay);
setupSocket(newSocket, relay);
const index = sockets.indexOf(socket);
if (index !== -1) {
sockets[index] = newSocket;
} else {
sockets.push(newSocket);
}
}
function setupSocket(socket, relay) {
socket.addEventListener("open", function () {
openConnection();
});
socket.addEventListener("close", function (e) {
console.log(
"Socket is closed for",
relay,
". Reconnect will be attempted.",
e.reason
);
// Only try reconnecting if the relay is still in the relays array.
if (relays.includes(relay)) {
setTimeout(() => {
reconnectSocket(socket, relay);
}, 1000);
}
});
socket.addEventListener("message", async function (message) {
var [type, subId, event] = JSON.parse(message.data);
var { kind, content } = event || {};
if (!event || event === true) return;
var real_msg = await detectRealMessage(event);
if (displayed_msgs.includes(event.id)) return;
displayed_msgs.push(event.id);
if (real_msg[0]) real_messages.push(real_msg);
if (real_msg[0]) populateRealMessages();
if (!subId.startsWith("00000001")) return;
num_of_messages = num_of_messages + 1;
timestamp_of_oldest_message = event.created_at;
if (num_of_messages < 45) return;
num_of_messages = 0;
var subId =
"00000001" +
bitcoinjs.ECPair.makeRandom()
.privateKey.toString("hex")
.substring(0, 8);
var filter = {
"#p": [shared_pub],
until: timestamp_of_oldest_message,
limit: 50,
};
var subscription = ["REQ", subId, filter];
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(subscription));
}
socket.addEventListener("close", (e) => {
console.log(
"Socket is closed. Reconnect will be attempted.",
e.reason
);
setTimeout(() => {
reconnectSocket(socket, relay);
}, 1000);
});
});
async function openConnection(e) {
if (!shared_pub) {
await waitSomeSeconds(1);
openConnection(e);
return;
}
var now = Math.floor(Date.now() / 1000);
var subId =
"00000000" +
bitcoinjs.ECPair.makeRandom()
.privateKey.toString("hex")
.substring(0, 8);
var filter = { "#p": [shared_pub], since: now };
var subscription = ["REQ", subId, filter];
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(subscription));
}
var subId =
"00000001" +
bitcoinjs.ECPair.makeRandom()
.privateKey.toString("hex")
.substring(0, 8);
var filter = { "#p": [shared_pub], until: now, limit: 50 };
var subscription = ["REQ", subId, filter];
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(subscription));
}
setTimeout(messageMaker, 3000);
}
socket.addEventListener("open", openConnection);
socket.addEventListener("close", (e) => {
console.log(
"Socket is closed. Reconnect will be attempted.",
e.reason
);
setTimeout(() => {
// Reconnect logic here.
}, 1000);
});
}
sockets.forEach(function (socket) {
setupSocket(socket);
});
async function getSignedEvent(event, privateKey) {
var eventData = JSON.stringify([
0, // Reserved for future use
event["pubkey"], // The sender's public key
event["created_at"], // Unix timestamp
event["kind"], // Message “kind” or type
event["tags"], // Tags identify replies/recipients
event["content"], // Your note contents
]);
event.id = sha256(eventData).toString("hex");
event.sig = await schnorr.sign(event.id, privateKey);
return event;
}
function hexToBytes(hex) {
return Uint8Array.from(
hex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))
);
}
function bytesToHex(bytes) {
return bytes.reduce(
(str, byte) => str + byte.toString(16).padStart(2, "0"),
""
);
}
function base64ToHex(str) {
var raw = atob(str);
var result = "";
var i;
for (i = 0; i < raw.length; i++) {
var hex = raw.charCodeAt(i).toString(16);
result += hex.length === 2 ? hex : "0" + hex;
}
return result;
}
function encrypt(privkey, pubkey, text) {
var key = nobleSecp256k1
.getSharedSecret(privkey, "02" + pubkey, true)
.substring(2);
var iv = window.crypto.getRandomValues(new Uint8Array(16));
var cipher = browserifyCipher.createCipheriv(
"aes-256-cbc",
hexToBytes(key),
iv
);
var encryptedMessage = cipher.update(text, "utf8", "base64");
emsg = encryptedMessage + cipher.final("base64");
var uint8View = new Uint8Array(iv.buffer);
var decoder = new TextDecoder();
return emsg + "?iv=" + btoa(String.fromCharCode.apply(null, uint8View));
}
function decrypt(privkey, pubkey, ciphertext) {
var [emsg, iv] = ciphertext.split("?iv=");
var key = nobleSecp256k1
.getSharedSecret(privkey, "02" + pubkey, true)
.substring(2);
var decipher = browserifyCipher.createDecipheriv(
"aes-256-cbc",
hexToBytes(key),
hexToBytes(base64ToHex(iv))
);
var decryptedMessage = decipher.update(emsg, "base64");
dmsg = decryptedMessage + decipher.final("utf8");
return dmsg;
}
</script>
<script>
function waitSomeSeconds(num) {
var num = num.toString() + "000";
num = Number(num);
return new Promise((resolve) => setTimeout(resolve, num));
}
function textToHex(text) {
var encoder = new TextEncoder().encode(text);
return [...new Uint8Array(encoder)]
.map((x) => x.toString(16).padStart(2, "0"))
.join("");
}
function hexToText(hex) {
var bytes = new Uint8Array(Math.ceil(hex.length / 2));
for (var i = 0; i < hex.length; i++)
bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
var text = new TextDecoder().decode(bytes);
return text;
}
var send = (msg) => {
var now = Math.floor(Date.now() / 1000);
var first_part = String(now).substring(0, String(now).length - 1);
var second_part = String(now).substring(String(now).length - 1);
var second_part = roundToOneFourOrSeven(Number(second_part));
now = Number(first_part + String(second_part));
message_queue.unshift([msg, now]);
messageMaker(true, msg, now);
};
var detectRealMessage = async (event) => {
var msg = decrypt(shared_secret, event.pubkey, event["content"]);
var pubkey = msg.substring(msg.length - 64);
var sig = msg.substring(msg.length - (128 + 64), msg.length - 64);
msg = msg.substring(0, msg.length - (128 + 64));
msg = msg.match(/(..?)/g);
var index_of_last_zero = -1;
msg.reverse();
msg.every((char, index) => {
if (char === "00") {
index_of_last_zero = 500 - index;
return;
}
return true;
});
msg.reverse();
msg.splice(0, index_of_last_zero);
msg = msg.join("");
msg = hexToText(msg);
event["content"] = msg;
event["pubkey"] = pubkey;
event["sig"] = sig;
var eventData = JSON.stringify([
0,
event["pubkey"],
event["created_at"],
event["kind"],
event["tags"],
event["content"],
]);
event["id"] = sha256(eventData).toString("hex");
if (msg)
var sig_is_valid = await schnorr.verify(sig, event["id"], pubkey);
var returnable = ["", sig, pubkey, event["created_at"]];
if (sig_is_valid) returnable = [msg, pubkey, event["created_at"]];
return returnable;
};
let aliases = JSON.parse(localStorage.getItem("aliases")) || {};
var populateRealMessages = () => {
real_messages.sort((a, b) => {
return a[2] - b[2];
});
document.querySelector(".messages").innerHTML = "";
real_messages.forEach((msg) => {
var div = document.createElement("div");
div.className = "message";
msg[1] === real_pubKey
? div.classList.add("user-message")
: div.classList.add("peer-message");
var span1 = document.createElement("span");
span1.innerText =
aliases[msg[1]] !== undefined
? aliases[msg[1]]
: msg[1] === real_pubKey
? "You"
: msg[1].substring(0, 26) + "...";
div.appendChild(span1);
if (div.classList.contains("peer-message")) {
var dropdown = createMessageDropdown(msg, div, span1);
div.appendChild(dropdown);
}
var pElement = document.createElement("p");
pElement.innerText = msg[0];
div.appendChild(pElement);
var span2 = document.createElement("span");
span2.classList.add("timestamp");
span2.setAttribute("data-timestamp", msg[2]);
span2.innerText = formatTimestamp(msg[2]);
div.appendChild(span2);
document.querySelector(".messages").appendChild(div); // Use appendChild here
});
// Scroll to bottom of chat
var messageBox = document.querySelector(".messages");
messageBox.scrollTop = messageBox.scrollHeight;
};
function createRelayRow(relay) {
var relayRow = document.createElement("div");
relayRow.classList.add("relay-row");
var stateDisplay = document.createElement("span");
stateDisplay.classList.add("stateDisplay");
// Look for the socket associated with the relay and attach a listener
sockets.forEach((socket) => {
if (socket.url === relay) {
if (socket.readyState === 1) {
stateDisplay.classList.add("online");
} else {
stateDisplay.classList.add("offline");
}
// Listener to update the status when it changes
socket.addEventListener("open", () =>
stateDisplay.classList.replace("offline", "online")
);
socket.addEventListener("close", () =>
stateDisplay.classList.replace("online", "offline")
);
}
});
relayRow.appendChild(stateDisplay);
var relayText = document.createElement("p");
relayText.innerText = relay;
relayRow.appendChild(relayText);
var trashIcon = document.createElement("img");
trashIcon.classList.add("icon");
trashIcon.src = "assets/trash-icon.png";
trashIcon.width = 25;
trashIcon.height = 25;
trashIcon.onclick = function () {
let index = relays.indexOf(relay);
if (index > -1) {
relays.splice(index, 1);
localStorage.setItem("relays", JSON.stringify(relays));
relayRow.remove();
}
};
relayRow.appendChild(trashIcon);
return relayRow;
}
function updateSockets() {
// Close sockets that aren't in the relays array
sockets.forEach((socket) => {
if (!relays.includes(socket.url)) {
socket.close();
const index = sockets.indexOf(socket);
if (index !== -1) {
sockets.splice(index, 1);
}
}
});
// Open sockets for relays not in the sockets array
relays.forEach((relay) => {
if (!sockets.some((socket) => socket.url === relay)) {
const socket = new WebSocket(relay);
setupSocket(socket, relay);
sockets.push(socket);
}
});
}
var createChatOptionsDropdown = () => {
const header = document.getElementsByTagName("header")[0];
var wrapper = document.createElement("div"); // create a new wrapper element
wrapper.className = "dropdown-wrapper"; // assign a class for the wrapper
var button = document.createElement("button");
button.className = "chat-options-button";
button.innerHTML = "...";
button.onclick = function () {
this.nextSibling.classList.toggle("show");
};
wrapper.appendChild(button); // append the button to the wrapper
var dropdownContent = document.createElement("div");
dropdownContent.className = "chat-dropdown-content";
var chatInfo = document.createElement("p");
chatInfo.innerText = "chat info";
chatInfo.onclick = function () {
let unique_pubkeys = [...new Set(real_messages.map((msg) => msg[1]))];
let oldestMessageTimestamp = Math.min(
...real_messages.map((msg) => msg[2])
);
let startDate = new Date(
oldestMessageTimestamp * 1000
).toLocaleDateString();
var startDateText = document.createElement("p");
startDateText.innerText = `Chat started on: ${startDate}`;
showModal(
`${unique_pubkeys.length} unique npubs in this chat`,
startDateText
);
};
dropdownContent.appendChild(chatInfo);
var copyChatString = document.createElement("p");
copyChatString.innerText = "copy chat string";
copyChatString.onclick = function () {
navigator.clipboard.writeText(shared_secret);
};
dropdownContent.appendChild(copyChatString);
var selectRelays = document.createElement("p");
selectRelays.innerText = "select relays";
var relayList;
selectRelays.onclick = function () {
var chatDropdown = document.getElementsByClassName(
"chat-dropdown-content"
)[0];
chatDropdown.classList.remove("show");
relayList = document.createElement("div");
relayList.classList.add("relay-list");
relays.forEach((relay) => {
var relayRow = document.createElement("div");
relayRow.classList.add("relay-row");
var stateDisplay = document.createElement("span");
stateDisplay.classList.add("stateDisplay");
sockets.forEach((socket) => {
if (socket.url === relay) {
if (socket.readyState === 1) {
stateDisplay.classList.add("online");
} else {
stateDisplay.classList.add("offline");
}
}
});
relayRow.appendChild(stateDisplay);
var relayText = document.createElement("p");
relayText.innerText = relay;
relayRow.appendChild(relayText);
var trashIcon = document.createElement("img");
trashIcon.classList.add("icon");
trashIcon.src = "assets/trash-icon.png";
trashIcon.width = 25;
trashIcon.height = 25;
trashIcon.onclick = function () {
// Remove relay from relays array
let index = relays.indexOf(relay);
if (index > -1) {
relays.splice(index, 1);
// Save updated relays back to localStorage
localStorage.setItem("relays", JSON.stringify(relays));
// Remove the relay row from the UI
relayRow.remove();
}
updateSockets();
};
relayRow.appendChild(trashIcon);
relayList.appendChild(relayRow);
});
var addRelayWrapper = document.createElement("div");
addRelayWrapper.classList.add("add-relay-wrapper");
var relayInput = document.createElement("input");
relayInput.setAttribute("type", "text");
relayInput.setAttribute("placeholder", "Enter new relay");
relayInput.classList.add("relay-input");
var addRelayButton = document.createElement("button");
addRelayButton.setAttribute("id", "relay-button");
addRelayButton.innerText = "Add Relay";
addRelayButton.onclick = function () {
var newRelay = relayInput.value.trim();
if (newRelay && !relays.includes(newRelay)) {
relays.push(newRelay);
// Save updated relays back to localStorage
localStorage.setItem("relays", JSON.stringify(relays));
// Create a new WebSocket for the relay
const newSocket = new WebSocket(newRelay);
setupSocket(newSocket, newRelay);
sockets.push(newSocket);
// Add the new relay to the UI
var newRelayRow = createRelayRow(newRelay);
relayList.insertBefore(newRelayRow, addRelayWrapper);
// Clear input for next relay addition
relayInput.value = "";
}
};
addRelayWrapper.appendChild(relayInput);
addRelayWrapper.appendChild(addRelayButton);
relayList.appendChild(addRelayWrapper);
showModal("", relayList);
};
dropdownContent.appendChild(selectRelays);
wrapper.appendChild(dropdownContent); // append the dropdown content to the wrapper
header.appendChild(wrapper); // append the wrapper to the header
return header;
};
var createMessageDropdown = (msg, div, span1) => {
var wrapper = document.createElement("div");
wrapper.className = "options-wrapper";
var button = document.createElement("button");
button.className = "options-button";
button.innerHTML = "...";
button.onclick = function () {
this.nextSibling.classList.toggle("show");
};
wrapper.appendChild(button);
var dropdownContent = document.createElement("div");
dropdownContent.className = "dropdown-content";
var copyNpubLink = document.createElement("p");
copyNpubLink.innerText = "copy npub";
copyNpubLink.onclick = function () {
navigator.clipboard.writeText(pubkeyToNpub(msg[1])).then(
() => {
console.log("Public key copied to clipboard");
},
(err) => {
console.error("Could not copy text: ", err);
}
);
};
dropdownContent.appendChild(copyNpubLink);
var createAliasLink = document.createElement("p");
createAliasLink.innerText = "edit user alias";
createAliasLink.onclick = function () {
// Hide the current alias
span1.style.display = "none";
var inputElement = document.createElement("input");
inputElement.value = aliases[msg[1]] || "";
inputElement.className = "alias-input";
var saveButton = document.createElement("button");
saveButton.innerHTML = "Save";
saveButton.className = "save-button";
var buttonWrapper = document.createElement("div");
buttonWrapper.appendChild(inputElement);
buttonWrapper.appendChild(saveButton);
saveButton.onclick = function () {
saveAlias(inputElement, buttonWrapper, span1);
};
inputElement.onkeypress = function (e) {
if (e.key === "Enter") {
saveAlias(inputElement, buttonWrapper, span1);
}
};
// Append the wrapper and show it
div.appendChild(buttonWrapper);
buttonWrapper.style.display = "block";
// Auto focus on the new input field
inputElement.focus();
};
function saveAlias(inputElement, buttonWrapper, span) {
var alias = inputElement.value;
console.log("Alias saved:", alias);
// assuming you have an aliases object for storage
aliases[msg[1]] = alias;
// Save aliases back to localStorage
localStorage.setItem("aliases", JSON.stringify(aliases));
// Update span with new alias
span.innerText = alias;
// Hide the input field and button, show the span
buttonWrapper.style.display = "none";
span.style.display = "block";
}
dropdownContent.appendChild(createAliasLink);
wrapper.appendChild(dropdownContent);
return wrapper;
};
function formatTimestamp(timestamp) {
const currentTime = new Date();
const msgTime = new Date(Number(timestamp) * 1000); // Convert timestamp string back to a number and to milliseconds
const timeDifference = currentTime - msgTime;
const differenceInMinutes = Math.floor(timeDifference / (60 * 1000));
if (differenceInMinutes < 1) {
return "less than a minute ago";
} else if (differenceInMinutes < 60) {
return `${differenceInMinutes} ${
differenceInMinutes > 1 ? "minutes" : "minute"
} ago`;
} else {
return msgTime.toLocaleString();
}
}
function updateTimestamps() {
const timestampElements = document.getElementsByClassName("timestamp");
for (let i = 0; i < timestampElements.length; i++) {
const timestampElement = timestampElements[i];
const timestamp = timestampElement.getAttribute("data-timestamp");
timestampElement.innerText = formatTimestamp(timestamp);
}
}
setTimeout(updateTimestamps, 60 * 1000); // Start after 1 minute delay
setInterval(updateTimestamps, 60 * 1000); // Then run every minute
var roundToOneFourOrSeven = (num) => {
if (num >= 0 && num < 3) num = 1;
if (num >= 3 && num < 6) num = 4;
if (num >= 6) num = 7;
return num;
};
var getRandomHex = () => {
var hex = bytesToHex(window.crypto.getRandomValues(new Uint8Array(1)));
if (hex === "00") return getRandomHex();
return hex;
};
function modalVanish() {
$(".black-bg").style.display = "none";
$(".modal").style.display = "none";
}
function showModal(content, additionalHTML) {
$(
".modal"
).innerHTML = `<div style="position: absolute; right: 1rem; top: 0.5rem; font-size: 2rem; cursor: pointer; color: black;" onclick="modalVanish()">×</div>`;
$(
".modal"
).innerHTML += `<div style="overflow-y: scroll; max-height: 80vh; margin-top: 1.5rem;">${content}</div>`;
if (additionalHTML) {
$(".modal").appendChild(additionalHTML);
}
$(".black-bg").style.display = "block";
$(".modal").style.display = "block";
}
window.onclick = function (event) {
if (
!event.target.matches(".chat-options-button") &&
!event.target.matches(".options-button") &&
!event.target.closest(".dropdown-wrapper") &&
!event.target.closest(".options-wrapper")
) {
var dropdowns = document.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains("show")) {
openDropdown.classList.remove("show");
}
}
var chatDropdowns = document.getElementsByClassName(
"chat-dropdown-content"
);
for (var i = 0; i < chatDropdowns.length; i++) {
var openDropdown = chatDropdowns[i];
if (openDropdown.classList.contains("show")) {
openDropdown.classList.remove("show");
}
}
}
};
</script>
<script>
window.addEventListener("resize", setBodyHeight);
function setBodyHeight() {
// set the height of the body
document.body.style.height = `${window.innerHeight}px`;
}
window.onload = async function () {
if (window.nostr) {
$(".nsec_div").classList.add("hidden");
$(".gen_nsec").classList.add("hidden");
var pk = await window.nostr.getPublicKey();
console.log("pk:", pk);
real_pubKey = pk;
}
setBodyHeight();
var torLink = document.createElement("a");
torLink.href =
"http://kzthpkengwzo7tjo7xh36xmjpxdyxlhky76lwxsiop2zogt44udidsqd.onion/";
torLink.innerText =
"http://kzthpkengwzo7tjo7xh36xmjpxdyxlhky76lwxsiop2zogt44udidsqd.onion/";
showModal(
"You're IP address is exposed unless you are using a VPN or our tor website found here:",
torLink
);
};
</script>
</head>
<body>
<header>
<div class="title-container">
<h1>Pulsar</h1>
<div class="lds-ripple">
<div></div>
<div></div>
</div>
</div>
</header>
<div id="chat-string-form" class="chat_string">
<p>Enter your generated chat string</p>
<p><input class="shared_secret" /></p>
<div class="nsec_div">
<p>Enter your nsec</p>
<p><input class="nsec" /></p>
</div>
<div class="button-row">
<button class="gen_nsec">Generate nsec</button>
<button class="submit">Submit</button>
</div>
</div>
<div class="messenger hidden">
<div class="messages"></div>
<div class="button-input-row">
<input class="msg" />
<button class="send">Send</button>
</div>
<div class="invisible_messages hidden"></div>
</div>
<script>
var messageMaker = async (once, msg, timestamp) => {
if (!shared_secret) {
await waitSomeSeconds(1);
if (!once) messageMaker();
return;
}
keypair = bitcoinjs.ECPair.makeRandom();
privKey = keypair.privateKey.toString("hex");
pubKey = keypair.publicKey.toString("hex").substring(2);
var padding = "0".repeat(1000);
if (!msg) {
var original_array = message_queue.pop() || "";
if (original_array) {
var original_message = original_array[0];
var original_timestamp = original_array[1];
} else {
var original_message = "";
var original_timestamp = 1234567890;
}
} else {
var original_message = msg;
var original_timestamp = timestamp;
}
var message = padding + textToHex(original_message);
message = message.substring(message.length - 1000);
message = message.match(/(..?)/g);
var index_of_last_zero = -1;
message.reverse();
message.every((char, index) => {
if (char === "00") {
index_of_last_zero = 500 - index;
return;
}
return true;
});
message.reverse();
message.splice(0, index_of_last_zero - 1);
var i;
for (i = 0; i < index_of_last_zero - 1; i++)
message.unshift(getRandomHex());
message = message.join("");
//sign the real version of the event
var event = {
content: original_message,
created_at: original_timestamp,
kind: 4,
tags: [["p", shared_pub]],
pubkey: real_pubKey,
};
if (window.nostr) {
var signedEvent = await window.nostr.signEvent(event);
if (typeof signedEvent == "string") {
event.sig = signedEvent;
} else {
event.sig = signedEvent.sig;
}
} else {
var signedEvent = await getSignedEvent(event, real_privKey);
}
var sig = signedEvent.sig;
message = message + sig + real_pubKey;
var div = document.createElement("div");
div.innerText = message;
div.className = "message";
$(".invisible_messages").prepend(div);
//sign the padded version of the event
encrypted_msg = encrypt(shared_secret, pubKey, message);
var event = {
content: encrypted_msg,
created_at: original_timestamp,
kind: 4,
tags: [["p", shared_pub]],
pubkey: pubKey,
};
var publishable_signed_event = await getSignedEvent(event, privKey);
if (!once)
sockets.forEach((socket) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(["EVENT", publishable_signed_event]));
}
});
if (original_message) {
var real_msg = await detectRealMessage(event);
} else {
var real_msg = [""];
}
if (
!real_msg[0] ||
displayed_msgs.includes(publishable_signed_event["id"])
) {
await waitSomeSeconds(3);
if (!once) messageMaker();
return;
}
displayed_msgs.push(publishable_signed_event["id"]);
real_messages.push(real_msg);
populateRealMessages();
await waitSomeSeconds(3);
if (!once) messageMaker();
};
$(".submit").onclick = () => {
shared_secret = $(".shared_secret").value;
shared_pub = nobleSecp256k1
.getPublicKey(shared_secret, true)
.substring(2);
$(".chat_string").classList.add("hidden");
$(".messenger").classList.remove("hidden");
if (window.nostr) return;
nsec = $(".nsec").value;
real_privKey = privkeyFromNsec(nsec);
real_pubKey = nobleSecp256k1
.getPublicKey(real_privKey, true)
.substring(2);
console.log(real_pubKey);
// Generate options button for chat
createChatOptionsDropdown();
};
$(".send").onclick = () => {
var msg = $(".msg").value;
if (msg.length > 0) {