forked from kausaltech/kausal-watch-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.mjs
412 lines (375 loc) · 11.6 KB
/
server.mjs
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/* eslint-disable no-console */
import Koa from 'koa';
import Router from '@koa/router';
import logger from 'koa-logger';
import originalUrl from 'original-url';
//import cacheableResponse from 'cacheable-response';
//import parseCacheControl from '@tusbar/cache-control';
//import normalizeUrl from 'normalize-url';
import LRU from 'lru-cache';
import apollo from '@apollo/client';
import 'dotenv/config';
import next from 'next';
console.log('> 💡 Starting server');
const { ApolloClient, HttpLink, InMemoryCache, gql } = apollo;
import * as Sentry from '@sentry/nextjs';
import './sentry.server.config.js';
if (process.env.SENTRY_DSN) {
console.log(`> ⚙️ Sentry initialized at ${process.env.SENTRY_DSN}`);
}
const serverPort = process.env.PORT || 3000;
const isDevMode = process.env.NODE_ENV !== 'production';
const isProductionInstance = process.env.DEPLOYMENT_TYPE === 'production';
const AUTH_CONFIG_PATTERN = /^[^:]+:[^:]+:[^:]+$/;
const BASIC_AUTH_PATTERN = /^Basic [^ ]+$/;
const BASIC_AUTH_ENV_VARIABLE = 'BASIC_AUTH_FOR_HOSTNAMES';
function parseBasicAuthConfig(encodedValue) {
const result = {};
if (encodedValue == null || encodedValue.trim().length === 0) {
return result;
}
const hostnameConfigs = encodedValue.split(',');
for (const config of hostnameConfigs) {
if (!AUTH_CONFIG_PATTERN.test(config)) {
const error = `Invalid basic auth configuration. Check the syntax of ENV variable ${BASIC_AUTH_ENV_VARIABLE}.`;
Sentry.captureMessage(error);
console.error(error);
continue;
}
const [hostname, username, password] = config.split(':');
result[hostname] = [username, password];
}
return result;
}
const basicAuthForHostnames = parseBasicAuthConfig(
process.env[BASIC_AUTH_ENV_VARIABLE]
);
/*
let ssrCache;
if (false && (('ENABLE_CACHE' in process.env)
? (process.env.ENABLE_CACHE === '1') : process.env.NODE_ENV === 'production')) {
console.log('SSR cache initialized');
ssrCache = cacheableResponse({
ttl: 1000 * 60, // 1 min
get: async ({ req, res, pagePath, queryParams }) => {
if ('force' in req.query) delete req.query.force;
const data = await app.renderToHTML(req, res, pagePath, queryParams);
return { data, statusCode: res.statusCode };
},
send: ({ statusCode, data, res }) => {
res.statusCode = statusCode;
res.send(data);
},
getKey: ({ req }) => {
const url = originalUrl(req);
const baseKey = normalizeUrl(url.full, {
removeQueryParameters: ['force', /^utm_\w+/i]
});
return baseKey;
},
});
}
*/
function getCurrentURL(req) {
const obj = originalUrl(req);
let port;
if (obj.protocol === 'http:' && obj.port === 80) {
port = '';
} else if (obj.protocol === 'https:' && obj.port === 443) {
port = '';
} else {
port = `:${obj.port}`;
}
const path = obj.pathname.replace(/\/$/, ''); // strip trailing slash
const baseURL = `${obj.protocol}//${obj.hostname}${port}`;
const hostname = obj.hostname;
return { baseURL, path, hostname };
}
Error.stackTraceLimit = 30;
const GET_PLANS_BY_HOSTNAME = gql`
query GetPlansByHostname($hostname: String) {
plansForHostname(hostname: $hostname) {
domains {
hostname
basePath
status
statusMessage
}
primaryLanguage
... on Plan {
id
identifier
otherLanguages
}
}
}
`;
class WatchServer {
constructor() {
this.nextConfig = null;
this.app = next({ dev: isDevMode });
this.nextHandleRequest = this.app.getRequestHandler();
this.hostnameCache = new LRU({
max: 500,
ttl: 1 * 60 * 1000,
});
}
initApollo() {
const uri =
this.nextConfig.publicRuntimeConfig.aplansApiBaseURL + '/graphql/';
const httpLink = new HttpLink({
uri,
});
console.log(`> 🚀 GraphQL API at ${uri}`);
return new ApolloClient({
ssrMode: true,
link: httpLink,
cache: new InMemoryCache(),
});
}
parseRequestPath(ctx, plans) {
const { path } = ctx;
let matchedPlan = null,
basePath = null;
let parts = path.split('/').splice(1);
for (const plan of plans) {
let prefix;
if (!plan.domains.length) {
prefix = '';
} else {
const domain = plan.domains[0];
prefix = (domain.basePath || '/').split('/').splice(1)[0];
}
if (!prefix) {
// Root plan
matchedPlan = plan;
basePath = '';
continue;
}
if (prefix === parts[0]) {
matchedPlan = plan;
parts = parts.splice(1);
basePath = `/${prefix}`;
break;
}
}
if (!matchedPlan) {
throw new Error(`Did not find a matching plan for path ${path}`);
}
let locale = matchedPlan.primaryLanguage;
if (parts.length) {
// Check if we have a locale prefix
for (const lang of matchedPlan.otherLanguages) {
if (parts[0] === lang) {
locale = lang;
break;
}
}
}
return { plan: matchedPlan, locale, basePath };
}
async getAvailablePlans(ctx) {
const { hostname } = ctx;
let plansForHostname;
const obj = this.hostnameCache.get(hostname);
if (obj) return JSON.parse(obj);
try {
const { data } = await this.apolloClient.query({
query: GET_PLANS_BY_HOSTNAME,
variables: {
hostname: hostname,
},
fetchPolicy: 'no-cache',
});
plansForHostname = data.plansForHostname;
} catch (error) {
console.error(`Unable to get plan for hostname: ${hostname}`);
if (error.networkError) {
if (!error.networkError.result) {
console.error(error.networkError);
} else {
console.log(error.networkError.result?.errors);
}
} else {
console.error(error);
}
Sentry.withScope((scope) => {
scope.setTag('hostname', hostname);
Sentry.captureException(error);
});
ctx.throw(500, 'Internal server error (unable to get plan data)');
return null;
}
if (!plansForHostname.length) {
const msg = `Unknown hostname: ${hostname}`;
console.error(msg);
ctx.throw(404, msg);
}
this.hostnameCache.set(hostname, JSON.stringify(plansForHostname));
return plansForHostname;
}
setBasePath(basePath) {
const srv = this.nextServer;
srv.nextConfig.basePath = basePath;
srv.nextConfig.assetPrefix = basePath;
srv.nextConfig.images.path = basePath + '/_next/image';
srv.nextConfig.publicRuntimeConfig.basePath = basePath;
srv.renderOpts.basePath = basePath;
srv.renderOpts.canonicalBase = basePath;
srv.renderOpts.runtimeConfig.basePath = basePath;
srv.renderOpts.assetPrefix = basePath;
srv.router.basePath = basePath;
}
setLocale(locale, defaultLocale, locales) {
const srv = this.nextServer;
// Insert defaultLocale as the first element in locale list
const loc = locales.filter((lang) => lang !== defaultLocale);
loc.splice(0, 0, defaultLocale);
srv.nextConfig.i18n.defaultLocale = defaultLocale;
srv.nextConfig.i18n.locales = loc;
srv.nextConfig.publicRuntimeConfig.locale = locale;
srv.router.locales = loc;
srv.incrementalCache.locales = loc;
}
validateCredentials(ctx) {
const requiredCredentials = basicAuthForHostnames[ctx.hostname];
if (requiredCredentials == null) {
return true;
}
const { authorization } = ctx.req.headers;
if (authorization == null) {
return false;
}
if (!BASIC_AUTH_PATTERN.test(authorization)) {
return false;
}
const providedCredentials = Buffer.from(
authorization.split(' ')[1],
'base64'
)
.toString('utf-8')
.split(':');
for (const prop of ['length', 0, 1]) {
if (providedCredentials[prop] !== requiredCredentials[prop]) {
return false;
}
}
return true;
}
async handleRequest(ctx) {
ctx.req.currentURL = getCurrentURL(ctx.req);
if (ctx.req.currentURL.path === '/_health') {
ctx.res.statusCode = 200;
ctx.res.statusMessage = 'OK';
return;
}
if (!this.validateCredentials(ctx)) {
ctx.res.statusCode = 401;
ctx.res.statusMessage =
'Please provide a valid username and password combination';
ctx.set(
'WWW-Authenticate',
`Basic realm="Access to ${ctx.hostname}", charset="UTF-8"`
);
return;
}
const plans = await this.getAvailablePlans(ctx);
if (!plans) return;
const domain = plans[0].domains[0];
// The domain is not shown for automatically configured domains
const publicationStatus = domain?.status ?? 'PUBLISHED';
const published = publicationStatus === 'PUBLISHED';
if (published) {
const { plan, locale, basePath } = this.parseRequestPath(ctx, plans);
this.setBasePath(basePath);
this.setLocale(locale, plan.primaryLanguage, plan.otherLanguages);
ctx.req.planIdentifier = plan.identifier;
} else {
ctx.req.publicationStatus = publicationStatus;
ctx.req.publicationStatusMessage = domain.statusMessage;
const plan = plans[0];
const primaryLanguage = plan?.primaryLanguage;
if (primaryLanguage != null) {
this.setLocale(primaryLanguage, primaryLanguage, []);
}
}
await this.nextHandleRequest(ctx.req, ctx.res);
ctx.respond = false;
}
async init() {
await this.app.prepare();
this.nextConfig = (await import('next/config.js')).default.default();
const router = new Router();
const server = new Koa();
this.apolloClient = this.initApollo();
this.nextServer = await this.app.getServer();
router.get('/favicon.ico', async (ctx) => {
ctx.throw(404, 'File not found');
});
router.get('/robots.txt', async (ctx) => {
let ret = 'User-agent: *\nDisallow:';
if (isProductionInstance) {
ret += '\n';
} else {
ret += ' /\n';
}
ctx.body = ret;
ctx.status = 200;
});
router.all('(.*)', this.handleRequest.bind(this));
server.use(logger());
server.use(router.routes());
server.on('error', (err, ctx) => {
// Do not report HTTP 404s to Sentry
if (err.statusCode && err.statusCode === 404) return;
Sentry.withScope((scope) => {
scope.addEventProcessor((event) =>
Sentry.Handlers.parseRequest(event, ctx.request)
);
Sentry.captureException(err);
});
console.error(err);
});
server.listen(serverPort, () => {
console.log(`> ✅ Ready on http://localhost:${serverPort}`);
});
}
}
const pathsServer = new WatchServer();
pathsServer.init().then(() => {
console.log('> Init done');
});
/*
// Serve locales as JSON
server.get('/locales/:lang([a-z]{2})/:ns([0-9a-z_-]+).json', function (req, res) {
const { lang, ns } = req.params;
let contents;
try {
contents = fs.readFileSync(`./locales/${lang}/${ns}.yaml`, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
res.sendStatus(404)
return;
}
}
const data = YAML.parse(contents);
res.json(data);
});
server.get('*', (req, res) => {
const { path } = req;
req.currentURL = getCurrentURL(req);
if (ssrCache) {
if (!path.startsWith('/static') && !path.startsWith('/_next')) {
const queryParams = { ...req.query };
const cacheControl = req.get('Cache-Control');
const parsed = parseCacheControl.parse(cacheControl);
// If browser requests a fresh version, we force a cache miss.
if (parsed.noCache || parsed.maxAge === 0) {
req.query.force = true;
}
return ssrCache({ req, res, pagePath: req.path, queryParams });
}
}
return handle(req, res);
});
*/