-
Notifications
You must be signed in to change notification settings - Fork 529
/
index.ts
217 lines (185 loc) · 7.57 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
const modulename = 'WebServer';
import crypto from 'node:crypto';
import path from 'node:path';
import HttpClass from 'node:http';
import Koa from 'koa';
import KoaBodyParser from 'koa-bodyparser';
//@ts-ignore
import KoaServe from 'koa-static';
import KoaCors from '@koa/cors';
import { Server as SocketIO } from 'socket.io';
import WebSocket from './webSocket';
import { customAlphabet } from 'nanoid';
import dict51 from 'nanoid-dictionary/nolookalikes';
import { convars, txEnv } from '@core/globalData';
import router from './router';
import consoleFactory from '@extras/console';
import TxAdmin from '@core/txAdmin';
import topLevelMw from './middlewares/topLevelMw';
import ctxVarsMw from './middlewares/ctxVarsMw';
import ctxUtilsMw from './middlewares/ctxUtilsMw';
import { SessionMemoryStorage, koaSessMw, socketioSessMw } from './middlewares/sessionMws';
import checkRateLimit from './middlewares/globalRateLimiterMw';
const console = consoleFactory(modulename);
const nanoid = customAlphabet(dict51, 32);
//Types
export type WebServerConfigType = {
disableNuiSourceCheck: boolean;
limiterMinutes: number;
limiterAttempts: number;
}
export default class WebServer {
readonly #txAdmin: TxAdmin;
public isListening = false;
private sessionCookieName: string;
public luaComToken: string;
//setupKoa
private app: Koa;
public sessionStore: SessionMemoryStorage;
private koaCallback: (req: any, res: any) => Promise<void>;
//setupWebSocket
private io: SocketIO;
private webSocket: WebSocket;
//setupServerCallbacks
private httpServer?: HttpClass.Server;
constructor(txAdmin: TxAdmin, public config: WebServerConfigType) {
this.#txAdmin = txAdmin;
//Generate cookie key & luaComToken
const pathHash = crypto.createHash('shake256', { outputLength: 6 })
.update(txAdmin.info.serverProfilePath)
.digest('hex');
this.sessionCookieName = `tx:${txAdmin.info.serverProfile}:${pathHash}`;
this.luaComToken = nanoid();
// ===================
// Setting up Koa
// ===================
this.app = new Koa();
this.app.keys = ['txAdmin' + nanoid()];
// Some people might want to enable it, but we are not guaranteeing XFF security
// due to the many possible ways you can connect to koa.
// this.app.proxy = true;
//Setting up app
this.app.on('error', (error, ctx) => {
if (!(
error.code?.startsWith('HPE_')
|| error.code?.startsWith('ECONN')
|| error.code === 'EPIPE'
|| error.code === 'ECANCELED'
)) {
console.error(`Probably harmless error on ${ctx.path}`);
console.error('Please be kind and send a screenshot of this error to the txAdmin developer.');
console.dir(error);
}
});
//Disable CORS on dev mode
if (convars.isDevMode) {
this.app.use(KoaCors());
}
//Setting up timeout/error/no-output/413
this.app.use(topLevelMw);
//Setting up additional middlewares:
const jsonLimit = '16MB';
const panelPublicPath = convars.isDevMode
? path.join(process.env.TXADMIN_DEV_SRC_PATH as string, 'panel/public')
: path.join(txEnv.txAdminResourcePath, 'panel');
this.app.use(KoaServe(path.join(txEnv.txAdminResourcePath, 'web/public'), { index: false, defer: false }));
this.app.use(KoaServe(panelPublicPath, { index: false, defer: false }));
this.app.use(KoaBodyParser({ jsonLimit }));
//Custom stuff
this.sessionStore = new SessionMemoryStorage();
this.app.use(koaSessMw(this.sessionCookieName, this.sessionStore));
this.app.use(ctxVarsMw(txAdmin));
this.app.use(ctxUtilsMw);
//Setting up routes
const txRouter = router(this.config);
this.app.use(txRouter.routes());
this.app.use(txRouter.allowedMethods());
this.app.use(async (ctx) => {
if (typeof ctx._matchedRoute === 'undefined') {
if (ctx.path.startsWith('/legacy')) {
ctx.status = 404;
console.verbose.warn(`Request 404 error: ${ctx.path}`);
return ctx.utils.render('standalone/404');
}else if (ctx.path.endsWith('.map')){
ctx.status = 404;
return ctx.send('Not found');
} else {
return ctx.utils.serveReactIndex();
}
}
});
this.koaCallback = this.app.callback();
// ===================
// Setting up SocketIO
// ===================
this.io = new SocketIO(HttpClass.createServer(), { serveClient: false });
this.io.use(socketioSessMw(this.sessionCookieName, this.sessionStore));
this.webSocket = new WebSocket(this.#txAdmin, this.io);
//@ts-ignore
this.io.on('connection', this.webSocket.handleConnection.bind(this.webSocket));
// ===================
// Setting up Callbacks
// ===================
this.setupServerCallbacks();
}
/**
* Handler for all HTTP requests
* Note: i gave up on typing these
*/
httpCallbackHandler(req: any, res: any) {
//Calls the appropriate callback
try {
// console.debug(`HTTP ${req.method} ${req.url}`);
if (!checkRateLimit(req?.socket?.remoteAddress)) return;
if (req.url.startsWith('/socket.io')) {
(this.io.engine as any).handleRequest(req, res);
} else {
this.koaCallback(req, res);
}
} catch (error) { }
}
/**
* Setup the HTTP server callbacks
*/
setupServerCallbacks() {
//Just in case i want to re-execute this function
this.isListening = false;
//HTTP Server
try {
const listenErrorHandler = (error: any) => {
if (error.code !== 'EADDRINUSE') return;
console.error(`Failed to start HTTP server, port ${error.port} is already in use.`);
console.error('Maybe you already have another txAdmin running in this port.');
console.error('If you want to run multiple txAdmin instances, check the documentation for the port convar.');
console.error('You can also try restarting the host machine.');
process.exit(5800);
};
//@ts-ignore
this.httpServer = HttpClass.createServer(this.httpCallbackHandler.bind(this));
this.httpServer.on('error', listenErrorHandler);
let iface: string;
if (convars.forceInterface) {
console.warn(`Starting with interface ${convars.forceInterface}.`);
console.warn('If the HTTP server doesn\'t start, this is probably the reason.');
iface = convars.forceInterface;
} else {
iface = '0.0.0.0';
}
this.httpServer.listen(convars.txAdminPort, iface, async () => {
console.ok(`Listening on ${iface}.`);
this.isListening = true;
});
} catch (error) {
console.error('Failed to start HTTP server with error:');
console.dir(error);
process.exit(5801);
}
}
/**
* Resetting lua comms token - called by fxRunner on spawnServer()
*/
resetToken() {
this.luaComToken = nanoid();
console.verbose.log('Resetting luaComToken.');
}
};