-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
251 lines (243 loc) · 8.3 KB
/
server.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
"use strict";
const { createReadStream, readFile } = require("node:fs");
const { join, basename, normalize, resolve } = require("node:path");
const { getCache, setCache } = require("./middleware/redis-connector");
require("dotenv").config();
let defaultHeader = {
Server: "Aki Solutions",
"X-Powered-By": "A System by Aki Solutions",
"Cache-Control": "private, max-age=" + process.env.ASSETS_CACHE_TTL,
"Content-Type": "text/html; charset=utf-8",
};
module.exports = async function (fastify, opts) {
let path_name = process.env.PATH_IDENTIFIER;
await fastify.register(require("@fastify/middie"));
const path = require("node:path");
const serveStatic = require("serve-static");
let req_id;
let req_ip;
fastify.addHook("onRequest", async (req, done) => {
req_id =
(await req.headers["cf-ray"]) ||
req.headers["cdn-requestid"] ||
req.headers["X-Amz-Cf-Id"] ||
req.headers["akamai-x-get-request-id"] ||
req.headers["x-appengine-request-log-id"] ||
req.headers["requestId"] ||
req.headers["opc-request-id"] ||
req.id;
req_ip =
(await req.headers["Cf-Connecting-Ip"]) ||
req.headers["cf-connecting-ipv6"] ||
req.headers["x-real-ip"] ||
req.headers["x-forwarded-for"] ||
req.ip;
console.log(req_id);
});
fastify.use(
["/css/*name{.css}", "/js/*name{.js}", "/fonts/*name{.tff}"],
serveStatic(path.join(__dirname + "/assets")),
);
fastify
.get(`/${path_name}/css/:asset`, (req, rep) => {
const reg = /\.css$/.test(req.params.asset);
if (!reg) {
return false;
}
let asset = basename(req.params.asset);
let filePath = normalize(join(__dirname, "/assets/css/", asset));
let basePath = resolve(__dirname, "assets/css");
if (filePath.indexOf(basePath) !== 0) {
rep.status(403).send("Forbidden");
} else {
const stream = createReadStream(filePath, "utf8");
rep
.headers({
"Content-Type": "text/css",
"Cache-Control": "public, max-age=" + process.env.ASSETS_CACHE_TTL,
})
.send(stream || null);
}
})
.get(`/${path_name}/fonts/:asset`, (req, rep) => {
const reg = /\.ttf$/.test(req.params.asset);
if (!reg) {
return false;
}
const stream = createReadStream(
path.join(__dirname, "/assets/fonts/" + req.params.asset),
"utf8",
);
rep
.headers({
"Content-Type": "font/ttf",
"Cache-Control": "public, max-age=" + process.env.ASSETS_CACHE_TTL,
})
.send(stream || null);
})
.get(`/${path_name}/js/:asset`, (req, rep) => {
const reg = /\.js$/.test(req.params.asset);
if (!reg) {
return false;
}
const stream = createReadStream(
join(__dirname, "/assets/js/" + req.params.asset),
"utf8",
);
rep
.headers({
"Content-Type": "application/javascript",
"Cache-Control": "public, max-age=" + process.env.ASSETS_CACHE_TTL,
})
.send(stream || null);
})
.get(`/${path_name}/status/:code`, (req, rep) => {
let fn;
switch (req.params.code) {
case "403":
fn = "accessForbidden.html";
break;
case "404":
fn = "pageNotFound.html";
break;
case "500":
fn = "internalServerError.html";
break;
case "502":
fn = "badGateway.html";
break;
case "503":
fn = "serviceUnavailable.html";
break;
case "504":
fn = "gatewayTimeout.html";
break;
case "1000":
fn = "directAccessForbidden.html";
break;
case "1001":
fn = "noDatabaseConnection.html";
break;
case "1002":
fn = "sslError.html";
break;
default:
fn = "pageNotFound.html";
}
readFile(join(__dirname, `/html/${fn}`), "utf-8", (err, data) => {
if (err) {
console.error(err);
}
// Inject the CloudFlare Ray ID
let res = data.replace("__implement-ray-id__", req_id);
// Inject the JavaScript Sources at the bottom of the Body
res = res.replace(
"__implement_body_script__",
'<!--Implement Body Scripts--><script src="/' +
path_name +
'/js/bootstrap.bundle.min.js"></script>',
);
// Inject the Styling
res = res.replace(
"__implement_style__",
'<!--Implemented Styling--><link rel="stylesheet" href="/' +
path_name +
'/css/bootstrap.min.css">' +
' <link rel="stylesheet" href="/' +
path_name +
'/css/style.css">',
);
// Inject the Client IP
const result = res.replace("__implement-ip__", req_ip);
rep.headers(defaultHeader).send(result);
});
})
.get(`/${path_name}/xray`, async (req, rep) => {
// Resolve the IP Country
const options = {
method: "GET",
headers: { "User-Agent": process.env.XRAY_RESOLVER_UA },
};
let ttl = process.env.IP_DATA_CACHE_TTL; // 3 Month
let val = await getCache(req_ip);
const rayResponse = function (response) {
return `Host=${req.headers[":authority"] || req.headers["host"]}\nrequest=${req_id}\nip=${req_ip}\ncountry=${response["data"]["located_resources"][0]["locations"][0]["country"]} # IP resolution by RIPE DB & MaxMind`;
};
const rayResponseLocal = `Host=${req.headers["host"]}\nRequest ID: ${req_id}\nIP: ${req_ip}\nCountry: Local IP`;
// Check if IP is local to reduce traffic
const ipv4RegEx =
/^(10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3})$/;
const ipv6RegEx = /^fd[a-fA-F0-9:]{0,39}$/;
if (ipv4RegEx.test(req_ip) || ipv6RegEx.test(req_ip)) {
return rep
.headers("Content-Type", "text/plain")
.code(200)
.send(rayResponseLocal);
}
if (!val) {
return await fetch(
"https://stat.ripe.net/data/maxmind-geo-lite/data.json?resource=" +
req_ip,
options,
)
.then((response) => response.json())
.then((response) => {
if (response && response["data"]["located_resources"].length > 0) {
return setCache(req_ip, response, ttl)
.then((r) => {
if (r.error) {
fastify.log.error(r.error);
return rep
.headers("Content-Type", "text/plain")
.code(500)
.send("Internal Server Error");
}
return rep
.headers("Content-Type", "text/plain")
.code(200)
.send(rayResponse(response));
})
.catch((err) => {
fastify.log.error(err);
return rep
.headers("Content-Type", "text/plain")
.code(500)
.send("Internal Server Error");
});
} else {
return setCache(req_ip, response, ttl)
.then((r) => {
if (r.error) {
fastify.log.error(r.error);
}
return rep
.headers("Content-Type", "text/plain")
.code(200)
.send(rayResponseLocal);
})
.catch((err) => {
fastify.log.error(err);
return rep
.headers("Content-Type", "text/plain")
.code(500)
.send("Internal Server Error");
});
}
})
.catch((err) => fastify.log.error(err));
} else {
const response = await JSON.parse(val);
if (response && response["data"]["located_resources"].length > 0) {
return rep
.headers("Content-Type", "text/plain")
.code(200)
.send(rayResponse(response));
} else {
return rep
.headers("Content-Type", "text/plain")
.code(200)
.send(rayResponseLocal);
}
}
});
};