-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
169 lines (135 loc) · 6.35 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
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const readline = require('readline');
const fetch = require("node-fetch");
const color = require("colors")
const WebSocketClient = require("websocket").client;
// Custom console.log that sends data to the server
function customLog(message) {
console.log(message); // Send message to nodejs console
// Remove lines starting with ">...."
const formattedMessage = message.replace(/^>+\.\.\.\..*/gm, '');
// Remove ANSI escape sequences
const cleanMessage = formattedMessage.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '');
// Send formatted message to client
if (cleanMessage.includes('WARN')) {
io.emit('consoleLog', `<p class="text-amber-500 bg-amber-500/20 hover:bg-amber-500/30 font-bold">⚠️ ` + cleanMessage + `</p>`);
return
} else if (cleanMessage.includes('ERROR')) {
io.emit('consoleLog', `<p class="text-red-500 bg-red-500/20 hover:bg-red-500/30 font-bold">❌ ` + cleanMessage + `</p>`);
return
} else if (cleanMessage.includes('container@pterodactyl~')) {
io.emit('consoleLog', `<span>` + cleanMessage.replace('container@pterodactyl~', "<span class='text-sky-400 font-bold'>container@pterodactyl ~ </span>") + `</span>`);
return
} else if (cleanMessage.includes('Server marked as')) {
io.emit('consoleLog', `<p class="text-amber-500 font-bold">` + cleanMessage + `</p>`)
} else {
// Send message without special formatting
io.emit('consoleLog', `<p class="hover:bg-slate-700">` + cleanMessage + `</p>`);
return
}
}
function escapeHtml(unsafe) {
return String(unsafe).replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
res.sendFile(__dirname + '/index.html');
});
// Config
const config = {
"panelUrl": "https://***",
"pterodactylUserApiKey": "***",
"serverUUID": "***",
"port": "3000"
};
// ReadLine for the commands
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
// Tramsmit between nodejs console and express
let recieveCommand;
io.on('connection', (socket) => {
customLog('🟢 <span class="font-bold text-emerald-400">A user connected<span>');
socket.on('disconnect', () => {
console.log('🔴 User disconnected');
});
});
http.listen(config.port, () => {
console.log(`Express is running on http://localhost:` + config.port);
});
// Init
const prod = () => {
//Fetch Token and socket URL
fetch(`${config.panelUrl}/api/client/servers/${config.serverUUID}/websocket`, {
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${config.pterodactylUserApiKey}`
}
}).then(res => res.json()).then(body => {
const token = body.data.token;
const socket = body.data.socket;
const client = new WebSocketClient();
client.on("connectFailed", function(error) {
console.log("Connect Error: " + error.toString());
});
client.on("connect", async function(connection) {
// Send Token auth on connection
await connection.sendUTF(`{"event":"auth","args":["${token}"]}`)
// request logs after 1 second
setTimeout(() => { connection.sendUTF(`{"event":"send logs","args":[null]}`) }, 1000)
connection.on("error", function(error) {
console.log("Connection Error: " + error.toString());
});
// receiving messages
connection.on("message", function(message) {
// return != UTF-8
if (message.type != "utf8") return;
if (message.utf8Data.startsWith(`{"event":"auth success"}`)) {
customLog('<p class="font-bold">🔑 Auth success</p>');
return
}
// Return stats (memory usage, ...)
if (message.utf8Data.startsWith(`{"event":"stats"`)) return;
// Logs Install output
if (message.utf8Data.startsWith(`{"event":"install output"`)) return customLog(color.blue(`[Daemon]: ${JSON.parse(message.utf8Data).args.toString()}`))
// Logs console output
if (message.utf8Data.startsWith(`{"event":"console output"`)) return customLog(JSON.parse(message.utf8Data).args.toString())
// On token expiring, close connection and restart program
if (message.utf8Data.startsWith(`{"event":"token expiring"`)) { connection.close(); prod(); return;}
// Logs status message (starting, start, stoping, stop, ...)
if (message.utf8Data.startsWith(`{"event":"status"`)) return customLog(color.yellow(`Server marked as ${JSON.parse(message.utf8Data).args.toString()}`))
customLog(color.red(message))
});
// On command on console
rl.on('line', function(line){
// If command "close", close connection and exit program but NOT close the server
if (line === 'close') { connection.close(); process.exit(0); }
// if command "power", change the power according to the argument (power kill = kill the server, power start = start the server, ...)
if (line.startsWith('power')) return connection.sendUTF(`{"event":"set state","args":["${line.split(/ +/)[1]}"]}`)
connection.sendUTF(`{"event":"send command","args":["${line}"]}`)
})
io.on('connection', (socket) => {
socket.on('command', (command) => {
const escapedCommand = escapeHtml(command.trim())
recieveCommand = escapedCommand
customLog('<span class="text-sky-400 font-bold"">~ </span>' + recieveCommand);
connection.sendUTF(`{"event":"send command","args":["${recieveCommand}"]}`)
});
});
});
//Connect to socket URL
client.connect(`${socket}`);
})
}
// First start
prod()