-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·180 lines (149 loc) · 5.88 KB
/
server.js
File metadata and controls
executable file
·180 lines (149 loc) · 5.88 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
// NOTE: Uses await etc so requires at least node 7.6
'use strict'
const url = require("url");
const zlib = require("zlib");
const fs = require("fs");
const cmdline = require("./command_line");
const express = require("express");
const accept = require("@hapi/accept");
const https = require("https");
const { createProxyMiddleware } = require("http-proxy-middleware");
const compression = require("compression");
const { ssr, startBrowser } = require("./ssr");
const log = require("loglevel");
// Start the server.
const app = express();
// Enable on the fly compression?
if(cmdline.compression) {
log.info("on the fly compression enabled");
app.use(compression({ level: zlib.constants.Z_BEST_COMPRESSION }));
}
// Do we know for sure that we're behind a proxy?
if(cmdline.proxy) {
log.info("behind a proxy: ", cmdline.proxy);
// From docs:
// Enabling trust proxy will have the following impact:
// The value of req.hostname is derived from the value set in the X-Forwarded-Host header, which can be set by the client or by the proxy.
// X-Forwarded-Proto can be set by the reverse proxy to tell the app whether it is https or http or even an invalid name. This value is reflected by req.protocol.
// The req.ip and req.ips values are populated with the list of addresses from X-Forwarded-For.
app.enable("trust proxy", cmdline.proxy);
}
// Serving static files?
if(cmdline.public) {
log.info("starting static server");
app.use(express.static(cmdline.public, { index: false }));
}
const proxyMap = new Map(cmdline.map);
const preRenderUrl = async (req, res, next) => {
// Does this URL look like something we render?
if(!req.originalUrl.match(/.(js|js.map|css|jpg|jpeg|png|ico|txt|xml)$/)) {
const protHostPort = `${req.protocol}://${req.get('Host')}`;
const pretendToBeUrl = `${protHostPort}${req.originalUrl}`;
const fetchFromUrl = `${proxyMap.get(protHostPort)}${req.originalUrl}`;
// Choose the appropriate response encoding. We can support brotli, gzip, and
// the identity transform. Give priority to brotli then gzip and finally nothing.
const encoding = accept.encoding(req.headers["accept-encoding"], ["br", "gzip"]);
log.debug(`decided response encoding is ${encoding} from "${req.headers["accept-encoding"]}"`);
log.debug(`ssr request: ${pretendToBeUrl}`);
try {
const { content, ttRenderMs } = await ssr({
url: pretendToBeUrl,
fetch: fetchFromUrl,
timeout: 5000,
blacklist: cmdline.blacklist,
whiteResources: ["document", "script", "xhr", "fetch"],
encoding: encoding,
copyToDir: cmdline.copyToDir
});
res.set({
"Server-Timing": `Prerender;dur=${ttRenderMs};desc="Headless render time (ms)"`,
"Content-Encoding": encoding,
"Content-Length": content.length,
"Content-Type": "text/html"
});
return res.status(200).send(content);
} catch(err) {
log.error("render error", err.message);
return res.status(404).send("error with rendering");
}
} else {
// Pass on to the proxy
return next();
}
};
const sendToProxy = createProxyMiddleware({
target: "http://localhost:9", // This is the default route if router returns falsy. It's the discard port. https://en.wikipedia.org/wiki/Discard_Protocol
changeOrigin: true,
ws: false,
secure: true,
onProxyReq: (proxyReq, req, res) => {
log.debug(`proxying ${req.protocol}://${req.get('Host')}${req.originalUrl}`);
},
router: (req) => {
const proxyFrom = `${req.protocol}://${req.get('Host')}`;
const proxyTo = proxyMap.get(proxyFrom);
log.debug(`proxy router ${proxyFrom} to ${proxyTo}`);
return proxyTo;
}
});
// Redirect GET on all routes and redirect them to either the
// SSR version or send along to the proxy for the authoritive
// answer.
app.get("*", preRenderUrl, sendToProxy);
async function runEarlyPreRender() {
// Run any initial rendering that is required.
for(let i = 0; i < cmdline.early.length; ++i) {
const urlToRender = cmdline.early[i];
log.debug(`premptive rendering for ${urlToRender}`);
const renderUrl = new url.URL(urlToRender);
const protHostPort = `${renderUrl.origin}`;
const fetchFromUrl = `${proxyMap.get(protHostPort)}${renderUrl.pathname}${renderUrl.search}${renderUrl.hash}`;
try {
await ssr({
url: urlToRender,
fetch: fetchFromUrl,
timeout: 5000,
blacklist: cmdline.blacklist,
whiteResources: ["document", "script", "xhr", "fetch"], // FIXME: used in 2 places.
encoding: "gzip", // doesn't matter so picking something at random.
copyToDir: cmdline.copyToDir
});
} catch(err) {
log.error(`unable to early render ${urlToRender} via ${fetchFromUrl}: ${err.message}`);
}
}
}
async function init() {
// Secure server or not?
let server = app;
if(cmdline.key && cmdline.cert && cmdline.server) {
log.info("Starting secure server");
const privateKey = fs.readFileSync(cmdline.key, "utf8");
const certificate = fs.readFileSync(cmdline.cert, "utf8");
server = https.createServer({
key: privateKey,
cert: certificate
}, app);
}
if(cmdline.drop) {
const ids = cmdline.drop.split(":");
log.debug("dropping privileges to %s based off %s:%s", cmdline.drop, ids[0], ids[1]);
process.setgid(ids[1]);
process.setuid(ids[0]);
log.debug("now %s:%s", process.getuid(), process.getgid());
}
await startBrowser();
await runEarlyPreRender();
// Make the server listen and then we're off to the races.
if(cmdline.server) {
server.listen(cmdline.port,
() => {
log.info("Server started on port %d. Press Ctrl+C to quit", cmdline.port);
});
} else {
console.log("Done preredering all files. Exiting.");
// Indicate that we'd like the program to exit when it can.
process.exit(0);
}
}
init();