-
Notifications
You must be signed in to change notification settings - Fork 309
/
apiServer.js
285 lines (229 loc) · 8.17 KB
/
apiServer.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
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
global.userconfig = require('./config/userconfig');
if (typeof AbortController === 'undefined') {
// polyfill for nodeJS 14.18.1 - without having to use experimental features
// eslint-disable-next-line global-require
const abortControler = require('node-abort-controller');
globalThis.AbortController = abortControler.AbortController;
}
process.env.NODE_CONFIG_DIR = `${__dirname}/ZelBack/config/`;
const fs = require('node:fs');
const http = require('node:http');
const https = require('node:https');
const path = require('node:path');
const { watch } = require('node:fs/promises');
const axios = require('axios').default;
const config = require('config');
const hash = require('object-hash');
const fluxServer = require('./ZelBack/src/lib/fluxServer');
const log = require('./ZelBack/src/lib/log');
const serviceManager = require('./ZelBack/src/services/serviceManager');
const serviceHelper = require('./ZelBack/src/services/serviceHelper');
const upnpService = require('./ZelBack/src/services/upnpService');
const requestHistoryStore = require('./ZelBack/src/services/utils/requestHistory');
const apiPort = userconfig.initial.apiport || config.server.apiport;
const apiPortHttps = +apiPort + 1;
let initialHash = hash(fs.readFileSync(path.join(__dirname, '/config/userconfig.js')));
let requestHistory = null;
let axiosDefaultsSet = false;
/**
* The Cacheable. So we only instantiate it once (and for testing)
*/
let cacheable = null;
function getrequestHistory() {
return requestHistory;
}
/**
* Gets the cacheable CacheableLookup() for testing
*/
function getCacheable() {
return cacheable;
}
/**
* Gets the cacheable CacheableLookup() for testing
*/
function resetCacheable() {
cacheable = null;
}
/**
* Adds extra servers to DNS, if they are not being used already. This is just
* within the NodeJS process, not systemwide.
*
* Sets these globally for both http and https (axios) It will use the OS servers
* by default, and if they fail, move on to our added servers, if a server fails, requests
* go to an active server immediately, for a period.
* @param {Map?} userCache An optional cache, we use this as a reference for testing
* @returns {Promise<void>}
*/
async function createDnsCache(userCache) {
try {
if (cacheable) return;
const cache = userCache || new Map();
// we have to dynamic import here as cacheable-lookup only supports ESM.
const { default: CacheableLookup } = await import('cacheable-lookup');
cacheable = new CacheableLookup({ maxTtl: 360, cache });
cacheable.install(http.globalAgent);
cacheable.install(https.globalAgent);
const cloudflareDns = '1.1.1.1';
const googleDns = '8.8.8.8';
const quad9Dns = '9.9.9.9';
const backupServers = [cloudflareDns, googleDns, quad9Dns];
const existingServers = cacheable.servers;
// it dedupes any servers
cacheable.servers = [...existingServers, ...backupServers];
} catch (error) {
log.error(error);
}
}
function setAxiosDefaults(socketIoServers) {
if (axiosDefaultsSet) return;
axiosDefaultsSet = true;
log.info('setting axios defaults');
axios.defaults.timeout = 20_000;
if (!globalThis.userconfig.initial.debug) return;
log.info('User defined debug set, setting up socket.io for debug.');
requestHistory = new requestHistoryStore.RequestHistory({ maxAge: 60_000 * 60 });
const rooms = [];
const requestRoom = 'outboundHttp';
socketIoServers.forEach((server) => {
const debugRoom = server.getRoom(requestRoom, { namespace: 'debug' });
rooms.push(debugRoom);
const debugAdapter = server.getAdapter('debug');
debugAdapter.on('join-room', (room, id) => {
if (room !== requestRoom) return;
const socket = server.getSocketById('debug', id);
socket.emit('addHistory', requestHistory.allHistory);
});
});
requestHistory.on('requestAdded', (request) => {
rooms.forEach((room) => room.emit('addRequest', request));
});
requestHistory.on('requestRemoved', (request) => {
rooms.forEach((room) => room.emit('removeRequest', request));
});
axios.interceptors.request.use(
(conf) => {
const {
baseURL, url, method, timeout,
} = conf;
const fullUrl = baseURL ? `${baseURL}${url}` : url;
const requestData = {
url: fullUrl, verb: method.toUpperCase(), timeout, timestamp: Date.now(),
};
requestHistory.storeRequest(requestData);
return conf;
},
(error) => Promise.reject(error),
);
}
async function loadUpnpIfRequired() {
try {
let verifyUpnp = false;
let setupUpnp = false;
if (userconfig.initial.apiport) {
verifyUpnp = await upnpService.verifyUPNPsupport(apiPort);
if (verifyUpnp) {
setupUpnp = await upnpService.setupUPNP(apiPort);
}
}
if ((userconfig.initial.apiport && userconfig.initial.apiport !== config.server.apiport) || userconfig.initial.routerIP) {
if (verifyUpnp !== true) {
log.error(`Flux port ${userconfig.initial.apiport} specified but UPnP failed to verify support. Shutting down.`);
process.exit();
}
if (setupUpnp !== true) {
log.error(`Flux port ${userconfig.initial.apiport} specified but UPnP failed to map to api or home port. Shutting down.`);
process.exit();
}
}
} catch (error) {
log.error(error);
}
}
async function configReload() {
try {
const watcher = watch(path.join(__dirname, '/config'));
// eslint-disable-next-line
for await (const event of watcher) {
if (event.eventType === 'change' && event.filename === 'userconfig.js') {
const hashCurrent = hash(fs.readFileSync(path.join(__dirname, '/config/userconfig.js')));
if (hashCurrent === initialHash) {
return;
}
initialHash = hashCurrent;
log.info(`Config file changed, reloading ${event.filename}...`);
delete require.cache[require.resolve('./config/userconfig')];
// eslint-disable-next-line
userconfig = require('./config/userconfig');
if (userconfig?.initial?.apiport) {
await loadUpnpIfRequired();
}
}
}
} catch (error) {
log.error(`Error watching files: ${error}`);
}
}
/**
* Main entrypoint
*
* @returns {Promise<String>}
*/
async function initiate() {
if (!config.server.allowedPorts.includes(+apiPort)) {
log.error(`Flux port ${apiPort} is not supported. Shutting down.`);
process.exit();
}
process.on('uncaughtException', (err) => {
const dnsErrors = ['ENOTFOUND', 'EAI_AGAIN', 'ESERVFAIL'];
// the express server port in use is uncatchable for some reason
// remove this in future
if (err.code === 'EADDRINUSE') {
log.error('Flux api server port in use, shutting down.');
// if shutting down clean, nodemon won't restart
process.exit();
} else if (dnsErrors.includes(err.code) && err.hostname) {
log.error('Uncaught DNS Lookup Error!!, swallowing.');
log.error(err);
return;
}
log.error(err);
process.exit(1);
});
await createDnsCache();
await loadUpnpIfRequired();
setInterval(async () => {
configReload();
}, 2 * 1000);
const appRoot = process.cwd();
// ToDo: move this to async
const certExists = fs.existsSync(path.join(appRoot, 'certs/v1.key'));
if (!certExists) {
const cwd = path.join(appRoot, 'helpers');
const scriptPath = path.join(cwd, 'createSSLcert.sh');
await serviceHelper.runCommand(scriptPath, { cwd });
}
// ToDo: move these to async
const key = fs.readFileSync(path.join(appRoot, 'certs/v1.key'), 'utf8');
const cert = fs.readFileSync(path.join(appRoot, 'certs/v1.crt'), 'utf8');
const httpServer = new fluxServer.FluxServer();
const httpsServer = new fluxServer.FluxServer({
mode: 'https', key, cert, expressApp: httpServer.app,
});
await httpServer.listen(apiPort);
log.info(`Flux listening on port ${apiPort}!`);
await httpsServer.listen(apiPortHttps);
log.info(`Flux https listening on port ${apiPortHttps}!`);
setAxiosDefaults([httpServer.socketIo, httpsServer.socketIo]);
serviceManager.startFluxFunctions();
return apiPort;
}
if (require.main === module) {
initiate();
}
module.exports = {
createDnsCache,
getCacheable,
getrequestHistory,
initiate,
resetCacheable,
};