-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
227 lines (198 loc) · 6.46 KB
/
index.js
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/** @format */
import express from "express";
import http from "http";
import { Server } from "socket.io";
import records from "./records.js";
import { fileURLToPath } from "url";
import { dirname } from "path";
import os from "os";
import speakeasy from "speakeasy";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const port = process.env.PORT || 3000;
let code = process.env.ROOM_TOKEN || "1234";
const adminPassword = process.env.ADMIN_TOKEN || "password";
const secret = process.env.TOTP_TOKEN || "MJHGQS2SEVKGOXSLKFIVWVRIIRFHSL3NMYXXIRRPEERVASKR";
let onlineCount = 0;
let blackList = [];
let vote = {};
const userTokenList = [];
app.use((req, res, next) => {
if (
req.header("x-forwarded-proto") !== "https" &&
process.env.NODE_ENV === "production"
) {
res.redirect(`https://${req.header("host")}${req.url}`);
} else {
next();
}
});
app.use("/static", express.static("static"));
const MAX_WRONG_ATTEMPTS = 3;
const BLOCK_DURATION = 60000; // 1 minute in milliseconds
const wrongAttempts = new Map();
app.get("/", (req, res) => {
const token = req.query.token;
const ip = req.ip;
if (wrongAttempts.has(ip) && wrongAttempts.get(ip) >= MAX_WRONG_ATTEMPTS) {
res.send("嘗試次數過多。請一分鐘後再試。");
return;
}
if (!token) {
res.sendFile(__dirname + "/pages/index.html");
return;
}
if (token == code) {
res.sendFile(__dirname + "/pages/room.html");
wrongAttempts.delete(ip);
} else {
res.sendFile(__dirname + "/pages/wrong.html");
console.log("登入失敗:" + token);
if (wrongAttempts.has(ip)) {
wrongAttempts.set(ip, wrongAttempts.get(ip) + 1);
} else {
wrongAttempts.set(ip, 1);
}
if (wrongAttempts.get(ip) >= MAX_WRONG_ATTEMPTS) {
setTimeout(() => {
wrongAttempts.delete(ip);
}, BLOCK_DURATION);
}
}
});
app.get("/admin", (req, res) => {
const token = req.query.token;
const totpCode = req.query.totpCode;
const ip = req.ip;
if (wrongAttempts.has(ip) && wrongAttempts.get(ip) >= MAX_WRONG_ATTEMPTS) {
res.send("嘗試次數過多。請一分鐘後再試。");
return;
}
if (token == adminPassword) {
// 假設我們收到的一次性驗證碼為 '132890'
// 我們選用 base32編碼的金鑰
const verified = speakeasy.totp.verify({
secret: secret,
encoding: "base32",
token: totpCode,
window: 2
});
if (!verified) {
res.sendFile(__dirname + "/pages/wrong.html");
console.log("TOTP 錯誤:" + token);
return;
}
res.sendFile(__dirname + "/pages/admin.html");
wrongAttempts.delete(ip);
return;
} else {
res.sendFile(__dirname + "/pages/index.html");
console.log("登入失敗:" + token);
}
if (wrongAttempts.has(ip)) {
wrongAttempts.set(ip, wrongAttempts.get(ip) + 1);
} else {
wrongAttempts.set(ip, 1);
}
if (wrongAttempts.get(ip) >= MAX_WRONG_ATTEMPTS) {
setTimeout(() => {
wrongAttempts.delete(ip);
}, BLOCK_DURATION);
}
});
io.on("connection", socket => {
const ip = socket.handshake.address;
if (blackList.includes(ip)) {
console.log(ip + "嘗試連線,但是被黑名單擋下了");
socket.disconnect(true);
return;
}
// 有連線發生時增加人數
onlineCount++;
// 發送人數給網頁
io.emit("online", onlineCount);
let token = generateToken();
while (userTokenList.includes(token)) {
token = generateToken();
}
userTokenList.push(token);
socket.emit("token", token);
// 發送紀錄
socket.emit("chatRecord", records.get());
// 發送投票結果
const voteCount = Object.values(vote).filter(v => v).length;
io.emit("voteCount", voteCount);
socket.on("greet", () => {
socket.emit("greet", onlineCount);
});
// 發送 roomCode
socket.emit("roomCode", code);
socket.on("send", msg => {
msg.ip = ip;
// 如果 msg 內容鍵值小於 2 等於是訊息傳送不完全
// 因此我們直接 return ,終止函式執行。
if (Object.keys(msg).length < 2) return;
records.push(msg);
});
socket.on("disconnect", () => {
// 有人離線了,扣人
onlineCount = onlineCount < 0 ? 0 : (onlineCount -= 1);
io.emit("online", onlineCount);
// 移除 token
const index = userTokenList.findIndex(t => t == token);
userTokenList.splice(index, 1);
// 移除投票
delete vote[token];
// 發送投票結果
const voteCount = Object.values(vote).filter(v => v).length;
io.emit("voteCount", voteCount);
});
socket.on("setCode", ({ token, room }) => {
if (token != adminPassword) {
console.log("有人嘗試更新代碼,密碼錯誤");
return;
}
code = room;
console.log("Code updated:", code);
io.sockets.sockets.forEach(socket => {
socket.disconnect(true);
});
});
socket.on("sendLink", msg => {
console.log("openLink", msg.link);
// 廣播訊息到聊天室
io.emit("openLink", msg.link);
});
socket.on("hand", checked => {
vote[checked.userToken] = checked.checked;
const voteCount = Object.values(vote).filter(v => v).length;
io.emit("voteCount", voteCount);
});
});
records.on("new_message", msg => {
// 廣播訊息到聊天室
io.emit("msg", msg);
});
server.listen(process.env.PORT || 3000, () => {
console.log("Express server listening on port");
});
function generateToken() {
const characters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let token = "";
for (let i = 0; i < 10; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
token += characters[randomIndex];
}
return token;
}
app.get("/ram-usage", (req, res) => {
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
const usedMemory = totalMemory - freeMemory;
const ramUsage = (usedMemory / totalMemory) * 100;
res.json({ totalMemory,usedMemory,ramUsage });
});