-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
193 lines (162 loc) · 4.84 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
const fs = require("fs");
const path = require("path");
const { parseArgs } = require("node:util");
//Do Not Edit =>
//Launch Parameters
const launchParams = require("./src/params");
const { values, tokens } = parseArgs(launchParams);
// <= Do Not Edit
//Server Stuff.
const express = require("express");
const cookieParser = require("cookie-parser");
const https = require("https");
const { logArray, displayHelp, displayTips, cookieMonster } = require("./src/utils");
const httpServerConfig = {
port: 8090,
};
if (values.help) {
displayHelp();
} else if (values.tips) {
displayTips();
} else {
startServer(values.secure);
}
function checkCerts() {
if (!fs.existsSync("./certs/key.pem")) {
console.error(
`I can't find PEM file, if you haven't created a certificate please run these commands and move to ./certs folder.`
);
let commands = [
"openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365",
"openssl rsa -in keytmp.pem -out key.pem",
];
logArray(commands, "code");
return false;
} else {
return true;
}
}
let viewers = {};
function startServer(isSecure) {
const app = express();
let isOk = true;
if (isSecure) {
isOk = checkCerts();
}
if (isOk) {
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(setHeaders);
app.use(cookieParser());
app.use(cookieMonster);
app.get("/live/:connectionId", handleViewers); //Live Data
app.all("*", handleRequests); //Handle Requests
if (isSecure) {
const key = fs.readFileSync("./certs/key.pem");
const cert = fs.readFileSync("./certs/cert.pem");
const server = https.createServer({ key: key, cert: cert }, app);
httpServerConfig.port++;
//"192.168.4.128",
server.listen(httpServerConfig.port, "0.0.0.0", () => {
console.log("Running with HTTPS", httpServerConfig.port);
});
} else {
app.listen(httpServerConfig.port, "0.0.0.0", () => {
console.log("Running", httpServerConfig.port);
});
}
}
function handleRequests(req, res) {
const {
originalUrl,
url,
method,
statusCode,
statusMessage,
body,
query,
headers,
aborted,
} = req;
const visitorIdCookie = req.cookies["visitor-id"];
//Display requested URL
let date = new Date().toISOString();
let requestedData = {
originalUrl,
query,
body,
headers,
method,
aborted,
visitorIdCookie,
};
//
if (Object.keys(body).length || Object.keys(query).length || method == "HEAD") {
if (method == "HEAD") {
// console.log(req)
}
//Store in a file
storeLog(date.replaceAll(":", "-"), requestedData);
//Broadcast to watchers.
publishEvent(requestedData);
//Return a response to the requesting party/
res.json({ received: date });
//
} else {
res.sendFile(path.join(__dirname, "/src/www/index.html"));
}
}
function handleViewers(req, response) {
response.setHeader("Connection", "keep-alive");
response.setHeader("Content-Type", "text/event-stream");
response.setHeader("Cache-Control", "no-cache");
let connectionId = req.params.connectionId;
//Store Viewer Client references.
viewers[connectionId] = response;
const helloMessage = {
message: "Hello!",
time: Date.now(),
clientId: connectionId,
};
//Send an initial message.
setTimeout(() => sendEvent(response, JSON.stringify(helloMessage)), 500);
console.log(
`A new client subscribed, ${connectionId}. Total clients: (${
Object.keys(viewers).length
})`
);
//Cleanup.
req.on("close", function () {
delete viewers[connectionId];
console.log(
`Viewer ${connectionId} left. Total clients: (${Object.keys(viewers).length})`
);
});
}
}
function publishEvent(requestedData) {
let viewerReferences = Object.keys(viewers);
if (viewerReferences.length) {
viewerReferences.forEach((refId) => {
console.log("Publishing to:", refId);
sendEvent(viewers[refId], JSON.stringify(requestedData));
});
}
}
function sendEvent(ref, event) {
ref.write(`event: update\ndata: ${event}\n\n`);
}
function storeLog(filename, request) {
if (!fs.existsSync("./logs/")) {
fs.mkdirSync("logs");
}
fs.writeFile(`./logs/${filename}.json`, JSON.stringify(request, null, 2), () => {});
}
function setHeaders(req, res, next) {
res.setHeader("Powered", "Yep!");
res.setHeader("X-nananana", "Batman!");
res.setHeader("X-Powered-By", "RequestJar");
res.setHeader("X-hacker", "This is a tool for testing requests, please don't hack.");
res.setHeader("X-GitHub-Repo", "https://github.com/siniradam/requestjar");
next();
}