-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
350 lines (305 loc) · 11.8 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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<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>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
text-align: left;
}
</style>
</head>
<body>
<form onsubmit="generate();return false">
<input type="submit" value="Generate"/> or input public/private keys:</br>
<textarea rows="2" cols="50" id="public_key" placeholder="Public key"></textarea>
</br>
<textarea rows="2" cols="50" id="private_key" placeholder="Private key"></textarea>
</form>
</br>
Input a relay url (choose from the <a href="https://nostr-registry.netlify.app/" target="_blank">Nostr Relay Registry</a>):</br>
<form onsubmit="connect();return false">
<input type="text" size="30" id="relay_url" value="wss://relay.nostr.info" placeholder="Relay Url"/>
<input id="connectButton" type="submit" value="Connect"/>
<input id="disconnectButton" hidden="true" type="button" value="Disconnect" onclick="disconnect()" />
</form>
</br>
Input a message:</br>
<form onsubmit="send();return false">
<textarea rows="2" cols="50" id="public_key_destination" placeholder="Input a destination public key for direct message or leave empty for public message"></textarea>
</br>
<textarea id="message" rows="4" cols="50" placeholder="Message"></textarea>
</br>
<input type="submit" value="Send"/>
</form>
</br>
<table id="messages"></table>
<script type="text/javascript">
function getPublicKey() {
return document.getElementById('public_key').value;
}
function setPublicKey(key) {
document.getElementById('public_key').value = key;
}
function getPrivateKey() {
return document.getElementById('private_key').value;
}
function setPrivateKey(key) {
document.getElementById('private_key').value = key;
}
function getRelayUrl() {
return document.getElementById('relay_url').value;
}
function getDestinationPublicKey() {
return document.getElementById('public_key_destination').value;
}
function getMessageToSend() {
return document.getElementById('message').value;
}
function clearMessageToSend() {
document.getElementById('message').value = "";
}
function clearMessages() {
messages = [];
var table = document.getElementById('messages');
table.replaceChildren();
}
function appendHeader(row, text) {
var header = document.createElement("th");
header.textContent = text;
row.appendChild(header);
}
function appendMessage(content, pubkey, created_at, tags) {
messages.push(
{
'date': created_at,
'from': pubkey,
'to': getDestinationPublicKeyFromTags(tags),
'message': content
}
);
messages = messages.sort((a, b) => (a.date < b.date) ? 1 : -1);
var table = document.getElementById('messages');
table.replaceChildren();
var headerRow = table.insertRow();
appendHeader(headerRow, "Date");
appendHeader(headerRow, "From");
appendHeader(headerRow, "To");
appendHeader(headerRow, "Message");
messages.forEach(element => {
var row = table.insertRow();
insertCell(row, dateToString(element.date));
insertCell(row, prettyFormatKey(element.from), element.from);
insertCell(row, prettyFormatKey(element.to), element.to);
insertCell(row, element.message);
});
}
function insertCell(row, text, mouseovertext) {
var cell = row.insertCell();
appendPreTag(cell, text, mouseovertext);
}
function appendPreTag(cell, text, mouseovertext) {
var pre = document.createElement('pre');
pre.textContent = text;
cell.appendChild(pre);
var preMouseOverText = document.createElement('pre');
preMouseOverText.textContent = mouseovertext;
preMouseOverText.hidden = true;
cell.appendChild(preMouseOverText);
if (mouseovertext) {
cell.addEventListener("mouseover", function(event) {
preMouseOverText.hidden = false;
pre.hidden = true;
});
cell.addEventListener("mouseout", function(event) {
preMouseOverText.hidden = true;
pre.hidden = false;
});
}
}
var socket;
var messages = [];
function generate() {
var keypair = bitcoinjs.ECPair.makeRandom();
var privKey = keypair.privateKey.toString("hex");
var pubKey = keypair.publicKey.toString("hex");
pubKey = pubKey.substring(2);
setPublicKey(pubKey);
setPrivateKey(privKey);
}
function disconnect() {
if (!socket) return;
socket.close();
}
function connect() {
if (getPublicKey().length < 1 || getPrivateKey().length < 1) {
alert("Generate or input public/private keys.");
return;
}
clearMessages();
var relayUrl = getRelayUrl();
if (socket) socket.close();
socket = new WebSocket(relayUrl);
socket.addEventListener('message', async function(message) {
var [type, subId, event] = JSON.parse(message.data);
if (!event) return;
console.log('Event:', event);
var {kind, content, tags, pubkey, created_at, id} = event || {};
console.log('Event (Nostr Gateway):', "https://nostr.com/e/" + id);
if (kind === 1) {
appendMessage(content, pubkey, created_at, tags);
} else if (kind === 4) {
if (pubkey == getPublicKey()) {
// I'm the sender of this encrypted direct message
// Decrypt content using private key and destination public key
var destinationPubKey = getDestinationPublicKeyFromTags(tags);
content = await decrypt(getPrivateKey(), destinationPubKey, content);
} else {
// I'm the destination of this encrypted direct message
// Decrypt content using my private key and the sender public key
content = await decrypt(getPrivateKey(), pubkey, content);
}
appendMessage(content, pubkey, created_at, tags);
}
});
socket.addEventListener('close', async function(e) {
console.log("Disconnected");
document.getElementById('connectButton').hidden = false;
document.getElementById('disconnectButton').hidden = true;
});
socket.addEventListener('open', async function(e) {
console.log("Connected to " + relayUrl);
console.log("Events (Nostr Gateway):", "https://nostr.com/p/" + getPublicKey());
document.getElementById('connectButton').hidden = true;
document.getElementById('disconnectButton').hidden = false;
var subId = bitcoinjs.ECPair.makeRandom().privateKey.toString("hex");
var authorFilter = { "authors": [getPublicKey()] };
var edmFilter = { "#p": [getPublicKey()] };
var subscription = ["REQ", subId, authorFilter, edmFilter];
console.log('Subscription:', subscription);
socket.send(JSON.stringify(subscription));
});
}
function getDestinationPublicKeyFromTags(tags) {
var i; for (i = 0; i < tags.length; i++) {
if (tags[i][0] === "p") {
return tags[i][1];
}
}
return "";
}
function send() {
if (!socket) {
alert("You must connect to a relay.");
return;
}
if (getMessageToSend().length < 1) {
alert("Write a message.");
return;
}
var destinationPubKey = getDestinationPublicKey();
if (destinationPubKey) {
sendEncryptedDirectMessage(getPrivateKey(), getPublicKey(), destinationPubKey, getMessageToSend());
} else {
sendTextNote(getPrivateKey(), getPublicKey(), getMessageToSend());
}
clearMessageToSend();
}
// https://github.com/nostr-protocol/nips/blob/master/01.md#basic-event-kinds
async function sendTextNote(privkey, pubkey, text) {
var event = {
"content": text,
"created_at": Math.floor(Date.now() / 1000),
"kind": 1,
"tags": [],
"pubkey": pubkey
};
var signedEvent = await getSignedEvent(event, privkey);
console.log('Signed Event:', signedEvent);
socket.send(JSON.stringify(["EVENT", signedEvent]));
}
// https://github.com/nostr-protocol/nips/blob/master/04.md
async function sendEncryptedDirectMessage(privkey, pubkey, destpubkey, text) {
var encrypted = encrypt(privkey, destpubkey, text)
var event = {
"content": encrypted,
"created_at": Math.floor(Date.now() / 1000),
"kind": 4,
"tags": [['p', destpubkey]],
"pubkey": pubkey
};
var signedEvent = await getSignedEvent(event, privkey);
console.log('Signed Event:', signedEvent);
socket.send(JSON.stringify([ "EVENT", signedEvent ]));
}
async function getSignedEvent(event, privateKey) {
var { schnorr } = nobleSecp256k1;
var sha256 = bitcoinjs.crypto.sha256;
var eventData = JSON.stringify([
0,
event['pubkey'],
event['created_at'],
event['kind'],
event['tags'],
event['content']
]);
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);
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");
return decryptedMessage + decipher.final("utf8");
}
function dateToString(unixTimestamp) {
return new Date(unixTimestamp * 1000).toLocaleString();
}
function prettyFormatKey(key) {
if (key) {
return key.slice(0, 4) + "..." + key.slice(-4);
} else {
return "PUBLIC";
}
}
</script>
</body>
</html>