-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
72 lines (65 loc) · 2.48 KB
/
Copy pathserver.mjs
File metadata and controls
72 lines (65 loc) · 2.48 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
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { createServer } from "node:http";
import { extname, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { handleApiRequest } from "./src/http.js";
import { createIncidentService } from "./src/service.js";
import { createMemoryStore } from "./src/store.js";
const root = resolve(fileURLToPath(new URL(".", import.meta.url)));
const port = Number(process.env.PORT || 4174);
const store = createMemoryStore();
const types = {
".css": "text/css; charset=utf-8",
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".svg": "image/svg+xml",
".webp": "image/webp",
};
async function webRequest(request) {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const body = chunks.length ? Buffer.concat(chunks) : undefined;
return new Request(`http://${request.headers.host}${request.url}`, {
method: request.method,
headers: request.headers,
body,
});
}
async function sendWebResponse(response, webResponse) {
response.writeHead(webResponse.status, Object.fromEntries(webResponse.headers));
response.end(Buffer.from(await webResponse.arrayBuffer()));
}
createServer(async (request, response) => {
const pathname = new URL(request.url, `http://${request.headers.host}`).pathname;
if (pathname.startsWith("/api/")) {
const webResponse = await handleApiRequest(await webRequest(request), (storageKey) =>
createIncidentService(store, storageKey),
);
await sendWebResponse(response, webResponse);
return;
}
const requested = pathname === "/" ? "index.html" : pathname.slice(1);
const path = resolve(root, requested);
if (path !== root && !path.startsWith(`${root}${sep}`)) {
response.writeHead(403).end("Forbidden");
return;
}
try {
const metadata = await stat(path);
if (!metadata.isFile()) throw new Error("Not a file");
response.writeHead(200, {
"Content-Type": types[extname(path)] || "application/octet-stream",
"Cache-Control": "no-store",
"Permissions-Policy": "tools=(self)",
"X-Content-Type-Options": "nosniff",
});
createReadStream(path).pipe(response);
} catch {
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
}
}).listen(port, "127.0.0.1", () => {
console.log(`Arrastra Relay prototype: http://127.0.0.1:${port}`);
});