| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
import { createHash, randomUUID } from "node:crypto"; |
| 11 |
import { join } from "node:path"; |
| 12 |
import { AGENTS, SLOTS } from "./abilities.ts"; |
| 13 |
import { |
| 14 |
addressCapped, |
| 15 |
attach, |
| 16 |
command, |
| 17 |
findPlayer, |
| 18 |
match, |
| 19 |
release, |
| 20 |
snapshot, |
| 21 |
startArena, |
| 22 |
takeSeat, |
| 23 |
unwatch, |
| 24 |
watch, |
| 25 |
type Command, |
| 26 |
type Why, |
| 27 |
} from "./arena.ts"; |
| 28 |
import { recentResults } from "./db.ts"; |
| 29 |
import { gridRows, TILE } from "./map.ts"; |
| 30 |
import { gamePage } from "./pages/game.ts"; |
| 31 |
|
| 32 |
const env = process.env.FORGE_APP_ENV ?? "local"; |
| 33 |
const pull = process.env.FORGE_APP_PULL; |
| 34 |
const commit = (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7); |
| 35 |
const where = env === "preview" ? `preview of pull #${pull ?? "?"}` : env; |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
const publicOrigin = new URL(process.env.FORGE_APP_URL ?? "http://localhost").origin; |
| 42 |
|
| 43 |
const SECURITY = { |
| 44 |
"content-security-policy": |
| 45 |
"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", |
| 46 |
"x-content-type-options": "nosniff", |
| 47 |
"referrer-policy": "strict-origin-when-cross-origin", |
| 48 |
"permissions-policy": "camera=(), microphone=(), geolocation=()", |
| 49 |
|
| 50 |
...(publicOrigin.startsWith("https:") |
| 51 |
? { "strict-transport-security": "max-age=31536000" } |
| 52 |
: {}), |
| 53 |
}; |
| 54 |
const html = (body: string, status = 200, extra: Record<string, string> = {}): Response => |
| 55 |
new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", ...SECURITY, ...extra } }); |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
const sameOrigin = (request: Request): boolean => { |
| 64 |
const site = request.headers.get("sec-fetch-site"); |
| 65 |
if (site !== null) return site === "same-origin" || site === "none"; |
| 66 |
const origin = request.headers.get("origin"); |
| 67 |
return origin === null || origin === publicOrigin || origin === new URL(request.url).origin; |
| 68 |
}; |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
const BODY_MAX = 64 * 1024; |
| 76 |
async function readBody(request: Request, max = BODY_MAX): Promise<Uint8Array | undefined> { |
| 77 |
const reader = request.body?.getReader(); |
| 78 |
if (reader === undefined) return new Uint8Array(); |
| 79 |
const parts: Uint8Array[] = []; |
| 80 |
let size = 0; |
| 81 |
for (;;) { |
| 82 |
const { done, value } = await reader.read(); |
| 83 |
if (done) break; |
| 84 |
size += value.byteLength; |
| 85 |
if (size > max) { |
| 86 |
for (;;) { |
| 87 |
const next = await reader.read(); |
| 88 |
if (next.done) return undefined; |
| 89 |
size += next.value.byteLength; |
| 90 |
if (size > max * 8) { |
| 91 |
await reader.cancel(); |
| 92 |
return undefined; |
| 93 |
} |
| 94 |
} |
| 95 |
} |
| 96 |
parts.push(value); |
| 97 |
} |
| 98 |
const body = new Uint8Array(size); |
| 99 |
let at = 0; |
| 100 |
for (const part of parts) { |
| 101 |
body.set(part, at); |
| 102 |
at += part.byteLength; |
| 103 |
} |
| 104 |
return body; |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
async function readForm(request: Request): Promise<FormData | undefined> { |
| 110 |
const body = await readBody(request); |
| 111 |
if (body === undefined) return undefined; |
| 112 |
return new Request(request.url, { |
| 113 |
method: "POST", |
| 114 |
headers: { "content-type": request.headers.get("content-type") ?? "" }, |
| 115 |
body, |
| 116 |
}).formData(); |
| 117 |
} |
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
const built = await Bun.build({ |
| 127 |
entrypoints: [join(import.meta.dir, "..", "static", "val.js")], |
| 128 |
target: "browser", |
| 129 |
}); |
| 130 |
if (!built.success) throw new AggregateError(built.logs, "the client would not build"); |
| 131 |
const scriptBody = await built.outputs[0]!.text(); |
| 132 |
const scriptHash = createHash("sha256").update(scriptBody).digest("hex").slice(0, 10); |
| 133 |
const scriptUrl = `/static/val.${scriptHash}.js`; |
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
const cookies = (request: Request): Record<string, string> => { |
| 138 |
const out: Record<string, string> = {}; |
| 139 |
for (const part of (request.headers.get("cookie") ?? "").split(";")) { |
| 140 |
const at = part.indexOf("="); |
| 141 |
if (at < 1) continue; |
| 142 |
out[part.slice(0, at).trim()] = decodeURIComponent(part.slice(at + 1).trim()); |
| 143 |
} |
| 144 |
return out; |
| 145 |
}; |
| 146 |
|
| 147 |
const SESSION = "val_session"; |
| 148 |
const NAME = "val_name"; |
| 149 |
|
| 150 |
|
| 151 |
const cleanName = (raw: unknown): string => { |
| 152 |
const text = String(raw ?? "") |
| 153 |
.replace(/[\u0000-\u001f\u007f<>"'\\]/g, "") |
| 154 |
.trim() |
| 155 |
.slice(0, 16); |
| 156 |
return text.length >= 1 ? text : ""; |
| 157 |
}; |
| 158 |
|
| 159 |
const setCookie = (name: string, value: string, httpOnly: boolean): string => |
| 160 |
`${name}=${encodeURIComponent(value)}; Path=/; SameSite=Lax; Max-Age=604800${httpOnly ? "; HttpOnly" : ""}${publicOrigin.startsWith("https:") ? "; Secure" : ""}`; |
| 161 |
|
| 162 |
type SocketData = { session: string; playerId: string; address: string; token: string; spectator: boolean; why: Why }; |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
export const server = Bun.serve<SocketData, Record<string, never>>({ |
| 167 |
port: Number(process.env.PORT ?? 8080), |
| 168 |
hostname: process.env.HOST ?? "127.0.0.1", |
| 169 |
async fetch(request, self) { |
| 170 |
const url = new URL(request.url); |
| 171 |
const jar = cookies(request); |
| 172 |
const session = jar[SESSION] ?? randomUUID(); |
| 173 |
const fresh = jar[SESSION] === undefined; |
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
const address = self?.requestIP?.(request)?.address ?? ""; |
| 178 |
|
| 179 |
if (request.method === "POST" && !sameOrigin(request)) |
| 180 |
return new Response("forbidden", { status: 403, headers: SECURITY }); |
| 181 |
|
| 182 |
if (request.method === "POST" && url.pathname === "/join") { |
| 183 |
const form = await readForm(request); |
| 184 |
if (form === undefined) return new Response("too large", { status: 413, headers: SECURITY }); |
| 185 |
const name = cleanName(form.get("name")); |
| 186 |
const headers = new Headers({ location: "/", ...SECURITY }); |
| 187 |
headers.append("set-cookie", setCookie(SESSION, session, true)); |
| 188 |
if (name) { |
| 189 |
headers.append("set-cookie", setCookie(NAME, name, false)); |
| 190 |
takeSeat(address, session, name); |
| 191 |
} |
| 192 |
return new Response(null, { status: 303, headers }); |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
if (url.pathname === "/ws") { |
| 202 |
if (!sameOrigin(request)) return new Response("forbidden", { status: 403, headers: SECURITY }); |
| 203 |
const token = randomUUID(); |
| 204 |
if (fresh || addressCapped(address, session)) { |
| 205 |
|
| 206 |
|
| 207 |
const why: Why = fresh ? "cookie" : "address"; |
| 208 |
const upgraded = self.upgrade(request, { data: { session, playerId: "", address, token, spectator: true, why } }); |
| 209 |
return upgraded ? undefined : new Response("expected a websocket", { status: 426, headers: SECURITY }); |
| 210 |
} |
| 211 |
const name = cleanName(jar[NAME]) || `Guest-${session.slice(0, 4)}`; |
| 212 |
const player = takeSeat(address, session, name); |
| 213 |
if (!player) return new Response("no seats", { status: 503, headers: SECURITY }); |
| 214 |
const upgraded = self.upgrade(request, { |
| 215 |
data: { session, playerId: player.id, address, token, spectator: false, why: "unsaid" }, |
| 216 |
}); |
| 217 |
return upgraded ? undefined : new Response("expected a websocket", { status: 426, headers: SECURITY }); |
| 218 |
} |
| 219 |
|
| 220 |
if (url.pathname === "/" && (request.method === "GET" || request.method === "HEAD")) { |
| 221 |
const body = gamePage({ |
| 222 |
state: match(), |
| 223 |
script: scriptUrl, |
| 224 |
name: cleanName(jar[NAME]), |
| 225 |
env: where, |
| 226 |
commit, |
| 227 |
ssh: process.env.FORGE_APP_SSH, |
| 228 |
results: recentResults(3), |
| 229 |
}); |
| 230 |
const response = html(body, 200, fresh ? { "set-cookie": setCookie(SESSION, session, true) } : {}); |
| 231 |
return request.method === "HEAD" |
| 232 |
? new Response(null, { status: response.status, headers: response.headers }) |
| 233 |
: response; |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
if (url.pathname === "/agents.json" && (request.method === "GET" || request.method === "HEAD")) |
| 240 |
return Response.json( |
| 241 |
{ |
| 242 |
agents: AGENTS.map((a) => ({ |
| 243 |
id: a.id, |
| 244 |
name: a.name, |
| 245 |
role: a.role, |
| 246 |
blurb: a.blurb, |
| 247 |
abilities: Object.fromEntries( |
| 248 |
SLOTS.map((slot) => { |
| 249 |
const ability = a.abilities[slot]; |
| 250 |
return [ |
| 251 |
slot, |
| 252 |
{ |
| 253 |
name: ability.name, |
| 254 |
cost: ability.cost, |
| 255 |
charges: ability.charges, |
| 256 |
cooldown: ability.cooldown, |
| 257 |
points: ability.points, |
| 258 |
text: ability.text, |
| 259 |
}, |
| 260 |
]; |
| 261 |
}), |
| 262 |
), |
| 263 |
})), |
| 264 |
}, |
| 265 |
{ headers: { "cache-control": "public, max-age=300", ...SECURITY } }, |
| 266 |
); |
| 267 |
|
| 268 |
|
| 269 |
if (url.pathname === "/map.json" && (request.method === "GET" || request.method === "HEAD")) |
| 270 |
return Response.json( |
| 271 |
{ rows: gridRows(), tile: TILE }, |
| 272 |
{ headers: { "cache-control": "public, max-age=300", ...SECURITY } }, |
| 273 |
); |
| 274 |
|
| 275 |
if (url.pathname === scriptUrl) |
| 276 |
return new Response(scriptBody, { |
| 277 |
headers: { |
| 278 |
"content-type": "text/javascript; charset=utf-8", |
| 279 |
"cache-control": "public, max-age=31536000, immutable", |
| 280 |
...SECURITY, |
| 281 |
}, |
| 282 |
}); |
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { |
| 288 |
const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1))); |
| 289 |
if (await file.exists()) |
| 290 |
return new Response(file, { |
| 291 |
headers: { "cache-control": "public, max-age=31536000, immutable", ...SECURITY }, |
| 292 |
}); |
| 293 |
} |
| 294 |
return new Response("not found", { status: 404, headers: SECURITY }); |
| 295 |
}, |
| 296 |
|
| 297 |
websocket: { |
| 298 |
maxPayloadLength: 4 * 1024, |
| 299 |
open(socket) { |
| 300 |
const { session, playerId, address, token, spectator, why } = socket.data; |
| 301 |
if (spectator) return void watch(token, (data) => socket.send(data), why); |
| 302 |
attach(session, playerId, address, token, (data) => socket.send(data)); |
| 303 |
socket.send(snapshot(playerId)); |
| 304 |
}, |
| 305 |
message(socket, raw) { |
| 306 |
if (socket.data.spectator) return; |
| 307 |
|
| 308 |
|
| 309 |
if (typeof raw !== "string" || raw.length > 4096) return; |
| 310 |
let parsed: unknown; |
| 311 |
try { |
| 312 |
parsed = JSON.parse(raw); |
| 313 |
} catch { |
| 314 |
return; |
| 315 |
} |
| 316 |
if (typeof parsed !== "object" || parsed === null) return; |
| 317 |
command(socket.data.playerId, parsed as Command); |
| 318 |
}, |
| 319 |
close(socket) { |
| 320 |
if (socket.data.spectator) return void unwatch(socket.data.token); |
| 321 |
release(socket.data.session, socket.data.token); |
| 322 |
}, |
| 323 |
}, |
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
error(error) { |
| 329 |
console.error(error); |
| 330 |
return html("<h1>Something went wrong</h1>", 500); |
| 331 |
}, |
| 332 |
}); |
| 333 |
|
| 334 |
startArena(); |
| 335 |
|
| 336 |
console.log(`val listening on http://${server.hostname}:${server.port} (${env})`); |
| 337 |
export { findPlayer }; |