-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
run.js
329 lines (288 loc) · 7.6 KB
/
run.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// LuisNet backend nodejs
const fs = require("fs");// importar el file interpreter (fs)
const path = require("path");
const session = require('express-session');
const esbuild = require("esbuild"); //BuildGame
var app = require('express')();
const express = require("express");
const ws = require("ws"); //WebSocket para multijugador
const Database = require("@replit/database"); //Conectar base de datos
const multiplayer = require("./multiplayer"); // buscar el archivo multiplayer
const db = new Database(); //Crear base de datos
const helmet = require("helmet"); //helmet
// Crear app express
// Crear servidor HTTP
const PORT = process.env.PORT || 9799; // Dejar puerto
const http = require("http").createServer(app); //HHTP para el backend web
var io = require('socket.io')(http)//Socket
let err = null;
//Fixed ratelimit cuando se efectua un ataque DoS comunicando a la Ip del servidor en si del socket
//Añadido WAF para bypassear la proxy del colegio ;)
//Start security improvements + rate-limit + helmet HEADERS BLOCK
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 min
max: 200, // limitar IPs cada 22 requests
message: "Su IP fue bloqueada con el fin de evitar que la web caiga, pues su trafico es sospechoso, si considera esto un error considere reportarlo a [email protected] o [email protected] - LuisSec" //Añadir mensaje de error cuando esta activo
});
app.use(limiter);
//Usar npm "helmet" para protejer la web un poco
app.use(helmet.dnsPrefetchControl());
app.use(helmet.expectCt());
//app.use(helmet.frameguard());
app.use(helmet.hidePoweredBy());
app.use(helmet.hsts());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.originAgentCluster());
//app.use(helmet.permittedCrossDomainPolicies());
app.use(helmet.referrerPolicy());
app.use(helmet.xssFilter());
// Empezar el servidor multijugador
multiplayer(http);
//Mapear los jugadores
const gameState = {
players: {}
}
io.on('connection', (socket) => {
socket.on('newPlayer', () => {
//Someone joined!
gameState.players[socket.id] = {
x: 250,
y: 250,
}
console.log("Servidor en uso #Luisnet")
})
socket.on('playerMovement', (playerMovement) => {
//Alguien se movió
const player = gameState.players[socket.id]
//Setear canvas
const canvasWidth = 1200
const canvasHeight = 700
//Usar objetos para que los jugadores muevan ciertas coordenadas
if (playerMovement.left && player.x > 0) {
player.x -= 4
}
if (playerMovement.right && player.x < canvasWidth) {
player.x += 4
}
if (playerMovement.up && player.y > 0) {
player.y -= 4
}
if (playerMovement.down && player.y < canvasHeight) {
player.y += 4
}
})
socket.on("disconnect", () => {
//Socket state
delete gameState.players[socket.id]
})
})
//Emitir state cada 1 minuo
setInterval(() => {
io.sockets.emit('state', gameState);
}, 9000 / 60);
// Construir juego de cliente + setear la función BuildGame()
function buildGame() {
const principal = fs.readFileSync("main.html", "utf-8");
let code = "";
code += `<script src="/dist/helper.js"></script>\n`;
code += `<script src="/dist/game.js"></script>\n`;
try {
// Construir codigo de cliente
esbuild.buildSync({
bundle: true,
sourcemap: true,
target: "es6",
keepNames: true,
logLevel: "silent",
entryPoints: ["code/main.js"],
outfile: "dist/game.js",
});
esbuild.buildSync({
bundle: true,
sourcemap: true,
target: "es6",
keepNames: true,
entryPoints: ["helper.ts"],
outfile: "dist/helper.js",
});
} catch (e) {
const loc = e.errors[0].location;
err = {
msg: e.errors[0].text,
stack: [
{
line: loc.line,
col: loc.column,
file: loc.file,
},
],
};
let msg = "";
msg += "<pre>";
msg += `ERROR: ${err.msg}\n`;
if (err.stack) {
err.stack.forEach((trace) => {
msg += ` -> ${trace.file}:${trace.line}:${trace.col}\n`;
});
}
msg += "</pre>";
fs.writeFileSync("dist/index.html", msg);
return;
}
fs.writeFileSync("dist/index.html", principal.replace("{{kaboom}}", code));
}
// Backend principal
app.use(express.json({ strict: false }));
app.get("/", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/index.html");
render();
});
app.get("/animstart", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/anim.html");
render();
});
app.get("/prueba", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/rick.html");
render();
});
app.get("/cinematic", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/cinematic_1.html");
render();
});
app.get("/load", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/intro.html");
render();
});
app.get("/playstart", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/playstart.html");
render();
});
app.get("/ctrl", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/controls.html");
render();
});
app.get("/f1", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/introf1.html");
render();
});
app.get("/menu", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/www/error.html");
render();
});
app.get("/usa", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/servers/eu.html");
render();
});
app.get("/jugar", (req, res) => {
err = null;
buildGame(); //Mostrar juego
res.sendFile(__dirname + "/dist/index.html");
render();
});
// Pagina de error
app.post("/error", (req, res) => {
err = req.body;
render();
});
// Base de datos, mapear usuario
app.get("/user", (req, res) => {
if (req.headers["x-replit-user-id"]) {
res.json({
id: req.headers["x-replit-user-id"] || null,
name: req.headers["x-replit-user-name"] || null,
});
} else {
res.json(null);
}
});
//API Busqueda base de datos
app.get("/db", async (req, res) => {
try {
res.json(await db.list());
} catch (e) {
res.sendStatus(500);
}
});
//API Busqueda base de datos
app.delete("/db", async (req, res) => {
try {
await db.empty();
res.sendStatus(200);
} catch (e) {
res.sendStatus(500);
}
});
//API Busqueda base de datos
app.get("/db/:item", async (req, res) => {
try {
res.json(await db.get(req.params.item));
} catch (e) {
res.sendStatus(500);
}
});
//API Busqueda base de datos
app.post("/db/:item", async (req, res) => {
try {
await db.set(req.params.item, req.body);
res.sendStatus(200);
} catch (e) {
res.sendStatus(500);
}
});
// Post DATABASE Api busqueda
app.delete("/db/:item", async (req, res) => {
try {
await db.delete(req.params.item);
res.sendStatus(200);
} catch (e) {
res.sendStatus(500);
}
});
// Dirname
app.use(express.static(__dirname));
// Express listen puerto
http.listen(PORT, () => {
console.log('Socket encendido en el puerto *:3000');
});
// Setear colores
const red = (msg) => `\x1b[31m${msg}\x1b[0m`;
const dim = (msg) => `\x1b[2m${msg}\x1b[0m`;
function render() {
// Iniciar servidor y renderizar juego
process.stdout.write("\x1b[2J");
process.stdout.write("\x1b[H");
process.stdout.write("#ConnectingTheUniverse LUISNET iniciado en el puerto 8080 https://pege.luisweb.cf\n");
console.log(red("\n#LuisNet"));
// Console log errores
if (err) {
console.log("");
console.error(red(`ERROR: ${err.msg}`));
if (err.stack) {
err.stack.forEach((trace) => {
console.error(` -> ${trace.file}:${trace.line}:${trace.col}`);
});
}
}
}