import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react'; import { Send, Mic, Square, Paperclip, Smile, Search, Phone, Video, Shield, ShieldCheck, Lock, Unlock, Settings, User, Users, Hash, Bookmark, Pin, MoreVertical, Check, CheckCheck, Reply, Forward, Edit3, Trash2, Copy, X, Plus, Volume2, VolumeX, Monitor, MonitorOff, MicOff, VideoOff, PhoneOff, Sparkles, Flame, Eye, EyeOff, Clock, Smartphone, Laptop, Globe, Cpu, Zap, ArrowLeft, ChevronRight, Download, Play, Pause, Radio, Sliders, KeyRound, LogOut, AlertTriangle, RefreshCw, Image as ImageIcon, FileText, Film, Maximize2, CheckCircle2, Info, MessageSquare } from 'lucide-react'; import { initializeApp } from 'firebase/app'; import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from 'firebase/auth'; import { getFirestore, doc, setDoc, getDoc, updateDoc, deleteDoc, collection, onSnapshot, addDoc } from 'firebase/firestore'; // ============================================================================ // 1. FIREBASE & REALTIME BACKEND INITIALIZATION (OUTSIDE COMPONENT) // Strictly adheres to environment globals with safe fallback config. // Architecture mirrors Cloudflare Pages + Edge WSS/TLS 1.3 transport. // ============================================================================ let firebaseApp = null; let auth = null; let db = null; const appId = typeof __app_id !== 'undefined' ? __app_id : 'opticore-messenger-v1'; try { if (typeof __firebase_config !== 'undefined' && __firebase_config) { const firebaseConfig = JSON.parse(__firebase_config); firebaseApp = initializeApp(firebaseConfig); auth = getAuth(firebaseApp); db = getFirestore(firebaseApp); } } catch (err) { console.error('Realtime transport init fallback:', err); } // Strict path helpers (RULE 1) const getPublicCol = (name) => collection(db, 'artifacts', appId, 'public', 'data', name); const getPublicDoc = (name, id) => doc(db, 'artifacts', appId, 'public', 'data', name, id); const getPrivateCol = (uid, name) => collection(db, 'artifacts', appId, 'users', uid, name); const getPrivateDoc = (uid, name, id) => doc(db, 'artifacts', appId, 'users', uid, name, id); // ============================================================================ // 2. INDEXEDDB VAULT & WEB CRYPTO API (ZERO-KNOWLEDGE E2EE ENGINE) // - ECDH P-256 keypair generation & persistent IndexedDB storage // - AES-GCM 256-bit message/file encryption with random 96-bit IV // - SHA-256 deterministic 4-Emoji Fingerprint verification // - Persistent device session marker (Zero localStorage usage) // ============================================================================ const IDB_NAME = 'OpticoreZeroKnowledgeVault'; const IDB_VERSION = 1; const IDB_STORE = 'vault'; const openVaultDB = () => new Promise((resolve, reject) => { try { const req = indexedDB.open(IDB_NAME, IDB_VERSION); req.onupgradeneeded = () => { const database = req.result; if (!database.objectStoreNames.contains(IDB_STORE)) { database.createObjectStore(IDB_STORE); } }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); } catch (e) { reject(e); } }); const vaultGet = async (key) => { try { const database = await openVaultDB(); return await new Promise((resolve, reject) => { const tx = database.transaction(IDB_STORE, 'readonly'); const req = tx.objectStore(IDB_STORE).get(key); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } catch { return null; } }; const vaultSet = async (key, value) => { try { const database = await openVaultDB(); return await new Promise((resolve, reject) => { const tx = database.transaction(IDB_STORE, 'readwrite'); const req = tx.objectStore(IDB_STORE).put(value, key); req.onsuccess = () => resolve(true); req.onerror = () => reject(req.error); }); } catch { return false; } }; const vaultClear = async () => { try { const database = await openVaultDB(); return await new Promise((resolve, reject) => { const tx = database.transaction(IDB_STORE, 'readwrite'); const req = tx.objectStore(IDB_STORE).clear(); req.onsuccess = () => resolve(true); req.onerror = () => reject(req.error); }); } catch { return false; } }; // Encoding utilities const bufToB64 = (buf) => { const bytes = new Uint8Array(buf); let bin = ''; for (let i = 0; i < bytes.byteLength; i++) bin += String.fromCharCode(bytes[i]); return btoa(bin); }; const b64ToBuf = (b64) => { const bin = atob(b64); const bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); return bytes.buffer; }; const sha256Hex = async (text) => { const data = new TextEncoder().encode(text); const hash = await window.crypto.subtle.digest('SHA-256', data); return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, '0')).join(''); }; const FINGERPRINT_EMOJIS = [ '🔮', '⚡', '🌌', '💎', '🦋', '🛸', '🧬', '🌙', '🔥', '❄️', '🪐', '🛡️', '🗝️', '🎭', '💠', '🌊', '☄️', '🧿', '✨', '🌈', '🦄', '🐉', '🧊', '🌸', '⚡', '🔭', '🛰️', '🎛️', '💿', '🪩', '🧪', '🌋' ]; // Deterministic 4-emoji verification fingerprint from shared secret/chat keys const generateEmojiFingerprint = async (seedA, seedB = '') => { const sorted = [String(seedA || ''), String(seedB || '')].sort().join('::OPTICORE::E2EE::'); const hashBuf = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(sorted)); const bytes = new Uint8Array(hashBuf); const emojis = [ FINGERPRINT_EMOJIS[bytes[0] % FINGERPRINT_EMOJIS.length], FINGERPRINT_EMOJIS[bytes[5] % FINGERPRINT_EMOJIS.length], FINGERPRINT_EMOJIS[bytes[11] % FINGERPRINT_EMOJIS.length], FINGERPRINT_EMOJIS[bytes[19] % FINGERPRINT_EMOJIS.length], ]; const hex = Array.from(bytes.slice(0, 16)) .map((b) => b.toString(16).padStart(2, '0').toUpperCase()) .join('') .match(/.{1,4}/g) .join(' '); return { emojis, hex }; }; // Manage persistent ECDH P-256 identity keypair in IndexedDB const ensureIdentityKeyPair = async (uid) => { const storeKey = `ecdh_keypair_${uid}`; let existing = await vaultGet(storeKey); if (existing && existing.privateKey && existing.publicKeyJwk) { return existing; } const keyPair = await window.crypto.subtle.generateKey( { name: 'ECDH', namedCurve: 'P-256' }, false, // non-extractable private key for security! ['deriveKey', 'deriveBits'] ); const publicKeyJwk = await window.crypto.subtle.exportKey('jwk', keyPair.publicKey); const record = { privateKey: keyPair.privateKey, publicKey: keyPair.publicKey, publicKeyJwk, createdAt: Date.now() }; await vaultSet(storeKey, record); return record; }; // Derive AES-GCM 256-bit key for a chat (ECDH for 1-on-1, deterministic PBKDF2/HKDF for rooms) const deriveChatAesKey = async (chat, myKeyRecord, peerPublicKeyJwk) => { try { if (peerPublicKeyJwk && myKeyRecord?.privateKey && (chat.type === 'personal' || chat.type === 'secret')) { const peerPub = await window.crypto.subtle.importKey( 'jwk', peerPublicKeyJwk, { name: 'ECDH', namedCurve: 'P-256' }, false, [] ); return await window.crypto.subtle.deriveKey( { name: 'ECDH', public: peerPub }, myKeyRecord.privateKey, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'] ); } // Group / Channel / Saved room E2EE key derivation from room keyMaterial const materialStr = chat.keyMaterial || `opticore-room-key-${chat.id}-v1`; const rawKey = await window.crypto.subtle.digest( 'SHA-256', new TextEncoder().encode(materialStr) ); return await window.crypto.subtle.importKey( 'raw', rawKey, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'] ); } catch (err) { // Fallback deterministic AES-GCM 256 key const rawKey = await window.crypto.subtle.digest( 'SHA-256', new TextEncoder().encode(`opticore-fallback-${chat?.id || 'global'}`) ); return await window.crypto.subtle.importKey('raw', rawKey, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); } }; const encryptPayload = async (plainObj, aesKey) => { const iv = window.crypto.getRandomValues(new Uint8Array(12)); const encoded = new TextEncoder().encode(JSON.stringify(plainObj)); const cipherBuf = await window.crypto.subtle.encrypt( { name: 'AES-GCM', iv }, aesKey, encoded ); return { iv: bufToB64(iv), ciphertext: bufToB64(cipherBuf), alg: 'AES-256-GCM' }; }; const decryptPayload = async (encObj, aesKey) => { if (!encObj?.iv || !encObj?.ciphertext) return null; try { const decrypted = await window.crypto.subtle.decrypt( { name: 'AES-GCM', iv: new Uint8Array(b64ToBuf(encObj.iv)) }, aesKey, b64ToBuf(encObj.ciphertext) ); return JSON.parse(new TextDecoder().decode(decrypted)); } catch { return null; } }; // ============================================================================ // 3. PROCEDURAL WEB AUDIO API TACTILE SOUND ENGINE // Zero external audio files; ultra-low latency crystalline cyber feedback. // ============================================================================ class SoundEngine { constructor() { this.ctx = null; this.enabled = true; } ensureCtx() { if (!this.enabled) return null; if (!this.ctx && typeof window !== 'undefined') { const AudioCtx = window.AudioContext || window.webkitAudioContext; if (AudioCtx) this.ctx = new AudioCtx(); } if (this.ctx && this.ctx.state === 'suspended') { this.ctx.resume().catch(() => {}); } return this.ctx; } play(type) { const ctx = this.ensureCtx(); if (!ctx) return; const now = ctx.currentTime; const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.connect(gain); gain.connect(ctx.destination); if (type === 'send') { osc.type = 'sine'; osc.frequency.setValueAtTime(520, now); osc.frequency.exponentialRampToValueAtTime(880, now + 0.09); gain.gain.setValueAtTime(0.001, now); gain.gain.linearRampToValueAtTime(0.06, now + 0.015); gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.14); osc.start(now); osc.stop(now + 0.15); } else if (type === 'receive') { osc.type = 'triangle'; osc.frequency.setValueAtTime(660, now); osc.frequency.setValueAtTime(990, now + 0.06); gain.gain.setValueAtTime(0.001, now); gain.gain.linearRampToValueAtTime(0.055, now + 0.02); gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.22); osc.start(now); osc.stop(now + 0.23); } else if (type === 'click') { osc.type = 'sine'; osc.frequency.setValueAtTime(1200, now); osc.frequency.exponentialRampToValueAtTime(420, now + 0.03); gain.gain.setValueAtTime(0.03, now); gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.035); osc.start(now); osc.stop(now + 0.04); } else if (type === 'rec_start') { osc.type = 'sine'; osc.frequency.setValueAtTime(440, now); osc.frequency.exponentialRampToValueAtTime(740, now + 0.12); gain.gain.setValueAtTime(0.001, now); gain.gain.linearRampToValueAtTime(0.07, now + 0.02); gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.16); osc.start(now); osc.stop(now + 0.17); } else if (type === 'rec_stop') { osc.type = 'sine'; osc.frequency.setValueAtTime(680, now); osc.frequency.exponentialRampToValueAtTime(340, now + 0.11); gain.gain.setValueAtTime(0.001, now); gain.gain.linearRampToValueAtTime(0.06, now + 0.02); gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.14); osc.start(now); osc.stop(now + 0.15); } else if (type === 'call') { osc.type = 'sine'; osc.frequency.setValueAtTime(587.33, now); osc.frequency.setValueAtTime(880, now + 0.12); gain.gain.setValueAtTime(0.001, now); gain.gain.linearRampToValueAtTime(0.07, now + 0.03); gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.35); osc.start(now); osc.stop(now + 0.36); } } } const soundEngine = new SoundEngine(); // ============================================================================ // 4. WEBGL GLSL SHADER #1: IRIDESCENT CHROMATIC PLASMA BACKGROUND // Deep #030306 obsidian base, holographic white/violet/ice-blue/peach // waves, RGB chromatic aberration dispersion, film grain, cursor & audio // reactivity, 120 FPS Ultra / 60 FPS Balanced adaptive scheduler. // ============================================================================ const PLASMA_VERT = ` attribute vec2 a_pos; void main() { gl_Position = vec4(a_pos, 0.0, 1.0); } `; const PLASMA_FRAG = ` precision highp float; uniform vec2 u_res; uniform float u_time; uniform vec2 u_mouse; uniform float u_audio; uniform float u_ultra; float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); } float noise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash(i + vec2(0.0, 0.0)), hash(i + vec2(1.0, 0.0)), u.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y ); } float fbm(vec2 p) { float v = 0.0; float a = 0.52; mat2 rot = mat2(0.80, 0.60, -0.60, 0.80); v += a * noise(p); p = rot * p * 2.02; a *= 0.5; v += a * noise(p); p = rot * p * 2.03; a *= 0.5; v += a * noise(p); p = rot * p * 2.01; a *= 0.5; if (u_ultra > 0.5) { v += a * noise(p); } return v; } // Compute plasma wave field intensity at point p float plasmaField(vec2 p, float t, vec2 m) { vec2 d = p - m; float md = exp(-dot(d, d) * 2.6); p += d * md * (0.28 + u_audio * 0.35); vec2 q = vec2( fbm(p * 1.15 + vec2(t * 0.12, -t * 0.09)), fbm(p * 1.15 + vec2(-t * 0.10, t * 0.14) + vec2(4.2, 1.7)) ); vec2 r = vec2( fbm(p * 1.4 + 2.2 * q + vec2(1.7, 9.2) + t * 0.08), fbm(p * 1.4 + 2.2 * q + vec2(8.3, 2.8) - t * 0.07) ); float f = fbm(p * 1.1 + 1.8 * r + sin(t * 0.15) * 0.2); // Sharp iridescent light ribbons float ridge = 1.0 - abs(f * 2.0 - 1.0); return pow(clamp(ridge, 0.0, 1.0), 2.15) + md * (0.18 + u_audio * 0.45); } void main() { vec2 uv = gl_FragCoord.xy / u_res.xy; vec2 p = (gl_FragCoord.xy - 0.5 * u_res.xy) / min(u_res.x, u_res.y); vec2 m = (u_mouse - 0.5) * vec2(u_res.x / min(u_res.x, u_res.y), u_res.y / min(u_res.x, u_res.y)); float t = u_time * (0.65 + u_audio * 0.55); // RGB Chromatic Aberration / Dispersion sampling along wave normal float disp = 0.018 + u_audio * 0.028; float fR = plasmaField(p + vec2(disp, disp * 0.4), t, m); float fG = plasmaField(p, t, m); float fB = plasmaField(p - vec2(disp * 0.9, -disp * 0.5), t, m); // Obsidian palette mapping (#030306 -> #2A0845 -> #8B5CF6 -> #EC4899 -> #3B82F6 -> #FF8A7A -> White) vec3 obsidian = vec3(0.012, 0.012, 0.024); vec3 ultraViolet = vec3(0.165, 0.031, 0.271); vec3 electricViolet = vec3(0.545, 0.361, 0.965); vec3 iceBlue = vec3(0.231, 0.510, 0.965); vec3 magenta = vec3(0.925, 0.282, 0.600); vec3 peach = vec3(1.000, 0.541, 0.478); vec3 col = obsidian; col += ultraViolet * smoothstep(0.12, 0.72, fG) * 0.85; col += electricViolet * vec3(fR, fG, fB) * smoothstep(0.28, 0.95, fG) * 0.68; col += iceBlue * smoothstep(0.45, 1.0, fB) * 0.48; col += magenta * smoothstep(0.48, 0.98, fR) * 0.44; col += peach * pow(clamp(fR - fB + 0.35, 0.0, 1.0), 3.0) * smoothstep(0.52, 1.0, fR) * 0.42; // Holographic crisp white-iridescent ridge core float core = smoothstep(0.76, 1.05, fG); col += vec3(0.95, 0.93, 1.0) * core * 0.48; // Chromatic edge halo amplification col.r += max(0.0, fR - fG) * 0.75; col.b += max(0.0, fB - fG) * 0.85; // Subtle vignette for crystal-clear foreground typography float vig = 1.0 - dot(uv - 0.5, uv - 0.5) * 0.85; col *= clamp(vig, 0.35, 1.05); // Subtle cinematic film grain float grain = (hash(gl_FragCoord.xy + fract(u_time) * 100.0) - 0.5) * 0.032; col += grain; gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0); } `; const IridescentPlasmaCanvas = React.memo(({ performanceMode, audioLevelRef }) => { const canvasRef = useRef(null); const mouseRef = useRef({ x: 0.5, y: 0.5, tx: 0.5, ty: 0.5 }); useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const gl = canvas.getContext('webgl', { alpha: false, antialias: false, powerPreference: 'high-performance' }); if (!gl) return; const compile = (type, src) => { const sh = gl.createShader(type); gl.shaderSource(sh, src); gl.compileShader(sh); return sh; }; const prog = gl.createProgram(); gl.attachShader(prog, compile(gl.VERTEX_SHADER, PLASMA_VERT)); gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, PLASMA_FRAG)); gl.linkProgram(prog); gl.useProgram(prog); const buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); const loc = gl.getAttribLocation(prog, 'a_pos'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); const uRes = gl.getUniformLocation(prog, 'u_res'); const uTime = gl.getUniformLocation(prog, 'u_time'); const uMouse = gl.getUniformLocation(prog, 'u_mouse'); const uAudio = gl.getUniformLocation(prog, 'u_audio'); const uUltra = gl.getUniformLocation(prog, 'u_ultra'); const resize = () => { const dpr = performanceMode === 'ultra' ? Math.min(window.devicePixelRatio || 1, 1.5) : 0.75; canvas.width = Math.max(1, Math.floor(window.innerWidth * dpr)); canvas.height = Math.max(1, Math.floor(window.innerHeight * dpr)); gl.viewport(0, 0, canvas.width, canvas.height); }; resize(); window.addEventListener('resize', resize); const onMove = (e) => { mouseRef.current.tx = e.clientX / Math.max(1, window.innerWidth); mouseRef.current.ty = 1.0 - e.clientY / Math.max(1, window.innerHeight); }; window.addEventListener('mousemove', onMove, { passive: true }); let rafId = 0; let start = performance.now(); let lastDraw = 0; let smoothedAudio = 0; const render = (now) => { rafId = requestAnimationFrame(render); const minDelta = performanceMode === 'ultra' ? 0 : 16.5; if (now - lastDraw < minDelta) return; lastDraw = now; const m = mouseRef.current; m.x += (m.tx - m.x) * 0.06; m.y += (m.ty - m.y) * 0.06; const targetAudio = audioLevelRef?.current || 0; smoothedAudio += (targetAudio - smoothedAudio) * 0.14; gl.uniform2f(uRes, canvas.width, canvas.height); gl.uniform1f(uTime, (now - start) * 0.001); gl.uniform2f(uMouse, m.x, m.y); gl.uniform1f(uAudio, smoothedAudio); gl.uniform1f(uUltra, performanceMode === 'ultra' ? 1.0 : 0.0); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); }; rafId = requestAnimationFrame(render); return () => { cancelAnimationFrame(rafId); window.removeEventListener('resize', resize); window.removeEventListener('mousemove', onMove); }; }, [performanceMode, audioLevelRef]); return (