package app import ( "context" "crypto/sha256" "crypto/subtle" "io/fs" "log/slog" "mime" "net/http" "strconv" "strings" "sync" "time" adminui "web-extract/web" ) const adminCookie = "web_extract_admin" const adminSessionTTL = 12 * time.Hour // Sessions are bounded and process-local: logout revokes them and restart clears them. type adminAuth struct { mu sync.Mutex sessions map[string]time.Time failures int window time.Time } func (s *Service) handler() http.Handler { api := s.apiHandler() mux := http.NewServeMux() admin := s.adminHandler(api) mux.Handle("/admin", admin) mux.Handle("/admin/", admin) mux.Handle("/", api) return mux } func (s *Service) adminHandler(api http.Handler) http.Handler { auth := &adminAuth{sessions: make(map[string]time.Time)} assets, err := fs.Sub(adminui.Files, "dist") if err != nil { panic(err) } files := http.StripPrefix("/admin/", http.FileServer(http.FS(assets))) routes := http.NewServeMux() routes.HandleFunc("POST /admin/api/login", func(w http.ResponseWriter, r *http.Request) { var input struct { Password string `json:"password"` } body, err := readBounded(r.Body, 4096) if err != nil || strictJSON(body, &input) != nil { adminError(w, 400, "provide a password as json") return } auth.mu.Lock() defer auth.mu.Unlock() now := time.Now() if now.Sub(auth.window) >= time.Minute { auth.window, auth.failures = now, 0 } if auth.failures >= 10 { w.Header().Set("Retry-After", "60") adminError(w, 429, "too many login attempts; try again in a minute") return } got, want := sha256.Sum256([]byte(input.Password)), sha256.Sum256([]byte(s.cfg.AdminPassword)) if subtle.ConstantTimeCompare(got[:], want[:]) != 1 { auth.failures++ adminError(w, 401, "incorrect password") return } for token, expiry := range auth.sessions { if !expiry.After(now) { delete(auth.sessions, token) } } if len(auth.sessions) >= 128 { adminError(w, 429, "too many active sessions; sign out of another browser") return } token := newID() + newID() auth.sessions[token] = now.Add(adminSessionTTL) s.adminSetCookie(w, r, token, int(adminSessionTTL.Seconds())) writeJSON(w, 200, map[string]bool{"authenticated": true}) }) protected := http.NewServeMux() protected.HandleFunc("GET /admin/api/session", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]bool{"authenticated": true}) }) protected.HandleFunc("POST /admin/api/logout", func(w http.ResponseWriter, r *http.Request) { cookie, _ := r.Cookie(adminCookie) auth.mu.Lock() delete(auth.sessions, cookie.Value) auth.mu.Unlock() s.adminSetCookie(w, r, "", -1) writeJSON(w, 200, map[string]bool{"authenticated": false}) }) protected.HandleFunc("GET /admin/api/overview", func(w http.ResponseWriter, r *http.Request) { data, err := s.adminOverview(r.Context()) adminRespond(w, data, err) }) protected.HandleFunc("GET /admin/api/requests", func(w http.ResponseWriter, r *http.Request) { before := int64(0) if raw := r.URL.Query().Get("before"); raw != "" { var err error before, err = strconv.ParseInt(raw, 10, 64) if err != nil || before < 1 { adminError(w, 400, "invalid pagination cursor") return } } endpoint := r.URL.Query().Get("endpoint") if endpoint != "" && endpoint != "search" && endpoint != "contents" && endpoint != "answer" { adminError(w, 400, "invalid endpoint filter") return } data, err := s.adminRequests(r.Context(), before, endpoint, r.URL.Query().Get("errors") == "true") adminRespond(w, data, err) }) protected.HandleFunc("GET /admin/api/requests/{id}", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") if len(id) > 128 { adminError(w, 400, "invalid request id") return } data, err := s.log.adminTrace(r.Context(), id) if err == nil && len(data.Requests) == 0 { adminError(w, 404, "request not found") return } adminRespond(w, data, err) }) // Reuse the exact public API validation, execution, response, and training logs. // The API token never travels to the browser, and cookie auth never grants /mcp access. for _, endpoint := range []string{"search", "contents", "answer"} { protected.HandleFunc("POST /admin/api/"+endpoint, func(w http.ResponseWriter, r *http.Request) { r = r.Clone(r.Context()) r.URL.Path = "/" + endpoint r.Header.Set("x-api-key", s.cfg.Token) r.Header.Set("x-caller", "admin-dashboard") api.ServeHTTP(w, r) }) } protected.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { adminError(w, 404, "unknown admin endpoint") }) routes.Handle("/admin/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie(adminCookie) auth.mu.Lock() valid := err == nil && auth.sessions[cookieValue(cookie)].After(time.Now()) auth.mu.Unlock() if !valid { adminError(w, 401, "sign in to continue") return } ctx, cancel := context.WithTimeout(r.Context(), s.cfg.RequestTimeout) defer cancel() protected.ServeHTTP(w, r.WithContext(ctx)) })) routes.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/admin/", http.StatusTemporaryRedirect) }) routes.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" && r.Method != "HEAD" { w.Header().Set("Allow", "GET, HEAD") adminError(w, 405, "use get") return } if r.URL.Path != "/admin/" && !strings.HasPrefix(r.URL.Path, "/admin/assets/") { http.NotFound(w, r) return } files.ServeHTTP(w, r) }) csrf := http.NewCrossOriginProtection() csrf.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { adminError(w, 403, "cross-origin requests are not allowed") })) handler := csrf.Handler(routes) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if s.cfg.AdminPassword == "" { http.NotFound(w, r) return } w.Header().Set("Cache-Control", "no-store") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'") if r.Method == "POST" { media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) if media != "application/json" { adminError(w, 415, "use application/json") return } } handler.ServeHTTP(w, r) }) } func cookieValue(c *http.Cookie) string { if c == nil { return "" } return c.Value } func (s *Service) adminSetCookie(w http.ResponseWriter, r *http.Request, value string, age int) { http.SetCookie(w, &http.Cookie{Name: adminCookie, Value: value, Path: "/admin", HttpOnly: true, Secure: s.cfg.AdminCookieSecure || r.TLS != nil, SameSite: http.SameSiteStrictMode, MaxAge: age}) } func adminError(w http.ResponseWriter, status int, message string) { writeJSON(w, status, map[string]string{"error": message}) } func adminRespond(w http.ResponseWriter, data any, err error) { if err != nil { slog.Error("admin query failed", "error", err) adminError(w, 500, "could not read the activity log; try refreshing") return } writeJSON(w, 200, data) }