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

forked from benjivers/val

workbenchthis machine
Files ad62f806cbbb0d37daa89167b8c4dd87c1d77999
337 lines · 13.6 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 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
  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
// The security floor every response stands on. Scripts and styles come from
38
// this origin (inline styles allowed, inline scripts not), nothing frames us,
39
// browsers never guess a content type, and referrers stay on this site.
40
// The app's public address is what the forge told us, never the socket's.
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
  // Once served over https, always: browsers remember for a year.
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
// A browser on another site can make a person's browser POST here; it cannot
58
// make that request look same-origin. Browsers say where a request came from
59
// (Sec-Fetch-Site, or Origin); a request that names another site is refused.
60
// The address the forge published is the one that counts, but a browser
61
// reaching the app by another name (localhost, an IP, a tunnel) sends that
62
// host in both the URL and the Origin — a cross-site request never can.
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
// A request body is read up to a cap and no further, counting the bytes as
71
// they arrive. A declared Content-Length is a claim: a chunked request has
72
// none, and a lie is free. Undefined means "too large" — refuse it. Past the
73
// cap the rest is drained and dropped so the connection stays usable for
74
// the next request; past eight times the cap it is cut off instead.
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
// The form fields of a capped body, decoded the way the browser sent them
108
// (a plain form or a multipart one), by handing the bytes back to a Request.
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
// ------------------------------------------------------------- the client
120
121
// The client is a handful of small modules under static/ — the renderer, the
122
// map, the crosshair, the ray maths — bundled into one file at start-up so a
123
// browser makes one request and the maths can still be imported by the tests.
124
// It is named by its content: a change is a new URL, so a year-long cache is
125
// never stale.
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
// ------------------------------------------------------------- sessions
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
/** A name is one line of plain text, sixteen characters, nothing clever. */
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
// ---------------------------------------------------------------- routing
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
    // A cookie costs one HTTP request, so it names a browser, not a person —
175
    // the address is the one thing here a single machine cannot mint a
176
    // second one of, which is what a playing seat is actually rationed by.
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
    // The socket: one playing seat per address, taken from a bot where it
196
    // stands. A connection with no session the page minted, or one whose
197
    // address already plays under a different session, gets no seat at all —
198
    // it watches instead, with a view built for no side, rather than being
199
    // handed the vision a seat would otherwise give it on top of the one it
200
    // already has.
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
        // Which of the two it is: the watching page says so in words, and the
206
        // answer differs — open the tab that plays, or keep the cookie.
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
    // The agents and their kits: what every ability does, its price and its
237
    // charges, so the buy panel can label itself. The same table the server
238
    // plays by, and no secret in it.
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
    // The map is the same for everybody and changes only when the code does.
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
    // Files under ./static are served as they are, cached for a year: name
285
    // them by content and a change is a new name, never a stale cache. The
286
    // path is confined to the directory.
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; // a watcher has no seat to drive
307
      // Anything a client sends is a claim: it is parsed, bounded and given
308
      // to the arena, which decides what it is allowed to mean.
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
  // A bug answers with the floor and nothing else: never the runtime's own
326
  // error page, which carries source and paths, and never without the
327
  // headers. The detail goes to the log, where it belongs.
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 };
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts