-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
77 lines (67 loc) · 2.13 KB
/
Copy pathserver.js
File metadata and controls
77 lines (67 loc) · 2.13 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
import Fastify from "fastify";
import toursPool from "./db/db_tours.js";
import ordersPool from "./db/db_orders.js";
const fastify = Fastify({
logger: true,
});
// 1. Определяем логику защиты (как и раньше)
const protectEveryRoute = async (request, reply) => {
// Запрещаем кэширование абсолютно везде
reply.header("Cache-Control", "no-store, no-cache, must-revalidate, private");
reply.header("Pragma", "no-cache");
reply.header("Expires", "0");
// Защита от подмены расширения (Web Cache Deception)
const forbiddenExtensions = /\.(jpg|jpeg|png|gif|css|js|ico|pdf|zip)$/i;
if (forbiddenExtensions.test(request.url)) {
reply.code(400).send({
error:
"Direct access to static extensions via application routes is forbidden",
});
return;
}
};
// 2. Регистрируем как ГЛОБАЛЬНЫЙ хук
fastify.addHook("preHandler", protectEveryRoute);
// 3. Теперь все маршруты защищены автоматически
fastify.get("/", async (request, reply) => {
return { message: "Main page is safe", hello: process.env.MESSAGE };
});
fastify.get("/profile", async (request, reply) => {
const apiKey = request.headers["x-api-key"];
if (apiKey !== process.env.API_KEY) {
return reply.code(401).send({
status: "error",
message: "Unathorized access denied",
});
}
return {
status: "success",
};
});
fastify.get("/orders", async (request, reply) => {
try {
const result = await ordersPool.query("SELECT * FROM tours");
return result.rows;
} catch (err) {
reply.code(500).send({ error: "Failed to fetch tours" });
}
});
/**
* Run the server!
*/
const start = async () => {
try {
const [toursClient, ordersClient] = await Promise.all([
toursPool.connect(),
ordersPool.connect(),
]);
console.log("Successfully connected to databases");
toursClient.release();
ordersClient.release();
await fastify.listen({ port: 3000, host: "0.0.0.0" });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();