-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.js
More file actions
256 lines (209 loc) · 7.71 KB
/
Copy pathapp.js
File metadata and controls
256 lines (209 loc) · 7.71 KB
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
'use strict';
const path = require('path');
const express = require('express');
const { program } = require('commander');
const morgan = require('morgan');
const compression = require('compression');
const { Server } = require('socket.io');
const routes = require('./api/routes');
const cache = require('./cache');
const adamantApi = require('./api/lib/adamant/requests/api');
const statisticsHandler = require('./api/lib/adamant/handlers/statistics');
const createAdamantApiReadinessMiddleware = require('./api/lib/adamant/middleware/readiness');
const packageJson = require('./package.json');
const utils = require('./utils');
const logger = require('./utils/log');
const { createHttpLogFormatter } = require('./utils/httpLogging');
const { isApiPath, isSupportedApiPath } = require('./api/lib/adamant/helpers/http');
const { createApiRateLimiter } = require('./modules/apiRateLimiter');
const { guardApiSurface } = require('./modules/apiSurface');
const { normalizePort } = require('./modules/configValidation');
const { buildContentSecurityPolicy } = require('./modules/httpSecurity');
const { createOsmTileProxy, createOsmTileRateLimiter } = require('./modules/osmTileProxy');
const config = require('./modules/configReader');
const app = express();
program
.version(packageJson.version)
.option('-p, --port <port>', 'listening port number')
.option('-h, --host <ip>', 'listening host name or IP address')
.parse(process.argv);
const cliOptions = program.opts();
let listeningPort = config.port;
if (cliOptions.port !== undefined) {
try {
listeningPort = normalizePort(cliOptions.port);
} catch (error) {
program.error(error.message);
}
}
app.set('host', cliOptions.host ?? config.host);
app.set('port', listeningPort);
app.set('trust proxy', config.trustedProxies);
app.disable('x-powered-by');
const client = require('./redis')(config);
app.exchange = new utils.exchange(config);
app.set('version', packageJson.version);
app.set('strict routing', true);
app.set('case sensitive routing', true);
app.set('exchange enabled', config.exchangeRates.enabled);
// Security headers allow self-hosted application resources. Network Monitor
// map tiles are served from the same origin via /osm-tiles/ (see below).
app.use((req, res, next) => {
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-XSS-Protection', '0');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader(
'Permissions-Policy',
'camera=(), geolocation=(), microphone=(), payment=(), usb=()',
);
res.setHeader('Content-Security-Policy', buildContentSecurityPolicy(req.get('host')));
return next();
});
// Proxy OSM raster tiles so Tor Browser on .onion (no Referer) and other
// referrer-stripping clients still receive map imagery under OSM tile policy.
// Registered before morgan intentionally: tile fan-out would drown access logs.
// Per-IP limiting and an in-process LRU cache reduce abuse and OSM upstream load.
app.get(
'/osm-tiles/:z/:x/:y.png',
createOsmTileRateLimiter(),
createOsmTileProxy({
userAgent: `ADAMANT-Explorer/${packageJson.version} (+${packageJson.homepage})`,
}),
);
app.use(
express.static(path.join(__dirname, 'public'), {
dotfiles: 'deny',
}),
);
// Share the Redis client with routes through the request object
app.locals.redis = client;
app.use((req, res, next) => {
req.redis = client;
return next();
});
// Keep routine access logs at debug while surfacing client and server failures.
// Query strings are omitted because they may contain user-supplied identifiers.
app.use(morgan(createHttpLogFormatter(logger)));
app.use(compression());
app.use(createApiRateLimiter());
app.use(guardApiSurface);
// Cache lookup: serve a cached API response when one exists
app.use(async (req, res, next) => {
if (!cache.isApiCacheMethod(req.method) || !isSupportedApiPath(req.path)) {
return next();
}
const latestBlock = statisticsHandler.getCachedBlocks()[0];
req.cacheKey = cache.getCacheKey(req.originalUrl, req.path, latestBlock);
if (!req.cacheKey) {
return next();
}
try {
const json = await req.redis.get(req.cacheKey);
if (json) {
logger.debug(`API cache: Hit for ${req.method} ${req.path}`);
return res.json(JSON.parse(json));
}
logger.debug(`API cache: Miss for ${req.method} ${req.path}`);
} catch (error) {
logger.warn(
`API cache: Redis read failed for ${req.method} ${req.path}; continuing without cache: ${error}`,
);
}
return next();
});
app.use(createAdamantApiReadinessMiddleware(adamantApi));
logger.debug('Explorer startup: Registering API routes');
routes(app);
logger.debug('Explorer startup: API routes registered');
// Cache store: routes that support caching call next() with the response in req.json
app.use((req, res, next) => {
if (
!cache.isApiCacheMethod(req.method) ||
!isSupportedApiPath(req.path) ||
req.json === undefined
) {
return next();
}
if (req.cacheKey) {
const ttl = cache.cacheTTLOverride[req.path] ?? config.redis.cacheTTL;
req.redis
.set(req.cacheKey, JSON.stringify(req.json), { expiration: { type: 'EX', value: ttl } })
.then(() => {
logger.debug(`API cache: Stored ${req.method} ${req.path}; ttl=${ttl}s`);
})
.catch((error) => {
logger.warn(
`API cache: Redis write failed for ${req.method} ${req.path}; ttl=${ttl}s: ${error}`,
);
});
}
return res.json(req.json);
});
app.use((req, res, next) => {
if (!isApiPath(req.path)) {
return next();
}
return res.status(404).json({
success: false,
error: 'API endpoint not found',
});
});
// Serve the single-page application for any non-API path
app.use((req, res, next) => {
if (!['GET', 'HEAD'].includes(req.method)) {
return next();
}
return res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.use((req, res) => {
return res.status(404).json({
success: false,
error: 'Not found',
});
});
// Keep internal error details in operational logs and return a stable response.
app.use((error, req, res, next) => {
if (res.headersSent) {
return next(error);
}
logger.error(`HTTP: Unhandled ${req.method} ${req.path}: ${error}`);
return res.status(503).json({
success: false,
error: 'Service temporarily unavailable',
});
});
// Initial rates load runs in the background; the periodic update
// is scheduled by the Exchange constructor
app.exchange.loadRates();
const server = app.listen(app.get('port'), app.get('host'), () => {
logger.info(
`Explorer startup: v${app.get('version')} listening on ${app.get('host')}:${app.get('port')}; ` +
`nodes=${config.nodes_adm.length}; exchangeRates=${config.exchangeRates.enabled ? 'enabled' : 'disabled'}; ` +
`logLevel=${config.log_level}`,
);
const io = new Server(server);
require('./sockets')(app, io);
statisticsHandler.startBlockStatisticsCache(client).catch((error) => {
logger.warn(
`Explorer startup: Block statistics cache initialization failed; background recovery remains active: ${error}`,
);
});
statisticsHandler.startPeerStatisticsCache(client).catch((error) => {
logger.warn(
`Explorer startup: Peer statistics cache initialization failed; background retry remains active: ${error}`,
);
});
});
// Bound slow or incomplete HTTP requests even when Explorer is exposed
// without the recommended reverse proxy. Upgraded Socket.IO connections are
// not governed by these HTTP request timers.
server.headersTimeout = 15_000;
server.requestTimeout = 30_000;
server.keepAliveTimeout = 5_000;
server.once('error', (error) => {
logger.error(
`Explorer startup: Failed to listen on ${app.get('host')}:${app.get('port')}: ${error}`,
);
process.exit(1);
});