-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserv.js
136 lines (97 loc) · 2.63 KB
/
serv.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
import url from 'url';
import net from 'net';
import fs from 'fs';
import http from 'http';
import path from 'path';
const PORT = 5111;
const HOST = "localhost"
const INDEX = "bluenoise6.html"
const basedir = process.cwd();
export const exports = {};
let mimemap = {
".js" : "application/javascript",
".json" : "text/json",
".html" : "text/html",
".png" : "image/png",
".jpg" : "image/jpeg",
".css" : "text/css",
".svg" : "image/svg+xml"
};
let getMime = (p) => {
p = p.toLowerCase().trim();
for (let k in mimemap) {
if (p.endsWith(k)) {
return mimemap[k];
}
}
return "text/plain";
}
let allowed_origins = new Set([
`http://${HOST}:${PORT}/`,
`http://${HOST}:${PORT}`
]);
exports.ServerResponse = class ServerResponse extends http.ServerResponse {
_addHeaders(origin) {
this.setHeader("X-Content-Type-Options", "nosniff");
if (allowed_origins.has(origin)) {
this.setHeader("Access-Control-Allow-Origin", origin);
}
this.setHeader("Document-Policy", "js-profiling");
this.setHeader("Cross-Origin-Opener-Policy", "same-origin");
this.setHeader("Cross-Origin-Resource-Policy", "same-origin");
this.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
this.setHeader("Vary", "Origin");
}
sendError(code, message) {
let buf = `<!doctype html>
<html>
<head><title>404</title></head>
<body><div>${message}<div><body>
</html>
`;
this.statusCode = code;
this.setHeader('Host', HOST);
this.setHeader('Content-Type', 'text/html');
this.setHeader('Content-Length', buf.length);
this._addHeaders();
this.writeHead(code)
this.end(buf);
}
}
const serv = http.createServer({
ServerResponse : exports.ServerResponse
}, (req, res) => {
let p = req.url.trim();
if (!p.startsWith("/")) {
p = "/" + p
}
let origin = req.headers["origin"] || "";
console.log(req.method, p, origin);
if (p === "/") {
p += INDEX
}
p = path.normalize(basedir + p);
if (p.search(/\.\./) >= 0 || !p.startsWith(basedir)) {
//normalize failed
return res.sendError(500, "malformed path");
}
let stt;
try {
stt = fs.statSync(p);
} catch(error) {
return res.sendError(404, "bad path");
}
if (stt === undefined || stt.isDirectory() || !stt.isFile()) {
console.log("access error for", p);
return res.sendError(404, "bad path");
}
let mime = getMime(p);
let buf = fs.readFileSync(p);
res.statusCode = 200;
res.setHeader('Content-Type', mime);
res._addHeaders(origin);
res.end(buf);
});
serv.listen(PORT, HOST, () => {
console.log("Server listening on", HOST + ":" + PORT);
});