benjivers/notes Public Public: anyone can read this; nobody can change it.

Files 6f31b533b13d96cd4b38d39bc59da84ada17375b
88 lines · 3.0 KB · ~869 tok Raw History
1
/**
2
 * The process the forge runs. `serve` opens the database and listens:
3
 * every request gets the floor (`http.ts`), an identity (`who.ts`), the
4
 * door (`security.ts`) and one route (`routes.ts`) — so a request from
5
 * another site, from someone going too fast, or from someone the contract
6
 * turns away is refused before a byte of it is read. Run directly, it
7
 * serves what the forge said; a test calls `serve` with its own.
8
 */
9
10
import { openDb } from "./db.ts";
11
import { dataDir, identityKey, title, where } from "./env.ts";
12
import { sessionWho } from "./accounts.ts";
13
import { html, readCookie, text } from "./http.ts";
14
import { SESSION_COOKIE } from "./routes.ts";
15
import { match } from "./routes.ts";
16
import { door } from "./security.ts";
17
import { who } from "./who.ts";
18
19
export interface ServeOptions {
20
  readonly port: number;
21
  readonly hostname?: string | undefined;
22
  readonly dataDir: string;
23
  readonly identityKey: string;
24
}
25
26
export function serve(options: ServeOptions) {
27
  const db = openDb(options.dataDir);
28
  return Bun.serve({
29
    port: options.port,
30
    hostname: options.hostname ?? "127.0.0.1",
31
    // A connection that says nothing for a minute is dropped. The event
32
    // stream heartbeats every 25 seconds to stay well inside that.
33
    idleTimeout: 60,
34
    async fetch(request, server) {
35
      const url = new URL(request.url);
36
      // The forge's signed word first; else the app's own session, if any.
37
      const signed = who(request, options.identityKey);
38
      const me =
39
        signed.role === "anon" ? sessionWho(db, readCookie(request, SESSION_COOKIE)) : signed;
40
      const refused = door(
41
        db,
42
        request,
43
        url,
44
        me,
45
        server.requestIP(request)?.address ?? "?",
46
      );
47
      if (refused !== undefined) return head(request, refused);
48
      const found = match(
49
        request.method === "HEAD" ? "GET" : request.method,
50
        url.pathname,
51
      );
52
      if (found === undefined) return text("not found", 404);
53
      const response = await found.route.handle({
54
        request,
55
        url,
56
        db,
57
        who: me,
58
        params: found.params,
59
      });
60
      return head(request, response);
61
    },
62
    // A bug answers with the floor and nothing else: never the runtime's
63
    // own error page, which carries source and paths, and never without
64
    // the headers. The detail goes to the log, where it belongs.
65
    error(error) {
66
      console.error(error);
67
      return html("<h1>Something went wrong</h1>", 500);
68
    },
69
  });
70
}
71
72
// HEAD is GET without the body: a health check sees the app up.
73
const head = (request: Request, response: Response): Response =>
74
  request.method === "HEAD"
75
    ? new Response(null, { status: response.status, headers: response.headers })
76
    : response;
77
78
if (import.meta.main) {
79
  const server = serve({
80
    port: Number(process.env.PORT ?? 8080),
81
    hostname: process.env.HOST,
82
    dataDir,
83
    identityKey,
84
  });
85
  console.log(
86
    `${title} listening on http://${server.hostname}:${server.port} (${where})`,
87
  );
88
}
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts