forked from cncjs/cncjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
273 lines (229 loc) · 10 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
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
import dns from 'dns';
import fs from 'fs';
import os from 'os';
import path from 'path';
import url from 'url';
import bcrypt from 'bcrypt-nodejs';
import chalk from 'chalk';
import ensureArray from 'ensure-array';
import expandTilde from 'expand-tilde';
import express from 'express';
import httpProxy from 'http-proxy';
import escapeRegExp from 'lodash/escapeRegExp';
import isEqual from 'lodash/isEqual';
import set from 'lodash/set';
import size from 'lodash/size';
import trimEnd from 'lodash/trimEnd';
import uniqWith from 'lodash/uniqWith';
import webappengine from 'webappengine';
import settings from './config/settings';
import app from './app';
import cncengine from './services/cncengine';
import monitor from './services/monitor';
import config from './services/configstore';
import { ensureString } from './lib/ensure-type';
import logger, { setLevel } from './lib/logger';
import urljoin from './lib/urljoin';
const log = logger('init');
const createServer = (options, callback) => {
options = { ...options };
{ // verbosity
const verbosity = options.verbosity;
// https://github.com/winstonjs/winston#logging-levels
if (verbosity === 1) {
set(settings, 'verbosity', verbosity);
setLevel('verbose');
}
if (verbosity === 2) {
set(settings, 'verbosity', verbosity);
setLevel('debug');
}
if (verbosity === 3) {
set(settings, 'verbosity', verbosity);
setLevel('silly');
}
}
const rcfile = path.resolve(options.configFile || settings.rcfile);
// configstore service
log.info(`Loading configuration from ${chalk.yellow(JSON.stringify(rcfile))}`);
config.load(rcfile);
// rcfile
settings.rcfile = rcfile;
{ // secret
if (!config.get('secret')) {
// generate a secret key
const secret = bcrypt.genSaltSync(); // TODO: use a strong secret
config.set('secret', secret);
}
settings.secret = config.get('secret', settings.secret);
}
{ // watchDirectory
const watchDirectory = options.watchDirectory || config.get('watchDirectory');
if (watchDirectory) {
if (fs.existsSync(watchDirectory)) {
log.info(`Watching ${chalk.yellow(JSON.stringify(watchDirectory))} for file changes`);
// monitor service
monitor.start({ watchDirectory: watchDirectory });
} else {
log.error(`The directory ${chalk.yellow(JSON.stringify(watchDirectory))} does not exist.`);
}
}
}
{ // accessTokenLifetime
const accessTokenLifetime = options.accessTokenLifetime || config.get('accessTokenLifetime');
if (accessTokenLifetime) {
set(settings, 'accessTokenLifetime', accessTokenLifetime);
}
}
{ // allowRemoteAccess
const allowRemoteAccess = options.allowRemoteAccess || config.get('allowRemoteAccess', false);
if (allowRemoteAccess) {
if (size(config.get('users')) === 0) {
log.warn('You\'ve enabled remote access to the server. It\'s recommended to create an user account to protect against malicious attacks.');
}
set(settings, 'allowRemoteAccess', allowRemoteAccess);
}
}
const { port = 0, host, backlog } = options;
const mountPoints = uniqWith([
...ensureArray(options.mountPoints),
...ensureArray(config.get('mountPoints'))
], isEqual).filter(mount => {
if (!mount || !mount.route || mount.route === '/') {
log.error(`Must specify a valid route path ${JSON.stringify(mount.route)}.`);
return false;
}
return true;
});
const routes = [];
mountPoints.forEach(mount => {
if (ensureString(mount.target).match(/^(http|https):\/\//i)) {
log.info(`Starting a proxy server to proxy all requests starting with ${chalk.yellow(mount.route)} to ${chalk.yellow(mount.target)}`);
routes.push({
type: 'server',
route: mount.route,
server: (options) => {
// route
// > '/custom-widget/'
// routeWithoutTrailingSlash
// > '/custom-widget'
// target
// > 'https://cncjs.github.io/cncjs-widget-boilerplate/'
// targetPathname
// > '/cncjs-widget-boilerplate/'
// proxyPathPattern
// > RegExp('^/cncjs-widget-boilerplate/custom-widget')
const { route = '/' } = { ...options };
const routeWithoutTrailingSlash = trimEnd(route, '/');
const target = mount.target;
const targetPathname = url.parse(target).pathname;
const proxyPathPattern = new RegExp('^' + escapeRegExp(urljoin(targetPathname, routeWithoutTrailingSlash)), 'i');
log.debug(`> route=${chalk.yellow(route)}`);
log.debug(`> routeWithoutTrailingSlash=${chalk.yellow(routeWithoutTrailingSlash)}`);
log.debug(`> target=${chalk.yellow(target)}`);
log.debug(`> targetPathname=${chalk.yellow(targetPathname)}`);
log.debug(`> proxyPathPattern=RegExp(${chalk.yellow(proxyPathPattern)})`);
const proxy = httpProxy.createProxyServer({
// Change the origin of the host header to the target URL
changeOrigin: true,
// Do not verify the SSL certificate for self-signed certs
//secure: false,
target: target
});
proxy.on('proxyReq', (proxyReq, req, res, options) => {
const originalPath = proxyReq.path || '';
proxyReq.path = originalPath
.replace(proxyPathPattern, targetPathname)
.replace('//', '/');
log.debug(`proxy.on('proxyReq'): modifiedPath=${chalk.yellow(proxyReq.path)}, originalPath=${chalk.yellow(originalPath)}`);
});
proxy.on('proxyRes', (proxyRes, req, res) => {
log.debug(`proxy.on('proxyRes'): headers=${JSON.stringify(proxyRes.headers, true, 2)}`);
});
const app = express();
// Matched routes:
// /widget/
// /widget/v1/
app.all(urljoin(routeWithoutTrailingSlash, '*'), (req, res) => {
const url = req.url;
log.debug(`proxy.web(): url=${chalk.yellow(url)}`);
proxy.web(req, res);
});
// Matched routes:
// /widget
app.all(routeWithoutTrailingSlash, (req, res, next) => {
const url = req.url;
// Redirect URL with a trailing slash
if (url.indexOf(routeWithoutTrailingSlash) === 0 &&
url.indexOf(routeWithoutTrailingSlash + '/') < 0) {
const redirectUrl = routeWithoutTrailingSlash + '/' + url.slice(routeWithoutTrailingSlash.length);
log.debug(`redirect: url=${chalk.yellow(url)}, redirectUrl=${chalk.yellow(redirectUrl)}`);
res.redirect(301, redirectUrl);
return;
}
next();
});
return app;
}
});
} else {
// expandTilde('~') => '/Users/<userhome>'
const directory = expandTilde(ensureString(mount.target)).trim();
log.info(`Mounting a directory ${chalk.yellow(JSON.stringify(directory))} to serve requests starting with ${chalk.yellow(mount.route)}`);
if (!directory) {
log.error(`The directory path ${chalk.yellow(JSON.stringify(directory))} must not be empty.`);
return;
}
if (!path.isAbsolute(directory)) {
log.error(`The directory path ${chalk.yellow(JSON.stringify(directory))} must be absolute.`);
return;
}
if (!fs.existsSync(directory)) {
log.error(`The directory path ${chalk.yellow(JSON.stringify(directory))} does not exist.`);
return;
}
routes.push({
type: 'static',
route: mount.route,
directory: directory
});
}
});
routes.push({
type: 'server',
route: '/',
server: () => app()
});
webappengine({ port, host, backlog, routes })
.on('ready', (server) => {
// cncengine service
cncengine.start(server, options.controller || config.get('controller', ''));
const address = server.address().address;
const port = server.address().port;
callback && callback(null, {
address,
port,
mountPoints,
});
if (address !== '0.0.0.0') {
log.info('Starting the server at ' + chalk.yellow(`http:https://${address}:${port}`));
return;
}
dns.lookup(os.hostname(), { family: 4, all: true }, (err, addresses) => {
if (err) {
log.error('Can\'t resolve host name:', err);
return;
}
addresses.forEach(({ address, family }) => {
log.info('Starting the server at ' + chalk.yellow(`http:https://${address}:${port}`));
});
});
})
.on('error', (err) => {
callback && callback(err);
log.error(err);
});
};
export {
createServer
};