-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.mjs
297 lines (263 loc) · 8.91 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
import express from "express";
import expressStaticGzip from "express-static-gzip";
import { readFile } from "fs/promises";
import { createProxyMiddleware } from "http-proxy-middleware";
import https from "https";
import path from "path";
const app = express();
// Define a separate router for routes that need to process body
// because otherwise we have to add a body parser fix to all proxies
const tokenRouter = express.Router();
tokenRouter.use(express.urlencoded({ extended: false }));
tokenRouter.use(express.json());
const __dirname = path.resolve(path.dirname("."));
// New http-proxy-middleware adds may add a slash in the end of the path
// which is recognized as a different path by some servers
// and causes 404 (e.g. /bimtrack/token)
function removeTrailingSlashFromPath(proxyReq) {
if (proxyReq.path.endsWith("/")) {
proxyReq.path = proxyReq.path.slice(0, -1);
}
}
function appendClientSecretToBody(proxyReq, req, res, envVarName) {
const secret = process.env[envVarName];
if (!secret) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: `Missing ${envVarName}` }));
proxyReq.destroy();
return;
}
appendToBody(proxyReq, req, { client_secret: secret });
}
// Based on https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/modify-post.md
function appendToBody(proxyReq, req, toAdd) {
// fixRequestBody(proxyReq, req);
const body = req.body;
if (req.method !== "POST" || !body) {
return;
}
const newBody = { ...body, ...toAdd };
let bodyStr = "";
switch (req.headers["content-type"]) {
case "application/json": {
bodyStr = JSON.stringify(newBody);
break;
}
case "application/x-www-form-urlencoded": {
bodyStr = Object.entries({ ...body, ...toAdd })
.map(([key, value]) => encodeURIComponent(key) + "=" + encodeURIComponent(value))
.join("&");
break;
}
default:
break;
}
if (!bodyStr) {
return;
}
proxyReq.setHeader("content-length", bodyStr.length);
proxyReq.write(bodyStr);
}
tokenRouter.use(
"/bimtrack/token",
createProxyMiddleware({
target: "https://auth.bimtrackapp.co/connect/token",
on: {
proxyReq: (proxyReq, req, res) => {
removeTrailingSlashFromPath(proxyReq);
appendClientSecretToBody(proxyReq, req, res, "BIMTRACK_CLIENT_SECRET");
},
},
changeOrigin: true,
}),
);
app.use(
"/bimtrack/bcf/2.1",
createProxyMiddleware({
router: (req) => {
const url = new URL(`https://explorer.novorender.com/${req.url}`);
const server = url.searchParams.get("server") ?? "";
return server + "/bcf/2.1";
},
on: {
proxyReq: (proxyReq) => removeTrailingSlashFromPath(proxyReq),
},
changeOrigin: true,
}),
);
app.use(
"/xsitemanage",
createProxyMiddleware({
target: "https://api.prod.xsitemanage.com",
pathRewrite: {
"^/xsitemanage/": "",
},
on: {
proxyReq: (proxyReq) => removeTrailingSlashFromPath(proxyReq),
},
changeOrigin: true,
}),
);
app.use(
"/ditio-file",
createProxyMiddleware({
target: "https://ditio-api-v3.azurewebsites.net/api/file/",
pathRewrite: {
"^/ditio-file": "",
},
changeOrigin: true,
}),
);
app.use(
"/ditio",
createProxyMiddleware({
target: "https://ditio-api-v3.azurewebsites.net",
pathRewrite: {
"^/ditio": "",
},
on: {
proxyReq: (proxyReq) => removeTrailingSlashFromPath(proxyReq),
},
changeOrigin: true,
}),
);
app.use(
"/ditio-machines",
createProxyMiddleware({
target: "https://ditio-report-api.azurewebsites.net/api",
pathRewrite: {
"^/ditio-machines": "",
},
on: {
proxyReq: (proxyReq) => removeTrailingSlashFromPath(proxyReq),
},
changeOrigin: true,
}),
);
app.use("/omega365", async (req, res) => {
try {
const appendUrl = new URL(req.originalUrl.replace(/^\/omega365/, "").replace(/^\//, ""), "https://localhost");
if (appendUrl.pathname !== "/api/rest/Novorender/EksportObjektDokumentLink") {
return res.status(400).send("Invalid path");
}
const url = new URL("https://nyeveier.pims365.no/" + appendUrl.pathname + appendUrl.search);
const omegaRes = await fetch(url, {
headers: {
authorization: req.headers.authorization,
},
});
if (omegaRes.ok) {
const cookieHeaders = omegaRes.headers.getSetCookie();
cookieHeaders.forEach((header) => res.append("set-cookie", header));
const json = await omegaRes.json();
res.json(json);
} else {
if (omegaRes.status >= 500) {
res.status(omegaRes.status).send();
} else {
res.status(401).send();
}
}
} catch (e) {
console.warn(e);
res.status(500).send();
}
});
tokenRouter.post(
"/token",
createProxyMiddleware({
target: process.env.AUTH_SERVER_URL ?? "https://auth.novorender.com",
on: {
proxyReq: (proxyReq, req, res) => {
appendClientSecretToBody(proxyReq, req, res, "NOVORENDER_CLIENT_SECRET");
},
},
changeOrigin: true,
}),
);
tokenRouter.use(
"/jira/token",
createProxyMiddleware({
target: "https://auth.atlassian.com/oauth/token",
on: {
proxyReq: (proxyReq, req, res) => {
removeTrailingSlashFromPath(proxyReq);
appendClientSecretToBody(proxyReq, req, res, "JIRA_CLIENT_SECRET");
},
},
changeOrigin: true,
}),
);
tokenRouter.use(
"/bimcollab/token",
createProxyMiddleware({
router: (req) => {
const url = new URL(req.url, "https://localhost");
const authUrlStr = url.searchParams.get("auth_url");
const authUrl = new URL(authUrlStr);
// Check that auth_url ends with bimcollab.com,
// otherwise somebody may pass their own URL and get the secret
if (!authUrl.hostname.endsWith(".bimcollab.com")) {
throw "Invalid auth_url for bimcollab/token, host must end with bimcollab.com";
}
return authUrlStr;
},
on: {
proxyReq: (proxyReq, req, res) => {
const url = new URL(proxyReq.path, `${proxyReq.protocol}//${proxyReq.host}`);
url.searchParams.delete("auth_url");
proxyReq.path = url.pathname;
removeTrailingSlashFromPath(proxyReq);
appendClientSecretToBody(proxyReq, req, res, "BIMCOLLAB_CLIENT_SECRET");
},
},
changeOrigin: true,
}),
);
app.use(tokenRouter);
app.use("/*", (_req, res, next) => {
res.header("Cross-Origin-Opener-Policy", "same-origin");
res.header("Cross-Origin-Embedder-Policy", "require-corp");
res.header("Cross-Origin-Resource-Policy", "cross-origin");
next();
});
app.use("/", express.static(path.resolve(__dirname, "dist")));
app.use(
"/",
expressStaticGzip(path.resolve(__dirname, "dist"), {
enableBrotli: true,
orderPreference: ["br", "gz"],
}),
);
app.get("/config.json", (_req, res) => {
res.json({
bimCollabClientId: process.env.BIMCOLLAB_CLIENT_ID ?? "",
bimTrackClientId: process.env.BIMTRACK_CLIENT_ID ?? "",
jiraClientId: process.env.JIRA_CLIENT_ID ?? "",
xsiteManageClientId: process.env.XSITEMANAGE_CLIENT_ID ?? "",
novorenderClientId: process.env.NOVORENDER_CLIENT_ID ?? "",
dataV2ServerUrl: process.env.DATA_V2_SERVER_URL ?? "",
authServerUrl: process.env.AUTH_SERVER_URL ?? "",
assetsUrl: process.env.ASSETS_URL ?? "",
mixpanelToken: process.env.MIXPANEL_TOKEN ?? "",
});
});
app.get("/*", function (_req, res) {
res.sendFile(path.resolve(__dirname, "dist/index.html"));
});
if (process.env.PORT) {
app.listen(process.env.PORT || 80, () => console.log("Server is listening on port 80 or whatever Azure wants"));
} else if (process.env.RUN_LOCALLY === "true") {
// Test locally with https://localhost:3000
// port is important because of some 3rd party auth redirect_uri rules
try {
const [key, cert] = await Promise.all([readFile("./localhost.key"), readFile("./localhost.crt")]);
https.createServer({ key, cert }, app).listen(3000, () => {
console.log("Server is running on https://localhost:3000");
});
} catch (err) {
console.error(`Failed to start server: ${err}`);
}
} else {
https.createServer({}, app).listen(443);
}