Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
-
// server.js (Bun)
|
| 2 |
const rooms = new Map(); // roomId ⇒ Set<ServerWebSocket>
|
|
|
|
| 3 |
|
| 4 |
Bun.serve({
|
| 5 |
port: Number(Bun.env.PORT) || 7860,
|
|
@@ -9,19 +10,22 @@ Bun.serve({
|
|
| 9 |
|
| 10 |
// Handle CORS preflight
|
| 11 |
if (req.method === "OPTIONS") {
|
| 12 |
-
return new Response(null, {
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
"Access-Control-Allow-Credentials": "true",
|
| 19 |
-
},
|
| 20 |
-
});
|
| 21 |
}
|
| 22 |
|
| 23 |
// Upgrade to WebSocket if requested
|
| 24 |
if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
// Accept the upgrade with CORS headers on the handshake
|
| 26 |
const upgradeRes = server.upgrade(req, {
|
| 27 |
headers: {
|
|
@@ -32,53 +36,53 @@ Bun.serve({
|
|
| 32 |
return upgradeRes ?? new Response("Upgrade failed", { status: 500 });
|
| 33 |
}
|
| 34 |
|
| 35 |
-
//
|
| 36 |
if (url.pathname === "/") {
|
| 37 |
return new Response(`<!doctype html>
|
| 38 |
-
<html><head>
|
| 39 |
-
<title>Dubem Realtime Rooms</title>
|
| 40 |
-
<meta charset="utf-8"/>
|
| 41 |
-
<style>
|
| 42 |
-
body { font-family: sans-serif; padding: 20px; background: #f0f0f0; }
|
| 43 |
-
#log { border: 1px solid #ccc; height:200px; overflow-y:auto; padding:10px; background:#fff;}
|
| 44 |
-
input, button { margin:5px 0; padding:8px; font-size:16px; }
|
| 45 |
-
</style>
|
| 46 |
-
</head><body>
|
| 47 |
<h2>Join a Room & Send Messages</h2>
|
| 48 |
-
<input
|
| 49 |
-
<button onclick="joinRoom()">Join Room</button>
|
| 50 |
<div id="log"></div>
|
| 51 |
-
<input id="msg" placeholder="Type a message" style="width:80%;"
|
| 52 |
-
<button onclick="sendMsg()">Send</button>
|
| 53 |
<script>
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
ws.onopen = function(){ log('🔌 Connected'); };
|
| 60 |
-
ws.onmessage = function(ev){
|
| 61 |
-
var m = JSON.parse(ev.data);
|
| 62 |
-
log('[' + m.roomId + '] ' + m.message);
|
| 63 |
-
};
|
| 64 |
-
ws.onerror = function(){ log('⚠️ WebSocket error'); };
|
| 65 |
-
ws.onclose = function(c){ log('❌ Disconnected (code='+c.code+')'); };
|
| 66 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
function joinRoom(){
|
| 68 |
-
|
| 69 |
if(!id) return alert('Enter room ID');
|
| 70 |
ws.send(JSON.stringify({ action:'join', roomId:id }));
|
| 71 |
-
currentRoom = id;
|
|
|
|
| 72 |
}
|
| 73 |
function sendMsg(){
|
| 74 |
-
|
| 75 |
if(!t) return;
|
| 76 |
if(!currentRoom) return alert('Join a room first');
|
| 77 |
ws.send(JSON.stringify({ action:'post', roomId:currentRoom, message:t }));
|
| 78 |
document.getElementById('msg').value = '';
|
| 79 |
}
|
| 80 |
function log(txt){
|
| 81 |
-
|
| 82 |
e.innerHTML += '<div>'+txt+'</div>';
|
| 83 |
e.scrollTop = e.scrollHeight;
|
| 84 |
}
|
|
@@ -101,19 +105,12 @@ Bun.serve({
|
|
| 101 |
message(ws, raw) {
|
| 102 |
let msg;
|
| 103 |
try { msg = JSON.parse(raw); } catch { return; }
|
| 104 |
-
|
| 105 |
if (msg.action === "join" && msg.roomId) {
|
| 106 |
-
// Leave all rooms
|
| 107 |
for (const set of rooms.values()) set.delete(ws);
|
| 108 |
-
// Join target room
|
| 109 |
let set = rooms.get(msg.roomId);
|
| 110 |
-
if (!set) {
|
| 111 |
-
set = new Set();
|
| 112 |
-
rooms.set(msg.roomId, set);
|
| 113 |
-
}
|
| 114 |
set.add(ws);
|
| 115 |
}
|
| 116 |
-
|
| 117 |
if (msg.action === "post" && msg.roomId && msg.message) {
|
| 118 |
const set = rooms.get(msg.roomId);
|
| 119 |
if (!set) return;
|
|
@@ -123,19 +120,14 @@ Bun.serve({
|
|
| 123 |
timestamp: Date.now(),
|
| 124 |
});
|
| 125 |
for (const client of set) {
|
| 126 |
-
if (client.readyState === 1)
|
| 127 |
-
client.send(payload);
|
| 128 |
-
}
|
| 129 |
}
|
| 130 |
}
|
| 131 |
},
|
| 132 |
-
|
| 133 |
close(ws) {
|
| 134 |
-
// Clean up on disconnect
|
| 135 |
for (const set of rooms.values()) set.delete(ws);
|
| 136 |
}
|
| 137 |
}
|
| 138 |
});
|
| 139 |
|
| 140 |
-
console.log("✅ Bun realtime server running on port " + (Bun.env.PORT || 7860));
|
| 141 |
-
|
|
|
|
| 1 |
+
// server.js (Bun)
|
| 2 |
const rooms = new Map(); // roomId ⇒ Set<ServerWebSocket>
|
| 3 |
+
const VALID_TOKEN = "mysecrettoken"; // ← your hard-coded secret
|
| 4 |
|
| 5 |
Bun.serve({
|
| 6 |
port: Number(Bun.env.PORT) || 7860,
|
|
|
|
| 10 |
|
| 11 |
// Handle CORS preflight
|
| 12 |
if (req.method === "OPTIONS") {
|
| 13 |
+
return new Response(null, { status: 204, headers: {
|
| 14 |
+
"Access-Control-Allow-Origin": "*",
|
| 15 |
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
| 16 |
+
"Access-Control-Allow-Headers": "Content-Type, Upgrade",
|
| 17 |
+
"Access-Control-Allow-Credentials": "true",
|
| 18 |
+
}});
|
|
|
|
|
|
|
|
|
|
| 19 |
}
|
| 20 |
|
| 21 |
// Upgrade to WebSocket if requested
|
| 22 |
if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
|
| 23 |
+
// **AUTH CHECK**: require ?token=VALID_TOKEN
|
| 24 |
+
const clientToken = url.searchParams.get("token");
|
| 25 |
+
if (clientToken !== VALID_TOKEN) {
|
| 26 |
+
return new Response("Unauthorized", { status: 401 });
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
// Accept the upgrade with CORS headers on the handshake
|
| 30 |
const upgradeRes = server.upgrade(req, {
|
| 31 |
headers: {
|
|
|
|
| 36 |
return upgradeRes ?? new Response("Upgrade failed", { status: 500 });
|
| 37 |
}
|
| 38 |
|
| 39 |
+
// … your existing HTML serve code unchanged …
|
| 40 |
if (url.pathname === "/") {
|
| 41 |
return new Response(`<!doctype html>
|
| 42 |
+
<html><head><title>Dubem Realtime Rooms</title><meta charset="utf-8"/></head><body>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
<h2>Join a Room & Send Messages</h2>
|
| 44 |
+
<label><input type="checkbox" id="authToggle"> Send Auth Token?</label><br/>
|
| 45 |
+
<input id="room" placeholder="Room ID"/><button onclick="joinRoom()">Join Room</button>
|
| 46 |
<div id="log"></div>
|
| 47 |
+
<input id="msg" placeholder="Type a message" style="width:80%;"/><button onclick="sendMsg()">Send</button>
|
|
|
|
| 48 |
<script>
|
| 49 |
+
const VALID_TOKEN = "mysecrettoken"; // must match backend
|
| 50 |
+
let includeAuth = false;
|
| 51 |
+
document.getElementById("authToggle").addEventListener("change", e => {
|
| 52 |
+
includeAuth = e.target.checked;
|
| 53 |
+
connect(); // reconnect on toggle
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
});
|
| 55 |
+
|
| 56 |
+
let ws, currentRoom;
|
| 57 |
+
function connect() {
|
| 58 |
+
if (ws) ws.close();
|
| 59 |
+
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
| 60 |
+
let socketUrl = scheme + '://' + location.host + '/';
|
| 61 |
+
if (includeAuth) socketUrl += "?token=" + VALID_TOKEN;
|
| 62 |
+
ws = new WebSocket(socketUrl);
|
| 63 |
+
ws.onopen = () => log('🔌 Connected');
|
| 64 |
+
ws.onmessage = ev => { const m = JSON.parse(ev.data); log('['+m.roomId+'] '+m.message); };
|
| 65 |
+
ws.onerror = () => log('⚠️ WebSocket error');
|
| 66 |
+
ws.onclose = c => log('❌ Disconnected (code='+c.code+')');
|
| 67 |
+
}
|
| 68 |
+
window.addEventListener('load', connect);
|
| 69 |
+
|
| 70 |
function joinRoom(){
|
| 71 |
+
const id = document.getElementById('room').value.trim();
|
| 72 |
if(!id) return alert('Enter room ID');
|
| 73 |
ws.send(JSON.stringify({ action:'join', roomId:id }));
|
| 74 |
+
currentRoom = id;
|
| 75 |
+
log('➡️ Joined '+id);
|
| 76 |
}
|
| 77 |
function sendMsg(){
|
| 78 |
+
const t = document.getElementById('msg').value.trim();
|
| 79 |
if(!t) return;
|
| 80 |
if(!currentRoom) return alert('Join a room first');
|
| 81 |
ws.send(JSON.stringify({ action:'post', roomId:currentRoom, message:t }));
|
| 82 |
document.getElementById('msg').value = '';
|
| 83 |
}
|
| 84 |
function log(txt){
|
| 85 |
+
const e = document.getElementById('log');
|
| 86 |
e.innerHTML += '<div>'+txt+'</div>';
|
| 87 |
e.scrollTop = e.scrollHeight;
|
| 88 |
}
|
|
|
|
| 105 |
message(ws, raw) {
|
| 106 |
let msg;
|
| 107 |
try { msg = JSON.parse(raw); } catch { return; }
|
|
|
|
| 108 |
if (msg.action === "join" && msg.roomId) {
|
|
|
|
| 109 |
for (const set of rooms.values()) set.delete(ws);
|
|
|
|
| 110 |
let set = rooms.get(msg.roomId);
|
| 111 |
+
if (!set) { set = new Set(); rooms.set(msg.roomId, set); }
|
|
|
|
|
|
|
|
|
|
| 112 |
set.add(ws);
|
| 113 |
}
|
|
|
|
| 114 |
if (msg.action === "post" && msg.roomId && msg.message) {
|
| 115 |
const set = rooms.get(msg.roomId);
|
| 116 |
if (!set) return;
|
|
|
|
| 120 |
timestamp: Date.now(),
|
| 121 |
});
|
| 122 |
for (const client of set) {
|
| 123 |
+
if (client.readyState === 1) client.send(payload);
|
|
|
|
|
|
|
| 124 |
}
|
| 125 |
}
|
| 126 |
},
|
|
|
|
| 127 |
close(ws) {
|
|
|
|
| 128 |
for (const set of rooms.values()) set.delete(ws);
|
| 129 |
}
|
| 130 |
}
|
| 131 |
});
|
| 132 |
|
| 133 |
+
console.log("✅ Bun realtime server running on port " + (Bun.env.PORT || 7860));
|
|
|