package gateway import ( "crypto/sha256" "crypto/subtle" "encoding/json" "fmt" "html/template" "io" "net/http" "os" "strconv" "strings" "time" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/prometheus/client_golang/prometheus/promhttp" "unified-dashboard/internal/khira" mymiddleware "unified-dashboard/internal/middleware" ) type DashboardData struct { ExclusiveTool DashboardTool KhiraTool DashboardTool Tools []DashboardTool TotalTools int } type DashboardTool struct { Key string Name string Icon string Description string Category string Path string Exclusive bool } func writeJSON(w http.ResponseWriter, status int, data any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(data) } func dashboardHandler(w http.ResponseWriter, r *http.Request) { tmpl, err := template.ParseFiles("web/dashboard/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } exclusive := DashboardTool{ Key: "docs", Name: "FastAPI Backend API Docs", Icon: "fa-solid fa-book-bookmark", Description: "Complete interactive API reference, schema definitions, endpoints, models and request/response specifications for the FastAPI Generative AI Backend services.", Category: "API Documentation", Path: "/docs/", Exclusive: true, } khiraTool := DashboardTool{ Key: "khira", Name: "Khira Dev Ticketing System", Icon: "fa-solid fa-ticket-simple", Description: "Interactive cross-team developer ticketing system. Report issues across frontend, backend and QA teams with API details, priority assignment, hold/resume workflows, resolution remarks and live browser notifications.", Category: "Dev Productivity & QA", Path: "/khira/", Exclusive: true, } var tools []DashboardTool for _, t := range Registry { if t.Key == "docs" || t.Key == "khira" { continue } tools = append(tools, DashboardTool{ Key: t.Key, Name: t.Name, Icon: t.Icon, Description: t.Description, Category: t.Category, Path: fmt.Sprintf("/tool/%s/", t.Key), }) } w.Header().Set("Content-Type", "text/html; charset=utf-8") tmpl.Execute(w, DashboardData{ ExclusiveTool: exclusive, KhiraTool: khiraTool, Tools: tools, TotalTools: len(tools) + 2, }) } const ( docsRequiredPassword = "docdoc@crecre" docsAuthCookieName = "nexus_docs_session" docsAdminUser = "admin" docsAdminPassword = "Polonium#209.00" docsAdminCookieName = "nexus_docs_admin_session" docsSessionDuration = 10 * time.Minute // 10 minutes session duration docsSalt = "nexus_docs_salt_2026" docsAdminSalt = "nexus_admin_salt_2026" ) func makeTimedToken(secret string, salt string) string { now := time.Now().Unix() payload := fmt.Sprintf("%d:%s:%s", now, secret, salt) sig := fmt.Sprintf("%x", sha256.Sum256([]byte(payload))) return fmt.Sprintf("%d.%s", now, sig) } func verifyTimedToken(token string, secret string, salt string) (bool, int64) { parts := strings.SplitN(token, ".", 2) if len(parts) != 2 { return false, 0 } ts, err := strconv.ParseInt(parts[0], 10, 64) if err != nil { return false, 0 } issuedAt := time.Unix(ts, 0) now := time.Now() elapsed := now.Sub(issuedAt) if elapsed < 0 || elapsed > docsSessionDuration { return false, 0 // Expired after 10 minutes } expectedPayload := fmt.Sprintf("%d:%s:%s", ts, secret, salt) expectedSig := fmt.Sprintf("%x", sha256.Sum256([]byte(expectedPayload))) if subtle.ConstantTimeCompare([]byte(parts[1]), []byte(expectedSig)) != 1 { return false, 0 } remaining := int64(docsSessionDuration.Seconds() - elapsed.Seconds()) if remaining < 0 { remaining = 0 } return true, remaining } func isDocsAuthenticated(r *http.Request) bool { cookie, err := r.Cookie(docsAuthCookieName) if err != nil { return false } valid, _ := verifyTimedToken(cookie.Value, docsRequiredPassword, docsSalt) return valid } func getDocsSessionRemaining(r *http.Request) (bool, int64) { cookie, err := r.Cookie(docsAuthCookieName) if err != nil { return false, 0 } return verifyTimedToken(cookie.Value, docsRequiredPassword, docsSalt) } func isDocsAdminAuthenticated(r *http.Request) bool { if cookie, err := r.Cookie(docsAdminCookieName); err == nil { valid, _ := verifyTimedToken(cookie.Value, docsAdminUser+":"+docsAdminPassword, docsAdminSalt) if valid { return true } } if user, pass, ok := r.BasicAuth(); ok { if user == docsAdminUser && pass == docsAdminPassword { return true } } return false } func renderDocsLogin(w http.ResponseWriter, r *http.Request, errMsg string) { tmpl, err := template.ParseFiles("web/docs/login.html") if err != nil { http.Error(w, "Documentation authentication required. Please enter password.", http.StatusUnauthorized) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") tmpl.Execute(w, map[string]string{ "Error": errMsg, }) } func renderDocsAdminLogin(w http.ResponseWriter, r *http.Request, errMsg string) { tmpl, err := template.ParseFiles("web/docs/admin_login.html") if err != nil { http.Error(w, "Admin authentication required. Enter admin credentials.", http.StatusUnauthorized) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") tmpl.Execute(w, map[string]string{ "Error": errMsg, }) } func healthHandler(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) } func prometheusHandler(w http.ResponseWriter, r *http.Request) { promhttp.Handler().ServeHTTP(w, r) } func NewRouter(pm *ProcessManager) http.Handler { r := chi.NewRouter() // Global middleware stack r.Use(middleware.RealIP) r.Use(middleware.RequestID) r.Use(mymiddleware.RequestLogger) // slog-based r.Use(middleware.Recoverer) r.Use(middleware.Compress(5)) // gzip // Dashboard r.Get("/", dashboardHandler) r.Get("/health", healthHandler) r.Get("/metrics", prometheusHandler) loginDocsHandler := func(w http.ResponseWriter, r *http.Request) { var password string if strings.Contains(r.Header.Get("Content-Type"), "application/json") { var reqBody struct { Password string `json:"password"` } if err := json.NewDecoder(r.Body).Decode(&reqBody); err == nil { password = reqBody.Password } } else { _ = r.ParseForm() password = r.FormValue("password") } wantsJSON := strings.Contains(r.Header.Get("Accept"), "application/json") || strings.Contains(r.Header.Get("Content-Type"), "application/json") if strings.TrimSpace(password) == docsRequiredPassword { http.SetCookie(w, &http.Cookie{ Name: docsAuthCookieName, Value: makeTimedToken(docsRequiredPassword, docsSalt), Path: "/", MaxAge: int(docsSessionDuration.Seconds()), // 10 minutes = 600s HttpOnly: true, SameSite: http.SameSiteLaxMode, }) if wantsJSON { writeJSON(w, http.StatusOK, map[string]interface{}{ "status": "ok", "redirect": "/docs/", }) return } http.Redirect(w, r, "/docs/", http.StatusSeeOther) return } if wantsJSON { writeJSON(w, http.StatusUnauthorized, map[string]interface{}{ "status": "error", "error": "Invalid password. Access denied.", }) return } renderDocsLogin(w, r, "Invalid password. Access denied.") } logoutDocsHandler := func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: docsAuthCookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteLaxMode, }) http.Redirect(w, r, "/docs/", http.StatusSeeOther) } // Documentation Admin & Editor Handlers editorHandler := func(w http.ResponseWriter, req *http.Request) { if !isDocsAdminAuthenticated(req) { renderDocsAdminLogin(w, req, "") return } w.Header().Set("Content-Type", "text/html; charset=utf-8") http.ServeFile(w, req, "web/docs/editor.html") } loginEditorHandler := func(w http.ResponseWriter, r *http.Request) { var username, password string if strings.Contains(r.Header.Get("Content-Type"), "application/json") { var body struct { Username string `json:"username"` Password string `json:"password"` } _ = json.NewDecoder(r.Body).Decode(&body) username = body.Username password = body.Password } else { _ = r.ParseForm() username = r.FormValue("username") password = r.FormValue("password") } wantsJSON := strings.Contains(r.Header.Get("Accept"), "application/json") || strings.Contains(r.Header.Get("Content-Type"), "application/json") if strings.TrimSpace(username) == docsAdminUser && strings.TrimSpace(password) == docsAdminPassword { http.SetCookie(w, &http.Cookie{ Name: docsAdminCookieName, Value: makeTimedToken(docsAdminUser+":"+docsAdminPassword, docsAdminSalt), Path: "/", MaxAge: int(docsSessionDuration.Seconds()), // 10 minutes = 600s HttpOnly: true, SameSite: http.SameSiteLaxMode, }) // Also ensure docs reader session is active for 10 minutes http.SetCookie(w, &http.Cookie{ Name: docsAuthCookieName, Value: makeTimedToken(docsRequiredPassword, docsSalt), Path: "/", MaxAge: int(docsSessionDuration.Seconds()), // 10 minutes = 600s HttpOnly: true, SameSite: http.SameSiteLaxMode, }) if wantsJSON { writeJSON(w, http.StatusOK, map[string]interface{}{ "status": "ok", "redirect": "/docs/editor", }) return } http.Redirect(w, r, "/docs/editor", http.StatusSeeOther) return } if wantsJSON { writeJSON(w, http.StatusUnauthorized, map[string]interface{}{ "status": "error", "error": "Invalid admin username or password. Access denied.", }) return } renderDocsAdminLogin(w, r, "Invalid admin username or password. Access denied.") } logoutEditorHandler := func(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: docsAdminCookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteLaxMode, }) http.Redirect(w, r, "/docs/", http.StatusSeeOther) } saveEditorHandler := func(w http.ResponseWriter, r *http.Request) { // Allow admin authenticated, reader authenticated, or localhost connection remoteIP := r.RemoteAddr isLocal := strings.HasPrefix(remoteIP, "127.0.0.1") || strings.HasPrefix(remoteIP, "[::1]") || strings.HasPrefix(remoteIP, "localhost") if !isDocsAdminAuthenticated(r) && !isDocsAuthenticated(r) && !isLocal { writeJSON(w, http.StatusUnauthorized, map[string]interface{}{ "status": "error", "error": "Unauthorized. Admin credentials required.", }) return } bodyBytes, err := io.ReadAll(r.Body) if err != nil || len(bodyBytes) < 5 { writeJSON(w, http.StatusBadRequest, map[string]interface{}{ "status": "error", "error": "Empty or invalid payload received.", }) return } var payload struct { HTML string `json:"html"` Data interface{} `json:"data"` } _ = json.Unmarshal(bodyBytes, &payload) var dataObj interface{} if payload.Data != nil { dataObj = payload.Data } else { // Check if the root payload itself is the data object var rawMap map[string]interface{} if err := json.Unmarshal(bodyBytes, &rawMap); err == nil { if _, hasSec := rawMap["sections"]; hasSec { dataObj = rawMap } else if _, hasMeta := rawMap["meta"]; hasMeta { dataObj = rawMap } } } // Fallback: extract from ` startIdx := strings.Index(payload.HTML, startTag) if startIdx != -1 { rem := payload.HTML[startIdx+len(startTag):] endIdx := strings.Index(rem, endTag) if endIdx != -1 { _ = json.Unmarshal([]byte(rem[:endIdx]), &dataObj) } } } if dataObj == nil { writeJSON(w, http.StatusBadRequest, map[string]interface{}{ "status": "error", "error": "No valid documentation data found in request payload.", }) return } // Marshal formatted JSON for data.json dataBytes, err := json.MarshalIndent(dataObj, "", " ") if err != nil { writeJSON(w, http.StatusInternalServerError, map[string]interface{}{ "status": "error", "error": "Failed to format data JSON: " + err.Error(), }) return } // Save to web/docs/data.json and scratch/faithful_docs_data.json if err := os.WriteFile("web/docs/data.json", dataBytes, 0644); err != nil { writeJSON(w, http.StatusInternalServerError, map[string]interface{}{ "status": "error", "error": "Failed to save data.json: " + err.Error(), }) return } _ = os.WriteFile("scratch/faithful_docs_data.json", dataBytes, 0644) // Synchronize the embedded ` startIdx := strings.Index(content, startTag) if startIdx != -1 { afterStart := startIdx + len(startTag) endIdx := strings.Index(content[afterStart:], endTag) if endIdx != -1 { rawJSONStr := strings.ReplaceAll(string(dataBytes), "<", `\u003c`) newContent := content[:afterStart] + rawJSONStr + content[afterStart+endIdx:] _ = os.WriteFile(filePath, []byte(newContent), 0644) } } } updateEmbedded("web/docs/index.html") updateEmbedded("web/docs/FASTAPI_BACKEND_API_DOCS.html") } writeJSON(w, http.StatusOK, map[string]interface{}{ "status": "ok", "data_written": len(dataBytes), "message": "Documentation data saved successfully to server.", }) } // Documentation Routes (/docs and /docs/) docsHandler := func(w http.ResponseWriter, req *http.Request) { if !isDocsAuthenticated(req) { renderDocsLogin(w, req, "") return } filePath := "web/docs/index.html" if _, err := os.Stat(filePath); os.IsNotExist(err) { filePath = "web/docs/FASTAPI_BACKEND_API_DOCS.html" } w.Header().Set("Content-Type", "text/html; charset=utf-8") http.ServeFile(w, req, filePath) } // Admin Editor Routes r.Get("/docs/editor", editorHandler) r.Head("/docs/editor", editorHandler) r.Get("/docs/editor/", editorHandler) r.Head("/docs/editor/", editorHandler) r.Get("/docs/editor.html", editorHandler) r.Post("/docs/editor/login", loginEditorHandler) r.Get("/docs/editor/logout", logoutEditorHandler) r.Post("/docs/editor/logout", logoutEditorHandler) r.Post("/docs/editor/save", saveEditorHandler) r.Post("/docs/save", saveEditorHandler) r.Post("/api/docs/save", saveEditorHandler) r.Get("/docs", func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, "/docs/", http.StatusMovedPermanently) }) r.Head("/docs", func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, "/docs/", http.StatusMovedPermanently) }) r.Get("/docs/", docsHandler) r.Head("/docs/", docsHandler) r.Post("/docs/login", loginDocsHandler) r.Get("/docs/logout", logoutDocsHandler) r.Post("/docs/logout", logoutDocsHandler) r.Get("/docs/session", func(w http.ResponseWriter, req *http.Request) { valid, remaining := getDocsSessionRemaining(req) if !valid { writeJSON(w, http.StatusUnauthorized, map[string]interface{}{ "authenticated": false, "remaining_seconds": 0, }) return } writeJSON(w, http.StatusOK, map[string]interface{}{ "authenticated": true, "remaining_seconds": remaining, "expires_in": fmt.Sprintf("%dm %ds", remaining/60, remaining%60), }) }) r.Get("/docs/data.json", func(w http.ResponseWriter, req *http.Request) { paths := []string{"web/docs/data.json", "scratch/faithful_docs_data.json"} for _, p := range paths { if b, err := os.ReadFile(p); err == nil { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write(b) return } } writeJSON(w, http.StatusNotFound, map[string]string{"error": "data not found"}) }) r.Get("/docs/health", func(w http.ResponseWriter, req *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) }) r.Head("/docs/health", func(w http.ResponseWriter, req *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) }) r.Get("/docs/*", func(w http.ResponseWriter, req *http.Request) { if strings.HasSuffix(req.URL.Path, "/session") { valid, remaining := getDocsSessionRemaining(req) if !valid { writeJSON(w, http.StatusUnauthorized, map[string]interface{}{ "authenticated": false, "remaining_seconds": 0, }) return } writeJSON(w, http.StatusOK, map[string]interface{}{ "authenticated": true, "remaining_seconds": remaining, "expires_in": fmt.Sprintf("%dm %ds", remaining/60, remaining%60), }) return } if strings.HasPrefix(req.URL.Path, "/docs/editor") { if strings.HasSuffix(req.URL.Path, "/login") { renderDocsAdminLogin(w, req, "") return } if strings.HasSuffix(req.URL.Path, "/logout") { logoutEditorHandler(w, req) return } editorHandler(w, req) return } if strings.HasSuffix(req.URL.Path, "/health") { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) return } if strings.HasSuffix(req.URL.Path, "/login") { renderDocsLogin(w, req, "") return } if strings.HasSuffix(req.URL.Path, "/logout") { logoutDocsHandler(w, req) return } docsHandler(w, req) }) r.Head("/docs/*", func(w http.ResponseWriter, req *http.Request) { if strings.HasPrefix(req.URL.Path, "/docs/editor") { editorHandler(w, req) return } if strings.HasSuffix(req.URL.Path, "/health") { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) return } docsHandler(w, req) }) // Initialize Khira ticketing store & routes khiraStore, err := khira.NewStore("data/khira") if err != nil { fmt.Fprintf(os.Stderr, "warning: failed to init khira store: %v\n", err) } khiraServer := khira.NewServer(khiraStore) r.Route("/khira", func(kr chi.Router) { khiraServer.RegisterRoutes(kr) }) r.Get("/tool/khira", func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, "/khira/", http.StatusTemporaryRedirect) }) r.Get("/tool/khira/*", func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, "/khira/", http.StatusTemporaryRedirect) }) // Tool launcher — idempotent (POST is best to bypass CDN caching) r.Post("/launch/{toolID}", func(w http.ResponseWriter, r *http.Request) { toolID := chi.URLParam(r, "toolID") if toolID == "docs" { writeJSON(w, http.StatusOK, map[string]string{"status": "started", "path": "/docs/"}) return } if toolID == "khira" { writeJSON(w, http.StatusOK, map[string]string{"status": "started", "path": "/khira/"}) return } path, err := pm.Launch(toolID) if err != nil { writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()}) return } writeJSON(w, http.StatusOK, map[string]string{"status": "started", "path": path}) }) // Per-tool reverse proxy — catch-all under /tool// for _, cfg := range Registry { if cfg.Port == 0 || cfg.Command == "" { continue // Static or internal tools handled directly } cfg := cfg // capture loop var prefix := "/tool/" + cfg.Key r.Mount(prefix, http.StripPrefix(prefix, toolProxy(pm, cfg.Key, cfg.Port))) } // Route /tool/docs to /docs/ r.Get("/tool/docs", func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, "/docs/", http.StatusTemporaryRedirect) }) r.Get("/tool/docs/*", func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, "/docs/", http.StatusTemporaryRedirect) }) // Special custom domain routing for Image Hoster (/hoster -> image-hoster:/files) r.Route("/hoster", func(r chi.Router) { r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // Find image-hoster config var cfg *ToolConfig for i := range Registry { if Registry[i].Key == "image-hoster" { cfg = &Registry[i] break } } if cfg == nil { http.Error(w, "Image Hoster not found", http.StatusNotFound) return } // Ensure it is running _ = pm.EnsureRunning(req.Context(), "image-hoster") // Rewrite URL from /hoster/SID/file to /files/SID/file originalPath := req.URL.Path req.URL.Path = "/files" + strings.TrimPrefix(originalPath, "/hoster") // Proxy proxy := toolProxy(pm, "image-hoster", cfg.Port) proxy.ServeHTTP(w, req) })) }) // Fallback routing aliases for Image Manipulator batch operations r.HandleFunc("/upload-batch", func(w http.ResponseWriter, req *http.Request) { _ = pm.EnsureRunning(req.Context(), "image-manipulator") cfg := pm.getConfig("image-manipulator") if cfg != nil { proxy := toolProxy(pm, "image-manipulator", cfg.Port) proxy.ServeHTTP(w, req) return } http.Error(w, "Image manipulator not found", http.StatusNotFound) }) r.HandleFunc("/batch-process-session", func(w http.ResponseWriter, req *http.Request) { _ = pm.EnsureRunning(req.Context(), "image-manipulator") cfg := pm.getConfig("image-manipulator") if cfg != nil { proxy := toolProxy(pm, "image-manipulator", cfg.Port) proxy.ServeHTTP(w, req) return } http.Error(w, "Image manipulator not found", http.StatusNotFound) }) r.HandleFunc("/preview-batch", func(w http.ResponseWriter, req *http.Request) { _ = pm.EnsureRunning(req.Context(), "image-manipulator") cfg := pm.getConfig("image-manipulator") if cfg != nil { proxy := toolProxy(pm, "image-manipulator", cfg.Port) proxy.ServeHTTP(w, req) return } http.Error(w, "Image manipulator not found", http.StatusNotFound) }) r.HandleFunc("/download-batch", func(w http.ResponseWriter, req *http.Request) { _ = pm.EnsureRunning(req.Context(), "image-manipulator") cfg := pm.getConfig("image-manipulator") if cfg != nil { proxy := toolProxy(pm, "image-manipulator", cfg.Port) proxy.ServeHTTP(w, req) return } http.Error(w, "Image manipulator not found", http.StatusNotFound) }) r.HandleFunc("/api/jobs/*", func(w http.ResponseWriter, req *http.Request) { _ = pm.EnsureRunning(req.Context(), "image-manipulator") cfg := pm.getConfig("image-manipulator") if cfg != nil { proxy := toolProxy(pm, "image-manipulator", cfg.Port) proxy.ServeHTTP(w, req) return } http.Error(w, "Image manipulator not found", http.StatusNotFound) }) r.HandleFunc("/files/*", func(w http.ResponseWriter, req *http.Request) { _ = pm.EnsureRunning(req.Context(), "image-hoster") cfg := pm.getConfig("image-hoster") if cfg != nil { proxy := toolProxy(pm, "image-hoster", cfg.Port) proxy.ServeHTTP(w, req) return } http.Error(w, "Image hoster not found", http.StatusNotFound) }) return r }