// Connect to Socket.IO server
const socket = io();
// --- DOM Elements ---
const usernamePrompt = document.getElementById('username-prompt');
const chatContainer = document.getElementById('chat-container');
const usernameInput = document.getElementById('username');
const joinButton = document.getElementById('join-button');
const userList = document.getElementById('user-list');
const recipientSelect = document.getElementById('recipient-select');
const messages = document.getElementById('messages');
const form = document.getElementById('form');
const input = document.getElementById('input');
// --- State ---
let myUsername = '';
let myKeyPair = null; // { privateKey: CryptoKey, publicKey: CryptoKey }
let myPublicKeyBase64 = '';
let users = {}; // { socketId: { username: string, publicKey: CryptoKey, publicKeyBase64: string } }
// --- Crypto Constants ---
const KEY_ALGORITHM = {
name: 'ECDH',
namedCurve: 'P-256' // NIST P-256 curve
};
const ENCRYPT_ALGORITHM = {
name: 'AES-GCM',
length: 256 // Key length
};
// --- Utility Functions ---
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
function base64ToArrayBuffer(base64) {
const binary_string = window.atob(base64);
const len = binary_string.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
// --- Crypto Functions ---
// Generate ECDH key pair
async function generateKeys() {
return await window.crypto.subtle.generateKey(
KEY_ALGORITHM,
true, // extractable
['deriveKey'] // key usages
);
}
// Export public key to Base64 format for sharing
async function exportPublicKey(key) {
const exported = await window.crypto.subtle.exportKey(
'spki', // SubjectPublicKeyInfo format
key
);
return arrayBufferToBase64(exported);
}
// Import a public key from Base64 format
async function importPublicKey(base64Key) {
const buffer = base64ToArrayBuffer(base64Key);
return await window.crypto.subtle.importKey(
'spki',
buffer,
KEY_ALGORITHM,
true, // extractable (false might be better practice if not re-exporting)
[] // key usages (empty for ECDH public key import)
);
}
// Derive shared secret key using own private key and peer's public key
async function deriveSecretKey(privateKey, publicKey) {
return await window.crypto.subtle.deriveKey(
{
name: 'ECDH',
public: publicKey // The peer's public key
},
privateKey, // Your private key
{ // Derived key algorithm
name: ENCRYPT_ALGORITHM.name,
length: ENCRYPT_ALGORITHM.length
},
false, // non-extractable is safer for the derived key
['encrypt', 'decrypt'] // Key usages for the derived key
);
}
// Encrypt a message using AES-GCM
async function encryptMessage(secretKey, plaintext) {
const iv = window.crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV is recommended for GCM
const encodedPlaintext = new TextEncoder().encode(plaintext);
const ciphertext = await window.crypto.subtle.encrypt(
{
name: ENCRYPT_ALGORITHM.name,
iv: iv
},
secretKey,
encodedPlaintext
);
return {
ciphertext: arrayBufferToBase64(ciphertext),
iv: arrayBufferToBase64(iv)
};
}
// Decrypt a message using AES-GCM
async function decryptMessage(secretKey, ciphertextBase64, ivBase64) {
const iv = base64ToArrayBuffer(ivBase64);
const ciphertext = base64ToArrayBuffer(ciphertextBase64);
try {
const decryptedBuffer = await window.crypto.subtle.decrypt(
{
name: ENCRYPT_ALGORITHM.name,
iv: iv
},
secretKey,
ciphertext
);
return new TextDecoder().decode(decryptedBuffer);
} catch (e) {
console.error("Decryption failed:", e);
return null; // Indicate decryption failure
}
}
// --- UI Update Functions ---
function displayMessage(senderUsername, content, isSystem = false, error = null, isDecrypted = false) {
const item = document.createElement('div');
const meta = document.createElement('div');
meta.classList.add('message-meta');
meta.textContent = senderUsername ? `${senderUsername}:` : '';
const contentDiv = document.createElement('div');
contentDiv.classList.add('message-content');
contentDiv.textContent = content;
if (isSystem) {
item.classList.add('system-message');
item.textContent = content; // System messages don't need meta/content separation
} else {
item.appendChild(meta);
item.appendChild(contentDiv);
if (error) {
contentDiv.classList.add('error');
contentDiv.textContent = `[Decryption Failed] ${content}`;
} else if (isDecrypted) {
contentDiv.classList.add('decrypted');
}
}
messages.appendChild(item);
messages.scrollTop = messages.scrollHeight; // Scroll to bottom
}
function updateUserList() {
userList.innerHTML = ''; // Clear list
recipientSelect.innerHTML = '<option value="" disabled selected>Select user...</option>'; // Clear and add default
// Add self
const selfItem = document.createElement('li');
selfItem.textContent = `${myUsername} (You)`;
selfItem.classList.add('you');
userList.appendChild(selfItem);
// Add other users
Object.entries(users).forEach(([id, userData]) => {
const listItem = document.createElement('li');
listItem.textContent = userData.username;
listItem.dataset.id = id;
userList.appendChild(listItem);
// Add to recipient dropdown
const optionItem = document.createElement('option');
optionItem.value = id;
optionItem.textContent = userData.username;
recipientSelect.appendChild(optionItem);
});
}
// --- Socket Event Handlers ---
socket.on('connect', () => {
console.log('Connected to server');
// Now wait for user to enter username
});
socket.on('existing_users', async (existingUsers) => {
console.log('Received existing users:', existingUsers);
for (const userData of existingUsers) {
try {
const publicKey = await importPublicKey(userData.publicKey);
users[userData.id] = {
username: userData.username,
publicKey: publicKey,
publicKeyBase64: userData.publicKey // Store base64 too if needed
};
} catch (e) {
console.error(`Failed to import public key for ${userData.username}:`, e);
}
}
updateUserList();
});
socket.on('user_joined', async (userData) => {
console.log('User joined:', userData);
if (userData.id === socket.id) return; // Ignore self joining
try {
const publicKey = await importPublicKey(userData.publicKey);
users[userData.id] = {
username: userData.username,
publicKey: publicKey,
publicKeyBase64: userData.publicKey
};
displayMessage(null, `${userData.username} joined the chat.`, true);
updateUserList();
} catch (e) {
console.error(`Failed to import public key for ${userData.username}:`, e);
}
});
socket.on('user_left', (userData) => {
console.log('User left:', userData);
if (users[userData.id]) {
displayMessage(null, `${users[userData.id].username} left the chat.`, true);
delete users[userData.id];
updateUserList();
}
});
socket.on('receive_message', async (data) => {
// data = { senderId, ciphertext, iv, senderPublicKey (base64) }
console.log('Received encrypted message from:', data.senderId);
const senderData = users[data.senderId];
if (!senderData) {
// We might not have the sender's key if they joined *after* us and we haven't received it yet,
// or if the server included the key in the message itself. Let's try importing it if provided.
if(data.senderPublicKey) {
try {
console.log(`Attempting to import unknown sender's key: ${data.senderId}`);
const publicKey = await importPublicKey(data.senderPublicKey);
// We don't know their username here, could request it or use ID
users[data.senderId] = { username: `User (${data.senderId.substring(0, 4)})`, publicKey: publicKey, publicKeyBase64: data.senderPublicKey };
console.log("Successfully imported key for sender " + data.senderId);
// Now retry decryption in the next block
} catch(e) {
console.error(`Failed to import received public key for ${data.senderId}:`, e);
displayMessage(`User (${data.senderId.substring(0,4)})`, data.ciphertext, false, "Cannot get sender public key");
return;
}
} else {
console.error(`Received message from unknown user ${data.senderId} without a public key.`);
displayMessage(`User (${data.senderId.substring(0,4)})`, data.ciphertext, false, "Unknown sender");
return;
}
}
const peerPublicKey = users[data.senderId]?.publicKey; // Get the CryptoKey object
if (!peerPublicKey) {
console.error("Could not find public key for sender:", data.senderId);
displayMessage(users[data.senderId]?.username || `User (${data.senderId.substring(0,4)})`, data.ciphertext, false, "Cannot find sender public key");
return;
}
try {
// Derive the shared secret using OUR private key and the SENDER'S public key
const secretKey = await deriveSecretKey(myKeyPair.privateKey, peerPublicKey);
// Decrypt the message
const decryptedMessage = await decryptMessage(secretKey, data.ciphertext, data.iv);
if (decryptedMessage === null) {
// Decryption function indicated failure
displayMessage(users[data.senderId]?.username, data.ciphertext, false, "Decryption failed");
} else {
// Display the decrypted message
displayMessage(users[data.senderId]?.username, decryptedMessage, false, null, true);
}
} catch (error) {
console.error("Error during decryption process:", error);
displayMessage(users[data.senderId]?.username, data.ciphertext, false, "Decryption process error");
}
});
socket.on('disconnect', () => {
displayMessage(null, 'You have been disconnected.', true);
// Maybe reset state or attempt reconnection
});
// --- Event Listeners ---
joinButton.addEventListener('click', async () => {
const username = usernameInput.value.trim();
if (username) {
myUsername = username;
usernamePrompt.style.display = 'none';
chatContainer.style.display = 'flex';
// Generate keys
try {
myKeyPair = await generateKeys();
myPublicKeyBase64 = await exportPublicKey(myKeyPair.publicKey);
console.log('Generated key pair. Public key:', myPublicKeyBase64);
// Join the chat by sending username and public key
socket.emit('join', { username: myUsername, publicKey: myPublicKeyBase64 });
updateUserList(); // Add self immediately
} catch (error) {
console.error('Failed to generate keys:', error);
displayMessage(null, 'Error initializing cryptography. Cannot join chat.', true, 'Crypto Init Error');
// Handle error appropriately, maybe disable chat functionality
}
}
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const messageText = input.value.trim();
const recipientId = recipientSelect.value;
if (messageText && recipientId && myKeyPair) {
const recipientData = users[recipientId];
if (!recipientData || !recipientData.publicKey) {
displayMessage(null, 'Error: Recipient not found or public key missing.', true);
return;
}
try {
// 1. Derive the shared secret key using OUR private key and RECIPIENT'S public key
const secretKey = await deriveSecretKey(myKeyPair.privateKey, recipientData.publicKey);
// 2. Encrypt the message
const { ciphertext, iv } = await encryptMessage(secretKey, messageText);
// 3. Send the encrypted data to the server for relaying
socket.emit('send_message', {
recipientId: recipientId,
senderId: socket.id, // Include sender ID
ciphertext: ciphertext, // Base64
iv: iv // Base64
// Server will look up sender's public key if needed by receiver,
// alternatively, we could include myPublicKeyBase64 here.
});
// Display the message locally (optional, maybe show as 'You to X: message')
// For simplicity, we'll wait for the server loopback if implemented,
// or just clear the input here.
displayMessage(`${myUsername} (to ${recipientData.username})`, messageText, false, null, true); // Show own sent message
input.value = ''; // Clear input field
} catch (error) {
console.error('Failed to encrypt or send message:', error);
displayMessage(null, 'Error sending message.', true, 'Encryption/Send Error');
}
} else if (!recipientId) {
displayMessage(null, 'Please select a recipient.', true);
} else if (!myKeyPair) {
displayMessage(null, 'Error: Cryptographic keys not initialized.', true);
}
});