SPB Git

Repository Public

index.ts 7.9 KB 186 lines typescript

1import Fastify from "fastify"2import cookie from "@fastify/cookie"3import fastifyStatic from "@fastify/static"4import fs from "node:fs"5import path from "node:path"6import { WebSocketServer } from "ws"7import { adminRoutes } from "./admin.js"8import { authRoutes } from "./auth.js"9import { config, cookieName } from "./config.js"10import { migrate, sql } from "./db.js"11import { fileRoutes, janitor } from "./files.js"12import { hub, memberIds, peersOf, type Conn } from "./hub.js"13import { messagingRoutes } from "./messaging.js"14import { authFromToken } from "./session.js"15import { HttpError, rateLimit } from "./util.js"1617const app = Fastify({18  trustProxy: config.trustProxy,19  bodyLimit: 6 * 1024 * 1024,20  // Request logging records method, path and status only: never bodies, cookies or query strings.21  logger: {22    level: process.env.SPM_LOG_LEVEL ?? "info",23    serializers: {24      req: (r) => ({ method: r.method, url: String(r.url).split("?")[0], ip: r.ip }),25      res: (r) => ({ status: r.statusCode }),26    },27  },28})2930await app.register(cookie)31app.addContentTypeParser("application/octet-stream", { parseAs: "buffer" }, (_req, body, done) => done(null, body))3233const wsOrigin = config.origin.replace(/^http/, "ws")34const csp = [35  "default-src 'self'",36  "script-src 'self' 'wasm-unsafe-eval'",37  "style-src 'self' 'unsafe-inline'",38  "img-src 'self' blob: data:",39  "media-src 'self' blob:",40  `connect-src 'self' ${wsOrigin}`,41  "worker-src 'self' blob:",42  "font-src 'self'",43  "object-src 'none'",44  "base-uri 'none'",45  "form-action 'self'",46  "frame-ancestors 'none'",47].join("; ")4849app.addHook("onRequest", async (req, reply) => {50  reply.header("content-security-policy", csp)51  reply.header("x-content-type-options", "nosniff")52  reply.header("x-frame-options", "DENY")53  reply.header("referrer-policy", "no-referrer")54  reply.header("cross-origin-opener-policy", "same-origin")55  reply.header("cross-origin-resource-policy", "same-origin")56  reply.header("permissions-policy", "camera=(self), microphone=(self), display-capture=(self), geolocation=(), payment=(), usb=()")57  reply.header("x-robots-tag", "noindex, nofollow")58  if (config.secureCookies) reply.header("strict-transport-security", "max-age=63072000; includeSubDomains")59  if (req.url.startsWith("/api/")) {60    reply.header("cache-control", "no-store")61    rateLimit(`global:${req.ip}`, 1500, 60_000)62    // CSRF: the session cookie is SameSite=Strict, and every state-changing request must also come63    // from this origin and carry a header that a cross-site form cannot set.64    if (req.method !== "GET" && req.method !== "HEAD") {65      const origin = req.headers.origin66      if (origin !== config.origin || req.headers["x-spm"] !== "1") throw new HttpError(403, "csrf", "Cross-origin request refused")67    }68  }69})7071app.setErrorHandler((err: Error & { statusCode?: number; code?: string }, req, reply) => {72  if (err instanceof HttpError) return reply.status(err.status).send({ error: err.code, message: err.message })73  if (err.statusCode && err.statusCode < 500) return reply.status(err.statusCode).send({ error: err.code ?? "bad_request", message: err.message })74  req.log.error({ err: { message: err.message, stack: err.stack } }, "unhandled error")75  return reply.status(500).send({ error: "internal", message: "Internal error" })76})7778app.get("/api/health/live", async () => ({ ok: true }))79app.get("/api/health/ready", async (_req, reply) => {80  try {81    await sql`select 1`82    await fs.promises.access(config.dataDir, fs.constants.W_OK)83    return { ok: true, version: process.env.SPM_VERSION ?? "dev", connections: hub.connections() }84  } catch {85    return reply.status(503).send({ ok: false })86  }87})8889authRoutes(app)90adminRoutes(app)91messagingRoutes(app)92fileRoutes(app)9394// Lets the native Apple apps use the same passkeys as the web application (Associated Domains).95app.get("/.well-known/apple-app-site-association", async (_req, reply) =>96  reply.type("application/json").header("cache-control", "public, max-age=3600").send(JSON.stringify({ webcredentials: { apps: config.appleAppIds } })))9798app.get("/robots.txt", async (_req, reply) => reply.type("text/plain").send("User-agent: *\nDisallow: /\n"))99100if (fs.existsSync(config.webDir)) {101  await app.register(fastifyStatic, {102    root: config.webDir,103    wildcard: false,104    setHeaders(res, p) {105      if (p.includes(`${path.sep}assets${path.sep}`)) res.header("cache-control", "public, max-age=31536000, immutable")106      else res.header("cache-control", "no-cache")107    },108  })109  const index = fs.readFileSync(path.join(config.webDir, "index.html"))110  app.setNotFoundHandler((req, reply) => {111    if (req.url.startsWith("/api/") || req.method !== "GET") return reply.status(404).send({ error: "not_found" })112    return reply.header("cache-control", "no-cache").type("text/html").send(index)113  })114}115116// ---------------- WebSocket gateway ----------------117const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 })118const typingCache = new Map<string, { at: number; members: string[] }>()119120app.server.on("upgrade", async (req, socket, head) => {121  const refuse = (code: string) => {122    socket.write(`HTTP/1.1 ${code}\r\nConnection: close\r\n\r\n`)123    socket.destroy()124  }125  try {126    if (!req.url?.startsWith("/ws")) return refuse("404 Not Found")127    if (req.headers.origin !== config.origin) return refuse("403 Forbidden")128    const token = app.parseCookie(req.headers.cookie ?? "")[cookieName]129    const auth = await authFromToken(token)130    if (!auth || auth.status !== "active") return refuse("401 Unauthorized")131    wss.handleUpgrade(req, socket, head, (ws) => {132      const conn: Conn = { ws, userId: auth.userId, deviceId: auth.deviceId, sessionId: auth.sessionId, alive: true }133      const wasOnline = hub.online(auth.userId)134      hub.add(conn)135      ws.send(JSON.stringify({ t: "hello", server_time: Date.now() }))136      if (!wasOnline) void presence(auth.userId, true)137      ws.on("pong", () => (conn.alive = true))138      ws.on("message", (raw) => void onMessage(conn, raw.toString()).catch(() => {}))139      ws.on("close", () => {140        hub.remove(conn)141        if (!hub.online(conn.userId)) void presence(conn.userId, false)142      })143      ws.on("error", () => ws.terminate())144    })145  } catch {146    refuse("500 Internal Server Error")147  }148})149150async function presence(userId: string, online: boolean) {151  const [u] = await sql`select presence_opt_in from users where id = ${userId}`152  if (!u?.presence_opt_in) return153  hub.toUsers((await peersOf(userId)).filter((p) => p !== userId), { t: "presence", user: userId, online })154}155156async function onMessage(conn: Conn, raw: string) {157  rateLimit(`ws:${conn.sessionId}`, 240, 60_000)158  const msg = JSON.parse(raw) as { t?: string; conversation?: string; on?: boolean }159  if (msg.t === "ping") return conn.ws.send('{"t":"pong"}')160  if (msg.t === "typing" && typeof msg.conversation === "string" && /^[0-9a-f-]{36}$/.test(msg.conversation)) {161    let c = typingCache.get(msg.conversation)162    if (!c || Date.now() - c.at > 30_000) typingCache.set(msg.conversation, (c = { at: Date.now(), members: await memberIds(msg.conversation) }))163    if (!c.members.includes(conn.userId)) return164    hub.toUsers(c.members.filter((m) => m !== conn.userId), { t: "typing", conversation: msg.conversation, user: conn.userId, on: msg.on !== false })165  }166}167168setInterval(() => {169  for (const ws of wss.clients) ws.ping()170}, 25_000).unref()171172await fs.promises.mkdir(path.join(config.dataDir, "blobs"), { recursive: true })173await migrate((m) => app.log.info(m))174await app.listen({ port: config.port, host: config.host })175const runJanitor = () => janitor((m) => app.log.info(m)).catch((e) => app.log.error({ err: { message: (e as Error).message } }, "janitor failed"))176setTimeout(runJanitor, 5_000).unref()177setInterval(runJanitor, 10 * 60_000).unref()178179for (const sig of ["SIGTERM", "SIGINT"] as const)180  process.on(sig, async () => {181    for (const ws of wss.clients) ws.close(1001, "server restarting")182    await app.close()183    await sql.end({ timeout: 5 })184    process.exit(0)185  })186
Files main
Menu

Theme