-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Expand file tree
/
Copy pathhttp-server.mjs
More file actions
200 lines (183 loc) · 7.89 KB
/
Copy pathhttp-server.mjs
File metadata and controls
200 lines (183 loc) · 7.89 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
// Local HTTP server for one BrainMax canvas instance: serves the static
// frontend (public/), streams state updates to it over Server-Sent Events,
// and accepts interactions from the page to relay back into chat
// via session.send().
import { createServer } from "node:http";
import { randomBytes, timingSafeEqual } from "node:crypto";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path from "node:path";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_DIR = path.join(__dirname, "..", "public");
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
};
const MAX_EVENT_BODY_BYTES = 64 * 1024;
const SSE_HEARTBEAT_MS = 20_000;
export async function readRequestBody(request, maxBytes = MAX_EVENT_BODY_BYTES) {
const bodyChunks = [];
let bodyByteLength = 0;
for await (const chunk of request) {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
bodyByteLength += bytes.length;
if (bodyByteLength > maxBytes) return null;
bodyChunks.push(bytes);
}
return Buffer.concat(bodyChunks).toString("utf8");
}
function writeHeaders(res, status, contentType, extra = {}) {
res.writeHead(status, {
"Content-Type": contentType,
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
"Cross-Origin-Resource-Policy": "same-origin",
"Content-Security-Policy": "default-src 'self'; connect-src 'self'; img-src 'self' data:; script-src 'self'; style-src 'self'; base-uri 'none'; form-action 'self'",
...extra,
});
}
/**
* @param {string} instanceId
* @param {() => import("./state.mjs").InstanceState} getStateFn - fn returning current state
* @param {(event: {type: string, [k: string]: unknown}) => void} onClientEvent
*/
export async function startInstanceServer(instanceId, getStateFn, onClientEvent) {
/** @type {Set<import("node:http").ServerResponse>} */
const sseClients = new Set();
const capabilityToken = randomBytes(32).toString("base64url");
const capabilityTokenBytes = Buffer.from(capabilityToken);
function hasCapability(url) {
const candidate = url.searchParams.get("token");
if (!candidate) return false;
const candidateBytes = Buffer.from(candidate);
return candidateBytes.length === capabilityTokenBytes.length && timingSafeEqual(candidateBytes, capabilityTokenBytes);
}
function rejectUnauthorized(res) {
writeHeaders(res, 403, MIME[".json"]);
res.end(JSON.stringify({ ok: false, error: "invalid canvas capability" }));
}
function broadcastState() {
const payload = `data: ${JSON.stringify(getStateFn())}\n\n`;
for (const res of sseClients) {
res.write(payload);
}
}
const heartbeat = setInterval(() => {
for (const res of sseClients) {
res.write(`: heartbeat ${Date.now()}\n\n`);
}
}, SSE_HEARTBEAT_MS);
heartbeat.unref?.();
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://localhost");
if (url.pathname === "/events" && req.method === "GET") {
if (!hasCapability(url)) {
rejectUnauthorized(res);
return;
}
writeHeaders(res, 200, "text/event-stream", { Connection: "keep-alive" });
res.write(`data: ${JSON.stringify(getStateFn())}\n\n`);
sseClients.add(res);
req.on("close", () => sseClients.delete(res));
return;
}
if (url.pathname === "/state" && req.method === "GET") {
if (!hasCapability(url)) {
rejectUnauthorized(res);
return;
}
writeHeaders(res, 200, MIME[".json"]);
res.end(JSON.stringify(getStateFn()));
return;
}
if (url.pathname === "/event" && req.method === "POST") {
if (!hasCapability(url)) {
rejectUnauthorized(res);
return;
}
if (!String(req.headers["content-type"] || "").toLowerCase().startsWith("application/json")) {
writeHeaders(res, 415, MIME[".json"]);
res.end(JSON.stringify({ ok: false, error: "content type must be application/json" }));
return;
}
const body = await readRequestBody(req);
if (body === null) {
writeHeaders(res, 413, MIME[".json"]);
res.end(JSON.stringify({ ok: false, error: "event payload is too large" }));
return;
}
let event;
try {
event = JSON.parse(body || "{}");
} catch {
writeHeaders(res, 400, MIME[".json"]);
res.end(JSON.stringify({ ok: false, error: "invalid JSON" }));
return;
}
if (!event || typeof event !== "object" || Array.isArray(event)) {
writeHeaders(res, 400, MIME[".json"]);
res.end(JSON.stringify({ ok: false, error: "event payload must be an object" }));
return;
}
const result = onClientEvent(event) || { ok: true };
writeHeaders(res, result.ok === false ? 400 : 202, MIME[".json"]);
res.end(JSON.stringify(result));
return;
}
// Static file serving for everything else, defaulting to index.html.
if (req.method !== "GET" && req.method !== "HEAD") {
writeHeaders(res, 405, "text/plain; charset=utf-8", { Allow: "GET, HEAD" });
res.end("Method not allowed");
return;
}
let relPath = url.pathname === "/" ? "/index.html" : url.pathname;
const filePath = path.resolve(PUBLIC_DIR, `.${relPath}`);
const relativePath = path.relative(PUBLIC_DIR, filePath);
if (relativePath.startsWith(`..${path.sep}`) || relativePath === ".." || path.isAbsolute(relativePath)) {
writeHeaders(res, 403, "text/plain; charset=utf-8");
res.end("Forbidden");
return;
}
const ext = path.extname(filePath);
const data = await readFile(filePath);
writeHeaders(res, 200, MIME[ext] || "application/octet-stream");
res.end(req.method === "HEAD" ? undefined : data);
} catch (err) {
if (err && err.code === "ENOENT") {
writeHeaders(res, 404, "text/plain; charset=utf-8");
res.end("Not found");
return;
}
console.error(`BrainMax canvas server error for ${instanceId}`, err);
writeHeaders(res, 500, "text/plain; charset=utf-8");
res.end("Internal server error");
}
});
try {
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
server.off("error", reject);
resolve();
});
});
} catch (error) {
clearInterval(heartbeat);
throw error;
}
const address = server.address();
const port = typeof address === "object" && address ? address.port : 0;
return {
url: `http://127.0.0.1:${port}/?token=${capabilityToken}`,
broadcastState,
close: () =>
new Promise((resolve) => {
clearInterval(heartbeat);
for (const res of sseClients) res.end();
server.close(() => resolve());
}),
};
}