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

forked from benjivers/val

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

Keyboard shortcuts