forked from Parli/node-simple-server-hackathon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
375 lines (346 loc) · 11.3 KB
/
server.ts
File metadata and controls
375 lines (346 loc) · 11.3 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import http from "http";
import fs from "fs";
import path from "path";
import https from "https";
import crypto from "crypto";
// Port 8080 is commonly supported for cloud deployments
const port = 8080;
// MIME types for different file extensions
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types
const supportedMimeTypes: Record<string, string> = {
".aac": "audio/aac",
".abw": "application/x-abiword",
".apng": "image/apng",
".arc": "application/x-freearc",
".avif": "image/avif",
".avi": "video/x-msvideo",
".azw": "application/vnd.amazon.ebook",
".bin": "application/octet-stream",
".bmp": "image/bmp",
".bz": "application/x-bzip",
".bz2": "application/x-bzip2",
".cda": "application/x-cdf",
".csh": "application/x-csh",
".css": "text/css",
".csv": "text/csv",
".doc": "application/msword",
".docx":
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".eot": "application/vnd.ms-fontobject",
".epub": "application/epub+zip",
".gz": "application/gzip",
".gif": "image/gif",
".htm": "text/html",
".html": "text/html",
".ico": "image/vnd.microsoft.icon",
".ics": "text/calendar",
".jar": "application/java-archive",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "text/javascript",
".json": "application/json",
".jsonld": "application/ld+json",
".mid": "audio/midi",
".midi": "audio/midi",
".mjs": "text/javascript",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".mpeg": "video/mpeg",
".mpkg": "application/vnd.apple.installer+xml",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/vnd.oasis.opendocument.spreadsheet",
".odt": "application/vnd.oasis.opendocument.text",
".oga": "audio/ogg",
".ogv": "video/ogg",
".ogx": "application/ogg",
".opus": "audio/ogg",
".otf": "font/otf",
".png": "image/png",
".pdf": "application/pdf",
".php": "application/x-httpd-php",
".ppt": "application/vnd.ms-powerpoint",
".pptx":
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
".rar": "application/vnd.rar",
".rtf": "application/rtf",
".sh": "application/x-sh",
".svg": "image/svg+xml",
".tar": "application/x-tar",
".tif": "image/tiff",
".tiff": "image/tiff",
".ts": "video/mp2t",
".ttf": "font/ttf",
".txt": "text/plain",
".vsd": "application/vnd.visio",
".wav": "audio/wav",
".weba": "audio/webm",
".webm": "video/webm",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
".xhtml": "application/xhtml+xml",
".xls": "application/vnd.ms-excel",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".xml": "application/xml",
".xul": "application/vnd.mozilla.xul+xml",
".zip": "application/zip",
".3gp": "video/3gpp",
".3g2": "video/3gpp2",
".7z": "application/x-7z-compressed",
};
// Resolve storage file location
const storageFilePath =
process.env["STORAGE_LOCATION"]?.startsWith(".") ||
process.env["STORAGE_LOCATION"] === undefined
? path.join(process.cwd(), process.env["STORAGE_LOCATION"] ?? "./storage")
: process.env["STORAGE_LOCATION"];
// Initialize in memory storage
interface StorageObject {
created: number
modified: number
body: string
}
let storage: Record<string, StorageObject> = {};
// Load storage from file if it exists
const loadStorage = () => {
try {
if (fs.existsSync(storageFilePath)) {
const data = fs.readFileSync(storageFilePath, "utf8");
storage = JSON.parse(data);
console.log("Storage loaded from file");
} else {
// Create directory if it doesn't exist
if (!fs.existsSync(path.dirname(storageFilePath))) {
fs.mkdirSync(path.dirname(storageFilePath), { recursive: true });
}
console.log("No storage file found, starting with empty storage");
}
} catch (error) {
console.error("Error loading storage file:", error);
}
};
let storagePromise = Promise.resolve();
// Save storage to file
const saveStorage = async () => {
const lastStoragePromise = storagePromise;
storagePromise = new Promise((resolve, reject) => {
lastStoragePromise.finally(() => {
fs.writeFile(
storageFilePath,
JSON.stringify(storage),
"utf8",
(error) => {
if (error) {
console.error("Error saving storage file:", error);
return reject(error);
}
return resolve();
}
);
});
});
};
// Load storage at startup
loadStorage();
// Environment Variable interpolation helper with trusted host whitelist
function interpolateEnvVars(value: string, host: string): string {
// Replace env vars if they match pattern "${ENV_VAR}"
return value.replaceAll(/\$\{(.+?)\}/g, (value, envVarName) => {
const envVarValue = process.env[envVarName];
// Check "ENV_VAR_ACCESS" for supported hostnames
const envVarAccess = process.env[`${envVarName}_ACCESS`];
const envVarAllowed =
envVarValue !== undefined &&
envVarAccess !== undefined &&
(envVarAccess === "*" || envVarAccess.split(",").includes(host));
if (envVarValue === undefined) {
console.error(`Interpolation error: "${envVarName}" value not defined`);
return value;
}
if (envVarAllowed === false) {
console.error(
`Interpolation error: "${envVarName}" value not allowed for host "${host}"`
);
return value;
}
return envVarValue;
});
}
const server = http.createServer(
{
maxHeaderSize: 16384 * 4, // Increase the default header size limit (default is 16KB, we're setting to 64KB)
},
(req, res) => {
console.log(`${req.method} ${req.url?.split("?").at(0)}`);
// Set CORS headers for all responses
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
// Request routing
if (req.method === "OPTIONS") {
// Handle OPTIONS requests (preflight)
res.statusCode = 204;
res.end();
} else if (req.url?.startsWith("/api/store/")) {
// Handle storage requests
storeRoute(req, res);
} else
if (req.url?.startsWith("/api/proxy/")) {
// Handle proxy requests
proxyRoute(req, res);
} else {
// Handle static file requests
staticRoute(req, res);
}
}
);
const storeRoute: http.RequestListener = (req, res) => {
if (req.method === "GET") {
const hashId = req.url?.replace("/api/store/", "");
if (hashId && storage[hashId] !== undefined) {
res.writeHead(200);
res.end(storage[hashId].body);
} else {
res.writeHead(404);
res.end("404 Not Found");
}
return;
}
if (req.method === "POST") {
let body = "";
const hash = crypto.createHash("md5");
req.on("data", (chunk) => {
const chunkString = chunk.toString();
hash.update(chunkString);
body += chunkString;
});
req.on("end", () => {
if (body.length > 100000) {
res.writeHead(413, { "Content-Type": "text/plain" });
res.end("Error content too large");
return;
}
try {
const hashId = hash
.digest("base64")
.replaceAll("=", "")
.replaceAll("+", "-")
.replaceAll("/", "_");
const modified = Date.now();
const created = storage[hashId]?.created ?? modified;
storage[hashId] = {
created,
modified,
body,
};
// Save to file after updating storage
saveStorage();
res.writeHead(created === modified ? 201 : 200);
res.end(hashId);
} catch (error) {
console.error("Error processing storage request:", error);
res.writeHead(500);
res.end("Storage request error" );
}
return;
});
return;
}
}
const proxyRoute: http.RequestListener = (req, res) => {
if (!req.url) {
return;
}
try {
// Set up the request to target resource
const proxyUrl = new URL(
decodeURIComponent(req.url.replace("/api/proxy/", ""))
);
// Create a filtered copy of the headers
const filteredHeaders: Record<string, string> = Object.fromEntries(Object.entries(req.headers).flatMap(([key, value]) => {
const lowerKey = key.toLowerCase();
const valueString = Array.isArray(value) ? value.join(",") : value;
// Skip host-specific and browser security headers
if (
[
"host",
"connection",
"content-length",
"user-agent",
"origin",
"referer",
].includes(lowerKey) ||
lowerKey.startsWith("sec-") || valueString === undefined
) {
return [];
}
// Replace env vars if they match pattern "${ENV_VAR}"
const interpolatedValue = typeof valueString === "string" ? interpolateEnvVars(valueString, proxyUrl.host) : valueString;
return [[key, interpolatedValue]]
}))
const options = {
method: req.method,
headers: filteredHeaders,
};
// Forward the request to the proxy resource and pipe it back to the original response
const proxyReq = https.request(interpolateEnvVars(proxyUrl.toString(), proxyUrl.host), options, (proxyRes) => {
res.writeHead(proxyRes.statusCode ?? 200, proxyRes.headers);
proxyRes.pipe(res);
});
// Handle proxy request errors
proxyReq.on("error", (error) => {
console.error("Proxy connection error:", error);
res.writeHead(500);
res.end("Proxy connection error");
});
// Forward the original request body to the proxy request
req.pipe(proxyReq);
} catch (error) {
console.error("Proxy request error:", error);
res.writeHead(500);
res.end("Proxy request error");
}
return;
}
const staticRoute: http.RequestListener = (req, res) => {
const urlPath = req.url?.split("?")[0] ?? "/";
// If URL is '/', serve index.html
const filePath = urlPath === "/" ? "/index.html" : urlPath;
// Ensure the path doesn't contain directory traversal
const sanitizedPath = path
.normalize(filePath ?? "")
.replace(/^(\.\.[\/\\])+/, "");
// Convert URL path to file system path
const absolutePath = path.join(process.cwd(), `/public/${sanitizedPath}`);
// Get file extension
const extname = path.extname(absolutePath);
// Set Content-Type based on file extension
const contentType =
supportedMimeTypes[extname] || "application/octet-stream";
// Read file
fs.readFile(absolutePath, (error, content) => {
if (error === null) {
// Success
res.writeHead(200, { "Content-Type": contentType });
res.end(content, "utf-8");
return;
}
if (error.code === "ENOENT") {
// File not found
console.error(`File not found: ${absolutePath}`);
res.writeHead(404);
res.end("404 Not Found");
return;
} else {
// Server error
console.error(`Server error: ${error.code}`);
res.writeHead(500);
res.end(`Server Error: ${error.code}`);
return;
}
});
}
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
console.log("Press Ctrl+C to stop the server");
});