-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
183 lines (150 loc) · 6.83 KB
/
script.js
File metadata and controls
183 lines (150 loc) · 6.83 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
// 0. Import the Firebase tools from Google's servers
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-app.js";
import { getDatabase, ref, push, onValue, onDisconnect, remove } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-database.js";
// 1. YOUR VIP ACCESS BADGE
const firebaseConfig = {
apiKey: "AIzaSyBT7Iolk2GC6WDcHhBcSbyibX9rRy4t0bw",
authDomain: "hashchat-f2658.firebaseapp.com",
projectId: "hashchat-f2658",
storageBucket: "hashchat-f2658.firebasestorage.app",
messagingSenderId: "377264995619",
appId: "1:377264995619:web:0649827cedeb7b49fde096",
measurementId: "G-MLXWJ90L2D"
};
// 2. Boot up the Database
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
let roomID = "";
const mySecretID = Math.random().toString(36).substring(2, 10);
// ==========================================
// 🛡️ E2EE CRYPTO ENGINE (NATIVE BROWSER API)
// ==========================================
async function getCryptoKey(password) {
const encoder = new TextEncoder();
const hash = await window.crypto.subtle.digest("SHA-256", encoder.encode(password));
return window.crypto.subtle.importKey("raw", hash, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
}
async function encryptMessage(realText) {
const key = await getCryptoKey(roomID); // Uses current roomID as the secret key
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encodedText = new TextEncoder().encode(realText);
const encrypted = await window.crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, encodedText);
const combined = new Uint8Array(iv.length + encrypted.byteLength);
combined.set(iv, 0);
combined.set(new Uint8Array(encrypted), iv.length);
return btoa(String.fromCharCode(...combined));
}
async function decryptMessage(base64Text) {
try {
const key = await getCryptoKey(roomID); // Uses current roomID as the secret key
const combined = new Uint8Array(atob(base64Text).split("").map(c => c.charCodeAt(0)));
const iv = combined.slice(0, 12);
const data = combined.slice(12);
const decrypted = await window.crypto.subtle.decrypt({ name: "AES-GCM", iv: iv }, key, data);
return new TextDecoder().decode(decrypted);
} catch (error) {
// If it fails (e.g. old unencrypted message), just return a locked string
return "🔒 [Encrypted]";
}
}
// ==========================================
// 3. Check if joining an existing room on page load
if (window.location.hash) {
roomID = window.location.hash.substring(1);
showChatScreen();
document.getElementById('room-id-display').textContent = `/chat#${roomID}`;
startListeningForMessages();
}
// Mobile Menu Toggle
window.toggleMobileMenu = function () {
const hamburger = document.querySelector('.hamburger');
const overlay = document.querySelector('.mobile-menu-overlay');
const mobileNav = document.querySelector('.mobile-nav');
hamburger.classList.toggle('active');
overlay.classList.toggle('active');
mobileNav.classList.toggle('active');
}
// Close mobile menu when clicking on overlay
document.querySelector('.mobile-menu-overlay').addEventListener('click', function () {
const hamburger = document.querySelector('.hamburger');
const overlay = document.querySelector('.mobile-menu-overlay');
const mobileNav = document.querySelector('.mobile-nav');
hamburger.classList.remove('active');
overlay.classList.remove('active');
mobileNav.classList.remove('active');
});
// 4. Create a new room with a 7-character ID
window.createNewRoom = function () {
roomID = Math.random().toString(36).substring(2, 9).toUpperCase();
window.location.hash = roomID;
showChatScreen();
document.getElementById('room-id-display').textContent = `/chat#${roomID}`;
startListeningForMessages();
}
// UI Toggle Helper
function showChatScreen() {
document.getElementById('landing-page').style.display = 'none';
document.getElementById('chat-page').style.display = 'flex';
}
// Modern Copy to Clipboard
window.copyHash = function () {
navigator.clipboard.writeText(window.location.href).then(() => {
alert("Link copied! Send it to your friend.");
});
}
// 5. Send Message Logic (NOW ASYNC & ENCRYPTED)
window.sendMessage = async function () {
const inputField = document.getElementById('message-input');
const message = inputField.value.trim();
if (!message) return; // Stop if the box is empty
// Clear the text box instantly for good UX
inputField.value = "";
// Encrypt the message before sending
const scrambledText = await encryptMessage(message);
const messagesRef = ref(db, 'rooms/' + roomID + '/messages');
// Push the ENCRYPTED data
push(messagesRef, {
text: scrambledText,
senderId: mySecretID,
timestamp: Date.now()
});
}
function startListeningForMessages() {
const roomRootRef = ref(db, 'rooms/' + roomID);
const messagesRef = ref(db, 'rooms/' + roomID + '/messages');
onDisconnect(roomRootRef).remove();
// Make the callback async so we can wait for decryption
onValue(messagesRef, async (snapshot) => {
let chatContainer = document.getElementById('chat-stream');
if (!chatContainer) {
console.error("ERROR: Could not find <div id='chat-stream'> in your HTML!");
return;
}
chatContainer.innerHTML = "";
// Collect all messages first
const messagesToProcess = [];
snapshot.forEach((childSnapshot) => {
messagesToProcess.push(childSnapshot.val());
});
// Loop through and decrypt them one by one
for (const msgData of messagesToProcess) {
// Decrypt the text back to normal
const plainText = await decryptMessage(msgData.text);
const bubbleClass = (msgData.senderId === mySecretID) ? 'outgoing' : 'incoming';
const timeString = new Date(msgData.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
let messageElement = document.createElement('div');
messageElement.classList.add('message', bubbleClass);
// Render using the plainText
messageElement.innerHTML = `<span class="message-time">${timeString}</span>
<div class="message-bubble">${plainText}</div>`;
chatContainer.appendChild(messageElement);
}
chatContainer.scrollTop = chatContainer.scrollHeight;
});
}
// Listen for the "Enter" key
document.getElementById('message-input').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
sendMessage();
}
});