This repository has been archived by the owner on Jan 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
148 lines (130 loc) · 5.07 KB
/
server.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
const express = require('express');
const mustacheExpress = require('mustache-express');
const compression = require('compression');
const getDecorator = require('./src/build/scripts/decorator');
const envSettings = require('./envSettings');
const cookieParser = require('cookie-parser');
const { initTokenX, exchangeToken } = require('./tokenx');
const { createProxyMiddleware } = require('http-proxy-middleware');
const Promise = require('promise');
const helmet = require('helmet');
const path = require('path');
const jose = require('jose');
const server = express();
server.use(
helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
})
);
server.use((req, res, next) => {
res.set('X-XSS-Protection', '1; mode=block');
res.set('Feature-Policy', "geolocation 'none'; microphone 'none'; camera 'none'");
next();
});
server.use(compression());
server.use(cookieParser());
server.set('views', `${__dirname}/dist`);
server.set('view engine', 'mustache');
server.engine('html', mustacheExpress());
const verifyLoginUrl = () =>
new Promise((resolve, reject) => {
if (!process.env.LOGIN_URL) {
reject();
} else {
resolve();
}
});
const renderApp = (decoratorFragments) =>
new Promise((resolve, reject) => {
server.render('index.html', decoratorFragments, (err, html) => {
if (err) {
reject(err);
} else {
resolve(html);
}
});
});
const isExpiredOrNotAuthorized = (token) => {
if (token) {
try {
const exp = jose.decodeJwt(token).exp;
return Date.now() >= exp * 1000;
} catch (err) {
console.error('Feilet med dekoding av token: ', err);
return true;
}
}
return true;
};
const startServer = async (html) => {
await Promise.all([initTokenX()]);
server.use(`${process.env.PUBLIC_PATH}/dist/js`, express.static(path.resolve(__dirname, 'dist/js')));
server.use(`${process.env.PUBLIC_PATH}/dist/css`, (req, res, next) => {
const requestReferer = req.headers.referer;
if (requestReferer !== undefined && requestReferer === 'https://nav.psplugin.com/') {
res.set('cross-origin-resource-policy', 'cross-origin');
}
next();
});
server.use(`${process.env.PUBLIC_PATH}/dist/css`, express.static(path.resolve(__dirname, 'dist/css')));
server.get(`${process.env.PUBLIC_PATH}/health/isAlive`, (req, res) => res.sendStatus(200));
server.get(`${process.env.PUBLIC_PATH}/health/isReady`, (req, res) => res.sendStatus(200));
server.get(`${process.env.PUBLIC_PATH}/dist/settings.js`, (req, res) => {
res.set('content-type', 'application/javascript');
res.send(`${envSettings()}`);
});
server.use(
process.env.FRONTEND_API_PATH,
createProxyMiddleware({
target: process.env.API_URL,
changeOrigin: true,
pathRewrite: (path) => {
return path.replace(process.env.FRONTEND_API_PATH, '');
},
router: async (req) => {
if (req.headers['authorization'] !== undefined) {
const token = req.headers['authorization'].replace('Bearer ', '');
if (isExpiredOrNotAuthorized(token)) {
return undefined;
}
const exchangedToken = await exchangeToken(token);
if (exchangedToken != null && !exchangedToken.expired() && exchangedToken.access_token) {
req.headers['authorization'] = `Bearer ${exchangedToken.access_token}`;
}
} else if (req.cookies['selvbetjening-idtoken'] !== undefined) {
const selvbetjeningIdtoken = req.cookies['selvbetjening-idtoken'];
if (isExpiredOrNotAuthorized(selvbetjeningIdtoken)) {
return undefined;
}
const exchangedToken = await exchangeToken(selvbetjeningIdtoken);
if (exchangedToken != null && !exchangedToken.expired() && exchangedToken.access_token) {
req.headers['authorization'] = `Bearer ${exchangedToken.access_token}`;
}
} else return undefined;
return undefined;
},
secure: true,
xfwd: true,
logLevel: 'info',
})
);
server.get(/^\/(?!.*api)(?!.*dist).*$/, (req, res) => {
res.send(html);
});
const port = process.env.PORT || 8080;
server.listen(port, () => {
console.log(`App listening on port: ${port}`);
});
};
const logError = (errorMessage, details) => console.log(errorMessage, details);
verifyLoginUrl()
.then(getDecorator, () => {
logError('LOGIN_URL is missing');
process.exit(1);
})
.then(renderApp, (error) => {
logError('Failed to get decorator', error);
process.exit(1);
})
.then(startServer, (error) => logError('Failed to render app', error));