benjivers/val Public Public: anyone can read this; the crew can change it.

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

Keyboard shortcuts