-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
180 lines (162 loc) · 5.08 KB
/
server.mjs
File metadata and controls
180 lines (162 loc) · 5.08 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
import http from "node:http";
import https from "node:https";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const PORT = Number(process.env.PORT) || 8080;
const HOST = process.env.HOST || "0.0.0.0";
const DIST = path.join(path.dirname(fileURLToPath(import.meta.url)), "dist");
const FORWARD_REQUEST_HEADERS = new Set([
"authorization",
"accept",
"content-type",
"user-agent",
]);
const DROP_RESPONSE_HEADERS = new Set([
"set-cookie",
"access-control-allow-origin",
"access-control-allow-credentials",
"access-control-allow-headers",
"access-control-allow-methods",
"access-control-expose-headers",
"access-control-max-age",
"connection",
"transfer-encoding",
]);
const MIME = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".map": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".ico": "image/x-icon",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
".txt": "text/plain; charset=utf-8",
};
function send(res, status, body, type = "text/plain; charset=utf-8") {
if (res.writableEnded) return;
res.writeHead(status, {
"content-type": type,
"content-length": Buffer.byteLength(body),
});
res.end(body);
}
function pickHeaders(headers) {
const out = {};
for (const [k, v] of Object.entries(headers)) {
if (FORWARD_REQUEST_HEADERS.has(k.toLowerCase())) out[k] = v;
}
return out;
}
function filterResponseHeaders(headers) {
const out = {};
for (const [k, v] of Object.entries(headers)) {
if (!DROP_RESPONSE_HEADERS.has(k.toLowerCase())) out[k] = v;
}
return out;
}
export function handleProxy(req, res) {
const targetHeader = req.headers["x-cpln-url"];
if (typeof targetHeader !== "string" || !targetHeader) {
return send(res, 400, "Missing X-Cpln-Url header");
}
let target;
try {
target = new URL(targetHeader);
} catch {
return send(res, 400, "Invalid X-Cpln-Url");
}
if (target.protocol !== "https:") {
return send(res, 400, "Only https targets are allowed");
}
if (!target.hostname.endsWith(".cpln.io")) {
return send(res, 403, `Target host not allowed: ${target.hostname}`);
}
const upstream = https.request(
{
method: req.method,
host: target.hostname,
port: target.port ? Number(target.port) : 443,
path: target.pathname + target.search,
headers: pickHeaders(req.headers),
},
(upRes) => {
res.writeHead(upRes.statusCode || 502, filterResponseHeaders(upRes.headers));
upRes.pipe(res);
},
);
upstream.on("error", (err) => {
console.error("[proxy] upstream error:", err.message);
send(res, 502, `Upstream error: ${err.message}`);
});
req.pipe(upstream);
}
function safeJoin(base, requested) {
const decoded = decodeURIComponent(requested.split("?")[0]);
const target = path.normalize(path.join(base, decoded));
if (target !== base && !target.startsWith(base + path.sep)) return null;
return target;
}
function tryFile(filePath) {
try {
const st = fs.statSync(filePath);
if (st.isFile()) return st;
} catch {
/* ignore */
}
return null;
}
function streamFile(req, res, filePath, stat) {
const ext = path.extname(filePath).toLowerCase();
const type = MIME[ext] || "application/octet-stream";
const cache = filePath.includes(path.join(DIST, "assets") + path.sep)
? "public, max-age=31536000, immutable"
: "no-cache";
res.writeHead(200, {
"content-type": type,
"content-length": stat.size,
"cache-control": cache,
});
if (req.method === "HEAD") return res.end();
fs.createReadStream(filePath).pipe(res);
}
function serveStatic(req, res) {
if (req.method !== "GET" && req.method !== "HEAD") {
return send(res, 405, "Method not allowed");
}
const requested = req.url === "/" ? "/index.html" : req.url;
const resolved = safeJoin(DIST, requested);
if (!resolved) return send(res, 400, "Bad path");
const direct = tryFile(resolved);
if (direct) return streamFile(req, res, resolved, direct);
if (!requested.startsWith("/assets/")) {
const indexPath = path.join(DIST, "index.html");
const indexStat = tryFile(indexPath);
if (indexStat) return streamFile(req, res, indexPath, indexStat);
}
send(res, 404, "Not found");
}
function isProxyRequest(url) {
return url === "/proxy" || url.startsWith("/proxy?");
}
const isMain = import.meta.url === `file://${process.argv[1]}`;
if (isMain) {
const server = http.createServer((req, res) => {
if (!req.url) return send(res, 400, "Bad request");
if (isProxyRequest(req.url)) return handleProxy(req, res);
serveStatic(req, res);
});
server.listen(PORT, HOST, () => {
console.log(`partner-test server listening on http://${HOST}:${PORT}`);
console.log(` static root: ${DIST}`);
console.log(` proxy endpoint: /proxy (X-Cpln-Url required, *.cpln.io only)`);
});
}