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

forked from benjivers/val

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

Keyboard shortcuts