Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
208 lines (182 loc) · 7.65 KB
/
Copy pathserver.js
File metadata and controls
208 lines (182 loc) · 7.65 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
// load express server
const express = require('express');
const app = express();
// load helpers
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const helmet = require('helmet')
const bodyParser = require('body-parser');
const rateLimit = require('express-rate-limit')
const { analyserAuthenticated } = require('./lib/auth');
const { originGate } = require('./lib/originGate');
const {
createTranslator,
formatDate,
formatDateTime,
localeForRequest,
isPublicLocalizedPath,
stripLocalePrefix,
localUrl,
languageUrl,
} = require('./lib/i18n');
require('dotenv').config();
// improve express security
app.use(helmet({
contentSecurityPolicy: {
directives: {
...helmet.contentSecurityPolicy.getDefaultDirectives(),
"img-src": ["'self'", "*.mzstatic.com"],
},
},
crossOriginEmbedderPolicy: false
}))
app.disable('x-powered-by')
const os = require('os');
const analyserPaths = new Set([
'/queue',
'/ping',
'/uploadanalysis',
'/reportanalysisfailure'
]);
// Express routing is case-insensitive and lenient about trailing slashes,
// so normalise the same way before matching against the analyser path set —
// otherwise `/UploadAnalysis` or `/queue/` reach the handlers while skipping
// this gate.
const isAnalyserPath = (req) =>
analyserPaths.has(req.path.toLowerCase().replace(/\/+$/, ''));
function sendError(req, res, status, message) {
if (isAnalyserPath(req) || !req.accepts('html'))
return res.status(status).send(message);
const translate = res.locals.t || createTranslator('en');
res.set('X-Robots-Tag', 'noindex');
return res.status(status).render('error', {
title: translate(status === 404 ? 'Page not found' : status === 429 ? 'Too many requests' : 'Request unavailable'),
status,
message: translate(message),
});
}
// /search and /request/:appId are GETs only so that a Cloudflare challenge can
// replay them; each one still reaches the App Store. The method therefore does
// not separate cheap from expensive here, and they are budgeted as the form
// submissions they are.
const appStorePaths = (path) =>
path === '/search' || path === '/request' || path.startsWith('/request/');
const isAppStorePath = (req) =>
appStorePaths(req.path.toLowerCase().replace(/\/+$/, ''));
// Reads of the published pages are served from the cached site data and
// reverse index, so they cost far less than an App Store call. They also
// arrive in very different volumes: sitemap.xml points crawlers at every app,
// tracker and company URL, and a crawler works through those from a narrow
// range of addresses. Sharing one budget between the two means either
// throttling a normal crawl or loosening the limit that actually matters, so
// they are budgeted separately.
const isBrowseRequest = (req) =>
(req.method === 'GET' || req.method === 'HEAD')
&& !isAnalyserPath(req)
&& !isAppStorePath(req);
// Resolve the display language before rate-limit path classification and route
// mounting. Only the explicitly public page routes accept the /da prefix;
// analyser, API, health, sitemap and asset paths keep their existing routing.
app.use((req, res, next) => {
const requestPath = new URL(req.url || '/', 'http://localhost').pathname;
if (isPublicLocalizedPath(requestPath, req.method)) {
req.locale = 'da';
req.url = stripLocalePrefix(req.url);
} else {
req.locale = 'en';
}
const selection = localeForRequest(req);
const locale = selection.locale;
res.locals.locale = locale;
res.locals.t = createTranslator(locale);
res.locals.siteName = res.locals.t('TrackerControl for iOS');
res.locals.formatDate = (value, options) => formatDate(value, locale, options);
res.locals.formatDateTime = (value) => formatDateTime(value, locale);
res.locals.languageUrl = (target) => languageUrl(req.originalUrl, target);
res.locals.localUrl = (path, target = locale) => localUrl(path, target, req.path);
next();
});
// Optional hardening for the case where the origin becomes reachable without
// Cloudflare: the WAF challenge rules protecting /search and the request page
// only apply to traffic that goes through the edge. Inert unless
// CLOUDFLARE_ORIGIN_SECRET is set.
app.use(originGate())
if(os.hostname().indexOf("local") <= -1) { // only on remote host
const windowMs = 5 * 60 * 1000; // 5 minutes
const skipAnalyser = (req) => isAnalyserPath(req) && analyserAuthenticated(req);
// Everything that is not a cacheable page view: the App Store entry points,
// the analysis request POST, and analyser endpoints called without
// credentials.
app.use(rateLimit({
windowMs,
max: Number(process.env.RATE_LIMIT_FORM_MAX) || 20,
standardHeaders: false,
legacyHeaders: false,
skip: (req) => skipAnalyser(req) || isBrowseRequest(req),
handler: (req, res) => sendError(req, res, 429, 'Too many requests, please try again later.'),
}))
app.use(rateLimit({
windowMs,
max: Number(process.env.RATE_LIMIT_BROWSE_MAX) || 300,
standardHeaders: false,
legacyHeaders: false,
skip: (req) => skipAnalyser(req) || !isBrowseRequest(req),
handler: (req, res) => sendError(req, res, 429, 'Too many requests, please try again later.'),
}))
}
const analyserBodyLimit = process.env.BODY_LIMIT || '25mb';
const publicFormBodyLimit = process.env.PUBLIC_FORM_BODY_LIMIT || '100kb';
app.use((req, res, next) => {
if (isAnalyserPath(req) && !analyserAuthenticated(req))
return res.status(400).send('Please provide correct password.');
next();
});
// use pug as templates engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Search is a GET, so the only public form body is the analysis request. Large
// analyser payload parsers are mounted on their authenticated endpoints so
// arbitrary public and nonexistent routes cannot consume the analyser body
// allowance.
app.post('/analysis/:appId', bodyParser.urlencoded({
extended: true,
limit: publicFormBodyLimit
}));
app.post('/uploadAnalysis', bodyParser.json({ limit: analyserBodyLimit }));
app.post('/reportAnalysisFailure', express.text({ limit: analyserBodyLimit }));
// serve static files
// New asset contents get new URLs, including through caches that ignore queries.
const assetHash = crypto.createHash('sha256');
for (const file of ['css/styles.css', 'js/filter.js', 'js/site.js', 'images/trackercontrol.png'])
assetHash.update(fs.readFileSync(path.join(__dirname, 'public', file)));
app.locals.assetPrefix = `/assets/${assetHash.digest('hex').slice(0, 16)}`;
app.use(app.locals.assetPrefix, express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));
app.use('/static', express.static('static'))
// serve favicon
app.use('/favicon.ico', express.static('favicon.ico'));
// load routes from /routes/index.js
const routes = require('./routes/index');
app.use('/', routes);
app.use((req, res, next) => {
if (!['GET', 'HEAD'].includes(req.method) || !req.accepts('html')) return next();
return sendError(req, res, 404, 'This page could not be found. Search for an app or browse the tracker directory.');
});
// Express 4 requires rejected async handlers to call next(err). Route handlers
// use asyncHandler for that bridge and all errors terminate here.
app.use((err, req, res, next) => {
if (res.headersSent)
return next(err);
const errorStatus = err.status || err.statusCode;
const status = Number.isInteger(errorStatus)
&& errorStatus >= 400
&& errorStatus <= 599
? errorStatus
: 500;
if (status >= 500)
console.error('Request failed:', err.stack || err.message);
const message = err.expose ? err.message : 'Internal server error.';
return sendError(req, res, status, message);
});
module.exports = app; // make accessible to /start.js