-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
235 lines (183 loc) · 7.25 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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const gradient = require('gradient-string');
const WebSocket = require('ws');
const readline = require('readline');
const axios = require('axios');
const { customRateLimiter } = require('./rateLimiter');
const { createSession, authorize, encryptCommand, executeCommand, getServerStatus, getPlayerInfo, getEasternTimeString } = require('./sessionManager');
const { logInfo, logSuccess, logError, logRequest, logBackend } = require('./logger');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const config = require('./config.json');
const dispatchUrl = config.dispatchUrl;
const adminKey = config.adminKey;
const PORT = config.port;
const CURRENT_VERSION = '0.0.1';
app.use((req, res, next) => {
const start = Date.now();
const { method, originalUrl } = req;
res.on('finish', () => {
const duration = Date.now() - start;
logRequest(`Frontend: ${method} ${originalUrl} - ${res.statusCode} (${duration}ms)`);
});
next();
});
const logBackendRequest = async (req, res, next) => {
const originalUrl = req.originalUrl;
const method = req.method;
const backendUrl = `${dispatchUrl}${originalUrl}`;
const originalSend = res.send.bind(res);
res.send = (body) => {
logBackend(` ${method} ${backendUrl} - ${res.statusCode}`);
originalSend(body);
};
try {
await next();
} catch (error) {
logError(`[BACKEND ERROR] ${method} ${backendUrl} - ${error.message}`);
throw error;
}
};
app.use('/muip', logBackendRequest);
app.get('/get', (req, res) => {
res.json({ success: true });
});
app.post('/api/submit', customRateLimiter, async (req, res) => {
const { keyType, uid, command } = req.body;
if (!uid || !command) {
logError(`Missing UID or command: UID=${uid}, Command=${command}`);
return res.status(400).json({ error: 'UID and command are required.' });
}
try {
logInfo(`Processing submit request: UID=${uid}, Command=${command}`);
const sessionData = await createSession(keyType || 'PEM');
logInfo(`Session created: ${JSON.stringify(sessionData)}`);
const authData = await authorize(sessionData.sessionId, sessionData.rsaPublicKey);
logInfo(`Authorization successful: ${JSON.stringify(authData)}`);
const encryptedCommand = encryptCommand(sessionData.rsaPublicKey, command);
logInfo(`Command encrypted: ${encryptedCommand}`);
const execResult = await executeCommand(authData.sessionId, encryptedCommand, uid);
logInfo(`Command executed: ${JSON.stringify(execResult)}`);
if (execResult.error) {
logError(`Execution error: ${JSON.stringify(execResult.error)}`);
return res.status(500).json(execResult);
}
const decodedMessage = Buffer.from(execResult.data.message, 'base64').toString('utf8');
logSuccess((decodedMessage));
res.json({ ...execResult, data: { ...execResult.data, message: decodedMessage } });
} catch (error) {
logError(`API submit error: ${error.message}`);
res.status(500).json({ error: error.message });
}
});
app.post('/api/player', async (req, res) => {
const { uid } = req.body;
if (!uid) {
logError(`Missing UID: UID=${uid}`);
return res.status(400).json({ error: 'UID is required.' });
}
try {
logInfo(`Processing player request: UID=${uid}`);
const sessionData = await createSession('PEM');
logInfo(`Session created: ${JSON.stringify(sessionData)}`);
const authData = await authorize(sessionData.sessionId, sessionData.rsaPublicKey);
logInfo(`Authorization successful: ${JSON.stringify(authData)}`);
const playerInfo = await getPlayerInfo(authData.sessionId, uid);
logInfo(`Player info fetched: ${JSON.stringify(playerInfo)}`);
res.json(playerInfo);
} catch (error) {
logError(`API player error: ${error.message}`);
res.status(500).json({ error: error.message });
}
});
app.get('/api/status', async (req, res) => {
try {
logInfo('Processing status request');
const sessionData = await createSession('PEM');
logInfo(`Session created: ${JSON.stringify(sessionData)}`);
const authData = await authorize(sessionData.sessionId, sessionData.rsaPublicKey);
logInfo(`Authorization successful: ${JSON.stringify(authData)}`);
const serverStatus = await getServerStatus(authData.sessionId);
logInfo(`Server status fetched.`);
res.json(serverStatus);
} catch (error) {
logError(`API status error: ${error.message}`);
res.status(500).json({ error: error.message });
}
});
async function checkVersion() {
try {
const response = await axios.get('https://pan.moraxs.cn/getlatestversion');
const latestVersion = response.data.latestTransmitVersion;
if (latestVersion > CURRENT_VERSION) {
logError('当前版本已过时,请前往https://github.com/lctoolsweb/DanhengWebTools-transmit更新。');
process.exit(1);
} else {
logInfo('当前版本为最新版本,无需更新。');
}
} catch (error) {
logError(`检查版本更新失败: ${error.message}`);
}
}
checkVersion().then(() => {
const server = app.listen(PORT, '0.0.0.0', () => {
logInfo(`Server is running on http://0.0.0.0:${PORT}`);
});
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', (message) => {
console.log('Received WebSocket message:', message);
rl.write(message + '\n');
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
const originalConsoleLog = console.log;
console.log = (...args) => {
originalConsoleLog.apply(console, args);
const message = args.join(' ');
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
};
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', async (input) => {
const commandMatch = input.match(/command:'([^']+)'/);
const uidMatch = input.match(/uid:'([^']+)'/);
if (commandMatch && uidMatch) {
const command = commandMatch[1];
const uid = uidMatch[1];
try {
logInfo(`Processing command from stdin: Command=${command}, UID=${uid}`);
const sessionData = await createSession('PEM');
logInfo(`Session created: ${JSON.stringify(sessionData)}`);
const authData = await authorize(sessionData.sessionId, sessionData.rsaPublicKey);
logInfo(`Authorization successful: ${JSON.stringify(authData)}`);
const encryptedCommand = encryptCommand(sessionData.rsaPublicKey, command);
logInfo(`Command encrypted: ${encryptedCommand}`);
const execResult = await executeCommand(authData.sessionId, encryptedCommand, uid);
logInfo(`Command executed: ${JSON.stringify(execResult)}`);
if (execResult.error) {
console.error('Command execution error:', execResult.error);
} else {
const decodedMessage = Buffer.from(execResult.data.message, 'base64').toString('utf8');
logSuccess((decodedMessage));
}
} catch (error) {
console.error('Command execution error:', error);
}
} else {
logError('Invalid input. Use format: command:\'command_text\' uid:\'uid_text\'');
}
});
})