-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
267 lines (257 loc) · 9.7 KB
/
index.js
File metadata and controls
267 lines (257 loc) · 9.7 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
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
const fs = require('fs-extra')
const fetch = require('node-fetch');
const postUrl = require("./package.json").homepage;
const extract = require('extract-zip')
const child_process = require('child_process');
let pidusage = require('pidusage');
var running = false;
var child
// things to do:
//
// put npm i commands in try catch stuff
var log = console.log
var error = console.error
console.log = function () {
log.apply(null, arguments);
var text = "";
Array.prototype.slice.call(arguments).forEach(arg => {
if (typeof arg === "object") arg = JSON.stringify(arg);
text += arg.toString() + " "
})
fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newLog: text,
time: Date.now()
})
}).catch(err => err)
}
console.error = function () {
error.apply(null, arguments);
var text = "";
Array.prototype.slice.call(arguments).forEach(arg => {
if (typeof arg === "object") arg = JSON.stringify(arg);
text += arg.toString() + " "
})
fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newLog: text,
time: Date.now()
})
}).catch(err => err)
}
async function main() {
var colors = require('colors/safe');
var ip = await fetch("https://jsonip.com/")
ip = await ip.json();
ip = ip.ip;
console.log("Starting server on " + ip);
let environmentalVariables = await fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ip: ip,
query: ["environmentalVariables", "runCmd"]
})
})
environmentalVariables = await environmentalVariables.json();
// installing dependencies
var stop = false;
try {
child_process.execSync("cd code; rm -rf node_modules")
child_process.execSync("cd code; npm install --force")
} catch (err) {
console.error(err.toString())
stop = true
}
// running client code
if ((environmentalVariables.query.runCmd || "npm run start").includes("../") || stop === true) {
fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newErr: "Run command includes ('../'). This is not allowed!",
time: Date.now()
})
}).catch(err => err)
} else {
if (!environmentalVariables.query.environmentalVariables) {
environmentalVariables.query.environmentalVariables = {}
}
environmentalVariables.query.environmentalVariables.PORT = 8888
try {
let jsonfile = fs.readFileSync("./code/package.json").toString()
jsonfile = JSON.parse(jsonfile);
var nonCustom = ["node", "cd", "ls", "npx", "npm"]
Object.entries(jsonfile.scripts).forEach(([key, value]) => {
if (value !== undefined) {
let allCmds = value.split(";");
for (let i = 0; i < allCmds.length; i++) {
var add = true;
for (let p = 0; p < nonCustom.length; p++) {
if (allCmds[i].trimStart().startsWith(nonCustom[p])) {
add = false;
}
}
if (add === true) {
allCmds[i] = "npx --no-install " + allCmds[i].trimStart();
}
}
allCmds = allCmds.join("; ");
jsonfile.scripts[key] = allCmds;
}
})
fs.writeFileSync("./code/package.json", JSON.stringify(jsonfile))
} catch (err) {
//console.log(err)
}
child = child_process.exec(`cd code; ${environmentalVariables.query.runCmd || "npm run start"}`, {
env: environmentalVariables.query.environmentalVariables
});
running = true;
child.stdout.on('data', (data) => {
console.log(data);
});
child.stderr.on('data', (data) => {
console.log(data);
});
child.on('close', async (code) => {
running = false;
fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
stopCode: code
})
}).catch(err => err)
console.log(colors.bold.red(`Child process exited with code ${code}`));
});
}
postData();
async function postData() {
while (true) {
try {
let currentResources = {
cpu: 0,
memory: 0
}
if (running === true && child.pid) {
try {
currentResources = await pidusage(child.pid);
} catch (err) {
currentResources = { cpu: 0, memory: 0 }
}
}
let dataRes = await fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
online: running,
resources: currentResources
})
}).catch(err => console.log(err))
let json = await dataRes.json();
log(json)
if (json.query && json.query.runCmd) {
fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
docAction: "executed-runcmd",
time: Date.now()
})
})
try {
runChild = child_process.exec("cd code; " + json.query.runCmd, {
env: environmentalVariables.query.environmentalVariables
});
runChild.stdout.on('data', (data) => {
console.log(data);
});
runChild.stderr.on('data', (data) => {
console.log(data);
});
} catch (err) {
console.log(err.toString())
}
}
if (json.status === "new-code") {
fetch(postUrl, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
docAction: "recieved-new-code",
time: Date.now()
})
}).catch(err => err)
console.log("Remote has changes! Fetching changes...")
console.log(`Downloading file at: ${postUrl.slice(0, -129)}/cdn/servers/--------------------------------------.zip`)
try {
fs.unlinkSync("./temp.zip")
} catch (err) { }
await downloadFile(`${postUrl.slice(0, -129)}/cdn/servers/${postUrl.slice(-109)}.zip`, __dirname + "/temp.zip")
console.log("Download complete")
if (running === true) {
child.kill("SIGKILL");
}
console.log("Deleting old code...")
fs.rmdirSync("./code", { recursive: true });
console.log("Extracting files...")
await extract("./temp.zip", { dir: __dirname + "/temp-extracted" });
let directory = fs.readdirSync("./temp-extracted/");
fs.moveSync("./temp-extracted/" + directory[0], "./code", function (err) {
if (err) {
console.error(err);
} else {
console.log("Moved folders successfully!");
}
});
if (running === true) {
child.kill("SIGKILL");
}
return restartProcess();
} else {
await sleep(60000)
}
} catch (err) {
console.log("We had trouble posting to the cloudiverse servers! Please check your internet connection. Processes will continue running. \n Full error string: " + err.toString())
}
}
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function restartProcess() {
if (running === true) {
child.kill("SIGKILL");
}
try {
child_process.execSync("lsof -i :8888 -sTCP:LISTEN |awk 'NR > 1 {print $2}' |xargs kill -15")
} catch (err) {
}
console.log("Restarting process due to code changes...")
await sleep(1000)
main();
}
const downloadFile = (async (url, path) => {
const res = await fetch(url);
const fileStream = fs.createWriteStream(path);
await new Promise((resolve, reject) => {
res.body.pipe(fileStream);
res.body.on("error", reject);
fileStream.on("finish", resolve);
});
});
process()
async function process() {
initialize()
main();
}
async function initialize() {
console.log("Initializing...")
fetch(postUrl.replace("/api/v1/dump-status/", "/api/v1/user/deploy/") + "?source=server")
}