Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

5.1 KB
Raw Blame
// The desktop bundle served from OMB_STATIC_DIR: content types, cache rules and the SPA fallback.
import { readFileSync, statSync } from "node:fs";
import type { IncomingMessage, ServerResponse } from "node:http";
import { extname, isAbsolute, join, relative, resolve } from "node:path";

const MIME: Record<string, string> = {
  ".html": "text/html",
  ".js": "text/javascript",
  ".css": "text/css",
  ".txt": "text/plain; charset=utf-8",
  ".svg": "image/svg+xml",
  ".png": "image/png",
  ".ico": "image/x-icon",
  ".json": "application/json",
  ".webmanifest": "application/manifest+json",
  ".woff2": "font/woff2",
  ".webp": "image/webp",
  ".mp4": "video/mp4",
};

/** Never framed (a hidden frame could act on a pair or sign-in page unseen), and no Referer. */
const PAGE_HEADERS = { "content-security-policy": "frame-ancestors 'none'", "x-frame-options": "DENY", "referrer-policy": "no-referrer" } as const;

/** Pages with an entry of their own: the app, and the desktop window's rail of places. */
const PAGES: Record<string, string> = { "/": "/index.html", "/rail": "/rail.html" };

/** Bounded stat-validated cache for small hot files (SPA HTML shells & small assets) to avoid repeated blocking reads. */
const MAX_CACHED_FILE_BYTES = 512 * 1024;
const MAX_CACHE_TOTAL_BYTES = 4 * 1024 * 1024;
const MAX_CACHE_ENTRIES = 64;

interface CachedFile {
  readonly data: Buffer;
  readonly mtimeMs: number;
  readonly size: number;
  readonly etag: string;
}

const fileCache = new Map<string, CachedFile>();
let cachedBytes = 0;

function readCachedFile(file: string): { data: Buffer; etag: string } | null {
  let stat;
  try {
    stat = statSync(file);
  } catch {
    return null;
  }
  if (!stat.isFile()) return null;
  const mtimeMs = Math.trunc(stat.mtimeMs);
  const etag = `W/"${stat.size.toString(16)}-${mtimeMs.toString(16)}"`;
  const hit = fileCache.get(file);
  if (hit && hit.size === stat.size && hit.mtimeMs === mtimeMs) {
    // Refresh LRU order.
    fileCache.delete(file);
    fileCache.set(file, hit);
    return { data: hit.data, etag: hit.etag };
  }
  const data = readFileSync(file);
  if (data.length <= MAX_CACHED_FILE_BYTES) {
    if (hit) {
      cachedBytes -= hit.data.length;
      fileCache.delete(file);
    }
    while (fileCache.size >= MAX_CACHE_ENTRIES || cachedBytes + data.length > MAX_CACHE_TOTAL_BYTES) {
      const oldestKey = fileCache.keys().next().value;
      if (oldestKey === undefined) break;
      const oldest = fileCache.get(oldestKey)!;
      cachedBytes -= oldest.data.length;
      fileCache.delete(oldestKey);
    }
    fileCache.set(file, { data, mtimeMs, size: stat.size, etag });
    cachedBytes += data.length;
  }
  return { data, etag };
}

function resolveInside(root: string, target: string): string | null {
  const base = resolve(root);
  const full = resolve(base, target.replace(/^\/+/, ""));
  const rel = relative(base, full);
  // isAbsolute: on Windows a path naming another drive ("/D:/x") resolves outside, and relative() returns it whole.
  if (rel.startsWith("..") || isAbsolute(rel) || rel.includes("\0")) return null;
  return full;
}

function etagMatches(ifNoneMatch: string | string[] | undefined, etag: string): boolean {
  if (!ifNoneMatch) return false;
  const header = Array.isArray(ifNoneMatch) ? ifNoneMatch.join(",") : ifNoneMatch;
  if (header.trim() === "*") return true;
  return header.split(",").some((part) => part.trim() === etag);
}

function sendStatic(
  res: ServerResponse,
  file: string,
  cache: string | null,
  req?: Pick<IncomingMessage, "headers">,
): boolean {
  const loaded = readCachedFile(file);
  if (!loaded) return false;
  const type = MIME[extname(file)] ?? "application/octet-stream";
  const headers: Record<string, string | number> = {
    "content-type": type,
    etag: loaded.etag,
    ...(type === "text/html" ? PAGE_HEADERS : {}),
    ...(cache ? { "cache-control": cache } : {}),
  };
  if (etagMatches(req?.headers["if-none-match"], loaded.etag)) {
    res.writeHead(304, headers);
    res.end();
    return true;
  }
  headers["content-length"] = loaded.data.length;
  res.writeHead(200, headers);
  res.end(loaded.data);
  return true;
}

/** Public by design: the same bundle anyone can download, with no secrets, and /pair must load before a session exists. */
export function serveStatic(
  res: ServerResponse,
  path: string,
  staticDir: string | null,
  req?: Pick<IncomingMessage, "headers">,
): boolean {
  if (!staticDir) return false;
  const safe = PAGES[path] ?? path.replace(/\.\./g, "");
  const file = resolveInside(staticDir, safe);
  if (file) {
    const type = MIME[extname(file)] ?? "application/octet-stream";
    // Vite content-hashes every file under /assets/, so those URLs are immutable while public/ has no assets/ dir.
    const cache = type === "text/html" ? "no-cache" : safe.startsWith("/assets/") ? "public, max-age=31536000, immutable" : null;
    if (sendStatic(res, file, cache, req)) return true;
  }
  // SPA fallback, never immutable: a missing chunk answered with the page must not stay cached under the chunk's URL.
  return sendStatic(res, join(staticDir, "index.html"), "no-cache", req);
}