(() => { // Application State const state = { token: localStorage.getItem('gsdchat_token') || null, user: JSON.parse(localStorage.getItem('gsdchat_user') || 'null'), publicKey: null, privateKey: null, serverPublicKey: null, serverEncryptedPrivateKey: null, accountE2eeEnabled: true, serverInfo: null, allowDmE2ee: true, maxGroupChatUsers: 10, activeChannelId: null, channels: [], directMessages: [], groupChats: [], messages: {}, // channelId -> array hasMoreHistory: {}, // channelId -> bool loadingHistory: {}, // channelId -> bool e2eePromptedDms: {}, // dmChannelId -> bool (prevent repeated intrusive prompts after dismiss) users: [], files: [], socket: null, isRegister: false, reconnectTimer: null }; // DOM Elements const el = { serverTitle: document.getElementById('serverTitle'), connIndicator: document.getElementById('connIndicator'), navTabs: document.querySelectorAll('.nav-tab'), tabViews: document.querySelectorAll('.tab-view'), currentUsername: document.getElementById('currentUsername'), currentUserRole: document.getElementById('currentUserRole'), e2eeVaultBtn: document.getElementById('e2eeVaultBtn'), logoutBtn: document.getElementById('logoutBtn'), userBadge: document.getElementById('userBadge'), // Chat View activeConvPrefix: document.getElementById('activeConvPrefix'), channelSelectDropdown: document.getElementById('channelSelectDropdown'), chatSecurityBadge: document.getElementById('chatSecurityBadge'), activeChannelTopic: document.getElementById('activeChannelTopic'), toggleDmE2eeBtn: document.getElementById('toggleDmE2eeBtn'), inviteGroupBtn: document.getElementById('inviteGroupBtn'), leaveGroupBtn: document.getElementById('leaveGroupBtn'), chatMessages: document.getElementById('chatMessages'), messageInput: document.getElementById('messageInput'), sendBtn: document.getElementById('sendBtn'), fileInput: document.getElementById('fileInput'), welcomeMotd: document.getElementById('welcomeMotd'), toggleMembersBtn: document.getElementById('toggleMembersBtn'), chatMembersSidebar: document.getElementById('chatMembersSidebar'), chatOnlineUsersList: document.getElementById('chatOnlineUsersList'), chatOnlineCountBadge: document.getElementById('chatOnlineCountBadge'), chatHeaderOnlineCount: document.getElementById('chatHeaderOnlineCount'), // Channels, Groups & DMs View channelList: document.getElementById('channelList'), openCreateChannelBtn: document.getElementById('openCreateChannelBtn'), createChannelCard: document.getElementById('createChannelCard'), newChannelName: document.getElementById('newChannelName'), newChannelTopic: document.getElementById('newChannelTopic'), submitCreateChannelBtn: document.getElementById('submitCreateChannelBtn'), cancelCreateChannelBtn: document.getElementById('cancelCreateChannelBtn'), groupChatList: document.getElementById('groupChatList'), maxGroupUsersHint: document.getElementById('maxGroupUsersHint'), openCreateGroupBtn: document.getElementById('openCreateGroupBtn'), createGroupCard: document.getElementById('createGroupCard'), newGroupName: document.getElementById('newGroupName'), newGroupMembers: document.getElementById('newGroupMembers'), newGroupTopic: document.getElementById('newGroupTopic'), submitCreateGroupBtn: document.getElementById('submitCreateGroupBtn'), cancelCreateGroupBtn: document.getElementById('cancelCreateGroupBtn'), dmList: document.getElementById('dmList'), dmE2eeStatusHint: document.getElementById('dmE2eeStatusHint'), openE2eeSettingsBtn: document.getElementById('openE2eeSettingsBtn'), openStartDmBtn: document.getElementById('openStartDmBtn'), startDmCard: document.getElementById('startDmCard'), dmTargetUsername: document.getElementById('dmTargetUsername'), submitStartDmBtn: document.getElementById('submitStartDmBtn'), cancelStartDmBtn: document.getElementById('cancelStartDmBtn'), // Users View userList: document.getElementById('userList'), userCountBadge: document.getElementById('userCountBadge'), // Files View filesList: document.getElementById('filesList'), filesViewUploadInput: document.getElementById('filesViewUploadInput'), // E2EE Vault Modal e2eeModal: document.getElementById('e2eeModal'), e2eeModalTitle: document.getElementById('e2eeModalTitle'), e2eeModalSubtitle: document.getElementById('e2eeModalSubtitle'), e2eeVaultStatusBanner: document.getElementById('e2eeVaultStatusBanner'), e2eePinForm: document.getElementById('e2eePinForm'), e2eePinLabel: document.getElementById('e2eePinLabel'), e2eePinInput: document.getElementById('e2eePinInput'), e2eeModalError: document.getElementById('e2eeModalError'), e2eeSubmitPinBtn: document.getElementById('e2eeSubmitPinBtn'), e2eeToggleAccountBtn: document.getElementById('e2eeToggleAccountBtn'), e2eeLockDeviceBtn: document.getElementById('e2eeLockDeviceBtn'), e2eeResetPinBtn: document.getElementById('e2eeResetPinBtn'), e2eeCloseModalBtn: document.getElementById('e2eeCloseModalBtn'), // Auth Modal authModal: document.getElementById('authModal'), modalServerName: document.getElementById('modalServerName'), modalMotd: document.getElementById('modalMotd'), tabLogin: document.getElementById('tabLogin'), tabRegister: document.getElementById('tabRegister'), authForm: document.getElementById('authForm'), groupServerPassword: document.getElementById('groupServerPassword'), groupInviteToken: document.getElementById('groupInviteToken'), authServerPassword: document.getElementById('authServerPassword'), authUsername: document.getElementById('authUsername'), authPassword: document.getElementById('authPassword'), authInviteToken: document.getElementById('authInviteToken'), authSubmitBtn: document.getElementById('authSubmitBtn'), authError: document.getElementById('authError'), toastContainer: document.getElementById('toastContainer'), dropOverlay: document.getElementById('dropOverlay') }; function initElements() { for (const key in el) { if (!el[key] && typeof key === 'string') { const found = document.getElementById(key); if (found) el[key] = found; } } } // ========================================== // Local Device E2EE Key Cache Helpers // ========================================== function getUserKeyCacheStorageKey(userId) { return `gsdchat_e2ee_vault_${userId}`; } function loadCachedKeysForCurrentUser() { if (!state.user || !state.user.id) return false; try { const raw = localStorage.getItem(getUserKeyCacheStorageKey(state.user.id)); if (raw) { const cached = JSON.parse(raw); if (cached && cached.publicKey && cached.privateKey) { // Verify cached public key matches server public key if server has one if (!state.serverPublicKey || state.serverPublicKey === cached.publicKey) { state.publicKey = cached.publicKey; state.privateKey = cached.privateKey; if (cached.encryptedPrivateKey && !state.serverEncryptedPrivateKey) { state.serverEncryptedPrivateKey = cached.encryptedPrivateKey; } return true; } } } } catch { // Ignore storage error } return false; } function saveCachedKeysForCurrentUser(pubKey, privKey, encPrivKey) { if (!state.user || !state.user.id) return; try { localStorage.setItem(getUserKeyCacheStorageKey(state.user.id), JSON.stringify({ publicKey: pubKey, privateKey: privKey, encryptedPrivateKey: encPrivKey || state.serverEncryptedPrivateKey || null })); // Also set legacy keys for compatibility if (pubKey) localStorage.setItem('gsdchat_e2ee_pub', pubKey); if (privKey) localStorage.setItem('gsdchat_e2ee_priv', privKey); } catch { // Ignore storage error } } function clearCachedKeysForCurrentUser() { if (state.user && state.user.id) { localStorage.removeItem(getUserKeyCacheStorageKey(state.user.id)); } localStorage.removeItem('gsdchat_e2ee_pub'); localStorage.removeItem('gsdchat_e2ee_priv'); state.publicKey = null; state.privateKey = null; } // ========================================== // Web Crypto E2EE Engine (P-256 ECDH + AES-256-GCM) // Compatible with GsDChat.Core.Security.E2eeCrypto // ========================================== const E2EE_PREFIX = 'E2EE:v1:'; const WRAP_PREFIX = 'WRAP:v1:'; function bytesToBase64(bytes) { let bin = ''; const arr = new Uint8Array(bytes); for (let i = 0; i < arr.length; i++) { bin += String.fromCharCode(arr[i]); } return btoa(bin); } function base64ToBytes(b64) { const bin = atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) { arr[i] = bin.charCodeAt(i); } return arr; } async function generateE2eeKeyPair() { if (!window.crypto || !window.crypto.subtle) { return { publicKey: '', privateKey: '' }; } const keyPair = await window.crypto.subtle.generateKey( { name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits'] ); const spki = await window.crypto.subtle.exportKey('spki', keyPair.publicKey); const pkcs8 = await window.crypto.subtle.exportKey('pkcs8', keyPair.privateKey); return { publicKey: bytesToBase64(spki), privateKey: bytesToBase64(pkcs8) }; } async function deriveWrappingAesKey(pinOrPassphrase, username) { const enc = new TextEncoder(); const saltInput = enc.encode(`GsDChat-E2EE-KeyWrap:${username.trim().toLowerCase()}`); const saltHash = await window.crypto.subtle.digest('SHA-256', saltInput); const baseKey = await window.crypto.subtle.importKey( 'raw', enc.encode(pinOrPassphrase), 'PBKDF2', false, ['deriveKey'] ); return window.crypto.subtle.deriveKey( { name: 'PBKDF2', salt: saltHash, iterations: 100000, hash: 'SHA-256' }, baseKey, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'] ); } async function wrapPrivateKey(privateKeyBase64, pinOrPassphrase, username) { if (!window.crypto || !window.crypto.subtle || !privateKeyBase64) return ''; try { const wrapKey = await deriveWrappingAesKey(pinOrPassphrase, username); const nonce = window.crypto.getRandomValues(new Uint8Array(12)); const plainBytes = new TextEncoder().encode(privateKeyBase64); const cipherBuf = await window.crypto.subtle.encrypt( { name: 'AES-GCM', iv: nonce, tagLength: 128 }, wrapKey, plainBytes ); return `${WRAP_PREFIX}${bytesToBase64(nonce)}:${bytesToBase64(cipherBuf)}`; } catch { return ''; } } async function unwrapPrivateKey(wrappedBlob, pinOrPassphrase, username) { if (!window.crypto || !window.crypto.subtle || !wrappedBlob || !wrappedBlob.startsWith(WRAP_PREFIX)) { return null; } try { const rest = wrappedBlob.substring(WRAP_PREFIX.length); const sep = rest.indexOf(':'); if (sep < 0) return null; const nonce = base64ToBytes(rest.substring(0, sep)); const combined = base64ToBytes(rest.substring(sep + 1)); const wrapKey = await deriveWrappingAesKey(pinOrPassphrase, username); const plainBuf = await window.crypto.subtle.decrypt( { name: 'AES-GCM', iv: nonce, tagLength: 128 }, wrapKey, combined ); return new TextDecoder().decode(plainBuf); } catch { return null; } } async function deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64) { const privBytes = base64ToBytes(myPrivateKeyB64); const pubBytes = base64ToBytes(peerPublicKeyB64); const myPrivKey = await window.crypto.subtle.importKey( 'pkcs8', privBytes, { name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'] ); const peerPubKey = await window.crypto.subtle.importKey( 'spki', pubBytes, { name: 'ECDH', namedCurve: 'P-256' }, false, [] ); const rawSecret = await window.crypto.subtle.deriveBits( { name: 'ECDH', public: peerPubKey }, myPrivKey, 256 ); const keyHash = await window.crypto.subtle.digest('SHA-256', rawSecret); return window.crypto.subtle.importKey( 'raw', keyHash, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'] ); } async function encryptDmMessage(plaintext, myPrivateKeyB64, peerPublicKeyB64) { if (!window.crypto || !window.crypto.subtle || !myPrivateKeyB64 || !peerPublicKeyB64) { return { content: plaintext, isEncrypted: false }; } try { const aesKey = await deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64); const nonce = window.crypto.getRandomValues(new Uint8Array(12)); const plainBytes = new TextEncoder().encode(plaintext); const cipherBuf = await window.crypto.subtle.encrypt( { name: 'AES-GCM', iv: nonce, tagLength: 128 }, aesKey, plainBytes ); return { content: `${E2EE_PREFIX}${bytesToBase64(nonce)}:${bytesToBase64(cipherBuf)}`, isEncrypted: true }; } catch (err) { console.error('E2EE encryption failed:', err); return { content: plaintext, isEncrypted: false }; } } async function decryptDmMessage(payload, myPrivateKeyB64, peerPublicKeyB64) { if (!payload || !payload.startsWith(E2EE_PREFIX)) { return payload; } if (!window.crypto || !window.crypto.subtle || !myPrivateKeyB64 || !peerPublicKeyB64) { return '[🔒 Encrypted Message - Unlock E2EE Vault with PIN]'; } try { const rest = payload.substring(E2EE_PREFIX.length); const sep = rest.indexOf(':'); if (sep < 0) return '[Encrypted Message - Malformed]'; const nonce = base64ToBytes(rest.substring(0, sep)); const combined = base64ToBytes(rest.substring(sep + 1)); const aesKey = await deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64); const plainBuf = await window.crypto.subtle.decrypt( { name: 'AES-GCM', iv: nonce, tagLength: 128 }, aesKey, combined ); return new TextDecoder().decode(plainBuf); } catch { return '[Encrypted Message - Decryption Failed (Wrong Key Vault)]'; } } function getPeerPublicKeyForDm(dm) { if (!dm) return null; const memberIds = dm.memberIds || dm.MemberIds || []; const memberNames = dm.memberUsernames || dm.MemberUsernames || []; const memberKeys = dm.memberPublicKeys || dm.MemberPublicKeys || {}; const myId = state.user ? state.user.id : ''; const myName = state.user ? state.user.username : ''; const peerId = memberIds.find(id => id.toLowerCase() !== (myId || '').toLowerCase()); if (peerId) { if (memberKeys[peerId]) return memberKeys[peerId]; const u = state.users.find(user => (user.id || user.Id || '').toLowerCase() === peerId.toLowerCase()); if (u && (u.publicKey || u.PublicKey)) return u.publicKey || u.PublicKey; } const rawDmName = (dm.name || dm.Name || '').replace(/^@/, ''); const peerName = memberNames.find(n => n.toLowerCase() !== (myName || '').toLowerCase()) || rawDmName; if (peerName) { if (memberKeys[peerName]) return memberKeys[peerName]; const u = state.users.find(user => (user.username || user.Username || '').toLowerCase() === peerName.toLowerCase()); if (u && (u.publicKey || u.PublicKey)) return u.publicKey || u.PublicKey; } // Self-DM fallback if (memberIds.length === 1 && myId && memberIds[0].toLowerCase() === myId.toLowerCase()) { return state.publicKey || state.serverPublicKey; } return null; } function isDmPeerE2eeReady(dm) { return !!getPeerPublicKeyForDm(dm); } async function decryptMessageObjectIfNeeded(msg) { const rawContent = msg._rawCiphertext || msg.content || msg.Content || ''; const isEnc = msg.isEncrypted || msg.IsEncrypted || rawContent.startsWith(E2EE_PREFIX); if (!isEnc) return msg; msg.isEncrypted = true; if (rawContent.startsWith(E2EE_PREFIX)) { msg._rawCiphertext = rawContent; } else { return msg; } if (!state.privateKey) { const lockedPlaceholder = '[🔒 Encrypted Message - Click [🔒 E2EE Vault] and enter PIN to unlock]'; msg.content = lockedPlaceholder; msg.Content = lockedPlaceholder; return msg; } const senderId = msg.senderId || msg.SenderId || ''; const senderPubKey = msg.senderPublicKey || msg.SenderPublicKey || ''; const recipientPubKey = msg.recipientPublicKey || msg.RecipientPublicKey || ''; const chId = msg.channelId || msg.ChannelId || ''; const isSentByMe = state.user && senderId.toLowerCase() === (state.user.id || '').toLowerCase(); let peerKey = null; if (isSentByMe) { if (recipientPubKey) peerKey = recipientPubKey; } else { if (senderPubKey) peerKey = senderPubKey; } if (!peerKey) { const conv = getConversationById(chId); if (conv) peerKey = getPeerPublicKeyForDm(conv); } if (!peerKey) { peerKey = recipientPubKey || senderPubKey || null; } if (peerKey && state.privateKey) { const decrypted = await decryptDmMessage(rawContent, state.privateKey, peerKey); msg.content = decrypted; msg.Content = decrypted; } return msg; } async function reDecryptAllLoadedMessages() { for (const chId of Object.keys(state.messages)) { const list = state.messages[chId] || []; for (const m of list) { if (m._rawCiphertext || (m.content && m.content.startsWith(E2EE_PREFIX))) { await decryptMessageObjectIfNeeded(m); } } } if (state.activeChannelId) { renderMessages(); } } async function unlockOrInitE2eeWithPin(pin, resetKeys = false) { if (!pin || !pin.trim()) { return { ok: false, message: 'E2EE PIN / passphrase cannot be empty.' }; } if (!state.user || !state.user.username) { return { ok: false, message: 'Not authenticated.' }; } const cleanPin = pin.trim(); if (!resetKeys && state.serverEncryptedPrivateKey) { const unwrapped = await unwrapPrivateKey(state.serverEncryptedPrivateKey, cleanPin, state.user.username); if (!unwrapped) { return { ok: false, message: 'Invalid E2EE PIN/passphrase. Try again or click [Reset PIN / New Keys] if forgotten.' }; } state.privateKey = unwrapped; state.publicKey = state.serverPublicKey || state.publicKey; saveCachedKeysForCurrentUser(state.publicKey, state.privateKey, state.serverEncryptedPrivateKey); await reDecryptAllLoadedMessages(); updateUserUI(); updateActiveChannelHeader(); renderChannels(); return { ok: true, message: '🔒 E2EE Key Vault unlocked and cached on this device.' }; } // Generate new P-256 keypair & wrap with dedicated PIN const generated = await generateE2eeKeyPair(); if (!generated.publicKey || !generated.privateKey) { return { ok: false, message: 'Web Crypto P-256 key generation failed.' }; } const wrappedPriv = await wrapPrivateKey(generated.privateKey, cleanPin, state.user.username); if (!wrappedPriv) { return { ok: false, message: 'Failed to wrap E2EE private key with PIN.' }; } state.publicKey = generated.publicKey; state.privateKey = generated.privateKey; state.serverPublicKey = generated.publicKey; state.serverEncryptedPrivateKey = wrappedPriv; saveCachedKeysForCurrentUser(state.publicKey, state.privateKey, wrappedPriv); if (state.socket && state.socket.readyState === WebSocket.OPEN) { sendEnvelope('PUBLISH_PUBLIC_KEY', { publicKey: generated.publicKey, encryptedPrivateKey: wrappedPriv, resetKeys: !!resetKeys }); } await reDecryptAllLoadedMessages(); updateUserUI(); updateActiveChannelHeader(); renderChannels(); return { ok: true, message: resetKeys ? '🔒 E2EE PIN & Keypair reset! New encrypted DMs will use your new keypair.' : '🔒 E2EE Key Vault initialized and backed up to server (zero-knowledge).' }; } // ========================================== // Initialization // ========================================== async function init() { initElements(); setupEventListeners(); await fetchServerInfo(); if (state.token && state.user) { loadCachedKeysForCurrentUser(); updateUserUI(); hideAuthModal(); connectWebSocket(); } else { showAuthModal(); } } // ========================================== // REST API Calls // ========================================== async function fetchServerInfo() { try { const res = await fetch('/api/info'); if (res.ok) { state.serverInfo = await res.json(); state.allowDmE2ee = state.serverInfo.allowDmE2ee !== undefined ? state.serverInfo.allowDmE2ee : (state.serverInfo.AllowDmE2ee !== undefined ? state.serverInfo.AllowDmE2ee : true); state.maxGroupChatUsers = state.serverInfo.maxGroupChatUsers || state.serverInfo.MaxGroupChatUsers || 10; el.serverTitle.textContent = state.serverInfo.serverName || 'GsDChat'; el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat'; if (state.serverInfo.motd) { el.modalMotd.textContent = state.serverInfo.motd; el.welcomeMotd.textContent = state.serverInfo.motd; } if (state.serverInfo.requiresServerPassword) { el.groupServerPassword.style.display = 'flex'; } if (state.serverInfo.registrationMode === 'InviteOnly') { el.groupInviteToken.style.display = 'flex'; } updateSettingsBadges(); } } catch (err) { showToast('Could not reach server info endpoint'); } } function updateSettingsBadges() { if (el.maxGroupUsersHint) { el.maxGroupUsersHint.textContent = `(Max ${state.maxGroupChatUsers} users)`; } if (el.dmE2eeStatusHint) { if (!state.allowDmE2ee) { el.dmE2eeStatusHint.textContent = '[Plaintext / Server-Visible]'; } else if (!state.accountE2eeEnabled) { el.dmE2eeStatusHint.textContent = '[Account E2EE: OFF]'; } else if (state.privateKey) { el.dmE2eeStatusHint.textContent = '[🔒 Vault Unlocked]'; } else { el.dmE2eeStatusHint.textContent = '[🔒 Vault Locked - Click E2EE Vault]'; } } if (el.e2eeVaultBtn) { if (!state.allowDmE2ee) { el.e2eeVaultBtn.textContent = '[E2EE: Server Off]'; } else if (!state.accountE2eeEnabled) { el.e2eeVaultBtn.textContent = '[E2EE: Account Off]'; } else if (state.privateKey) { el.e2eeVaultBtn.textContent = '[🔒 E2EE Unlocked]'; } else { el.e2eeVaultBtn.textContent = '[🔓 Unlock E2EE PIN]'; } } } async function handleAuthSubmit() { el.authError.textContent = ''; const username = el.authUsername.value.trim(); const password = el.authPassword.value; const serverPassword = el.authServerPassword.value; const inviteToken = el.authInviteToken.value.trim(); if (!username || !password) { el.authError.textContent = 'Please enter username and password.'; return; } const endpoint = state.isRegister ? '/api/auth/register' : '/api/auth/login'; try { el.authSubmitBtn.disabled = true; el.authSubmitBtn.textContent = '[ Authenticating... ]'; // Strictly username + password login/registration (E2EE keys are lazily unlocked/initialized on DM open) const body = { username, password, serverPassword: serverPassword || null, inviteToken: inviteToken || null }; const res = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const data = await res.json(); if (!res.ok || !data.success) { el.authError.textContent = data.errorMessage || 'Authentication failed.'; return; } state.token = data.token || data.Token; state.user = { id: data.userId || data.UserId, username: data.username || data.Username, role: data.role || data.Role }; state.serverPublicKey = data.publicKey || data.PublicKey || null; state.serverEncryptedPrivateKey = data.encryptedPrivateKey || data.EncryptedPrivateKey || null; state.accountE2eeEnabled = data.e2eeEnabled ?? data.E2eeEnabled ?? true; state.publicKey = null; state.privateKey = null; localStorage.setItem('gsdchat_token', state.token); localStorage.setItem('gsdchat_user', JSON.stringify(state.user)); // Attempt to restore unlocked E2EE keys from trusted local device cache loadCachedKeysForCurrentUser(); updateUserUI(); updateSettingsBadges(); hideAuthModal(); connectWebSocket(); } catch (err) { el.authError.textContent = 'Connection error. Please try again.'; } finally { el.authSubmitBtn.disabled = false; el.authSubmitBtn.textContent = state.isRegister ? '[ Register ]' : '[ Login ]'; } } // ========================================== // WebSocket Communication // ========================================== function connectWebSocket() { if (state.socket) { state.socket.close(); } const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${wsProto}//${window.location.host}/ws?token=${encodeURIComponent(state.token)}`; try { state.socket = new WebSocket(wsUrl); state.socket.onopen = () => { el.connIndicator.classList.add('online'); el.connIndicator.title = 'Connected'; showToast('Connected to chat server'); }; state.socket.onclose = () => { el.connIndicator.classList.remove('online'); el.connIndicator.title = 'Disconnected'; if (state.token) { clearTimeout(state.reconnectTimer); state.reconnectTimer = setTimeout(connectWebSocket, 3000); } }; state.socket.onerror = () => { el.connIndicator.classList.remove('online'); }; state.socket.onmessage = (event) => { try { const envelope = JSON.parse(event.data); handleNetworkEnvelope(envelope); } catch (err) { console.error('Failed to parse WebSocket message', err); } }; } catch (err) { console.error('WebSocket connection error', err); } } function sendEnvelope(type, payload) { if (!state.socket || state.socket.readyState !== WebSocket.OPEN) { showToast('Not connected to server'); return; } const envelope = { type: type, payload: JSON.stringify(payload) }; state.socket.send(JSON.stringify(envelope)); } function fetchOlderHistory(channelId) { if (!channelId || state.loadingHistory[channelId]) return; const currentMsgs = state.messages[channelId] || []; state.loadingHistory[channelId] = true; sendEnvelope('FETCH_HISTORY', { channelId: channelId, offset: currentMsgs.length, limit: 50 }); } async function handleNetworkEnvelope(envelope) { const type = (envelope.type || envelope.Type || '').toUpperCase(); const payloadRaw = envelope.payload ?? envelope.Payload ?? '{}'; let payload = {}; try { payload = typeof payloadRaw === 'string' ? JSON.parse(payloadRaw) : payloadRaw; } catch (e) { console.error('Failed to parse envelope payload', e); return; } switch (type) { case 'AUTH_RESULT': if (payload.success ?? payload.Success) { const srvPub = payload.publicKey ?? payload.PublicKey; const srvEnc = payload.encryptedPrivateKey ?? payload.EncryptedPrivateKey; if (srvPub !== undefined) state.serverPublicKey = srvPub; if (srvEnc !== undefined) state.serverEncryptedPrivateKey = srvEnc; if (payload.e2eeEnabled !== undefined || payload.E2eeEnabled !== undefined) { state.accountE2eeEnabled = payload.e2eeEnabled ?? payload.E2eeEnabled; } // Re-validate cached device keys against server public key if (state.publicKey && state.serverPublicKey && state.publicKey !== state.serverPublicKey) { clearCachedKeysForCurrentUser(); } else if (!state.privateKey) { loadCachedKeysForCurrentUser(); } updateSettingsBadges(); updateActiveChannelHeader(); updateE2eeModalUI(); } break; case 'UI_SYNC': if (payload.allowDmE2ee !== undefined || payload.AllowDmE2ee !== undefined) { state.allowDmE2ee = payload.allowDmE2ee ?? payload.AllowDmE2ee; } if (payload.maxGroupChatUsers || payload.MaxGroupChatUsers) { state.maxGroupChatUsers = payload.maxGroupChatUsers || payload.MaxGroupChatUsers; } updateSettingsBadges(); updateActiveChannelHeader(); break; case 'CHANNEL_LIST_SYNC': state.channels = payload.channels || payload.Channels || []; state.directMessages = payload.directMessages || payload.DirectMessages || []; state.groupChats = payload.groupChats || payload.GroupChats || []; const activeCh = payload.activeChannelId || payload.ActiveChannelId; if (activeCh) { state.activeChannelId = activeCh; } else if (!state.activeChannelId && state.channels.length > 0) { const first = state.channels[0]; state.activeChannelId = first.id || first.Id; } renderChannels(); updateActiveChannelHeader(); checkLazyDmE2eePrompt(); break; case 'HISTORY_SYNC': const histChId = payload.channelId || payload.ChannelId; if (histChId) { const rawMsgs = payload.messages || payload.Messages || []; const isPrepend = payload.prepend || payload.Prepend || false; const hasMore = payload.hasMore ?? payload.HasMore ?? false; state.hasMoreHistory[histChId] = hasMore; state.loadingHistory[histChId] = false; const processedMsgs = []; for (const m of rawMsgs) { processedMsgs.push(await decryptMessageObjectIfNeeded(m)); } if (isPrepend && state.messages[histChId]) { const existingIds = new Set(state.messages[histChId].map(x => x.id || x.Id)); const olderUnique = processedMsgs.filter(x => !existingIds.has(x.id || x.Id)); state.messages[histChId] = [...olderUnique, ...state.messages[histChId]]; } else { state.messages[histChId] = processedMsgs; } if (state.activeChannelId === histChId) { renderMessages(!isPrepend); } } break; case 'MESSAGE_BROADCAST': const msg = payload.message || payload.Message; if (msg) { await decryptMessageObjectIfNeeded(msg); const chId = msg.channelId || msg.ChannelId; if (!state.messages[chId]) state.messages[chId] = []; state.messages[chId].push(msg); if (state.activeChannelId === chId) { appendMessage(msg); } } break; case 'USER_LIST_SYNC': state.users = payload.users || payload.Users || []; if (state.user) { const me = state.users.find(u => (u.id || u.Id || '').toLowerCase() === (state.user.id || '').toLowerCase()); if (me) { if (me.e2eeEnabled !== undefined || me.E2eeEnabled !== undefined) { state.accountE2eeEnabled = me.e2eeEnabled ?? me.E2eeEnabled; } if (me.publicKey || me.PublicKey) { state.serverPublicKey = me.publicKey || me.PublicKey; } } } await reDecryptAllLoadedMessages(); renderUsers(); updateSettingsBadges(); updateActiveChannelHeader(); break; case 'FILE_LIST_SYNC': state.files = payload.files || payload.Files || []; renderFiles(); break; case 'SYSTEM_NOTICE': const noticeText = payload.text || payload.Text; if (noticeText) { showToast(noticeText); if (state.activeChannelId) { appendSystemNotice(noticeText); } } break; case 'COMMAND_RESULT': const cmdOut = payload.output || payload.Output; if (cmdOut) { appendSystemNotice(cmdOut); } break; case 'ERROR': const errMsg = payload.message || payload.Message; if (errMsg) { showToast(`Error: ${errMsg}`); appendSystemNotice(`[Error] ${errMsg}`); } break; } } // ========================================== // Conversation Lookup & E2EE Vault UI Helpers // ========================================== function getAllConversations() { return [...state.channels, ...state.groupChats, ...state.directMessages]; } function getConversationById(channelId) { if (!channelId) return null; return getAllConversations().find(c => (c.id || c.Id) === channelId) || null; } function getConversationType(conv) { if (!conv) return 'Channel'; return conv.type || conv.Type || 'Channel'; } function checkLazyDmE2eePrompt() { const active = getConversationById(state.activeChannelId); if (!active || getConversationType(active) !== 'DM') return; const dmId = active.id || active.Id; const isDmE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled; if (isDmE2ee && !state.privateKey && !state.e2eePromptedDms[dmId]) { state.e2eePromptedDms[dmId] = true; showE2eeModal(); } } function updateE2eeModalUI() { if (!el.e2eeVaultStatusBanner) return; const hasServerVault = !!state.serverEncryptedPrivateKey; const isUnlocked = !!state.privateKey; const acctStatus = state.accountE2eeEnabled ? 'ENABLED' : 'DISABLED'; if (!state.allowDmE2ee) { el.e2eeVaultStatusBanner.textContent = 'Server Setting: DM End-to-End Encryption is disabled by the server administrator.'; } else if (isUnlocked) { el.e2eeVaultStatusBanner.textContent = `Vault Status: 🔒 UNLOCKED & CACHED ON THIS DEVICE | Account E2EE: ${acctStatus}`; } else if (hasServerVault) { el.e2eeVaultStatusBanner.textContent = `Vault Status: 🔓 LOCKED (Existing WRAP:v1 Key Vault on Server) | Account E2EE: ${acctStatus}\nEnter your E2EE PIN below to unlock your DM history on this device.`; } else { el.e2eeVaultStatusBanner.textContent = `Vault Status: ✨ NEW VAULT SETUP REQUIRED | Account E2EE: ${acctStatus}\nCreate a dedicated E2EE PIN/passphrase below (never sent to server) to initialize your P-256 keypair.`; } if (el.e2eePinLabel) { el.e2eePinLabel.textContent = hasServerVault && !isUnlocked ? 'Enter E2EE PIN / Passphrase to Unlock Key Vault' : (isUnlocked ? 'Enter New or Current E2EE PIN' : 'Create Dedicated E2EE PIN / Passphrase'); } if (el.e2eeSubmitPinBtn) { el.e2eeSubmitPinBtn.textContent = hasServerVault && !isUnlocked ? '[ Unlock E2EE Key Vault ]' : '[ Initialize / Unlock E2EE Key Vault ]'; } if (el.e2eeToggleAccountBtn) { el.e2eeToggleAccountBtn.textContent = `[Account E2EE: ${state.accountE2eeEnabled ? 'ON' : 'OFF'}]`; } } function showE2eeModal() { initElements(); if (!el.e2eeModal) return; if (el.e2eeModalError) el.e2eeModalError.textContent = ''; if (el.e2eePinInput) el.e2eePinInput.value = ''; updateE2eeModalUI(); el.e2eeModal.style.display = 'flex'; if (el.e2eePinInput) { setTimeout(() => el.e2eePinInput.focus(), 50); } } function hideE2eeModal() { if (el.e2eeModal) { el.e2eeModal.style.display = 'none'; } } function toggleDmE2ee(channelId) { const conv = getConversationById(channelId || state.activeChannelId); if (!conv || getConversationType(conv) !== 'DM') { showToast('Select a Direct Message to toggle per-DM E2EE'); return; } const current = conv.isE2ee ?? conv.IsE2ee ?? true; sendEnvelope('TOGGLE_E2EE', { scope: 'dm', channelId: conv.id || conv.Id, enabled: !current }); } function toggleAccountE2ee(explicitEnabled) { const nextState = explicitEnabled !== undefined ? explicitEnabled : !state.accountE2eeEnabled; state.accountE2eeEnabled = nextState; sendEnvelope('TOGGLE_E2EE', { scope: 'account', enabled: nextState }); updateSettingsBadges(); updateActiveChannelHeader(); updateE2eeModalUI(); } // ========================================== // UI Renderers // ========================================== function switchTab(tabName) { el.navTabs.forEach(tab => { tab.classList.toggle('active', tab.dataset.tab === tabName); }); el.tabViews.forEach(view => { view.classList.toggle('active', view.id === `view-${tabName}`); }); if (tabName === 'users') { renderUsers(); if (state.socket && state.socket.readyState === WebSocket.OPEN) { sendEnvelope('USER_LIST_SYNC', {}); } } else if (tabName === 'channels') { renderChannels(); } else if (tabName === 'files') { renderFiles(); } else if (tabName === 'chat') { renderMessages(); } } function updateActiveChannelHeader() { const active = getConversationById(state.activeChannelId); if (!active) return; const chId = active.id || active.Id; const chName = active.name || active.Name || 'general'; const chTopic = active.topic || active.Topic || ''; const chType = getConversationType(active); if (el.channelSelectDropdown && el.channelSelectDropdown.value !== chId) { el.channelSelectDropdown.value = chId; } if (chType === 'DM') { if (el.activeConvPrefix) el.activeConvPrefix.textContent = '@'; const dmIsE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled; const peerReady = isDmPeerE2eeReady(active); const hasMyKey = !!state.privateKey; let badgeText = '[Plaintext DM]'; let badgeClass = 'e2ee-off'; if (!state.allowDmE2ee) { badgeText = '[Plaintext DM (Server E2EE Off)]'; } else if (!dmIsE2ee) { badgeText = '[Plaintext DM (E2EE Disabled)]'; } else if (!hasMyKey) { badgeText = '[🔒 E2EE Locked - Click to Enter PIN]'; } else if (!peerReady) { badgeText = '[⚠️ Peer E2EE Not Set Up (Plaintext)]'; } else { badgeText = '[🔒 Full E2EE Active]'; badgeClass = 'e2ee-on'; } if (el.chatSecurityBadge) { el.chatSecurityBadge.style.display = 'inline-flex'; el.chatSecurityBadge.className = 'conv-security-badge ' + badgeClass; el.chatSecurityBadge.textContent = badgeText; } if (el.toggleDmE2eeBtn) { el.toggleDmE2eeBtn.style.display = state.allowDmE2ee ? 'inline-flex' : 'none'; el.toggleDmE2eeBtn.textContent = dmIsE2ee ? '[DM E2EE: ON]' : '[DM E2EE: OFF]'; } if (el.inviteGroupBtn) el.inviteGroupBtn.style.display = 'none'; if (el.leaveGroupBtn) el.leaveGroupBtn.style.display = 'none'; el.activeChannelTopic.textContent = ''; el.messageInput.placeholder = `Direct Message @${chName.replace(/^@/, '')} (${dmIsE2ee && hasMyKey && peerReady ? 'Full E2EE' : 'Plaintext'})...`; } else if (chType === 'Group') { if (el.activeConvPrefix) el.activeConvPrefix.textContent = '[G]'; const memberIds = active.memberIds || active.MemberIds || []; const maxU = active.maxUsers || active.MaxUsers || state.maxGroupChatUsers; if (el.chatSecurityBadge) { el.chatSecurityBadge.style.display = 'inline-flex'; el.chatSecurityBadge.className = 'conv-security-badge group-badge'; el.chatSecurityBadge.textContent = `[${memberIds.length}/${maxU} Members]`; } if (el.toggleDmE2eeBtn) el.toggleDmE2eeBtn.style.display = 'none'; if (el.inviteGroupBtn) el.inviteGroupBtn.style.display = 'inline-flex'; if (el.leaveGroupBtn) el.leaveGroupBtn.style.display = 'inline-flex'; el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : ''; el.messageInput.placeholder = `Message group ${chName}...`; } else { if (el.activeConvPrefix) el.activeConvPrefix.textContent = '#'; if (el.chatSecurityBadge) el.chatSecurityBadge.style.display = 'none'; if (el.toggleDmE2eeBtn) el.toggleDmE2eeBtn.style.display = 'none'; if (el.inviteGroupBtn) el.inviteGroupBtn.style.display = 'none'; if (el.leaveGroupBtn) el.leaveGroupBtn.style.display = 'none'; el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : ''; el.messageInput.placeholder = `Message #${chName}... (or /help)`; } } function renderChannels() { // 1. Public Channels if (el.channelList) { el.channelList.innerHTML = ''; state.channels.forEach(ch => { const chId = ch.id || ch.Id; const chName = ch.name || ch.Name; const chTopic = ch.topic || ch.Topic || ''; const isActive = chId === state.activeChannelId; const item = document.createElement('div'); item.className = 'channel-item' + (isActive ? ' active' : ''); item.innerHTML = `
${isActive ? '[ACTIVE]' : ''} `; item.addEventListener('click', () => { joinChannel(chId); switchTab('chat'); }); el.channelList.appendChild(item); }); } // 2. Group Chats if (el.groupChatList) { el.groupChatList.innerHTML = ''; if (state.groupChats.length === 0) { el.groupChatList.innerHTML = '