This repository has been archived by the owner on Jun 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
executable file
·477 lines (411 loc) · 14.9 KB
/
index.ts
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
const arch = require('os').arch()
if (arch != 'x64' && arch != "ia32" && arch != "x86_64") {
console.warn('WARN: DeblokManager seems to be only compatible with x86 and x64 architectures. Expect errors!')
}
import { Elysia, error,t } from "elysia";
import { basicAuth } from '@eelkevdbos/elysia-basic-auth';
import Docker from "dockerode";
import Bun from "bun";
import fs from 'fs';
const conffile = Bun.file("config/config.json");
const config = JSON.parse(await conffile.text());
let sessionKeepalive:any[] = []
let managedContainers:any[] = []
process.env["BASIC_AUTH_CREDENTIALS"] = config.authentication["username"]+":"+config.authentication["password"]
async function ping(url: string): Promise<string> {
try {
const response = await fetch(url);
if (response.status >= 200 && response.status < 400) {
return 'up';
} else {
return 'down';
}
} catch (error) {
return 'down';
}
}
if (process.argv.includes('--ignore-linux-check') && require("os").platform() != "linux") {
console.warn('WARN: Incompatibility detected!')
console.warn(
" - DeblokManager can only run on Linux devices.",
);
console.warn(" This warning is being ignored due to --ignore-linux-check.")
} else
if (require("os").platform() != "linux") {
console.error("FATAL: Incompatibility detected!");
console.error(
" - DeblokManager can only run on Linux devices.",
);
console.error(
" Pass --ignore-linux-check to ignore this warning",
);
process.exit(2);
}
if (process.argv[2] != "--socket") {
if (await ping('http://127.0.0.1:2375/_ping') == "down") {
console.warn('Extra configuration is needed:');
console.error(' - The Docker Daemon (dockerd) needs to be running via TCP (:2375).');
process.exit(2);
}
}
let docker:any= undefined;
if (process.argv[2] == "--socket") {
docker = new Docker();
} else {
docker = new Docker({protocol:'http',host: '127.0.0.1', port: 2375, version: 'v1.44' });
}
let netaddr = '[::1]';
netaddr = require('os').hostname();
const server = new Elysia();
server.use(
basicAuth({
credentials: [config.authentication],
})
);
server.get("/", () => {
return "DeblokManager is alive!";
});
server.get("/containers/list", async () => {
let dl = await new Promise((resolve, reject) => {
let containerList: string[] = [];
docker.listContainers((err: any, containers: Docker.ContainerInfo[]) => {
if (err) {
console.error(err);
reject(err);
} else {
containers.forEach((container: Docker.ContainerInfo) => {
containerList.push(`${container.Id}, ${container.Names[0]}, ${container.Status}`);
});
resolve(containerList);
}
});
});
return dl;
});
async function createContainer(containerOptions:any) {
try {
containerOptions.HostConfig = { AutoRemove: true, ...containerOptions.HostConfig };
// containerOptions.Cmd = containerOptions.Cmd || ['sleep','7d']; // sleep for a week, which is gonna be the max time a nd container can run for.
const container = await docker.createContainer(containerOptions);
await container.start();
return `${container.id}`;
} catch (err) {
console.error(err);
throw err;
}
}
function readableToBytes(ramString: string): number {
const match = ramString.match(/^(\d+)([GMB])$/);
if (match && match.length === 3) {
const value = parseInt(match[1]);
const unit = match[2].toUpperCase();
switch (unit) {
case "G":
return value * 1024 * 1024 * 1024;
case "M":
return value * 1024 * 1024;
case "B":
return value;
default:
throw new Error("Invalid RAM unit. Use G, M, or B.");
}
} else {
throw new Error("Invalid RAM format. Use G, M, or B.");
}
}
server.get("/policy/", async () => {
return config.policy;
});
server.post("/containers/create", async ({ body, set }) => {
let b:any=body // the body variable is actually a string, this is here to fix a ts error
var bjson:any={"name":"","image":"","resources":{"ram":"","cores":""},"ports":""} // boilerplate to not piss off TypeScript.
try {
bjson = JSON.parse(b);
} catch (e) {
console.error(e);
console.error(body)
set.status = 400;
return `ERR: ${e}`;
}
if (!process.argv.includes('--no-whitelist')) {
const imagewl = fs.readFileSync('config/list.txt', 'utf-8').split('\n');
if (!imagewl.includes(bjson.image)) {
set.status = 400;
return `ERR: This image (${bjson.image}) is not whitelisted.`;
}
}
// Check if required fields are present
if (!bjson.name || bjson.name == "" || !bjson.image || bjson.image == "") {
set.status = 400;
return "ERR: Name and Image fields are required.";
}
if (readableToBytes(bjson.resources.ram) > readableToBytes(config.policy.resources.maxram)) {
set.status = 400;
return `ERR: RAM exceeds the maximum allowed value of ${config.policy.resources.maxram}.`;
}
if (parseFloat(bjson.resources.cores) > parseFloat(config.policy.resources.maxcores)) {
set.status = 400;
return `ERR: vCores exceed the maximum allowed value of ${config.policy.resources.maxcores}.`;
}
interface PortBinding {
HostPort: string;
}
interface PortBindings {
[key: string]: PortBinding[];
}
const containerOptions = {
name: bjson.name + "_" + String(crypto.randomUUID()).replaceAll("-",""),
Image: bjson.image,
HostConfig: {
Memory: readableToBytes(bjson.resources.ram), // Set memory limit
NanoCPUs: Number(bjson.resources.cores * 1e9), // Set CPU limit
PortBindings: {} as PortBindings, // Set port bindings
}
};
// Update the type of PortBindings when setting up port bindings
if (bjson.ports && bjson.ports !== "") {
const portPairs = bjson.ports.split(",").map((portPair: any) => portPair.trim());
portPairs.forEach((portPair: string) => {
const [external, internal] = portPair.split(":").map((port: string) => port.trim());
if (!containerOptions.HostConfig.PortBindings[`${internal}/tcp`]) {
containerOptions.HostConfig.PortBindings[`${internal}/tcp`] = [];
}
containerOptions.HostConfig.PortBindings[`${internal}/tcp`].push({ HostPort: external });
});
}
// Set up port bindings
if (bjson.ports && bjson.ports !== "") {
const portPairs = bjson.ports.split(",").map((portPair: any) => portPair.trim());
portPairs.forEach((portPair: string) => {
const [external, internal] = portPair.split(":").map((port: string) => port.trim());
containerOptions.HostConfig.PortBindings[`${internal}/tcp`] = [{ HostPort: external }];
});
}
try {
const result:any = await createContainer(containerOptions);
sessionKeepalive.push([result,Date.now() + config.policy.keepalive.initial * 1000])
managedContainers.push(result)
return result;
} catch (err) {
set.status = 500;
console.error(err)
return err;
}
});
server.post("/containers/kill", async ({ body, set }) => {
const b:any=body // the body variable is actually a string, this is here to fix a ts error
var bjson:any={id:""} // boilerplate to not piss off TypeScript.
try {
bjson = JSON.parse(b);
} catch (e) {
console.error(e);
set.status = 400;
return "ERR: Bad JSON";
}
if (!managedContainers.includes(bjson.id)) {
set.status = 400;
return "ERR: DeblokManager doesn't manage this container.";
}
try {
const container = docker.getContainer(bjson.id);
await container.kill();
// managedContainers.splice(managedContainers.indexOf(bjson.id),1)
removeKeepalive(bjson.id)
return `${bjson.id}`;
} catch (err) {
set.status = 500;
console.error(err);
return err;
}
});
server.post("/containers/delete", async ({ body, set }) => {
const b:any=body // the body variable is actually a string, this is here to fix a ts error
var bjson:any={id:""} // boilerplate to not piss off TypeScript.
try {
bjson = JSON.parse(b);
} catch (e) {
console.error(e);
set.status = 400;
return "ERR: Bad JSON";
}
if (!managedContainers.includes(bjson.id)) {
set.status = 400;
return "ERR: DeblokManager doesn't manage this container.";
}
try {
const container = docker.getContainer(bjson.id);
await container.remove();
managedContainers.splice(managedContainers.indexOf(bjson.id),1)
removeKeepalive(bjson.id)
return `${bjson.id}`;
} catch (err) {
set.status = 500;
console.error(err);
return err;
}
});
server.post("/containers/pause", async ({ body, set }) => {
const b:any=body // the body variable is actually a string, this is here to fix a ts error
var bjson:any={id:""} // boilerplate to not piss off TypeScript.
try {
bjson = JSON.parse(b);
} catch (e) {
console.error(e);
set.status = 400;
return "ERR: Bad JSON";
}
if (!managedContainers.includes(bjson.id)) {
set.status = 400;
return "ERR: DeblokManager doesn't manage this container.";
}
try {
const container = docker.getContainer(bjson.id);
await container.pause();
addToKeepalive(bjson.id,config.policy.keepalive.increment * 1000)
return `${bjson.id}`;
} catch (err) {
set.status = 500;
console.error(err);
return err;
}
});
server.post("/containers/unpause", async ({ body, set }) => {
const b:any=body // the body variable is actually a string, this is here to fix a ts error
var bjson:any={id:""} // boilerplate to not piss off TypeScript.
try {
bjson = JSON.parse(b);
} catch (e) {
console.error(e);
set.status = 400;
return "ERR: Bad JSON";
}
if (!managedContainers.includes(bjson.id)) {
set.status = 400;
return "ERR: DeblokManager doesn't manage this container.";
}
try {
const container = docker.getContainer(bjson.id);
await container.unpause();
addToKeepalive(bjson.id,config.policy.keepalive.initial * 1000) // 1 minute
return `${bjson.id}`;
} catch (err) {
set.status = 500;
console.error(err);
return err;
}
});
server.post("/containers/restart", async ({ body, set }) => {
const b:any=body // the body variable is actually a string, this is here to fix a ts error
var bjson:any={id:""} // boilerplate to not piss off TypeScript.
try {
bjson = JSON.parse(b);
} catch (e) {
console.error(e);
set.status = 400;
return "ERR: Bad JSON";
}
if (!managedContainers.includes(bjson.id)) {
set.status = 400;
return "ERR: DeblokManager doesn't manage this container.";
}
try {
const container = docker.getContainer(bjson.id);
await container.restart();
addToKeepalive(bjson.id,config.policy.keepalive.initial * 1000) // 1 minute
return `${bjson.id}`;
} catch (err) {
set.status = 500;
console.error(err);
return err;
}
});
server.post("/containers/keepalive", async ({ body, set }) => {
const b:any=body // the body variable is actually a string, this is here to fix a ts error
var bjson:any={id:""} // boilerplate to not piss off TypeScript.
try {
bjson = JSON.parse(b);
} catch (e) {
console.error(e);
set.status = 400;
return "ERR: Bad JSON";
}
if (!managedContainers.includes(bjson.id)) {
set.status = 400;
return "ERR: DeblokManager doesn't manage this container.";
}
let containerExists = false
for (let i = 0;i < sessionKeepalive.length;i++) {
if (sessionKeepalive[i][0] == bjson.id) {
containerExists = true; break;
}
}
if (containerExists) {
addToKeepalive(bjson.id,config.policy.keepalive.initial * 1000) // 5 mins
return "Updated."
} else {
set.status = 400
return "ERR: Keepalive does not exist."
}
})
import portscanner from 'portscanner';
async function getPorts(): Promise<number[]> {
const range: number[] = config["port-range"].split('-').map(Number);
const startPort: number = range[0];
const endPort: number = range[1];
const availablePorts: number[] = [];
for (let port = startPort; port <= endPort; port++) {
const isPortOpen = await portscanner.checkPortStatus(port);
if (isPortOpen === 'closed') {
availablePorts.push(port);
}
}
return availablePorts;
}
server.get("/ports/list", async ({body, set}) => {
try {
return getPorts()
} catch (e) {
set.status = 500;
console.error(e)
return ["There was an error retrieving the availiable ports. Are you on x86_64?",e]
}
});
console.log(`Listening on port ${config.webserver.port} or`);
console.log(` │ 0.0.0.0:${config.webserver.port}`);
console.log(` │ 127.0.0.1:${config.webserver.port}`);
console.log(` │ ${netaddr}:${config.webserver.port}`);
console.log(` └─────────────────────────>`);
if (process.argv.includes('--no-whitelist')) {
console.log()
console.warn('WARN: ####################################')
console.warn('WARN: # YOU HAVE DISABLED THE WHITELIST! #')
console.warn('WARN: ####################################')
console.log()
console.warn('WARN: Disabling the whitelist allows ANYONE to create/delete/kill ANY Docker container!')
console.warn('WARN: This has MAJOR security implications, CTRL+C NOW if this was unintentional.')
}
function removeKeepalive(id:string) {
for (let i = 0;i < sessionKeepalive.length;i++) {
if (sessionKeepalive[i][0] == id) {
sessionKeepalive.splice(i,1);break;
}
}
}
function addToKeepalive(id:string,msAdded:number) {
for (let i = 0;i < sessionKeepalive.length;i++) {
if (sessionKeepalive[i][0] == id) {
sessionKeepalive[i][1] = sessionKeepalive[i][1] + msAdded;break;
}
}
}
setInterval(async ()=>{
for (let i = 0;i < sessionKeepalive.length;i++) {
if (Date.now() > sessionKeepalive[i][1]) {
const container = docker.getContainer(sessionKeepalive[i][0]);
removeKeepalive(sessionKeepalive[i][0])
await container.kill();
// await container.remove();
}
}
},2000)
server.listen(config.webserver);