forked from hyperledger-labs/blockchain-explorer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
192 lines (174 loc) · 4.71 KB
/
main.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
/*
* SPDX-License-Identifier: Apache-2.0
*/
/**
*
* Created by shouhewu on 6/8/17.
*
*/
const express = require('express');
const helmet = require('helmet');
const path = require('path');
const http = require('http');
const https = require('https');
const fs = require('fs');
const url = require('url');
const WebSocket = require('ws');
const appconfig = require('./appconfig.json');
const helper = require('./app/common/helper');
const logger = helper.getLogger('main');
const Explorer = require('./app/Explorer');
const ExplorerError = require('./app/common/ExplorerError');
const sslEnabled = process.env.SSL_ENABLED || appconfig.sslEnabled;
const sslCertsPath = process.env.SSL_CERTS_PATH || appconfig.sslCertsPath;
const host = process.env.HOST || appconfig.host;
const port = process.env.PORT || appconfig.port;
const protocol = sslEnabled ? 'https' : 'http';
/**
*
*
* @class Broadcaster
* @extends {WebSocket.Server}
*/
class Broadcaster extends WebSocket.Server {
/**
* Creates an instance of Broadcaster.
* @param {*} server
* @memberof Broadcaster
*/
constructor(server) {
super({
server
});
this.on('connection', function connection(ws, req) {
const location = url.parse(req.url, true);
this.on('message', message => {
logger.info('received: %s, %s', location, message);
});
});
}
/**
*
*
* @param {*} data
* @memberof Broadcaster
*/
broadcast(data) {
this.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
logger.debug('Broadcast >> %j', data);
client.send(JSON.stringify(data));
}
});
}
}
let server;
let explorer;
async function startExplorer() {
explorer = new Explorer();
// Application headers
explorer.getApp().use(helmet());
explorer.getApp().use(helmet.xssFilter());
explorer.getApp().use(helmet.hidePoweredBy());
explorer.getApp().use(helmet.referrerPolicy());
explorer.getApp().use(helmet.noSniff());
/* eslint-disable */
explorer.getApp().use(helmet.frameguard({ action: 'SAMEORIGIN' }));
explorer.getApp().use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
objectSrc: ["'self'"],
frameSrc: ["'self'"],
fontSrc: ["'self'"],
imgSrc: ["'self' data: https:; "]
}
})
);
/* eslint-enable */
// Application headers
// = =========== web socket ==============//
const sslPath = path.join(__dirname, sslCertsPath);
logger.debug(sslEnabled, sslCertsPath, sslPath);
if (sslEnabled) {
const options = {
key: fs.readFileSync(sslPath + '/privatekey.pem').toString(),
cert: fs.readFileSync(sslPath + '/certificate.pem').toString()
};
server = https.createServer(options, explorer.getApp());
} else {
server = http.createServer(explorer.getApp());
}
const broadcaster = new Broadcaster(server);
await explorer.initialize(broadcaster);
explorer.getApp().use(express.static(path.join(__dirname, 'client/build')));
// ============= start server =======================
server.listen(port, () => {
logger.info(
`Please open web browser to access :${protocol}://${host}:${port}/`
);
logger.info(`pid is ${process.pid}`);
});
}
startExplorer();
/* eslint-disable */
let connections = [];
server.on('connection', connection => {
connections.push(connection);
connection.on(
'close',
() => (connections = connections.filter(curr => curr !== connection))
);
});
/* eslint-enable */
/*
* This function is called when you want the server to die gracefully
* i.e. wait for existing connections
*/
const shutDown = function(exitCode) {
logger.info('Received kill signal, shutting down gracefully');
server.close(() => {
explorer.close();
logger.info('Closed out connections');
process.exit(exitCode);
});
setTimeout(() => {
logger.error('Could not close connections in time, forcefully shutting down');
explorer.close();
process.exit(1);
}, 10000);
connections.forEach(curr => curr.end());
setTimeout(() => connections.forEach(curr => curr.destroy()), 5000);
};
process.on('unhandledRejection', up => {
logger.error(
'<<<<<<<<<<<<<<<<<<<<<<<<<< Explorer Error >>>>>>>>>>>>>>>>>>>>>'
);
if (up instanceof ExplorerError) {
logger.error('Error : ', up.message);
} else {
logger.error(up);
}
setTimeout(() => {
shutDown(1);
}, 2000);
});
process.on('uncaughtException', up => {
logger.error(
'<<<<<<<<<<<<<<<<<<<<<<<<<< Explorer Error >>>>>>>>>>>>>>>>>>>>>'
);
if (up instanceof ExplorerError) {
logger.error('Error : ', up.message);
} else {
logger.error(up);
}
setTimeout(() => {
shutDown(1);
}, 2000);
});
// Listen for TERM signal .e.g. kill
process.on('SIGTERM', shutDown);
// Listen for INT signal e.g. Ctrl-C
process.on('SIGINT', shutDown);