forked from getify/youperiod.app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
180 lines (158 loc) · 4.38 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
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
"use strict";
process.on("uncaughtException",function(err){
console.log(err.stack);
});
var path = require("path");
var http = require("http");
var httpServer = http.createServer(handleRequest);
var nodeStaticAlias = require("@getify/node-static-alias");
var AccessControlHeader = {
"Access-Control-Allow-Origin": "https://youperiod.app",
};
var HSTSHeader = {
"Strict-Transport-Security": `max-age=${ 1E9 }`,
};
var noSniffHeader = {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
"X-Content-Type-Options": "nosniff",
};
var CSPHeader = {
"Content-Security-Policy":
[
`default-src ${[
"'self'",
].join(" ")};`,
`style-src ${[
"'self'",
"'unsafe-inline'",
].join(" ")};`,
`script-src ${[
"'self'",
// inline <script> tag for re-computing the vw/vh units
"'sha256-CoCYJ/tTxH9vJyISOUlowiGKF8OokDL5QBuS3H8R1/g='",
].join(" ")};`,
`connect-src ${[
"'none'",
].join(" ")};`
].join(" ")
};
const STATIC_DIR = path.join(__dirname,"web");
const DEV = true;
const CACHE_FILES = false;
const PORT = process.env.HTTP_SERVER_PORT || 8034;
var staticServer = new nodeStaticAlias.Server(STATIC_DIR,{
serverInfo: "YouPeriod",
cache: CACHE_FILES ? (60 * 60 * 3) : 0,
gzip: /^(?:(?:text\/.+)|(?:image\/svg\+xml)|(?:application\/javascript)|(?:application\/json)|(?:application\/manifest\+json))(?:; charset=utf-8)?$/,
headers: {
...AccessControlHeader,
...(!DEV ? HSTSHeader : {}),
},
onContentType(contentType,headers) {
// apparently this is the new preferred mime-type for JS
if (contentType == "application/javascript") {
contentType = "text/javascript";
}
// only add CSP headers for text/html pages
if (contentType == "text/html") {
Object.assign(headers,CSPHeader);
}
// no-sniff header for CSS and JS only
if (/^(?:text\/(?:css|javascript))|(?:application\/json)$/.test(contentType)) {
Object.assign(headers,noSniffHeader);
}
// add utf-8 charset for some text file types
if (
/^((text\/(?:html|css|javascript))|(?:application\/json)|(image\/svg\+xml)|(application\/manifest\+json))$/.test(contentType)
) {
contentType = `${contentType}; charset=utf-8`;
}
return contentType;
},
alias: [
// basic static page friendly URL rewrites
{
match: /\/(?:index(?:\.html)?)?(?:[#?]|$)/,
serve: "index.html",
force: true,
},
],
});
httpServer.listen(PORT, () => {
console.log(`The app is running on http://localhost:${PORT}`);
});
// *************************************
function handleRequest(req,res) {
if (!DEV && !/^youperiod\.app$/.test(req.headers["host"])) {
res.writeHeader(307,{
Location: `https://youperiod.app${req.url}`,
"Cache-Control": "public, max-age=3600",
Expires: new Date(Date.now() + (3600 * 1000) ).toUTCString(),
});
res.end();
}
// unconditional, permanent HTTPS redirect
else if (!DEV && req.headers["x-forwarded-proto"] !== "https") {
res.writeHead(301,{
"Cache-Control": "public, max-age=31536000",
Expires: new Date(Date.now() + 31536000000).toUTCString(),
Location: `https://youperiod.app${req.url}`
});
res.end();
}
else {
onRequest(req,res);
}
}
async function onRequest(req,res) {
if (["GET","HEAD"].includes(req.method)) {
if (!DEV) {
// basic page load logging
if (/^\/(?:index\.html)?(?:[\?#]|$)/.test(req.url)) {
console.log(`page request: ${
req.headers["x-forwarded-for"]?.split(',').shift() ||
req.socket?.remoteAddress
} | ${new Date(Date.now()).toLocaleString("en-US")}`);
}
// special cache expiration behavior for favicon
if (/^\/favicon\.ico$/.test(req.url)) {
try {
await serveFile(req.url,200,{
"Cache-Control": `public, max-age=${60*60*24*30}`,
...HSTSHeader,
},req,res);
}
catch (err) {
res.writeHead(404);
res.end();
}
return;
}
}
// handle all other static files
staticServer.serve(req,res,async function onStaticComplete(err){
if (err) {
try {
return await serveFile("/index.html",200,{
...HSTSHeader,
...CSPHeader,
},req,res);
}
catch (err2) {}
}
res.writeHead(404);
res.end();
});
}
else {
res.writeHead(404);
res.end();
}
}
function serveFile(url,statusCode,headers,req,res) {
var listener = staticServer.serveFile(url,statusCode,headers,req,res);
return new Promise(function c(resolve,reject){
listener.on("success",resolve);
listener.on("error",reject);
});
}