-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
190 lines (175 loc) · 5.51 KB
/
Copy pathscripts.js
File metadata and controls
190 lines (175 loc) · 5.51 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
const peer = new Peer({
config: {
iceServers: [
{
urls: "stun:stun.relay.metered.ca:80",
},
{
urls: "turn:global.relay.metered.ca:80",
username: "a97fd3a4f8c9592fbb10eac4",
credential: "pi3gSvNSb+u/lKMh",
},
{
urls: "turn:global.relay.metered.ca:80?transport=tcp",
username: "a97fd3a4f8c9592fbb10eac4",
credential: "pi3gSvNSb+u/lKMh",
},
{
urls: "turn:global.relay.metered.ca:443",
username: "a97fd3a4f8c9592fbb10eac4",
credential: "pi3gSvNSb+u/lKMh",
},
{
urls: "turns:global.relay.metered.ca:443?transport=tcp",
username: "a97fd3a4f8c9592fbb10eac4",
credential: "pi3gSvNSb+u/lKMh",
}
],
iceTransportPolicy: "relay",
}
});
let conn = null;
let username = null;
let aesKey = null;
const loginScreen = document.getElementById('loginScreen');
const mainChat = document.getElementById('mainChat');
const usernameInput = document.getElementById('usernameInput');
const setUsernameBtn = document.getElementById('setUsernameBtn');
const currentUsername = document.getElementById('currentUsername');
const messages = document.getElementById('messages');
const msgInput = document.getElementById('msgInput');
const sendBtn = document.getElementById('sendBtn');
const offerOut = document.getElementById('offerOut');
const offerIn = document.getElementById('offerIn');
async function deriveKeyFromSecret(secret) {
const enc = new TextEncoder();
const keyMaterial = await window.crypto.subtle.importKey(
"raw", enc.encode(secret), "PBKDF2", false, ["deriveKey"]);
return window.crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: enc.encode("peerjs-p2p-chat"),
iterations: 120_000,
hash: "SHA-256"
},
keyMaterial,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}
async function encryptMsg(key, msg) {
const enc = new TextEncoder();
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await window.crypto.subtle.encrypt(
{ name: "AES-GCM", iv }, key, enc.encode(msg)
);
const buf = new Uint8Array(iv.length + ciphertext.byteLength);
buf.set(iv, 0);
buf.set(new Uint8Array(ciphertext), iv.length);
return btoa(String.fromCharCode(...buf));
}
async function decryptMsg(key, str) {
const bin = Uint8Array.from(atob(str), c => c.charCodeAt(0));
const iv = bin.slice(0, 12);
const ct = bin.slice(12);
const dec = await window.crypto.subtle.decrypt(
{ name: "AES-GCM", iv }, key, ct
);
return new TextDecoder().decode(dec);
}
function setStatus(text, state = "") {
const el = document.getElementById('status');
el.textContent = text;
el.className = "status-indicator" + (state ? " " + state : "");
}
setUsernameBtn.onclick = () => {
const input = usernameInput.value.trim();
if (!input) return alert("Please choose a username.");
username = input;
loginScreen.classList.add("animate-out");
setTimeout(() => {
loginScreen.style.display = "none";
mainChat.style.display = "block";
mainChat.classList.add("animate-in");
currentUsername.textContent = username;
}, 450);
};
usernameInput.addEventListener('keydown', e => {
if (e.key === 'Enter') setUsernameBtn.onclick();
});
function log(msg, sender = '🧑💻') {
const div = document.createElement('div');
div.textContent = `${sender}: ${msg}`;
messages.appendChild(div);
messages.scrollTop = messages.scrollHeight;
}
document.getElementById('startBtn').onclick = async () => {
const otherId = offerIn.value.trim();
if (!otherId) return alert("Please enter a valid ID.");
aesKey = await deriveKeyFromSecret(offerIn.value);
conn = peer.connect(otherId);
setupConnection();
};
offerIn.addEventListener('keydown', e => {
if (e.key === 'Enter') document.getElementById('startBtn').onclick();
});
sendBtn.onclick = async () => {
const msg = msgInput.value;
if (msg && conn?.open && aesKey) {
const toSend = JSON.stringify({ user: username, msg });
const encrypted = await encryptMsg(aesKey, toSend);
conn.send(encrypted);
log(msg, "Moi");
msgInput.value = '';
}
};
msgInput.addEventListener('keydown', e => {
if (e.key === 'Enter') sendBtn.onclick();
});
peer.on('open', async id => {
offerOut.value = id;
setStatus("Pending...", "pending");
aesKey = await deriveKeyFromSecret(offerOut.value);
});
peer.on('connection', incomingConn => {
conn = incomingConn;
setupConnection();
setStatus("Connected", "connected");
});
function setupConnection() {
conn.on('open', () => {
setStatus("Connected", "connected");
});
conn.on('data', async data => {
let text, sender = "👤";
try {
const decrypted = await decryptMsg(aesKey, data);
const d = JSON.parse(decrypted);
text = d.msg;
sender = d.user || "👤";
} catch (e) {
text = "[Decryption error]";
sender = "⚠️";
}
log(text, sender);
});
conn.on('close', () => {
setStatus("Disconnected", "");
log("Please refresh the page before reconnect", "⚠️");
});
conn.on('error', err => {
console.error("Connection error :", err);
setStatus("failed", "failed");
});
}
document.getElementById('copyIdBtn').onclick = () => {
const id = offerOut.value.trim();
if (!id) return;
navigator.clipboard.writeText(id)
.then(() => {
})
.catch(() => {
alert("Unable to copy ID.");
});
};