Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(cloud): fix ChromeEngine leaks, add SQLite WAL bounds and static ETag caching
milind-sonib9bc3f6b4260
diff --git a/server/browser/chrome/launch.ts b/server/browser/chrome/launch.tsindex 262705ffbe..a26d8e804e 100644--- a/server/browser/chrome/launch.ts+++ b/server/browser/chrome/launch.ts@@ -1,4 +1,5 @@import { execFile, spawn, type ChildProcess } from "node:child_process";+import { readFileSync } from "node:fs";import type { Readable, Writable } from "node:stream";import { spawnBotWork } from "../../oom-score.ts";@@ -99,6 +100,18 @@ function handshake(transport: CdpTransport, exited: Promise<ChromeExit>, timeout});}+function linuxStartTime(pid: number): string | null {+ if (process.platform !== "linux") return null;+ try {+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");+ const afterComm = stat.lastIndexOf(")");+ if (afterComm < 0) return null;+ return stat.slice(afterComm + 2).split(" ")[19] ?? null;+ } catch {+ return null;+ }+}+/** Starts Chrome on --remote-debugging-pipe (fd 3 to Chrome, fd 4 back) and waits until it answers. */export async function launchChrome(options: LaunchOptions): Promise<ChromeProcess> {const argv = chromeArgs({ ...options, smallShm: options.smallShm ?? devShmIsSmall() });@@ -128,7 +141,7 @@ export async function launchChrome(options: LaunchOptions): Promise<ChromeProcesconst transport = pipeTransport(child.stdio[3] as Writable, child.stdio[4] as Readable);let version: BrowserVersion;try {- if (pid !== undefined) options.registry?.add({ pid, startTime: null, userDataDir: options.userDataDir, ownerPid: process.pid, launchedAt: new Date().toISOString() });+ if (pid !== undefined) options.registry?.add({ pid, startTime: linuxStartTime(pid), userDataDir: options.userDataDir, ownerPid: process.pid, launchedAt: new Date().toISOString() });version = await handshake(transport, exited, options.handshakeTimeoutMs ?? 60_000);} catch (error) {killTree(child, "SIGKILL");diff --git a/server/browser/egress/registry.test.ts b/server/browser/egress/registry.test.tsindex 6650f30e98..d368dba70c 100644--- a/server/browser/egress/registry.test.ts+++ b/server/browser/egress/registry.test.ts@@ -278,4 +278,17 @@ describe("a session's gate once its browser has ended", () => {await egress.close();}});++ it("forgets cached port and pending notices when released with forget: true", async () => {+ const egress = new BrowserEgress();+ egress.configure({ host: "server", config: () => undefined });+ try {+ await egress.open("temp:ephemeral-1");+ await egress.release("temp:ephemeral-1", { forget: true });+ expect(egress.sessions()).toEqual([]);+ expect(egress.takeNotice("temp:ephemeral-1")).toBeNull();+ } finally {+ await egress.close();+ }+ });});diff --git a/server/browser/egress/registry.ts b/server/browser/egress/registry.tsindex 406a92ea7a..9c7030f856 100644--- a/server/browser/egress/registry.ts+++ b/server/browser/egress/registry.ts@@ -186,7 +186,12 @@ export class BrowserEgress {sessions(): string[] { return [...this.gates.keys()]; }/** Closes `session`'s listener: its browser has ended, so nothing connects through it until the next open. */- async release(session: string): Promise<void> {+ async release(session: string, options?: { forget?: boolean }): Promise<void> {+ if (options?.forget) {+ this.ports.delete(session);+ this.blocked.delete(session);+ this.toldAway.delete(session);+ }const gate = this.gates.get(session);if (!gate) return;this.gates.delete(session);diff --git a/server/browser/engines.ts b/server/browser/engines.tsindex a9b5770301..4f0f99fb2e 100644--- a/server/browser/engines.ts+++ b/server/browser/engines.ts@@ -53,6 +53,7 @@ export interface ChromeEngineOptions {env?: NodeJS.ProcessEnv;platform?: NodeJS.Platform;egressPort(key: string): Promise<number>;+ releaseEgress?(key: string, options?: { forget?: boolean }): Promise<void> | void;idleMs(): number;held?(session: string): boolean;egressNotice(key: string): string | null;@@ -136,6 +137,7 @@ export class ChromeEngine {idleMs: options.idleMs,held: options.held,egressNotice: options.egressNotice,+ ...(options.releaseEgress ? { releaseEgress: options.releaseEgress } : {}),...(options.log ? { log: options.log } : {}),});this.live = new LiveV1({ service: this.service, target: (session) => this.target(session) });diff --git a/server/browser/service.test.ts b/server/browser/service.test.tsindex a17e4a9693..3e42d8b391 100644--- a/server/browser/service.test.ts+++ b/server/browser/service.test.ts@@ -705,4 +705,28 @@ describe("browsers on one computer", () => {const { existsSync } = await import("node:fs");expect(existsSync(replacement.downloadDir)).toBe(true);});++ it("releases the profile's egress gate on close and drops closed temporary profiles from memory", async () => {+ const released: Array<{ key: string; forget?: boolean }> = [];+ const { service, call } = setup({+ releaseEgress: (key, options) => { released.push({ key, forget: options?.forget }); },+ });+ const temp = { session: "guest-1", key: "temp:guest-1" };+ await call("agent_browser_open", { url: "https://example.com/form" }, temp);+ expect(service.profiles().map((p) => p.key)).toEqual(["temp:guest-1"]);+ await service.close(temp.session);+ expect(service.profiles()).toHaveLength(0);+ expect(released).toEqual([{ key: "temp:guest-1", forget: true }]);+ });++ it("releases the profile's egress gate when Chrome exits unexpectedly", async () => {+ const released: Array<{ key: string; forget?: boolean }> = [];+ const { call, backend } = setup({+ releaseEgress: (key, options) => { released.push({ key, forget: options?.forget }); },+ });+ await call("agent_browser_open", { url: "https://example.com/form" });+ backend.chromes[0]!.exit("killed");+ await sleep(25);+ expect(released).toEqual([{ key: "bot:a", forget: false }]);+ });});diff --git a/server/browser/service.ts b/server/browser/service.tsindex f6768737aa..6787dab3b7 100644--- a/server/browser/service.ts+++ b/server/browser/service.ts@@ -6,7 +6,7 @@// Copyright (c) 2026 T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified: a Chrome per profile behind the// CDP driver instead of Playwright contexts, and OpenMausBot's idle close, caps and person/bot control rules.import { randomUUID } from "node:crypto";-import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";import { join } from "node:path";import { scrubHeldSecrets } from "../../shared/redact.ts";@@ -55,6 +55,8 @@ const STARTING_MARGIN_MS = 15_000;export const BROWSER_STARTING = "The browser is still starting (this computer is busy), so this call did not run. Call again in a moment: the next call uses the same browser once it is up.";const SERVER_TAB_LIMIT = 32;const PROFILE_TAB_LIMIT = 8;+const MAX_PROFILE_SCREENSHOTS = 50;+const MAX_CLOSED_TEMP_PROFILES = 32;export interface BrowserServiceOptions {dataDir: string;@@ -67,6 +69,8 @@ export interface BrowserServiceOptions {scrub?: (text: string) => string;/** What the egress gate of this profile's browser refused since it was last asked, as one line. */egressNotice?: (key: string) => string | null;+ /** Releases the loopback egress gate opened for this profile once its browser is no longer running. */+ releaseEgress?: (key: string, options?: { forget?: boolean }) => Promise<void> | void;onTiming?: (timing: BrowserTiming) => void;callBudgetMs?: number;laneWaitMs?: number;@@ -222,7 +226,13 @@ export class BrowserService {profile.fresh = false;rmSync(profile.downloadDir, { recursive: true, force: true });mkdirSync(profile.downloadDir, { recursive: true, mode: 0o700 });- const opened = await this.#options.backend(profile.key).open({ key: profile.key, mode: "headless", fresh, viewport: profile.hub.viewport(), downloadDir: profile.downloadDir });+ let opened: OpenedBrowser;+ try {+ opened = await this.#options.backend(profile.key).open({ key: profile.key, mode: "headless", fresh, viewport: profile.hub.viewport(), downloadDir: profile.downloadDir });+ } catch (error) {+ await Promise.resolve(this.#options.releaseEgress?.(profile.key, { forget: profile.temporary })).catch(() => undefined);+ throw error;+ }const run: Running = { opened, browser: opened.browser, offs: [], closing: false };const browser = opened.browser;const adopt = (page: CdpPage, origin: Tab["origin"]) => {@@ -281,6 +291,7 @@ export class BrowserService {run.closing = true;for (const off of run.offs) off();await opened.close().catch(() => undefined);+ await Promise.resolve(this.#options.releaseEgress?.(profile.key, { forget: profile.temporary })).catch(() => undefined);throw error;}profile.run = run;@@ -307,6 +318,7 @@ export class BrowserService {profile.run = null;profile.tabs.clear();if (run.closing) return;+ void Promise.resolve(this.#options.releaseEgress?.(profile.key, { forget: profile.temporary })).catch(() => undefined);try {rmSync(profile.downloadDir, { recursive: true, force: true });} catch (error) {@@ -343,10 +355,15 @@ export class BrowserService {if (profile.run === run) profile.run = null;profile.tabs.clear();if (reopened) profile.reopened = reopened;+ if (run || opening || erase) {+ await Promise.resolve(this.#options.releaseEgress?.(profile.key, { forget: erase || profile.temporary })).catch(() => undefined);+ }try {- if (erase) this.#erase(profile);- else if (profile.temporary) this.#eraseFiles(profile.key);- else rmSync(profile.downloadDir, { recursive: true, force: true });+ if (erase || (profile.temporary && !reopened)) this.#erase(profile);+ else if (profile.temporary) {+ this.#eraseFiles(profile.key);+ this.#pruneClosedTempProfiles();+ } else rmSync(profile.downloadDir, { recursive: true, force: true });} finally {profile.control.closing = false;profile.control.settle();@@ -374,6 +391,15 @@ export class BrowserService {for (const folder of ["downloads", "screenshots"]) rmSync(join(root, folder, hash), { recursive: true, force: true });}+ #pruneClosedTempProfiles(): void {+ const idleTemps = [...this.#profiles.values()].filter((p) => p.temporary && !p.run && !p.starting && !p.stopping && p.hub.size === 0);+ if (idleTemps.length <= MAX_CLOSED_TEMP_PROFILES) return;+ idleTemps.sort((a, b) => a.lastUsed - b.lastUsed);+ for (const stale of idleTemps.slice(0, idleTemps.length - MAX_CLOSED_TEMP_PROFILES)) {+ this.#profiles.delete(stale.key);+ }+ }+#unused(profile: ProfileState, idleMs: number): boolean {return profile.run !== null && !profile.starting && !profile.stopping && profile.calls === 0&& profile.control.owner === null && profile.control.agents === 0 && !this.#lanes.held(profile.key)@@ -586,9 +612,24 @@ export class BrowserService {try { host = new URL(pageUrl).hostname.replace(/[^a-z0-9]+/giu, "-").slice(0, 40) || "page"; } catch {}const path = join(folder, `browser-screenshot-${host}-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}.png`);writeFileSync(path, data, { mode: 0o600 });+ this.#pruneScreenshots(folder);return path;}+ #pruneScreenshots(folder: string): void {+ try {+ const names = readdirSync(folder).filter((name) => name.startsWith("browser-screenshot-") && name.endsWith(".png"));+ if (names.length <= MAX_PROFILE_SCREENSHOTS) return;+ const entries = names.map((name) => {+ const file = join(folder, name);+ try { return { file, mtimeMs: statSync(file).mtimeMs }; } catch { return { file, mtimeMs: 0 }; }+ }).sort((a, b) => a.mtimeMs - b.mtimeMs);+ for (const stale of entries.slice(0, entries.length - MAX_PROFILE_SCREENSHOTS)) {+ try { unlinkSync(stale.file); } catch {}+ }+ } catch {}+ }+async #openTab(profile: ProfileState, origin: Tab["origin"]): Promise<Tab> {const run = await this.running(profile);if (profile.tabs.list().length >= PROFILE_TAB_LIMIT) throw new Error(`This browser already has ${PROFILE_TAB_LIMIT} tabs open, the most it keeps. Close one with agent_browser_tabs first.`);diff --git a/server/burst/store.ts b/server/burst/store.tsindex a63671f9e4..305111a973 100644--- a/server/burst/store.ts+++ b/server/burst/store.ts@@ -76,7 +76,13 @@ export function openBurstStore(dataDir: string) {chmodSync(file, 0o600);}const db = new DatabaseSync(file);- db.exec("PRAGMA journal_mode = WAL");+ if (file !== ":memory:") {+ db.exec("PRAGMA busy_timeout = 5000");+ db.exec("PRAGMA journal_mode = WAL");+ db.exec("PRAGMA synchronous = NORMAL");+ db.exec("PRAGMA journal_size_limit = 67108864");+ db.exec("PRAGMA temp_store = MEMORY");+ }db.exec(SCHEMA);const rows = {insertBurst: db.prepare("INSERT INTO bursts (id, json, phase, created_at) VALUES (?, ?, ?, ?)"),diff --git a/server/host/browser.ts b/server/host/browser.tsindex f0dd46d71c..3bf75866d6 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -196,6 +196,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {host,...(paneLink ? { pane: { backend: new PaneBackend(paneLink, DATA_DIR, (key) => browserEgress.open(key), { identity: () => cfg.browserEngine?.paneIdentity ?? "native" }), wanted: () => browserPaneWanted(cfg) } } : {}),egressPort: (key) => browserEgress.open(key),+ releaseEgress: (key, options) => browserEgress.release(key, options),egressNotice: (key) => browserEgress.takeNotice(key),idleMs,language: deps.language,@@ -704,7 +705,15 @@ export function createBrowserHost(deps: BrowserHostDeps) {function browserOwners(): Array<{ pid: number; start?: string; session: string; botIds: string[]; kind: "browser" }> {return [...usedBrowserSessions].flatMap(([session, spec]) => {// A browser attached to the person's own Chrome is theirs, not a bot's.- if (chromeTarget(session, spec) || attachesToChrome(spec.env)) return [];+ if (attachesToChrome(spec.env)) return [];+ const target = chromeTarget(session, spec);+ if (target) {+ const profile = chromeEngine.service.profiles().find((p) => p.key === target.key);+ const pid = profile?.run?.opened.surface === "pane" ? null : (profile?.run?.opened.pid ?? null);+ if (!pid || pid <= 0) return [];+ const botIds = store.bots.filter((bot) => browserSessionsOf(bot.id, bot.browserProfile).includes(session)).map((bot) => bot.id);+ return [{ pid, session, botIds, kind: "browser" as const }];+ }let pid: number;try { pid = Number(readFileSync(browserDaemonFile(browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session }), ".pid"), "utf8").trim()); } catch { return []; }// Only a pid checked to run this session's daemon (the file may outlive it on a Cloud's volume): browser-daemons.ts.@@ -722,7 +731,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {for (const threadId of threadIds) {const browser = threadBrowser(threadId), botId = store.botByThread(threadId)?.id;const { session, spec } = browser ?? {};- if (session === undefined || !spec || chromeTarget(session, spec) || attachesToChrome(spec.env)) continue;+ if (session === undefined || !spec || attachesToChrome(spec.env)) continue;if (store.bots.some((other) => other.id !== botId && browserSessionsOf(other.id, other.browserProfile).includes(session))) continue;sessions.set(session, spec);}diff --git a/server/index.ts b/server/index.tsindex e8b24b6a66..d828aa3a78 100644--- a/server/index.ts+++ b/server/index.ts@@ -12408,7 +12408,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return;}// Two public routes come first; everything else needs the loopback owner or a paired session with the right scope.- if (method === "GET" && !path.startsWith("/api/") && !path.startsWith("/.well-known/") && (moveFreeze.screen(path) ? (res.writeHead(302, { location: moveFreeze.screen(path)!, "cache-control": "no-store" }).end(), true) : serveStatic(res, path, STATIC_DIR))) return;+ if (method === "GET" && !path.startsWith("/api/") && !path.startsWith("/.well-known/") && (moveFreeze.screen(path) ? (res.writeHead(302, { location: moveFreeze.screen(path)!, "cache-control": "no-store" }).end(), true) : serveStatic(res, path, STATIC_DIR, req))) return;if (method === "GET" && path === "/.well-known/openmausbot/environment") {return json(res, 200, environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !HOSTED_WORKSPACE && !CLOUD_HOME && emailSignIn.enabled(), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() }));}diff --git a/server/message-db.ts b/server/message-db.tsindex e0ff7b585d..175f27c9d9 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -46,8 +46,11 @@ function open(): DatabaseSync {chmodSync(file, 0o600);} catch {}const db = new DatabaseSync(file);+ db.exec("PRAGMA busy_timeout = 5000");db.exec("PRAGMA journal_mode = WAL");db.exec("PRAGMA synchronous = NORMAL");+ db.exec("PRAGMA journal_size_limit = 67108864");+ db.exec("PRAGMA temp_store = MEMORY");db.exec(`CREATE TABLE IF NOT EXISTS messages (thread_id TEXT NOT NULL,diff --git a/server/runtime/store.ts b/server/runtime/store.tsindex 1e1403c7cf..d1053ef4b6 100644--- a/server/runtime/store.ts+++ b/server/runtime/store.ts@@ -233,8 +233,11 @@ export function openRuntimeStore(path: string): RuntimeStore {}const db = new DatabaseSync(path);if (!memory) {+ db.exec("PRAGMA busy_timeout = 5000");db.exec("PRAGMA journal_mode = WAL");db.exec("PRAGMA synchronous = NORMAL");+ db.exec("PRAGMA journal_size_limit = 67108864");+ db.exec("PRAGMA temp_store = MEMORY");}db.exec(SCHEMA);diff --git a/server/static-files.test.ts b/server/static-files.test.tsindex f35904c794..bad68eb254 100644--- a/server/static-files.test.ts+++ b/server/static-files.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";import type { ServerResponse } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";@@ -13,13 +13,13 @@ mkdirSync(join(dir, "assets"));writeFileSync(join(dir, "assets", "rail-1a2b.js"), "js");afterAll(() => rmSync(dir, { recursive: true, force: true }));-function get(path: string, staticDir: string = dir) {- const answer: { status?: number; headers: Record<string, string>; body?: string } = { headers: {} };+function get(path: string, staticDir: string = dir, headers: Record<string, string> = {}) {+ const answer: { status?: number; headers: Record<string, string | number>; body?: string } = { headers: {} };const res = {- writeHead(status: number, headers: Record<string, string>) { answer.status = status; answer.headers = headers; return res; },- end(data: Buffer) { answer.body = String(data); },+ writeHead(status: number, h: Record<string, string | number>) { answer.status = status; answer.headers = h; return res; },+ end(data?: Buffer) { answer.body = data === undefined ? undefined : String(data); },} as unknown as ServerResponse;- return { served: serveStatic(res, path, staticDir), ...answer };+ return { served: serveStatic(res, path, staticDir, { headers }), ...answer };}describe("serveStatic", () => {@@ -27,6 +27,8 @@ describe("serveStatic", () => {const rail = get("/rail");expect(rail.body).toBe("rail");expect(rail.headers).toMatchObject({ "content-type": "text/html", "cache-control": "no-cache", "x-frame-options": "DENY" });+ expect(rail.headers.etag).toMatch(/^W\/"/);+ expect(rail.headers["content-length"]).toBe(4);});it("answers the app's paths with the app, and keeps hashed assets for good", () => {@@ -35,4 +37,26 @@ describe("serveStatic", () => {expect(get("/rail/more").body).toBe("app");expect(get("/assets/rail-1a2b.js").headers["cache-control"]).toBe("public, max-age=31536000, immutable");});++ it("returns 304 Not Modified when If-None-Match matches the current ETag, and refreshes after file updates", () => {+ const first = get("/");+ expect(first.status).toBe(200);+ const etag = String(first.headers.etag);++ const notModified = get("/", dir, { "if-none-match": etag });+ expect(notModified.served).toBe(true);+ expect(notModified.status).toBe(304);+ expect(notModified.body).toBeUndefined();+ expect(notModified.headers["cache-control"]).toBe("no-cache");++ const file = join(dir, "index.html");+ writeFileSync(file, "app-v2");+ const future = new Date(Date.now() + 5_000);+ utimesSync(file, future, future);++ const updated = get("/", dir, { "if-none-match": etag });+ expect(updated.status).toBe(200);+ expect(updated.body).toBe("app-v2");+ expect(updated.headers.etag).not.toBe(etag);+ });});diff --git a/server/static-files.ts b/server/static-files.tsindex ee2405b139..cf49a57c7b 100644--- a/server/static-files.ts+++ b/server/static-files.ts@@ -1,7 +1,7 @@// The desktop bundle served from OMB_STATIC_DIR: content types, cache rules and the SPA fallback.-import { readFileSync } from "node:fs";-import type { ServerResponse } from "node:http";-import { extname, join } from "node:path";+import { readFileSync, statSync } from "node:fs";+import type { IncomingMessage, ServerResponse } from "node:http";+import { extname, join, relative, resolve } from "node:path";const MIME: Record<string, string> = {".html": "text/html",@@ -24,28 +24,114 @@ const PAGE_HEADERS = { "content-security-policy": "frame-ancestors 'none'", "x-f/** 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);+ if (rel.startsWith("..") || 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): boolean {+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 = join(staticDir, safe);- try {- const data = readFileSync(file);+ 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;- res.writeHead(200, { "content-type": type, ...(type === "text/html" ? PAGE_HEADERS : {}), ...(cache ? { "cache-control": cache } : {}) });- res.end(data);- return true;- } catch {- // SPA fallback, never immutable: a missing chunk answered with the page must not stay cached under the chunk's URL.- try {- const data = readFileSync(join(staticDir, "index.html"));- res.writeHead(200, { "content-type": "text/html", "cache-control": "no-cache", ...PAGE_HEADERS });- res.end(data);- return true;- } catch {- return false;- }+ 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);}