forked from RunOnFlux/flux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiServer.js
186 lines (163 loc) · 5.59 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
/* global userconfig */
global.userconfig = require('./config/userconfig');
process.env.NODE_CONFIG_DIR = `${__dirname}/ZelBack/config/`;
// Flux configuration
const config = require('config');
const fs = require('fs');
const http = require('node:http');
const https = require('https');
const path = require('path');
const util = require('util');
const nodecmd = require('node-cmd');
const app = require('./ZelBack/src/lib/server');
const log = require('./ZelBack/src/lib/log');
const socket = require('./ZelBack/src/lib/socket');
const serviceManager = require('./ZelBack/src/services/serviceManager');
const upnpService = require('./ZelBack/src/services/upnpService');
const hash = require('object-hash');
const { watch } = require('fs/promises');
const eWS = require('express-ws');
const cmdAsync = util.promisify(nodecmd.get);
const apiPort = userconfig.initial.apiport || config.server.apiport;
const apiPortHttps = +apiPort + 1;
let initialHash = hash(fs.readFileSync(path.join(__dirname, '/config/userconfig.js')));
/**
* The Cacheable. So we only instantiate it once (and for testing)
*/
let cacheable = null;
/**
* 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);
}
}
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}`);
}
}
/**
*
* @returns {Promise<String>}
*/
async function initiate() {
if (!config.server.allowedPorts.includes(+apiPort)) {
log.error(`Flux port ${apiPort} is not supported. Shutting down.`);
process.exit();
}
await createDnsCache();
await loadUpnpIfRequired();
setInterval(async () => {
configReload();
}, 2 * 1000);
const server = app.listen(apiPort, () => {
log.info(`Flux listening on port ${apiPort}!`);
serviceManager.startFluxFunctions();
});
socket.initIO(server);
try {
const certExists = fs.existsSync(path.join(__dirname, './certs/v1.key'));
if (!certExists) {
const nodedpath = path.join(__dirname, './helpers');
const exec = `cd ${nodedpath} && bash createSSLcert.sh`;
await cmdAsync(exec);
}
const key = fs.readFileSync(path.join(__dirname, './certs/v1.key'), 'utf8');
const cert = fs.readFileSync(path.join(__dirname, './certs/v1.crt'), 'utf8');
const credentials = { key, cert };
const httpsServer = https.createServer(credentials, app);
eWS(app, httpsServer);
const serverHttps = httpsServer.listen(apiPortHttps, () => {
log.info(`Flux https listening on port ${apiPortHttps}!`);
});
socket.initIO(serverHttps);
} catch (error) {
log.error(error);
}
return apiPort;
}
module.exports = {
createDnsCache,
getCacheable,
resetCacheable,
initiate,
};