import { randomBytes, timingSafeEqual } from "node:crypto"; import { serveStatic } from "@hono/node-server/serve-static"; import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; import { Hono } from "hono"; import { cors } from "hono/cors"; import { chatbotRouter } from "./chatbot-router.js"; import { createContext } from "./context.js"; import { diagramsRouter } from "./diagrams-router.js"; import { docsRouter } from "./docs-router.js"; import { googleAuthRouter } from "./google-auth-router.js"; import { healthRouter } from "./health-router.js"; import { discoverAllProviders } from "./lib/ai-router.js"; import { ensureDatabase, getMigrationOutcome } from "./lib/db-init.js"; import { env } from "./lib/env.js"; import { logger as appLogger } from "./lib/logger.js"; import { initRedis } from "./lib/rate-limiter.js"; import { maintenanceRouter } from "./maintenance-router.js"; import { securityMiddleware } from "./middleware/security.js"; import { paymobWebhook, paymobWebhookAlias } from "./paymob-webhook.js"; import { promoRouter } from "./promo-router.js"; import { appRouter } from "./router.js"; /** * Build ID — loaded from build-id.json at startup. * Changes on every deploy, used by cache-nuke.js to detect new versions. * Falls back to a runtime-generated ID if the file doesn't exist (dev mode). */ let buildId: string | null = null; // Version is captured from build-id.json (written at BUILD time by // vite.config.ts buildIdPlugin). Reading process.env.npm_package_version // at runtime returns "unknown" inside the Docker container — the server // runs via node/tsx, outside any npm-script context. let buildVersion: string | null = null; async function loadBuildId() { try { const { readFile } = await import("node:fs/promises"); const content = await readFile("./dist/public/build-id.json", "utf-8"); const data = JSON.parse(content); buildId = data.buildId; buildVersion = typeof data.version === "string" && data.version !== "unknown" ? data.version : null; appLogger.info(`[Server] Build ID loaded: ${buildId} (version ${buildVersion ?? "n/a"})`); } catch { // Fallback for dev mode or if build-id.json is missing buildId = `runtime-${randomBytes(4).toString("hex")}`; appLogger.info(`[Server] No build-id.json found, using runtime ID: ${buildId}`); } } import { buildRobotsTxt } from "./lib/seo-meta.js"; import { createSpaHandler } from "./lib/spa-handler.js"; import { cacheMiddleware } from "./middleware/cache.js"; declare const Bun: { serve: (opts: { fetch: (r: Request) => Response | Promise; port?: number; hostname?: string }) => { close: (cb?: () => void) => void } } | undefined; type AppVariables = { cspNonce: string; requestId: string; }; import { approvalActionRoute } from "./approval-action-route.js"; import { startYoutubeWatcher, stopYoutubeWatcher } from "./lib/youtube-watcher.js"; import { shieldMiddleware } from "./middleware/shield.js"; import { notificationRoute } from "./notification-route.js"; const app = new Hono<{ Variables: AppVariables }>({ strict: false }); // ✅ SECURITY FIX (audit run-1, request-logger.full-url): hono's default // logger prints the full URL including the query string — and reset/verify // tokens, OAuth codes and payment HMACs travel in query strings. Log the // path only; credential material never enters the log stream. app.use("*", async (c, next) => { const method = c.req.method; const path = c.req.path; const start = Date.now(); await next(); const status = c.res.status; if (path.startsWith("/api/")) { appLogger.info(`${method} ${path}`, { status, ms: Date.now() - start }); } }); app.use("*", shieldMiddleware); // 🛡️ Elite Shield: First line of defense app.use("*", securityMiddleware); const corsOrigins = env.CORS_ORIGINS ? env.CORS_ORIGINS.split(",").map((o) => o.trim()) : [env.FRONTEND_URL]; // ✅ SECURITY FIX (pre-launch audit run-2, cors.wildcard-guard): CORS runs // with credentials:true, where a wildcard origin would let ANY site read // authenticated responses. A literal "*" entry in the array form is inert in // hono (exact-match), but silently breaks the whole SPA; and a future // refactor to a dynamic origin function could turn it into a real hole. // Strip wildcards at boot and say so loudly. const wildcardOrigins = corsOrigins.filter((o) => o === "*"); if (wildcardOrigins.length > 0) { appLogger.error("[Boot] CORS_ORIGINS contains a wildcard \"*\" — removed. credentials:true forbids wildcards; list exact origins instead.", { count: wildcardOrigins.length }); } const safeCorsOrigins = corsOrigins.filter((o) => o && o !== "*"); if (safeCorsOrigins.length === 0 && corsOrigins.length > 0) { appLogger.error("[Boot] CORS_ORIGINS was ONLY wildcards — falling back to FRONTEND_URL"); } const finalCorsOrigins = safeCorsOrigins.length > 0 ? safeCorsOrigins : [env.FRONTEND_URL]; // ✅ SESSION PERSISTENCE FIX (Capacitor/Electron apps): the shipped Android // WebView runs on https://localhost and the desktop shell on file:// (Origin // "null") — without these in the allowlist every APK request died at CORS // preflight (x-capacitor-platform is a custom header → OPTIONS check) and the // app could neither log in nor keep a session. const NATIVE_APP_ORIGINS = [ "https://localhost", // Capacitor Android WebView "http://localhost", // Capacitor Android cleartext (capacitor.config server.cleartext) "capacitor://localhost", // Capacitor iOS // ✅ SECURITY FIX (pre-launch audit): "null" (Electron file:// opaque origin) // was REMOVED from the CORS allowlist. Since the session-persistence fix, // Electron production loads the LIVE site (first-party origin, allowlisted // via FRONTEND_URL) — file:// is only an offline fallback where no API calls // are possible anyway. Keeping "null" allowed any website to embed a // sandboxed