-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.html
More file actions
408 lines (387 loc) · 15.4 KB
/
chat.html
File metadata and controls
408 lines (387 loc) · 15.4 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
<html><head><title>real time chat over CJP2P</title></head>
<body>
<div id=ethstuff hidden=true>
you have to pick one of these, and can start messaging
when the bottom one filed<p>
gnosis safe address <input id=safe_address size=60>
<br>their eth addr <input id=their_eth_addr size=80>
<button id="connect-btn">Connect an Ethereum Wallet if you want to message by eth address</button>
</div>
<br>their ed25519 addr<input id=their_ed25519 size=80>
<p>Give this URL to the other person to chat with you:
<p><a id=link href="" ></a>
<p>or do these other things with them:
<p><a id=video href="">video call</a> --
<a id=pong href="">play pong</a> --
<a id=line_mode href="">switch to line by line chat (no javascript needed)</a>
<br><button id="single-btn">toggle single/dual window</button>
<br>
<p><a href=/>return to network status page</a>
<p>try /ping or /version
<div style='display: flex; height: 70vh;'>
<textarea id='input' style='width: 50%; height: 100%;' readonly></textarea>
<textarea id='output' style='width: 50%; height: 100%;' readonly></textarea>
</div>
<div id="saw-status" style="font-size:12px; padding:4px; color:#888;">Seen by them: never</div>
<br>
debuging :
<button onclick="logging=true">enable </button> (then scroll down)
<button onclick="logging=false">disable </button>
<script src="https://cdn.jsdelivr.net/npm/web3@1.8.0/dist/web3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ethers@6.13.0/dist/ethers.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ethers@6/dist/ethers.umd.min.js"></script>
<script>
const logBox = document.createElement('div');
logBox.id = 'log';
logBox.style.cssText = 'font-family:monospace; font-size:12px; padding:8px; white-space:pre-wrap; word-break:break-all;';
document.body.appendChild(logBox); // safe, no reset
const logDiv = document.createElement('div');
logDiv.id = 'log';
logDiv.style.cssText = 'position:fixed; bottom:0; left:0; right:0; max-height:30vh; overflow:auto; background:#111; color:#0f0; font-family:monospace; font-size:12px; padding:4px; z-index:9999;';
let logging=false;
let logQueue = Promise.resolve();
function log_always(...args) {
const line = document.createElement('div');
logQueue = logQueue.then(() => {
line.textContent = `[${new Date().toLocaleTimeString()}] ${args.join(' ')}`;
logBox.appendChild(line);
while (logBox.children.length > 2000) {
logBox.removeChild(logBox.firstChild);
}
// window.scrollTo(0, document.body.scrollHeight);
});
}
function log(...args) {
if (logging) log_always(args);
}
document.body.appendChild(logDiv);
const signed_ed25519s = new Map();
const safe_address = document.getElementById('safe_address');
const their_eth_addr = document.getElementById('their_eth_addr');
const their_ed25519 = document.getElementById('their_ed25519');
const input = document.getElementById('input');
let output = document.getElementById('output');
const link = document.getElementById('link');
function update_links() {
let url=location.origin+location.pathname;
if (safe_address.value.length>1) {
url += "?safe=" + safe_address.value;
document.getElementById('ethstuff').hidden=false;
}
else if (my_eth_address!=null) {
url += "?eth=" + my_eth_address;
their_eth_addr.hidden=false;
document.getElementById('ethstuff').hidden=false;
}
else {
url += "?ed25519=" + my_ed25519;
}
link.href = url;
link.textContent = url;
document.getElementById('video').href = "video.html?ed25519=" + their_ed25519.value;
document.getElementById('pong').href = "pong.html?ed25519=" + their_ed25519.value;
document.getElementById('line_mode').href = "/chat/" + their_ed25519.value;
}
function lsKey(ed, suffix) { return 'cjp2p_' + ed + '_' + suffix; }
function saveChat() {
const ed = their_ed25519.value;
if (!ed) return;
localStorage.setItem('cjp2p_last_ed25519', ed);
localStorage.setItem(lsKey(ed, 'input'), input.value);
localStorage.setItem(lsKey(ed, 'output'), document.getElementById('output').value);
}
function loadChat(ed) {
if (!ed) return;
const si = localStorage.getItem(lsKey(ed, 'input'));
const so = localStorage.getItem(lsKey(ed, 'output'));
if (si !== null) input.value = si;
if (so !== null) document.getElementById('output').value = so;
}
function set_their_ed25519(ed25519) {
input.readOnly = false;
their_ed25519.value=ed25519;
loadChat(ed25519);
update_links();
}
let my_eth_address = null;
function request_ed25519_from_eth_addr() {
socket.send(JSON.stringify([{GetPubByEth:{eth_addr:their_eth_addr.value}}]));
}
async function getSigners() {
if (safe_address.value.length == 0) {
return;
}
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
my_eth_address = accounts[0];
const provider = new ethers.BrowserProvider(window.ethereum)
const abi = ["function getOwners() view returns (address[])"]
const safe = new ethers.Contract(safe_address.value, abi, provider)
const owners = await safe.getOwners()
owners.forEach(function(v,k) {
if (v.toUpperCase()!=my_eth_address.toUpperCase()) {
their_eth_addr.value = v;
request_ed25519_from_eth_addr();
}
} );
}
async function sha256hex(text) {
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('');
}
let lastReceivedHash = null;
let lastSentHash = null;
let seenTop = false;
let seenBottom = false;
let sawSent = false;
const sawStatus = document.getElementById('saw-status');
function updateScrollSeen() {
const el = document.getElementById('output');
if (el.scrollTop <= 1) seenTop = true;
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 1) seenBottom = true;
}
async function checkAndSendSaw() {
updateScrollSeen();
if (seenTop && seenBottom && !sawSent && lastReceivedHash && their_ed25519.value) {
// sawSent = true;
socket.send(JSON.stringify([{Forward:{to_ed25519:their_ed25519.value, messages:[{SawMessage:{hash:lastReceivedHash}}]}}]));
}
}
document.getElementById('output').addEventListener('scroll', () => checkAndSendSaw());
function updateSawStatus(receivedHash, receivedTime) {
const timeStr = receivedTime.toLocaleTimeString();
if (lastSentHash && receivedHash === lastSentHash) {
sawStatus.textContent = 'Seen by them: ' + timeStr + ' \u2713';
sawStatus.style.color = '#2a2';
} else {
sawStatus.textContent = 'Seen by them: ' + timeStr + ' (older message)';
sawStatus.style.color = '#a80';
}
}
let originalTitle = document.title;
let blinkInterval;
function notifyNewMessage() {
let blinkCount = 0;
clearInterval(blinkInterval);
blinkInterval = setInterval(() => {
document.title = (blinkCount % 2 === 0) ? "(New Message!) " + originalTitle : originalTitle;
blinkCount++;
}, 1000);
};
window.addEventListener('focus', () => {
clearInterval(blinkInterval);
document.title = originalTitle;
checkAndSendSaw();
});
let my_ed25519_to_sign = null;
let my_ed25519 = null;
let single_window=false;
document.getElementById('single-btn').addEventListener('click', async () => {
if (!single_window) {
single_window=true;
output.style.width="0";
output=input;
output.style.width="100%";
} else {
single_window=false;
output.style.width="50%";
output = document.getElementById('output');
output.style.width="50%";
}
});
document.getElementById('connect-btn').addEventListener('click', async () => {
if (!window.ethereum) {
alert('Install MetaMask!');
return;
}
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
my_eth_address = accounts[0];
if ( my_ed25519_to_sign != null ) {
let sig = await window.ethereum.request({
method: 'personal_sign',
params: ["my ed25519 public key is " + my_ed25519_to_sign,my_eth_address],
});
socket.send(JSON.stringify([{MyPublicKey:{ed25519h:my_ed25519,ed25519_eth_signed:sig}}] ));
}
await getSigners();
document.getElementById('connect-btn').disabled = true;
});
function str(obj) {
if (obj instanceof Error) return `${obj.name}: ${obj.message}`;
try { return JSON.stringify(obj, null, 2); }
catch { return String(obj); }
}
window.onerror = (msg, url, line, col, err) => {
log('ERROR:', msg, 'at', url + ':' + line + ':' + col);
if (err && err.stack) log(err.stack);
return false;
};
window.onunhandledrejection = e => {
log('UNHANDLED PROMISE:', e.reason?.stack || e.reason || e);
};
['log', 'warn', 'error', 'info'].forEach(k => {
const orig = console[k].bind(console);
console[k] = (...args) => {
orig.apply(console, args); // still goes to real console if you have one
log(k.toUpperCase() + ':',...args);
};
});
let socket;
function connect() {
log("websocket connencting");
const url = new URL('/wt', window.location.href);
url.protocol = url.protocol.replace('http', 'ws');
// use url to use the websocket on the page's source system, though some functionality is security restricted unless its wss:// (https)
socket = new WebSocket("ws://localhost:24255/wt");
socket.onclose = () => {
console.log('Socket closed. Reconnecting ...');
log("websocket reconnencting");
setTimeout(connect, 200);
};
socket.onopen = () => {
let work = Promise.resolve();
socket.onmessage = async(event) => {
work = work.then(async () => {
log( "\n\n___________________n\n");
log(event.data);
let messages_ = JSON.parse(event.data);
let messages;
log( "\n\n==============\n\n");
let src=null;
let forwarded=false;
if ("Forwarded" in messages_[0]) {
src=messages_[0].Forwarded.from_ed25519;
forwarded=true;
messages = JSON.parse(messages_[0].Forwarded.messages);
log( "\n" + messages_[0].Forwarded.messages);
} else messages=messages_;
log( "\n");
for (i in messages) {
let msg = messages[i]
log("\n" + JSON.stringify(msg));
if ("ChatMessage" in msg) {
txt = "NOT VERIFIED\n";
if (
their_ed25519.value == src
|| their_ed25519.value == ("0x"+ src)
) {
txt = "VERIFIED ed25519 " + their_ed25519.value + "\n";
} else {
log("wrong key, wanted " + their_ed25519.value + " got " + src);
return;
}
log("their ed25519 signature ",signed_ed25519s.get(src));
log("signed by eth addr",their_eth_addr.value);
if ( signed_ed25519s.get(src) == their_eth_addr.value ) {
txt += "VERIFIED eth " + their_eth_addr.value + "\n";
}
txt += "\n";
txt += msg.ChatMessage.message;
output.value = txt;
saveChat();
seenTop = false; seenBottom = false; sawSent = false;
sha256hex(msg.ChatMessage.message).then(h => { lastReceivedHash = h; if (document.hasFocus()) checkAndSendSaw(); });
}
if ("SawMessage" in msg && forwarded) {
updateSawStatus(msg.SawMessage.hash, new Date());
}
if ("MyPublicKey" in msg) {
let mpk=msg.MyPublicKey;
log("\n\n-- got mypublickey\n--myeth " + my_eth_address + "\n\n");
log( "\n\n-- their_eth " + their_eth_addr.value + "\n\n");
let sig = mpk.ed25519_eth_signed;
log( "\n\n-- sig: " + sig + "\n\n");
let ed25519 = mpk.ed25519h;
log( "\n\n-- ed25519 sent this message (using Noise IK, verified on the node): " + ed25519 + "\n\n");
let unsigned_message = "my ed25519 public key is " + ed25519
let signer;
try {
signer = ethers.verifyMessage(unsigned_message, sig);
} catch (e) {
log('VERIFY FAILED:', e.message);
}
log( "\n\n-- " + signer + " signed \"" + unsigned_message + "\" --verified in browser\n\n");
if (signer != null && their_eth_addr.value != null &&
signer.toUpperCase() == their_eth_addr.value.toUpperCase()) {
set_their_ed25519(ed25519);
signed_ed25519s.set(ed25519,their_eth_addr.value);
log( "\n\n****** MATCHED their ed25519 " + their_ed25519.value + " signed by eth_addr: " + signer);
} else {
log( "\n\nnot the key we're looking for: " + signer + " != " + their_eth_addr.value );
}
}
if (!forwarded && "YourEd25519" in msg) {
my_ed25519 = msg.YourEd25519.ed25519
update_links();
}
if (!forwarded && "PleaseSignYourPub" in msg) {
my_ed25519_to_sign = msg.PleaseSignYourPub.ed25519
my_ed25519 = my_ed25519_to_sign;
update_links();
}
}
});
};
const params = new URLSearchParams(window.location.search)
let old_way=true;
params.forEach(function(v,k) {
log_always(k,"=",v);
if (v!="")
old_way=false;
switch (k) {
case "safe":
safe_address.value=v;
document.getElementById('ethstuff').hidden=false;
break;
case "eth":
their_eth_addr.value = v;
request_ed25519_from_eth_addr();
document.getElementById('ethstuff').hidden=false;
break;
case "ed25519":
set_their_ed25519(v);
}
});
if (old_way) {
const parts = window.location.href.split('?');
if (parts.length > 1) {
if (parts[1].length > 50) {
set_their_ed25519(parts[1]);
} else {
safe_address.value=parts[1];
}
}
}
update_links();
}
}
connect();
their_eth_addr.addEventListener('input', () => {
request_ed25519_from_eth_addr();
their_ed25519.value = "";
their_ed25519.disabled = true;
});
their_ed25519.addEventListener('input', () => {
input.readOnly = false;
update_links();
saveChat();
});
input.addEventListener('input', () => {
lines = input.value.split(/\r?\n/);
while ( single_window
&& ( lines[0].startsWith("VERIFIED " )
|| lines[0].length==0)
) {
lines.shift();
log_always("len " + lines[0].length);
}
txt = lines.join('\n');
socket.send(JSON.stringify([{Forward:{to_ed25519:their_ed25519.value,messages:[{ChatMessage:{message:txt}}]}}] ));
sha256hex(txt).then(h => {
lastSentHash = h;
sawStatus.style.color = '#888';
});
saveChat();
});
</script>
</body>
</html>