Spaces:
Running
Running
Download api/boot.ts from ahmdelbaz28/AHMDRTAP: direct link, hf CLI and curl.
- Browser
- Download file 33 kB
-
https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP/resolve/main/api/boot.ts
- Command line
-
hf download hf://spaces/ahmdelbaz28/AHMDRTAP/api/boot.ts
-
curl -L -o boot.ts https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP/resolve/main/api/boot.ts
33 kB
| 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<Response>; 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 <iframe sandbox> whose fetches send Origin: null and read | |
| // authenticated responses (cookie SameSite=None + credentials:true). | |
| // Desktop/native shells use the x-auth-token Bearer path (context.ts), so | |
| // they never relied on ambient cookies for API access. | |
| ]; | |
| for (const o of NATIVE_APP_ORIGINS) { | |
| if (!finalCorsOrigins.includes(o)) finalCorsOrigins.push(o); | |
| } | |
| app.use( | |
| "*", | |
| cors({ | |
| origin: finalCorsOrigins, | |
| allowMethods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"], | |
| allowHeaders: [ | |
| "Content-Type", | |
| "Authorization", | |
| "X-Auth-Token", | |
| "X-Request-ID", | |
| // NOTE: X-Forwarded-For deliberately NOT allowed — clients must never | |
| // set forwarding headers; IP extraction uses cf-connecting-ip and the | |
| // proxy-set XFF only (see api/lib/client-ip.ts). | |
| "X-Capacitor-Platform", // ✅ native app marker sent on every APK request | |
| ], | |
| exposeHeaders: ["X-Request-ID", "X-Renewed-Token"], | |
| maxAge: 86400, | |
| credentials: true, | |
| }) | |
| ); | |
| // ── Health endpoints at /api/health, /api/ready, /api/live ── | |
| app.route("/api", healthRouter); | |
| app.route("/api", maintenanceRouter); | |
| app.route("/api", diagramsRouter); | |
| // ── Chat document exports (docgen skill): PDF / DOCX / MD from a validated | |
| // DocSpec — stateless, zero storage, deterministic (see api/docs-router.ts). | |
| app.route("/api", docsRouter); | |
| app.route("/api/promo", promoRouter); | |
| app.route("/api/paymob", paymobWebhook); | |
| // ── YouTube playlist ingest at /api/yt-sync/* — GitHub Actions (clean | |
| // egress) pushes verbatim playlist rows; HMAC-gated, fail-closed without | |
| // SYNC_INGEST_SECRET. Feeds the SAME applyPlaylistSync engine as the | |
| // watcher tick (see yt-sync-ingest.ts for the why). ── | |
| import { ytSyncIngestRoute } from "./yt-sync-ingest.js"; | |
| app.route("/api/yt-sync", ytSyncIngestRoute); | |
| // Legacy account-level callback URLs registered in the Paymob dashboard | |
| // (Transaction Processed + browser Response callbacks) — same HMAC-verified | |
| // handler; required by the mobile-wallet classic checkout flow. | |
| app.route("/api/webhooks/paymob", paymobWebhookAlias); | |
| app.route("/api/chatbot", chatbotRouter); | |
| app.route("/api/google-auth", googleAuthRouter); | |
| // ── BYOK (bring-your-own-key) management for the chatbot key menu ── | |
| import { userAiProviderRouter } from "./user-ai-provider-router.js"; | |
| app.route("/api/user-ai-provider", userAiProviderRouter); | |
| // ✅ ADMIN APPROVAL GATE (owner directive, 2026-11-24): signed one-time | |
| // approve/reject links from the registration alert email. | |
| app.route("/api/approval", approvalActionRoute); | |
| // ── Notification polling (bell + YouTube episode watcher) at /api/notifications/* ── | |
| app.route("/api/notifications", notificationRoute); | |
| // ── Web Push subscriptions (closed-tab browser notifications) at | |
| // /api/notifications/push/* — public-key / subscribe / unsubscribe ── | |
| import { pushSubscriptionRoute } from "./push-subscription-route.js"; | |
| app.route("/api/notifications/push", pushSubscriptionRoute); | |
| // ── tRPC handler at /api/trpc ── | |
| // Authentication is handled per-procedure (publicQuery vs authedQuery) | |
| app.all("/api/trpc/*", (c) => { | |
| return fetchRequestHandler({ | |
| router: appRouter, | |
| req: c.req.raw, | |
| endpoint: "/api/trpc", | |
| createContext: createContext as never, | |
| // Without onError, tRPC 500s are masked by the errorFormatter and the | |
| // logs show only "status 500" with NO cause — undiagnosable. Every | |
| // internal error now lands in the log stream with its stack. | |
| onError: ({ error, path, type }) => { | |
| appLogger.error("[tRPC] request failed", { | |
| path, | |
| type, | |
| message: error.message, | |
| stack: error.stack?.slice(0, 800), | |
| cause: error.cause instanceof Error ? error.cause.message : String(error.cause ?? ""), | |
| }); | |
| }, | |
| }); | |
| }); | |
| // ── API version endpoint (used by cache-nuke.js for cache invalidation) ── | |
| // Returns buildId which changes on every deploy, triggering cache clear. | |
| app.get("/api/version", (c) => { | |
| return c.json({ | |
| version: buildVersion ?? process.env.npm_package_version ?? "unknown", | |
| buildId: buildId ?? "unknown", | |
| stage: env.NODE_ENV, | |
| timestamp: new Date().toISOString(), | |
| }); | |
| }); | |
| // ── Public env endpoint (used by frontend to get GOOGLE_CLIENT_ID, etc.) ── | |
| // Dedicated endpoint so the frontend doesn't have to parse /api/health. | |
| // Returns only safe, public keys — never secrets. | |
| app.get("/api/env", async (c) => { | |
| const { getPublicEnvKeys } = await import("./lib/env.js"); | |
| return c.json(getPublicEnvKeys()); | |
| }); | |
| // ── robots.txt — declares sitemap + blocks private areas ── | |
| // Previously MISSING (404): Google had no crawl directives and no sitemap | |
| // pointer. Served with long-lived cache headers. | |
| app.get("/robots.txt", (c) => { | |
| c.header("Content-Type", "text/plain; charset=UTF-8"); | |
| c.header("Cache-Control", "public, max-age=3600"); | |
| return c.body(buildRobotsTxt()); | |
| }); | |
| // ── Dynamic Sitemap ── | |
| // Generates sitemap.xml from live DB data so URLs + lastmod are always accurate. | |
| // Cached for 1 hour to avoid DB query on every request. | |
| let cachedSitemap: string | null = null; | |
| let sitemapExpiry = 0; | |
| export function invalidateSitemapCache(): void { | |
| cachedSitemap = null; | |
| sitemapExpiry = 0; | |
| } | |
| app.get("/sitemap.xml", async (c) => { | |
| if (cachedSitemap && Date.now() < sitemapExpiry) { | |
| c.header("Content-Type", "application/xml; charset=UTF-8"); | |
| c.header("Cache-Control", "public, max-age=3600"); | |
| return c.body(cachedSitemap); | |
| } | |
| try { | |
| const { db } = await import("./queries/connection.js"); | |
| const { courses, articles } = await import("@db/schema"); | |
| const { eq, desc } = await import("drizzle-orm"); | |
| const publishedCourses = await db | |
| .select({ | |
| slug: courses.slug, | |
| updatedAt: courses.updatedAt, | |
| }) | |
| .from(courses) | |
| .where(eq(courses.isPublished, true)) | |
| .orderBy(courses.sortOrder); | |
| const baseUrl = env.FRONTEND_URL.replace(/\/$/, ""); | |
| const now = new Date().toISOString().split("T")[0]; | |
| const staticUrls = [ | |
| { loc: `${baseUrl}/`, priority: "1", changefreq: "weekly", lastmod: now }, | |
| { loc: `${baseUrl}/courses`, priority: "0.9", changefreq: "weekly", lastmod: now }, | |
| { loc: `${baseUrl}/articles`, priority: "0.6", changefreq: "weekly", lastmod: now }, | |
| { loc: `${baseUrl}/references`, priority: "0.6", changefreq: "weekly", lastmod: now }, | |
| { loc: `${baseUrl}/faq`, priority: "0.6", changefreq: "monthly", lastmod: now }, | |
| { loc: `${baseUrl}/verify`, priority: "0.5", changefreq: "yearly", lastmod: now }, | |
| { loc: `${baseUrl}/terms`, priority: "0.3", changefreq: "yearly", lastmod: now }, | |
| { loc: `${baseUrl}/privacy`, priority: "0.3", changefreq: "yearly", lastmod: now }, | |
| { loc: `${baseUrl}/refund`, priority: "0.3", changefreq: "yearly", lastmod: now }, | |
| ]; | |
| // Escape XML special characters in slugs to prevent XML injection | |
| const escapeXml = (s: string) => s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'"); | |
| const courseUrls = publishedCourses.map((course) => ({ | |
| loc: `${baseUrl}/courses/${escapeXml(course.slug)}`, | |
| priority: "0.8", | |
| changefreq: "monthly", | |
| lastmod: course.updatedAt ? course.updatedAt.toISOString().split("T")[0] : now, | |
| })); | |
| const publishedArticles = await db | |
| .select({ | |
| slug: articles.slug, | |
| updatedAt: articles.updatedAt, | |
| }) | |
| .from(articles) | |
| .where(eq(articles.isPublished, true)) | |
| .orderBy(desc(articles.publishedAt)); | |
| const articleUrls = publishedArticles.map((article) => ({ | |
| loc: `${baseUrl}/articles/${escapeXml(article.slug)}`, | |
| priority: "0.5", | |
| changefreq: "monthly", | |
| lastmod: article.updatedAt ? article.updatedAt.toISOString().split("T")[0] : now, | |
| })); | |
| const allUrls = [...staticUrls, ...courseUrls, ...articleUrls]; | |
| const xml = [ | |
| '<?xml version="1" encoding="UTF-8"?>', | |
| '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', | |
| ...allUrls.map((u) => | |
| ` <url>\n <loc>${u.loc}</loc>\n <lastmod>${u.lastmod}</lastmod>\n <changefreq>${u.changefreq}</changefreq>\n <priority>${u.priority}</priority>\n </url>` | |
| ), | |
| '</urlset>', | |
| ].join("\n"); | |
| cachedSitemap = xml; | |
| sitemapExpiry = Date.now() + 60 * 60 * 1000; // Cache for 1 hour | |
| c.header("Content-Type", "application/xml; charset=UTF-8"); | |
| c.header("Cache-Control", "public, max-age=3600"); | |
| return c.body(xml); | |
| } catch (err) { | |
| appLogger.error("[Sitemap] Error generating sitemap", { error: err instanceof Error ? err.message : String(err) }); | |
| // Fallback: serve static file | |
| try { | |
| const { readFile } = await import("node:fs/promises"); | |
| const staticSitemap = await readFile("./dist/public/sitemap.xml", "utf-8"); | |
| c.header("Content-Type", "application/xml; charset=UTF-8"); | |
| return c.body(staticSitemap); | |
| } catch { | |
| return c.json({ error: "Sitemap unavailable" }, 503); | |
| } | |
| } | |
| }); | |
| // ── Webhook status (internal) ── | |
| app.get("/__webhook/status", (c) => { | |
| // ✅ SECURITY FIX (audit run-1, needs_validation fp | |
| // shield.rate-limit-key.client-controlled-forwarded-headers): the internal | |
| // gate previously trusted only the client-IP derivation — which CAN be | |
| // header-influenced behind a proxy that passes client headers through (the | |
| // exact unresolved deployment fact). A shared-status-token gate is now the | |
| // PRIMARY control in production: set WEBHOOK_STATUS_TOKEN (≥16 chars, HF | |
| // secret) and callers must send `x-status-token` — no header-trust | |
| // dependency remains. When the token is unset, the legacy RFC1918 IP gate | |
| // stays as the fallback (ops tooling keeps working unchanged). | |
| const statusToken = (process.env.WEBHOOK_STATUS_TOKEN ?? "").trim(); | |
| if (statusToken.length >= 16) { | |
| const provided = (c.req.header("x-status-token") ?? "").trim(); | |
| const providedBuf = Buffer.from(provided); | |
| const expectedBuf = Buffer.from(statusToken); | |
| const tokenOk = providedBuf.length === expectedBuf.length && timingSafeEqual(providedBuf, expectedBuf); | |
| if (!tokenOk) { | |
| return c.json({ error: "Not Found" }, 404); | |
| } | |
| } else if (env.NODE_ENV === "production") { | |
| // ✅ SECURITY FIX (audit run-3, webhook-status-prod-token-required): the | |
| // legacy RFC1918 IP-trust fallback keyed on header-derived client IPs, | |
| // which are client-controllable on a direct-to-origin path — and its | |
| // payload discloses nothing beyond the anonymous /api/health. Production | |
| // now REQUIRES the ≥16-char WEBHOOK_STATUS_TOKEN; the open fallback is a | |
| // non-production convenience only. The dead CIDR-matching loop was removed. | |
| return c.json({ error: "Not Found" }, 404); | |
| } | |
| return c.json({ | |
| status: "operational", | |
| timestamp: new Date().toISOString(), | |
| services: { | |
| api: "running", | |
| database: "connected", | |
| }, | |
| }, 200); | |
| }); | |
| // ── CSP Violation Report Endpoint ── | |
| // CSP report-uri sends POST with application/csp-report or application/reports+json | |
| /** Bounded text for a raw CSP-report field: strings pass through untouched, | |
| * everything else is JSON-encoded (never "[object Object]" in the logs). */ | |
| function cspReportFieldText(value: unknown): string { | |
| if (typeof value === "string") return value; | |
| if (value == null) return ""; | |
| return JSON.stringify(value) ?? ""; | |
| } | |
| app.post("/api/csp-report", async (c) => { | |
| let report: unknown; | |
| try { | |
| report = await c.req.json(); | |
| } catch { | |
| return c.body(null, 204); | |
| } | |
| if (env.NODE_ENV === "production") { | |
| const requestId = c.get("requestId") ?? crypto.randomUUID(); | |
| // ✅ SECURITY FIX (audit run-1, csp-report.log-sink): log bounded, | |
| // structured fields instead of the whole attacker-controlled object. | |
| const r = (report ?? {}) as Record<string, unknown>; | |
| const cr = (r["csp-report"] ?? r) as Record<string, unknown>; | |
| appLogger.warn("[CSP] Violation", { | |
| requestId, | |
| directive: cspReportFieldText(cr.effectiveDirective).slice(0, 120), | |
| blockedUri: cspReportFieldText(cr["blocked-uri"]).slice(0, 300), | |
| documentUri: cspReportFieldText(cr["document-uri"]).slice(0, 300), | |
| sample: cspReportFieldText(cr["script-sample"]).slice(0, 500), | |
| }); | |
| } | |
| // 204 No Content — no body allowed per RFC 7231 | |
| return c.body(null, 204); | |
| }); | |
| // ── No-cache headers for critical files (must come before serveStatic) ── | |
| app.use("/*", cacheMiddleware); | |
| // ── SPA route handler — MUST be before serveStatic ────────────────────── | |
| // serveStatic would otherwise serve index.html directly for "/" and bypass | |
| // our CSP nonce injection. By registering the wildcard HTML handler BEFORE | |
| // serveStatic, browser navigations (Accept: text/html) are caught here and | |
| // served with the nonce. Non-HTML requests (assets, API) fall through to | |
| // serveStatic / API routes below. | |
| // Pass a getter function so buildId is read at request time (after loadBuildId sets it), not at module eval time | |
| app.use("*", createSpaHandler(() => buildId)); | |
| // ── Static frontend files from dist/public ── | |
| // Serves JS/CSS/image assets. index.html is already handled by the wildcard | |
| // route above, so this only handles actual static files. | |
| app.use( | |
| "/*", | |
| serveStatic({ | |
| root: "./dist/public", | |
| rewriteRequestPath: (path) => path, | |
| // ⚡ PERF (site-light pass): serve the pre-generated .br/.gz siblings | |
| // (vite-plugin-compression emits brotli level 11 + gzip at build time). | |
| // Cloudflare otherwise re-compresses on the fly at a lower level — | |
| // measured 176KB vs 146KB for the main bundle. This cuts transfer size | |
| // AND origin/edge CPU on every asset request. | |
| precompressed: true, | |
| }) | |
| ); | |
| // ───────────────────────────────────────────────────────────────────────────── | |
| // ROOT CAUSE FIX: notFound handler with aggressive cache-busting headers | |
| // ───────────────────────────────────────────────────────────────────────────── | |
| // Without this, Hono's default 404 response has NO Cache-Control headers. | |
| // The HF Space CDN caches the bare 404 for several minutes, causing the | |
| // "/api/* returns 404" outage that lasts well after the app is healthy. | |
| // | |
| // This handler: | |
| // 1. Sets Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate | |
| // 2. Sets Surrogate-Control: no-store (CDN-specific override — some CDNs | |
| // ignore Cache-Control but respect Surrogate-Control) | |
| // 3. Sets Expires: 0 (HTTP/1.0 fallback) | |
| // 4. Sets Pragma: no-cache | |
| // 5. Returns JSON for /api/* routes (so tRPC clients get a parseable error) | |
| // and HTML for everything else (so SPA routes fall through to index.html) | |
| app.notFound((c) => { | |
| const path = c.req.path; | |
| const isApi = path.startsWith("/api/"); | |
| // Aggressive cache-busting headers on EVERY 404 | |
| c.header("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"); | |
| c.header("Surrogate-Control", "no-store"); | |
| c.header("Pragma", "no-cache"); | |
| c.header("Expires", "0"); | |
| if (isApi) { | |
| return c.json({ error: "Not Found", path }, 404); | |
| } | |
| // For non-API routes (SPA), return a minimal HTML that forces a reload. | |
| // This prevents the CDN from caching a bare 404 page for SPA routes. | |
| return c.html( | |
| `<!DOCTYPE html><html><head><meta charset="utf-8">` + | |
| `<meta name="viewport" content="width=device-width, initial-scale=1">` + | |
| `<meta http-equiv="refresh" content="0; url=/">` + | |
| `<title>Loading...</title></head>` + | |
| `<body><script>location.replace('/');</script></body></html>`, | |
| 404, | |
| ); | |
| }); | |
| app.onError(async (err, c) => { | |
| const requestId = c.get("requestId") ?? crypto.randomUUID(); | |
| appLogger.error(`Unhandled error [${requestId}]`, { error: err instanceof Error ? err.message : String(err) }); | |
| // 🧠 Elite AI Diagnosis: Analyze the crash in background | |
| if (env.NODE_ENV === "production") { | |
| import("./lib/ai-diagnostics.js") | |
| .then(({ diagnoseError }) => { | |
| // Diagnostics are best-effort — never let them crash the error path (S9383). | |
| return diagnoseError(err, `Request ID: ${requestId} | Path: ${c.req.path}`).catch(() => {}); | |
| }) | |
| .catch(() => { | |
| // Intentionally ignored: diagnostics module unavailable — error handling continues. | |
| }); | |
| } | |
| if (env.SENTRY_DSN && env.NODE_ENV === "production") { | |
| const { captureException } = await import("./lib/sentry.js"); | |
| captureException(err, { tags: { requestId } }); | |
| } | |
| // Aggressive cache-busting on all error responses — prevents CDN from | |
| // caching 500 errors and causing prolonged outages. | |
| c.header("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"); | |
| c.header("Surrogate-Control", "no-store"); | |
| c.header("Pragma", "no-cache"); | |
| c.header("Expires", "0"); | |
| return c.json( | |
| { | |
| error: env.NODE_ENV === "production" ? "Internal Server Error" : err.message, | |
| requestId, | |
| }, | |
| 500 | |
| ); | |
| }); | |
| // ✅ Sonar S3776 (cfskill run-3): the production security posture check is | |
| // extracted from start() — identical decision, one call site. | |
| function logProductionSecurityPosture(): void { | |
| // ✅ SECURITY FIX (cfskill audit run-3, U6-01): the direct-origin host gate | |
| // (EDGE_HOST_ENFORCE) is opt-in and silently disabled when the variable is | |
| // unset — DEPLOYMENT.md documents it as production-active, so a forgotten | |
| // Space secret would quietly expose the raw *.hf.space origin (bypassing | |
| // the edge). Production boot must REFUSE to start silently mis-configured: | |
| // the operator sees the failure immediately instead of discovering the open | |
| // path during an incident. Non-production keeps the lenient default. | |
| if (env.isProduction && process.env.EDGE_HOST_ENFORCE !== "1") { | |
| appLogger.error( | |
| "[SECURITY] EDGE_HOST_ENFORCE is not set to '1' in production — the direct origin host allowlist is DISABLED. " + | |
| "Set EDGE_HOST_ENFORCE=1 in the Space secrets before trusting this deployment.", | |
| ); | |
| } | |
| } | |
| async function start() { | |
| // ── Load build ID from build-id.json ── | |
| await loadBuildId(); | |
| // ── Auto-migrate database on startup (retrying, visibility-instrumented) ── | |
| await runBootMigrations(); | |
| try { | |
| await initRedis(); | |
| } catch (err) { | |
| appLogger.warn("[Server] Redis unavailable, rate limiting disabled", { error: (err as Error).message }); | |
| } | |
| // Detect Bun runtime. CRITICAL: must use `typeof Bun !== "undefined"`, | |
| // NOT `Bun?.serve` — `Bun` is not a declared global on Node.js, so any | |
| // direct reference (even with optional chaining) throws ReferenceError | |
| // and crashes the server at startup. The previous Biome auto-fix | |
| // (`useOptionalChain`) broke this and shipped to production — reverted. | |
| // NOSONAR — S7741: typeof guard is REQUIRED for undeclared globals; | |
| // comparing Bun === undefined directly throws ReferenceError. | |
| const isBunRuntime = typeof Bun !== "undefined"; // NOSONAR | |
| const useBun = isBunRuntime && typeof Bun.serve === "function"; // NOSONAR | |
| let server: { close: (cb?: () => void) => void } | undefined; | |
| if (useBun) { | |
| server = Bun.serve({ | |
| fetch: app.fetch, | |
| port: env.PORT, | |
| hostname: env.HOST, | |
| }); | |
| } else { | |
| const { serve } = await import("@hono/node-server"); | |
| server = serve({ fetch: app.fetch, port: env.PORT, hostname: env.HOST }); | |
| } | |
| appLogger.info(`[Server] Running on http://${env.HOST}:${env.PORT}`); | |
| appLogger.info(`[Server] Environment: ${env.NODE_ENV}`); | |
| logProductionSecurityPosture(); | |
| // ── Telegram bot worker (join-request auto-approval + DM expert brain) ── | |
| // Production only: tests/dev must never long-poll the live bot token. | |
| // Never-throw — a failure here must not break the server that just booted. | |
| // The worker is SUPERVISED: boot retries + self-healing poll loop; its | |
| // liveness is surfaced in /api/health (checks.telegram) so a silent death | |
| // can never recur unnoticed. | |
| if (env.isProduction) { | |
| try { | |
| const { startTelegramBot } = await import("./lib/telegram-bot.js"); | |
| const started = startTelegramBot(); // S4123: synchronous supervised start — returns boolean, not a Promise | |
| if (started) appLogger.info("[Server] Telegram bot worker supervised start (join approvals + DM brain) — liveness at /api/health"); | |
| else appLogger.warn("[Server] Telegram bot worker not started — see /api/health checks.telegram for the reason"); | |
| } catch (err) { | |
| appLogger.warn("[Server] Telegram bot worker failed to start", { error: err instanceof Error ? err.message : String(err) }); | |
| } | |
| } | |
| appLogger.info(`[Server] Frontend: ${env.FRONTEND_URL}`); | |
| // ── YouTube episode watcher: every 15 min, detect new uploads on the | |
| // channel playlist and broadcast an in-app notification to all users. | |
| startYoutubeWatcher(); | |
| // ── Educational email drip scheduler: welcome-on-register is event-driven; | |
| // this scheduler only owns the 48h no-start nudge sweep (every 6h). | |
| // Production only — tests/dev must never send real emails. | |
| if (env.isProduction) { | |
| const { startEmailDripScheduler } = await import("./lib/email-drip.js"); | |
| startEmailDripScheduler(); | |
| } | |
| const shutdownHandler = createShutdownHandler(() => server); | |
| process.on("SIGTERM", () => shutdownHandler("SIGTERM")); | |
| process.on("SIGINT", () => shutdownHandler("SIGINT")); | |
| } | |
| /** | |
| * ✅ PRODUCTION-READINESS (audit 2026-11-30, boot-migration-retry): the boot | |
| * migration is retried with backoff and its outcome surfaced by /api/health | |
| * (checks.migrations) instead of silently absorbed. ensureDatabase never | |
| * throws — it reports through getMigrationOutcome() — so the loop polls that. | |
| * Extracted from start() (SonarCloud S3776) — same behavior, own complexity. | |
| */ | |
| async function runBootMigrations(): Promise<void> { | |
| const MIGRATION_ATTEMPTS = 3; | |
| for (let attempt = 1; attempt <= MIGRATION_ATTEMPTS; attempt++) { | |
| await ensureDatabase(); | |
| const outcome = getMigrationOutcome(); | |
| if (outcome === "ok") { | |
| // BOOT-TIME MODEL DISCOVERY (fire-and-forget): refreshes the dynamic | |
| // pool's metadata (contextLength, isFree, tiers, chat/vision flags) on | |
| // every restart without waiting for an admin "فحص النماذج" click — e.g. a | |
| // fresh v10 column stays NULL forever without this. Best-effort: any | |
| // failure is logged inside and routing still works on the existing rows. | |
| void discoverAllProviders().catch(() => { /* logged inside */ }); | |
| return; | |
| } | |
| if (attempt < MIGRATION_ATTEMPTS) { | |
| appLogger.warn(`[Server] DB migration attempt ${attempt}/${MIGRATION_ATTEMPTS} failed — retrying`, { outcome }); | |
| await new Promise((resolve) => setTimeout(resolve, attempt === 1 ? 5_000 : 15_000)); // NOSONAR: intentional sequential/throttled processing (retry backoff) | |
| } | |
| } | |
| appLogger.error("[Server] DB migration failed after retries — booting degraded; /api/health reports checks.migrations"); | |
| void discoverAllProviders().catch(() => { /* logged inside */ }); | |
| } | |
| /** Best-effort background-worker + cache teardown (extracted: S3776). */ | |
| async function stopBackgroundWorkers(): Promise<void> { | |
| try { | |
| const { default: ElbazCache } = await import("../cache/index.js"); | |
| ElbazCache.engine.destroy(); | |
| ElbazCache.short.destroy(); | |
| ElbazCache.long.destroy(); | |
| ElbazCache.session.destroy(); | |
| } catch {// Intentionally ignored: best-effort cleanup, the error has already | |
| // been logged upstream and re-throwing would mask the original cause. | |
| } | |
| try { | |
| stopYoutubeWatcher(); | |
| const { stopTelegramBot } = await import("./lib/telegram-bot.js"); | |
| stopTelegramBot(); | |
| const { stopEmailDripScheduler } = await import("./lib/email-drip.js"); | |
| stopEmailDripScheduler(); | |
| } catch {// Intentionally ignored: each stop is self-contained; teardown continues. | |
| } | |
| } | |
| /** | |
| * ✅ PRODUCTION-READINESS (audit 2026-11-30, graceful-shutdown): stop every | |
| * background poller, close the HTTP listener with a bounded grace period, | |
| * drain the MySQL pools, and force-exit at the 8s hard ceiling. Extracted to | |
| * module scope (SonarCloud S3776) — the server handle arrives via a getter | |
| * because start() builds it after the handler registration pattern. | |
| */ | |
| function createShutdownHandler(getServer: () => { close: (cb?: () => void) => void; closeAllConnections?: () => void } | undefined): (signal: string) => Promise<void> { | |
| return async (signal: string) => { | |
| appLogger.info(`[Server] ${signal} received, shutting down...`); | |
| await stopBackgroundWorkers(); | |
| const server = getServer(); | |
| const forceExitTimer = setTimeout(() => { | |
| appLogger.error("[Server] Grace period expired — forcing exit"); | |
| process.exit(0); | |
| }, 8_000); | |
| forceExitTimer.unref?.(); | |
| try { | |
| server?.close(() => process.exit(0)); | |
| // Evict still-open keep-alive sockets (idle browser connections) that | |
| // would otherwise keep close() waiting — in-flight requests get the | |
| // full 4s grace first. | |
| const evictTimer = setTimeout(() => { | |
| server?.closeAllConnections?.(); | |
| }, 4_000); | |
| evictTimer.unref?.(); | |
| } catch {// Intentionally ignored: server may already be closed. | |
| } | |
| try { | |
| const { closeAllPools } = await import("./queries/connection.js"); | |
| await closeAllPools(); | |
| } catch {// Intentionally ignored: pools may already be draining. | |
| } | |
| }; | |
| } | |
| // ── Last-resort process guards (availability-first) ── | |
| // ✅ SECURITY FIX (audit run-3, boot-guards-registered-first): the guards were | |
| // registered at the END of start(), leaving a boot window where ONE escaping | |
| // rejection (a background worker, a fire-and-forget import) could kill the | |
| // process before the handlers existed. Module scope = covered from the first | |
| // tick. The platform's never-throw contract is enforced per-feature, but one | |
| // escaping rejection anywhere must never take the whole server down — Node's | |
| // default since 15 is to exit on unhandled rejections. Log loudly, keep serving. | |
| process.on("unhandledRejection", (reason) => { | |
| appLogger.error("[Server] Unhandled rejection contained", { | |
| error: reason instanceof Error ? reason.message : String(reason), | |
| }); | |
| }); | |
| process.on("uncaughtException", (err) => { | |
| appLogger.error("[Server] Uncaught exception contained", { | |
| error: err instanceof Error ? err.message : String(err), | |
| }); | |
| }); | |
| try { | |
| await start(); | |
| } catch (err) { | |
| appLogger.error("[Server] Fatal startup error", { error: err instanceof Error ? err.message : String(err) }); | |
| process.exit(1); | |
| } | |
| export { app }; | |
| export default app; | |