package server import ( "context" "encoding/json" "fmt" "net/http" "strings" "time" gonostr "github.com/nbd-wtf/go-nostr" "gitcitadel-online/internal/cache" "gitcitadel-online/internal/generator" "gitcitadel-online/internal/logger" "gitcitadel-online/internal/nostr" ) // setupRoutes sets up all HTTP routes func (s *Server) setupRoutes(mux *http.ServeMux) { // Static files mux.HandleFunc("/static/", s.handleStatic) // Favicon mux.HandleFunc("/favicon.ico", s.handleFavicon) // Main routes mux.HandleFunc("/", s.handleLanding) mux.HandleFunc("/wiki/", s.handleWiki) mux.HandleFunc("/blog", s.handleBlog) mux.HandleFunc("/ebooks", s.handleEBooks) mux.HandleFunc("/contact", s.handleContact) // Health and metrics mux.HandleFunc("/health", s.handleHealth) mux.HandleFunc("/metrics", s.handleMetrics) // SEO mux.HandleFunc("/sitemap.xml", s.handleSitemap) mux.HandleFunc("/robots.txt", s.handleRobots) // API endpoints mux.HandleFunc("/api/contact", s.handleContactAPI) } // handleLanding handles the landing page func (s *Server) handleLanding(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { s.handle404(w, r) return } page, exists := s.cache.Get("/") if !exists { http.Error(w, "Page not ready", http.StatusServiceUnavailable) return } s.servePage(w, r, page) } // handleWiki handles wiki article pages and wiki index func (s *Server) handleWiki(w http.ResponseWriter, r *http.Request) { path := r.URL.Path // Handle wiki index page (/wiki or /wiki/) if path == "/wiki" || path == "/wiki/" { page, exists := s.cache.Get("/wiki") if !exists { http.Error(w, "Page not ready", http.StatusServiceUnavailable) return } s.servePage(w, r, page) return } // Handle individual wiki pages (/wiki/{dTag}) page, exists := s.cache.Get(path) if !exists { s.handle404(w, r) return } s.servePage(w, r, page) } // handleBlog handles the blog page func (s *Server) handleBlog(w http.ResponseWriter, r *http.Request) { page, exists := s.cache.Get("/blog") if !exists { http.Error(w, "Page not ready", http.StatusServiceUnavailable) return } s.servePage(w, r, page) } // handleEBooks handles the e-books listing page func (s *Server) handleEBooks(w http.ResponseWriter, r *http.Request) { page, exists := s.cache.Get("/ebooks") if !exists { http.Error(w, "Page not ready", http.StatusServiceUnavailable) return } s.servePage(w, r, page) } // handleContact handles the contact form (GET and POST) func (s *Server) handleContact(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { // Fetch repo announcement for embedding in page ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() var repoAnnouncement *nostr.RepoAnnouncement var err error if s.repoAnnouncement != "" { repoAnnouncement, err = s.issueService.FetchRepoAnnouncement(ctx, s.repoAnnouncement) if err != nil { logger.Warnf("Failed to fetch repo announcement for contact page: %v", err) // Continue without repo announcement - form will show error } } // Fetch profile for npub var profile *nostr.Profile npub := "npub1s3ht77dq4zqnya8vjun5jp3p44pr794ru36d0ltxu65chljw8xjqd975wz" if s.nostrClient != nil { profile, err = s.nostrClient.FetchProfile(ctx, npub) if err != nil { logger.Warnf("Failed to fetch profile for contact page: %v", err) // Continue without profile - not critical } } // Render the contact form (feed items not needed - only on landing page) html, err := s.htmlGenerator.GenerateContactPage(false, "", "", nil, repoAnnouncement, []generator.FeedItemInfo{}, profile) if err != nil { http.Error(w, "Failed to generate contact page", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(html)) return } if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } // Parse form data if err := r.ParseForm(); err != nil { html, _ := s.htmlGenerator.GenerateContactPage(false, "Failed to parse form data", "", nil, nil, []generator.FeedItemInfo{}, nil) w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(html)) return } subject := strings.TrimSpace(r.FormValue("subject")) content := strings.TrimSpace(r.FormValue("content")) labelsStr := strings.TrimSpace(r.FormValue("labels")) // Validate required fields if subject == "" || content == "" { formData := map[string]string{ "subject": subject, "content": content, "labels": labelsStr, } html, _ := s.htmlGenerator.GenerateContactPage(false, "Subject and message are required", "", formData, nil, []generator.FeedItemInfo{}, nil) w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(html)) return } // Parse labels var labels []string if labelsStr != "" { labelParts := strings.Split(labelsStr, ",") for _, label := range labelParts { label = strings.TrimSpace(label) if label != "" { labels = append(labels, label) } } } // Fetch repo announcement ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() repoAnnouncement, err := s.issueService.FetchRepoAnnouncement(ctx, s.repoAnnouncement) if err != nil { logger.Errorf("Failed to fetch repo announcement: %v", err) formData := map[string]string{ "subject": subject, "content": content, "labels": labelsStr, } html, _ := s.htmlGenerator.GenerateContactPage(false, "Failed to connect to repository. Please try again later.", "", formData, nil, []generator.FeedItemInfo{}, nil) w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(html)) return } // Create issue request issueReq := &nostr.IssueRequest{ Subject: subject, Content: content, Labels: labels, } // Publish issue (using anonymous key - server generates random key) eventID, err := s.issueService.PublishIssue(ctx, repoAnnouncement, issueReq, "") if err != nil { logger.Errorf("Failed to publish issue: %v", err) formData := map[string]string{ "subject": subject, "content": content, "labels": labelsStr, } html, _ := s.htmlGenerator.GenerateContactPage(false, "Failed to submit your message. Please try again later.", "", formData, nil, []generator.FeedItemInfo{}, nil) w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(html)) return } // Success - render success page html, err := s.htmlGenerator.GenerateContactPage(true, "", eventID, nil, repoAnnouncement, []generator.FeedItemInfo{}, nil) if err != nil { http.Error(w, "Failed to generate success page", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(html)) } // handleContactAPI handles API requests for contact form with browser-signed events func (s *Server) handleContactAPI(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } // Parse JSON request var req struct { Event *gonostr.Event `json:"event"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) return } if req.Event == nil { http.Error(w, "Event is required", http.StatusBadRequest) return } // Validate event kind (will be validated again in PublishSignedIssue) // Note: issueKind is stored in issueService, validation happens there // Publish the signed event ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() eventID, err := s.issueService.PublishSignedIssue(ctx, req.Event) if err != nil { logger.Errorf("Failed to publish signed issue: %v", err) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, `{"error": "Failed to publish issue: %s"}`, err.Error()) return } // Return success response w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{"success": true, "event_id": "%s"}`, eventID) } // handleStatic serves static files func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request) { // Serve static files from the static directory http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))).ServeHTTP(w, r) } // handleFavicon serves the favicon func (s *Server) handleFavicon(w http.ResponseWriter, r *http.Request) { // Serve the SVG icon as favicon http.ServeFile(w, r, "./static/GitCitadel_Icon_Black.svg") } // handleHealth handles health check requests func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { if s.cache.Size() == 0 { w.WriteHeader(http.StatusServiceUnavailable) w.Write([]byte("Not ready")) return } w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) } // handleMetrics handles metrics requests func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "cache_size %d\n", s.cache.Size()) fmt.Fprintf(w, "feed_items %d\n", len(s.feedCache.Get())) } // handleSitemap handles sitemap requests func (s *Server) handleSitemap(w http.ResponseWriter, r *http.Request) { // TODO: Generate sitemap from cache w.Header().Set("Content-Type", "application/xml") w.Write([]byte(` `)) } // handleRobots handles robots.txt requests func (s *Server) handleRobots(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("User-agent: *\nAllow: /\nSitemap: /sitemap.xml\n")) } // handle404 handles 404 errors func (s *Server) handle404(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) html, err := s.htmlGenerator.GenerateErrorPage(404, []generator.FeedItemInfo{}) if err != nil { w.Write([]byte("404 - Page Not Found")) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write([]byte(html)) } // servePage serves a cached page with proper headers func (s *Server) servePage(w http.ResponseWriter, r *http.Request, page *cache.CachedPage) { // Set headers w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("ETag", page.ETag) w.Header().Set("Cache-Control", "public, max-age=3600") w.Header().Set("Last-Modified", page.LastUpdated.Format(http.TimeFormat)) // Check If-None-Match for conditional requests if match := r.Header.Get("If-None-Match"); match == page.ETag { w.WriteHeader(http.StatusNotModified) return } // Check Accept-Encoding for compression acceptEncoding := r.Header.Get("Accept-Encoding") if strings.Contains(acceptEncoding, "gzip") && len(page.Compressed) > 0 { w.Header().Set("Content-Encoding", "gzip") w.Header().Set("Vary", "Accept-Encoding") w.Write(page.Compressed) return } // Serve uncompressed w.Write([]byte(page.Content)) } // middleware adds security headers and logging func (s *Server) middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Security headers w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("X-XSS-Protection", "1; mode=block") w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") // CSP header - allow unpkg.com for Lucide icons w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline' https://unpkg.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:;") // Log request (only in debug mode to reduce noise) start := time.Now() next.ServeHTTP(w, r) logger.WithFields(map[string]interface{}{ "method": r.Method, "path": r.URL.Path, "duration": time.Since(start), }).Debug("HTTP request") }) }