quill/val Public Public: anyone can read this; nobody can change it.

forked from benjivers/val

workbenchthis machine
Files 19b0f58ca24daca7a3766f319cc2ed42ce27e794
338 lines · 13.7 KB · ~4.0k tok Raw History
1
/**
2
 * val — the door. Routing, sessions, sockets and the security floor; the
3
 * game itself is in src/match.ts, the live one in src/arena.ts, and the
4
 * machinery that serves any game in src/engine/.
5
 *
6
 * A seat belongs to a session cookie, so the same browser gets the same
7
 * player back across a reload, and a socket is only ever given a seat the
8
 * server chose.
9
 */
10
11
import { createHash, randomUUID } from "node:crypto";
12
import { join } from "node:path";
13
import { AGENTS, SLOTS } from "./abilities.ts";
14
import {
15
  addressCapped,
16
  attach,
17
  command,
18
  findPlayer,
19
  match,
20
  release,
21
  snapshot,
22
  startArena,
23
  takeSeat,
24
  unwatch,
25
  watch,
26
  type Command,
27
  type Why,
28
} from "./arena.ts";
29
import { recentResults } from "./db.ts";
30
import { gridRows, TILE } from "./map.ts";
31
import { gamePage } from "./pages/game.ts";
32
33
const env = process.env.FORGE_APP_ENV ?? "local";
34
const pull = process.env.FORGE_APP_PULL;
35
const commit = (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7);
36
const where = env === "preview" ? `preview of pull #${pull ?? "?"}` : env;
37
38
// The security floor every response stands on. Scripts and styles come from
39
// this origin (inline styles allowed, inline scripts not), nothing frames us,
40
// browsers never guess a content type, and referrers stay on this site.
41
// The app's public address is what the forge told us, never the socket's.
42
const publicOrigin = new URL(process.env.FORGE_APP_URL ?? "http://localhost").origin;
43
44
const SECURITY = {
45
  "content-security-policy":
46
    "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
47
  "x-content-type-options": "nosniff",
48
  "referrer-policy": "strict-origin-when-cross-origin",
49
  "permissions-policy": "camera=(), microphone=(), geolocation=()",
50
  // Once served over https, always: browsers remember for a year.
51
  ...(publicOrigin.startsWith("https:")
52
    ? { "strict-transport-security": "max-age=31536000" }
53
    : {}),
54
};
55
const html = (body: string, status = 200, extra: Record<string, string> = {}): Response =>
56
  new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", ...SECURITY, ...extra } });
57
58
// A browser on another site can make a person's browser POST here; it cannot
59
// make that request look same-origin. Browsers say where a request came from
60
// (Sec-Fetch-Site, or Origin); a request that names another site is refused.
61
// The address the forge published is the one that counts, but a browser
62
// reaching the app by another name (localhost, an IP, a tunnel) sends that
63
// host in both the URL and the Origin — a cross-site request never can.
64
const sameOrigin = (request: Request): boolean => {
65
  const site = request.headers.get("sec-fetch-site");
66
  if (site !== null) return site === "same-origin" || site === "none";
67
  const origin = request.headers.get("origin");
68
  return origin === null || origin === publicOrigin || origin === new URL(request.url).origin;
69
};
70
71
// A request body is read up to a cap and no further, counting the bytes as
72
// they arrive. A declared Content-Length is a claim: a chunked request has
73
// none, and a lie is free. Undefined means "too large" — refuse it. Past the
74
// cap the rest is drained and dropped so the connection stays usable for
75
// the next request; past eight times the cap it is cut off instead.
76
const BODY_MAX = 64 * 1024;
77
async function readBody(request: Request, max = BODY_MAX): Promise<Uint8Array | undefined> {
78
  const reader = request.body?.getReader();
79
  if (reader === undefined) return new Uint8Array();
80
  const parts: Uint8Array[] = [];
81
  let size = 0;
82
  for (;;) {
83
    const { done, value } = await reader.read();
84
    if (done) break;
85
    size += value.byteLength;
86
    if (size > max) {
87
      for (;;) {
88
        const next = await reader.read();
89
        if (next.done) return undefined;
90
        size += next.value.byteLength;
91
        if (size > max * 8) {
92
          await reader.cancel();
93
          return undefined;
94
        }
95
      }
96
    }
97
    parts.push(value);
98
  }
99
  const body = new Uint8Array(size);
100
  let at = 0;
101
  for (const part of parts) {
102
    body.set(part, at);
103
    at += part.byteLength;
104
  }
105
  return body;
106
}
107
108
// The form fields of a capped body, decoded the way the browser sent them
109
// (a plain form or a multipart one), by handing the bytes back to a Request.
110
async function readForm(request: Request): Promise<FormData | undefined> {
111
  const body = await readBody(request);
112
  if (body === undefined) return undefined;
113
  return new Request(request.url, {
114
    method: "POST",
115
    headers: { "content-type": request.headers.get("content-type") ?? "" },
116
    body,
117
  }).formData();
118
}
119
120
// ------------------------------------------------------------- the client
121
122
// The client is a handful of small modules under static/ — the renderer, the
123
// map, the crosshair, the ray maths — bundled into one file at start-up so a
124
// browser makes one request and the maths can still be imported by the tests.
125
// It is named by its content: a change is a new URL, so a year-long cache is
126
// never stale.
127
const built = await Bun.build({
128
  entrypoints: [join(import.meta.dir, "..", "static", "val.js")],
129
  target: "browser",
130
});
131
if (!built.success) throw new AggregateError(built.logs, "the client would not build");
132
const scriptBody = await built.outputs[0]!.text();
133
const scriptHash = createHash("sha256").update(scriptBody).digest("hex").slice(0, 10);
134
const scriptUrl = `/static/val.${scriptHash}.js`;
135
136
// ------------------------------------------------------------- sessions
137
138
const cookies = (request: Request): Record<string, string> => {
139
  const out: Record<string, string> = {};
140
  for (const part of (request.headers.get("cookie") ?? "").split(";")) {
141
    const at = part.indexOf("=");
142
    if (at < 1) continue;
143
    out[part.slice(0, at).trim()] = decodeURIComponent(part.slice(at + 1).trim());
144
  }
145
  return out;
146
};
147
148
const SESSION = "val_session";
149
const NAME = "val_name";
150
151
/** A name is one line of plain text, sixteen characters, nothing clever. */
152
const cleanName = (raw: unknown): string => {
153
  const text = String(raw ?? "")
154
    .replace(/[\u0000-\u001f\u007f<>"'\\]/g, "")
155
    .trim()
156
    .slice(0, 16);
157
  return text.length >= 1 ? text : "";
158
};
159
160
const setCookie = (name: string, value: string, httpOnly: boolean): string =>
161
  `${name}=${encodeURIComponent(value)}; Path=/; SameSite=Lax; Max-Age=604800${httpOnly ? "; HttpOnly" : ""}${publicOrigin.startsWith("https:") ? "; Secure" : ""}`;
162
163
type SocketData = { session: string; playerId: string; address: string; token: string; spectator: boolean; why: Why };
164
165
// ---------------------------------------------------------------- routing
166
167
export const server = Bun.serve<SocketData, Record<string, never>>({
168
  port: Number(process.env.PORT ?? 8080),
169
  hostname: process.env.HOST ?? "127.0.0.1",
170
  async fetch(request, self) {
171
    const url = new URL(request.url);
172
    const jar = cookies(request);
173
    const session = jar[SESSION] ?? randomUUID();
174
    const fresh = jar[SESSION] === undefined;
175
    // A cookie costs one HTTP request, so it names a browser, not a person —
176
    // the address is the one thing here a single machine cannot mint a
177
    // second one of, which is what a playing seat is actually rationed by.
178
    const address = self?.requestIP?.(request)?.address ?? "";
179
180
    if (request.method === "POST" && !sameOrigin(request))
181
      return new Response("forbidden", { status: 403, headers: SECURITY });
182
183
    if (request.method === "POST" && url.pathname === "/join") {
184
      const form = await readForm(request);
185
      if (form === undefined) return new Response("too large", { status: 413, headers: SECURITY });
186
      const name = cleanName(form.get("name"));
187
      const headers = new Headers({ location: "/", ...SECURITY });
188
      headers.append("set-cookie", setCookie(SESSION, session, true));
189
      if (name) {
190
        headers.append("set-cookie", setCookie(NAME, name, false));
191
        takeSeat(address, session, name);
192
      }
193
      return new Response(null, { status: 303, headers });
194
    }
195
196
    // The socket: one playing seat per address, taken from a bot where it
197
    // stands. A connection with no session the page minted, or one whose
198
    // address already plays under a different session, gets no seat at all —
199
    // it watches instead, with a view built for no side, rather than being
200
    // handed the vision a seat would otherwise give it on top of the one it
201
    // already has.
202
    if (url.pathname === "/ws") {
203
      if (!sameOrigin(request)) return new Response("forbidden", { status: 403, headers: SECURITY });
204
      const token = randomUUID();
205
      if (fresh || addressCapped(address, session)) {
206
        // Which of the two it is: the watching page says so in words, and the
207
        // answer differs — open the tab that plays, or keep the cookie.
208
        const why: Why = fresh ? "cookie" : "address";
209
        const upgraded = self.upgrade(request, { data: { session, playerId: "", address, token, spectator: true, why } });
210
        return upgraded ? undefined : new Response("expected a websocket", { status: 426, headers: SECURITY });
211
      }
212
      const name = cleanName(jar[NAME]) || `Guest-${session.slice(0, 4)}`;
213
      const player = takeSeat(address, session, name);
214
      if (!player) return new Response("no seats", { status: 503, headers: SECURITY });
215
      const upgraded = self.upgrade(request, {
216
        data: { session, playerId: player.id, address, token, spectator: false, why: "unsaid" },
217
      });
218
      return upgraded ? undefined : new Response("expected a websocket", { status: 426, headers: SECURITY });
219
    }
220
221
    if (url.pathname === "/" && (request.method === "GET" || request.method === "HEAD")) {
222
      const body = gamePage({
223
        state: match(),
224
        script: scriptUrl,
225
        name: cleanName(jar[NAME]),
226
        env: where,
227
        commit,
228
        ssh: process.env.FORGE_APP_SSH,
229
        results: recentResults(3),
230
      });
231
      const response = html(body, 200, fresh ? { "set-cookie": setCookie(SESSION, session, true) } : {});
232
      return request.method === "HEAD"
233
        ? new Response(null, { status: response.status, headers: response.headers })
234
        : response;
235
    }
236
237
    // The agents and their kits: what every ability does, its price and its
238
    // charges, so the buy panel can label itself. The same table the server
239
    // plays by, and no secret in it.
240
    if (url.pathname === "/agents.json" && (request.method === "GET" || request.method === "HEAD"))
241
      return Response.json(
242
        {
243
          agents: AGENTS.map((a) => ({
244
            id: a.id,
245
            name: a.name,
246
            role: a.role,
247
            blurb: a.blurb,
248
            abilities: Object.fromEntries(
249
              SLOTS.map((slot) => {
250
                const ability = a.abilities[slot];
251
                return [
252
                  slot,
253
                  {
254
                    name: ability.name,
255
                    cost: ability.cost,
256
                    charges: ability.charges,
257
                    cooldown: ability.cooldown,
258
                    points: ability.points,
259
                    text: ability.text,
260
                  },
261
                ];
262
              }),
263
            ),
264
          })),
265
        },
266
        { headers: { "cache-control": "public, max-age=300", ...SECURITY } },
267
      );
268
269
    // The map is the same for everybody and changes only when the code does.
270
    if (url.pathname === "/map.json" && (request.method === "GET" || request.method === "HEAD"))
271
      return Response.json(
272
        { rows: gridRows(), tile: TILE },
273
        { headers: { "cache-control": "public, max-age=300", ...SECURITY } },
274
      );
275
276
    if (url.pathname === scriptUrl)
277
      return new Response(scriptBody, {
278
        headers: {
279
          "content-type": "text/javascript; charset=utf-8",
280
          "cache-control": "public, max-age=31536000, immutable",
281
          ...SECURITY,
282
        },
283
      });
284
285
    // Files under ./static are served as they are, cached for a year: name
286
    // them by content and a change is a new name, never a stale cache. The
287
    // path is confined to the directory.
288
    if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) {
289
      const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1)));
290
      if (await file.exists())
291
        return new Response(file, {
292
          headers: { "cache-control": "public, max-age=31536000, immutable", ...SECURITY },
293
        });
294
    }
295
    return new Response("not found", { status: 404, headers: SECURITY });
296
  },
297
298
  websocket: {
299
    maxPayloadLength: 4 * 1024,
300
    open(socket) {
301
      const { session, playerId, address, token, spectator, why } = socket.data;
302
      if (spectator) return void watch(token, (data) => socket.send(data), why);
303
      attach(session, playerId, address, token, (data) => socket.send(data));
304
      socket.send(snapshot(playerId));
305
    },
306
    message(socket, raw) {
307
      if (socket.data.spectator) return; // a watcher has no seat to drive
308
      // Anything a client sends is a claim: it is parsed, bounded and given
309
      // to the arena, which decides what it is allowed to mean.
310
      if (typeof raw !== "string" || raw.length > 4096) return;
311
      let parsed: unknown;
312
      try {
313
        parsed = JSON.parse(raw);
314
      } catch {
315
        return;
316
      }
317
      if (typeof parsed !== "object" || parsed === null) return;
318
      command(socket.data.playerId, parsed as Command);
319
    },
320
    close(socket) {
321
      if (socket.data.spectator) return void unwatch(socket.data.token);
322
      release(socket.data.session, socket.data.token);
323
    },
324
  },
325
326
  // A bug answers with the floor and nothing else: never the runtime's own
327
  // error page, which carries source and paths, and never without the
328
  // headers. The detail goes to the log, where it belongs.
329
  error(error) {
330
    console.error(error);
331
    return html("<h1>Something went wrong</h1>", 500);
332
  },
333
});
334
335
startArena();
336
337
console.log(`val listening on http://${server.hostname}:${server.port} (${env})`);
338
export { findPlayer };
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts